Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.push() multiple objects into JavaScript array returns 'undefined'

When I add items to the beats array and then console.log the User, I'm getting the correct number of items in the array. But when I check .length, I always get 1. Trying to call the index will always give me 'undefined' like so: Tom.beats[1] I think I'm missing something obvious, but this is beating me. I suspect that I'm misusing the .push method but I'm unsure. Any help is greatly appreciated! (using Chrome dev tools)

//The USER

function User(name, role){
    this.beats = [ ]; 

    this.name = name;
    this.role = role;

    // add beats to beats array

    this.addBeats = function(beats){ 
        return this.beats.push(beats);
   };

}

// Three New Instances. Three New Users.

var Mal = new User("Mal", "Rapper");
Mal.addBeats(["love", "cash"]);

var Dan = new User("Dan", "Producer");
Dan.addBeats(["cake", "dirt", "sally-mae"]);

var Tom = new User("Tom", "Producer");
Tom.addBeats(["Fun", "Little", "Samsung", "Turtle", "PC"]);

// Check for position in beats array

console.log(Tom.beats); 
console.log(Mal.beats); 
console.log(Dan.beats); 

console.log(Mal.beats[1]);
console.log(Dan.beats[1]);
console.log(Tom.beats[1]);
like image 706
MFrazier Avatar asked Jun 17 '12 23:06

MFrazier


People also ask

Can I push multiple objects into array JavaScript?

As you can see, we simply pass the obj object to the push() method and it will add it to the end of the array. To add multiple objects to an array, you can pass multiple objects as arguments to the push() method, which will add all of the items to the end of the array.

Can you push multiple items into an array?

Use the Array. push() method to push multiple values to an array, e.g. arr. push('b', 'c', 'd'); . The push() method adds one or more values to the end of an array.

Does Push return a new array JavaScript?

push() The push() method adds one or more elements to the end of an array and returns the new length of the array.


2 Answers

Array.push(...) takes multiple arguments to append to the list. If you put them in an array itself, this very array of "beats" will be appended.

Array.concat(...) is most likely not what you are looking for, because it generates a new array instead of appending to the existing one.

You can use [].push.apply(Array, arg_list) to append the items of the argument list:

this.addBeats = function(beats) { 
    return [].push.apply(this.beats, beats);
};
like image 98
kay Avatar answered Oct 16 '22 08:10

kay


Spread operator

In environments that support the spread operator you may now do the following:

this.addBeats = function (beats) {
    return this.beats.push(...beats);
};

Or if you need more control for overwriting etc

this.addBeats = function(beats) { 
    return this.beats.splice(this.beats.length, null, ...beats);
};
like image 32
Ashley Coolman Avatar answered Oct 16 '22 09:10

Ashley Coolman