Guide to getting methods and functions up and running in JavaScript

Having trouble with the following method and function, can anyone provide assistance?

hasMoreOscarsThan - A method that takes an actor object as a parameter and determines 
    if they have more Oscars than the specified object. Returns true or false.

Create the following functions:

getActorByName - Function that takes a string and returns the actor object from 
    the array whose name matches the input string.

Here is my code:

function Person(firstName, lastName, age, numOscars) {

    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.numOscars = numOscars;
    this.hello = function() { console.log("Hello, my name is " + this.firstName); }
    this.hasMoreOscarsThan = function(x, y) {
        if (this.numOscars > this.numOscars) {
            return this.firstName;
        } else {
            return "False!";
        }
    }

};


var actors = new Array();
actors[0] = new Person("Leonardo", "DiCaprio", 41, 1);
actors[1] = new Person("Jennifer", "Lawrence", 25, 1);
actors[2] = new Person("Samuel L.", " Jackson", 67, 0);
actors[3] = new Person("Meryl", "Streep", 66, 3);
actors[4] = new Person("John", "Cho", 43, 0);

actors.forEach(function(item) {
    item.hello();
})

actors.forEach(function(item) {
    item.hasMoreOscarsThan();
})


function getActorByName(person) {
    console.log(actors.firstName + " " + actors.lastName);
}


function list() {
    var actorsLength = actors.length;
    for (var i = 0; i < actorsLength; i++) {
        getActorByName(actors[i]);
    }
}


var search = function(lastName) {
    var actorsLength = actors.length;
    for (var i = 0; i < actorsLength; i++) {
        if (lastName == actors[i].lastName) {
            getActorByName(actors[i]);
        }
    }
}


search("DiCaprio");

var getAverageAge;

getAverageAge = (actors[0].age + actors[1].age + actors[2].age + actors[3].age + actors[4].age) / actors.length;
console.log(getAverageAge);

Appreciate your help in advance!!!

Answer №1

I made modifications to your script:

function Person(firstName, lastName, age, numOscars) {

    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.numOscars = numOscars;
    this.hello = function() { console.log("Hello, my name is " + this.firstName); }
    this.hasMoreOscarsThan = function(x) {
        if (this.numOscars > x) {
            return this.firstName;
        } else {
            return "False!";
        }
    }

};


var actors = new Array();
actors[0] = new Person("Leonardo", "DiCaprio", 41, 1);
actors[1] = new Person("Jennifer", "Lawrence", 25, 1);
actors[2] = new Person("Samuel L.", " Jackson", 67, 0);
actors[3] = new Person("Meryl", "Streep", 66, 3);
actors[4] = new Person("John", "Cho", 43, 0);

actors.forEach(function(item) {
    item.hello();
})

actors.forEach(function(item) {
    console.log(item.hasMoreOscarsThan(2));
})


function getActorByName(person) {
    console.log(person.firstName + " " + person.lastName);
}


function list() {
    var actorsLength = actors.length;
    for (var i = 0; i < actorsLength; i++) {
        getActorByName(actors[i]);
    }
}


var search = function(lastName) {
    var actorsLength = actors.length;
    for (var i = 0; i < actorsLength; i++) {
        if (lastName == actors[i].lastName) {
            getActorByName(actors[i]);
        }
    }
}

search("DiCaprio");

var getAverageAge;

getAverageAge = (actors[0].age + actors[1].age + actors[2].age + actors[3].age + actors[4].age) / actors.length;
console.log(getAverageAge);

After running the script:

Hello, my name is Leonardo

Hello, my name is Jennifer

Hello, my name is Samuel L.

Hello, my name is Meryl

Hello, my name is John

False! False! False! Meryl False! Leonardo DiCaprio 48.4

Answer №2

There seems to be confusion in the argument being passed as personobject, as references are made to actors which is not defined within the function. To rectify this, the references have been changed to person.firstName and person.lastName

function getActorByName(person) {
    console.log(person.firstName + " " + person.lastName);
}

JSFIDDLE

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add a file to the input field using JavaScript and the input type="file"

I am facing the challenge of sending a file (up to a few MB) generated by JavaScript to a server using POST (not ajax POST). I am wondering how I can add a file to an input type="file" using JavaScript. After checking Pre-Populate HTML form file input, it ...

How can I color the first, second, and third buttons when the third button is clicked? And how can I color all the buttons when the fourth button is clicked?

I am trying to achieve a task with 4 buttons. When the third button is clicked, I want the first, second, and third buttons to change color. Similarly, when the fourth button is clicked, I want all buttons to change color. Additionally, I need to save a va ...

Is the current version of Bootstrap experiencing issues with Data-bs-toggle functionality?

I have encountered an issue where the bootstrap 5.1.3 data-bs-toggle feature is no longer functioning properly. For example: <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" datadat-b ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...

Modified the component based on the state passed from another component

One issue I'm facing is with my hamburger component in TodoHeader.jsx. It only has a color prop, no className prop. I noticed that when using the ternary operator to change its color, it only takes effect after a page reload. On the other hand, FontAw ...

Utilize Restangular to send data as a payload rather than a query string

Currently, my backend service is set up to register a new user in our system using the following URL: /api/users/register When using Restangular, post requests are typically sent as either query string: Restangular.all('users').post("register" ...

Retrieving raw PCM data from webAudio / mozAudio APIs

I have been exploring ways to store the output from the webAudio API for future reference. It seems that capturing PCM data and saving it as a file might meet my needs. I am curious to know if the webAudio or mozAudio APIs have built-in functionality for ...

Replace pipeline function during component testing

During my unit testing of a component that utilizes a custom pipe, I encountered the need to provide a fake implementation for the transform method in my test. While exploring options, I discovered that it's feasible to override components, modules, ...

The modal in Bootstrap V5 refuses to hide using JavaScript unless the window method is utilized

Currently in the process of developing a react application and utilizing standard bootstrap. The command to display a modal and switch to one is functioning properly; but, the command to hide the modal does not work unless I establish it as a property on t ...

Uncover the hidden href link that has been obscured using the code javascript:void(0)

Currently, I am in the process of developing a straightforward PHP script to extract the actual link from a website that conceals the real link/key using the javascript:void(0) approach. Upon inspecting the source code, I noticed that the href link is empt ...

Looping through JSON data to dynamically generate DIV elements

Currently, I have in my possession a JSON array that contains various values. To convert this List to JSONArray, I employed the JSON-lib and some groovy classes. Along with the JSON array, I also have a JS file and a JSF for the front end. My task at hand ...

Is there a way to delete an Object from a MongoDB array without using $pull?

I'm in the process of developing a social media application, and I have created a route that allows users to like posts. However, I want the functionality such that if a user has already liked a post and clicks the "like" button again, it should remov ...

Adjusting the size of tables in raw JavaScript without altering their positioning

I am attempting to adjust the size of a th element without impacting the position of the next th in the row. Specifically, I want the width of the th to influence the width of the next th accordingly, rather than pushing it to the left. Below is the code ...

Eliminate an item from a JavaScript array

I am trying to remove a specific element from a JavaScript array. The element I need to remove is the one with the value of 'NT'. In my HTML input, I have: <input type="text" id="caseType" size="50"/> To populate it, I use: var c ...

Implementing bidirectional data binding with Semantic UI's search dropdown feature in Vue.js

I'm currently facing an issue with the Semantic-UI searchable dropdown and Vuejs data binding. It seems like only one changed option is being model-bound, no matter which dropdown option I select. Here's a snippet of my code. I attempted to use ...

Submitting values using the serialize method and Ajax involves sending placeholders

Looking for a solution: <form class="pure-form pure-form-stacked" method="post" enctype="multipart/form-data"> <input type="text" name="name" class="button-size-1" placeholder="*Name"> <input type="text" name="email" class="but ...

Display or conceal HTML content based on the input's property type

Looking to toggle the visibility of an icon on my input based on the prop type. If the type is set to password, the icon will be displayed for toggling between visible and hidden password; if the type is not password, the icon should be hidden by setting ...

Tips for redirecting in Vuejs when the input focus is not true

I have a Vue view where the search input automatically focuses when opened. However, if the user clicks away from the input, I want the view to redirect back. I've searched for solutions to this problem but have not had any luck. Here is my code usin ...

Which kinds of data are ideal for storage within the Vuex (Flux) pattern?

Currently delving into the world of Vuex for the first time as I develop an application in Vue.js. The complexity of this project requires a singleton storage object that is shared across all components. While Vuex appears to be a suitable solution, I am s ...

What is the best way to access the value of an HTML tag in React?

Currently in the process of developing a feature for the price tab using React. These components are designed to allow users to add price classes to their shopping cart. One challenge I'm facing is how to retrieve the HTML string of an HTML tag. Here& ...