In the below code I am trying to print out just the first value (name) of the array, but it doesn't work as I expect:
function Person (name, age) {
this.name = name;
this.age = age;
}// Our Person constructor
// Now we can make an array of people
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);
// loop through our new array
for(i = 0; i <= family.Length; i++) {
console.log( family[i].this.name);
}
You are using the "this" keyword incorrectly. When you access family[i] you are already accessing an instance of that prototype in JavaScript. Just drop the "this."
To get the first item from the array you could do the below without the loop:
console.log(family[0].name);
Without looping, as the loop is unnecessary if you know which item you want to print.
Or, if the loop is necessary you could add some logic such as
if(i === 0) {
console.log(family[0].name);
}
You do not need to use this when accessing the name property of the object in the array.
function Person (name, age) {
this.name = name;
this.age = age;
}// Our Person constructor
// Now we can make an array of people
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);
// loop through our new array
for(i = 0; i < family.length; i++) {
console.log( family[i].name);
}
Related
I have a code with 4 vars named Alex John Billy and Bob. I created an if-else statement and for now i only want the if statement to execute if ANY of the var's this.age value is found under 14 , and else statement if all vars are over 14
but right now only the else statement executes and i am assuming its because 2/4 vars have this.age value over 14. My question is how exactly can i consider all vars
function person(name, age){
this.name = name;
this.age = age;
}
var Alex = new person("Alex", 15);
var John = new person("John", 16);
var Billy = new person("Billy", 13);
var Bob = new person("Bob", 11);
if(this.age < 14){
document.write("oops!");
}
else{
document.write("yay!");
}
You could add your objects to an array and then check if at least one of the contained objects has an age lower than 14 using Array.prototype.some().
function person(name, age){
this.name = name;
this.age = age;
}
persons = [];
persons.push(new person("Alex", 15));
persons.push(new person("John", 16));
persons.push(new person("Billy", 13));
persons.push(new person("Bob", 11));
if(persons.some(p => p.age < 14)){
document.write("oops!");
}
else{
document.write("yay!");
}
You can push your person objects into another object, I've called it persons. Then you can loop through all the entries with a for of loop.
You can use Object.keys() to get an array of all the keys, or person objects in this case.
function person(name, age) {
this.name = name;
this.age = age;
}
const persons = {};
persons.Alex = new person("Alex", 15);
persons.John = new person("John", 16);
persons.Billy = new person("Billy", 13);
persons.Bob = new person("Bob", 11);
for (let pers of Object.keys(persons)) {
if (persons[pers].age < 14) {
console.log(persons[pers].name+": oops!");
} else {
console.log(persons[pers].name+": yay!");
}
}
EDIT:
As it transpires you only want one outcome for all the objects, this will change our code a little.
Now it's best to push() all the objects to an array, again, called persons then you can use every() to check each object against a function. If all the values pass you will get a TRUE but if one or more fail you will get a FALSE
function person(name, age) {
this.name = name;
this.age = age;
}
const persons = [];
persons.push(new person("Alex", 15));
persons.push(new person("John", 16));
persons.push(new person("Billy", 13));
persons.push(new person("Bob", 11));
if (persons.every(p => { p.age > 14 })) {
console.log('Yay!')
} else {
console.log('oops!')
}
Keeping the object:
If you want to keep the object for ease of use later we can make an array of all the ages using map()
function person(name, age) {
this.name = name;
this.age = age;
}
const persons = {};
persons.Alex = new person("Alex", 15);
persons.John = new person("John", 16);
persons.Billy = new person("Billy", 13);
persons.Bob = new person("Bob", 11);
if (!Object.keys(persons).map(k => {
return persons[k].age
}).some(e => e < 14)) {
console.log('Yay!');
} else {
console.log('oops!');
}
Create array for the 4person and use .map() to check them all like this example
function person(name, age) {
this.name = name;
this.age = age;
}
var Alex = new person("Alex", 15);
var John = new person("John", 16);
var Billy = new person("Billy", 13);
var Bob = new person("Bob", 11);
var persons = [Alex, John, Billy, Bob];
persons.map(prrson => {
if (prrson.age < 14) {
console.log("oops!");
} else {
console.log("yay!");
}
});
You have multiple possibilities so you want to create an array after we will check.
function person(name, age) {
this.name = name;
this.age = age;
}
var Alex = new person("Alex", 15);
var John = new person("John", 16);
var Billy = new person("Billy", 13);
var Bob = new person("Bob", 11);
var ages = [Alex.age, John.age, Billy.age, Bob.age];
for (i = 0; i < ages.length; i++) {
if (ages[i] < 14) {
document.write("oops!");
} else {
document.write("yay!");
}
}
Make Unique Objects by Passing Parameters to our Constructor:
The constructor we have is great, but what if we don't always want to create the same object?
To solve this we can add parameters to our constructor. We do this like the following example:
var Car = function(wheels, seats, engines) {
this.wheels = wheels;
this.seats = seats;
this.engines = engines;
};
Now we can pass in arguments when we call our constructor.
var myCar = new Car(6, 3, 1);
This code will create an object that uses the arguments we passed in and looks like:
{
wheels: 6,
seats: 3,
engines: 1
}
Now give it a try yourself! Alter the Car constructor to use parameters to assign values to the wheels, seats, and engines properties.
Then call your new constructor with three number arguments and assign it to myCar to see it in action.
Please complete the code given below :
var Car = function() {
//Change this constructor
this.wheels = 4;
this.seats = 1;
this.engines = 1;
};
//Try it out here
var myCar;
Instructions :
Calling new Car(3,1,2) should produce an object with a wheels
property of 3, a seats property of 1, and an engines property of 2.
Calling new Car(4,4,2) should produce an object with a wheels
property of 4, a seats property of 4, and an engines property of 2.
Calling new Car(2,6,3) should produce an object with a wheels
property of 2, a seats property of 6, and an engines property of 3.
myCar should have number values for the wheels, seats, and engines
properties.
My attempt :
var Car = function() {
//Change this constructor
this.wheels = 4;
this.seats = 1;
this.engines = 1;
};
//Try it out here
var myCar = function(wheels, seats, engines) {
this.wheels = wheels;
this.seats = seats;
this.engines = engines;
};
var myCar = new Car(6, 3, 1);
Coding challenge answer for the link you added will be :
var Car = function(wheels, seats, engines) {
if(isNaN(wheels))
wheels = 0;
if(isNaN(seats))
seats = 0;
if(isNaN(engines))
engines = 0;
this.wheels = wheels;
this.seats = seats;
this.engines = engines;
};
//Try it out here
var myCar = new Car(2,6,3);
myCar = new Car(3,1,2);
myCar = new Car(4,4,2);
Run tests after adding this code. - all will pass
You answered already yourself:
var Car = function(wheels, seats, engines) {
//additional checks
if(isNaN(wheels))
wheels = 0;
if(isNaN(seats))
seats = 0;
if(isNaN(engines))
engines = 0;
this.wheels = wheels;
this.seats = seats;
this.engines = engines;
};
//Try it out here
var myCar = new Car(3,1,2);
console.dir(myCar);
myCar = new Car(4,4,2);
console.dir(myCar);
myCar = new Car(2,6,3);
console.dir(myCar);
I am working on a Person constructor function that takes a name and age as its parameters, and trying to implement a method that retrieves all the 'Person' instances current age value and outputs the average. Here's my code...
var Person = (function() {
//private state
var inst = 1;
function Person(name, age) {
this.name = name;
this.age = age;
Object.defineProperty(this, "age", {
get: function() {
return age;
},
set: function(num) {
age = num;
}
});
Object.defineProperty(this, "_id", {
value: inst++
});
}
//Attempt to return number of instances divided by all current Person weights
Person.prototype.aveAge = function() {
return inst;
};
return Person;
}());
var jim = new Person("jim", 32);
var richard = new Person("richard", 27);
richard.age = 28;
var alfie = new Person("alfie", 42);
Person.aveAge() //Returns TypeError: Person.aveAge is not a function
I have set up a variable that is shared across all instances (inst) that increments each time an another instance is created and assigns a unique id. I cannot figure out how I can get to each 'age' value of all Person instances in existence using the aveAge prototype I have added at the bottom. I am also getting a 'TypeError: Person.aveAge is not a function' when I attempt to call it to even test that variable 'inst' holds the correct number of instances. Does anybody know where I am going wrong?
It feels strange to keep ages on a person when it references people. Notice that hanging things on __proto__ makes them available from the constructor (Person), while hanging things on prototype makes them available from the instance (richard). If Age is updated, it needs to be done via setAge so the PeopleTracker knows to update it's memory. Also, in my example, the average is only calculated when needed rather than each time a person wants to know what is is.
var peopleTracker = {
_count: 0,
_ages: [],
averageAge: 0,
addPerson: function (age) {
var pt = peopleTracker;
pt._count += 1;
pt._ages.push(age);
pt.getAverage();
},
getAverage: function () {
var sum = 0,
pt = peopleTracker;
sum = pt._ages.reduce(function (a, b) {
return a + b;
});
pt.averageAge = Math.round(sum / pt._count);
},
update: function (oldAge, newAge) {
var pt = peopleTracker,
ages = pt._ages,
i = ages.indexOf(oldAge);
ages.splice(i, 1, newAge);
pt.getAverage();
}
};
var Person = function (name, age) {
this.name = name;
this.age = age;
peopleTracker.addPerson(age);
};
Person.__proto__ = { // available from the constructor
Constructor: Person,
setAge: function (age) {
var oldAge = this.age;
this.age = age;
peopleTracker.update(oldAge, age);
},
aveAge: function () {
return peopleTracker.averageAge;
}
};
Person.prototype = Person.__proto__; // now also available from the instance
var jim = new Person("Jim", 32),
richard = new Person("Richard", 27),
alfie = new Person("Alfie", 42);
Person.aveAge(); // 34
richard.aveAge(); // 34
richard.setAge(20);
Person.aveAge(); // 31
richard.aveAge(); // 31
I have an array variable, filled by objects.
I need to sort this array primary by array[i].target; then secondary by array[i].weaponPriority
I can sort an array by one value, but unfortunally i cant grasp how i could refine it further.
Please advice.
var ships = []
function Ship(name, target, priority){
this.name = name;
this.target = target;
this.id = ships.length;
this.weaponPriority = priority;
}
var ship = new Ship("Alpha", 10, 3);
ships.push(ship);
var ship = new Ship("Beta", 10, 1);
ships.push(ship);
var ship = new Ship("Gamma", 10, 3);
ships.push(ship);
var ship = new Ship("Delta", 15, 2);
ships.push(ship);
function log(){
for (var i = 0; i < ships.length; i++){
var shippy = ships[i];
console.log(shippy.name + " ---, targetID: " + shippy.target + ", weaponPrio: " + shippy.weaponPriority);
}
ships .sort(function(obj1, obj2){
...
});
log();
You could try something like this:
function( obj1, obj2 ){
// We check if the target values are different.
// If they are we will sort based on target
if( obj1.target !== obj2.target )
return obj1.target-obj2.target
else // The target values are the same. So we sort based on weaponPriority
return obj1.weaponPriority-obj2.weaponPriority;
}
You will pass this function to the sort.
I'm getting the next error in function getOlder():
TypeError: Cannot read property 'age' of undefined
What's the problem and how to fix it?
function person(name, age) {
this.name=name;
this.age=age
}
// Returns the older person in a group of persons.
var getOlder = function(people) {
if (people.length === 0) {
return new person();
}
var older = people[0]; // The first one is the older for now.
var value;
for (var _ in people) {
value = people[_];
if (value.age > older.age) {
older = value;
}
}
return older;
};
// Declare some persons.
var paul = new person("Paul", 23);
var jim = new person("Jim", 24);
var sam = new person("Sam", 84);
var rob = new person("Rob", 54);
var karl = new person("Karl", 19);
var older = getOlder(paul, jim);
if (older.name !== "Jim") {
console.log("Fail");
}
Look at the signature of your function:
var getOlder = function(people) {
You did not create your function such that it accepts two person objects. You apparently only accept an array, as you're using people.length and people[0] inside the function. So you also have to pass an array:
var older = getOlder([paul, jim]);
var getOlder = function() {
var people = arguments;
if (people.length === 0) {
return new person();
}
var older = people[0]; // The first one is the older for now.
var value;
for (var _ in people) {
value = people[_];
if (value.age > older.age) {
older = value;
}
}
return older;
};
By Accepting no arguments in the function definition and relying on the variable arguments feature of JS you can get away with calling getOlder(paul, jim).
arguments is a property of every function which is basically an array of variable arguments provided to it while calling .