Misgevolution
Misgevolution

Reputation: 845

JavaScript push method changing values

I am using Node shell to test this: BTW, I am new to Javascript

x = [1,2]
y = [3,4]
k = []
for ( n in x.concat(y) ) { k.push(n); }

Now typing k prints the following:

[ '0', '1', '2', '3' ]

Upvotes: 0

Views: 632

Answers (5)

Morklympious
Morklympious

Reputation: 1095

You're using a for...in loop on a data structure that doesn't typically operate with key/value pairs.

So what's actually happening is in each iteration of your for...in loop, you're passing the index to n and pushing that index to a new array.

What you're probably wanting is actually the forEach method native to arrays.

Which changes your code to be something like this...

var x = [1,2];
var y = [3,4];
var k = [];
x.concat(y).forEach(function(element, index) {
 k.push(element);
}

There's also the Array.map method also native to arrays that will actually produce an entirely new array (instead of you having to define k and push to it.

var x = [1,2];
var y = [3,4];

var k = x.concat(y).map(function(element, index) {
 // the return value is the element that will be at the
 // new array's index. 
 return element; 
}

Upvotes: 1

Jain
Jain

Reputation: 1249

Try this (in ES5):

var k = x.concat(y);

Try this (in ES6):

for (let n of x.concat(y)) {
  k.push(n);
}

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115232

There is no need of for loop at all simply assign the Array#concat method return value, which is the concatenated array.

var k = x.concat(y)

FYI : In for...in loop you are getting the key, in case it will be the array index. It's designed to use for object iteration. Use simple for loop instead. Even Array#map or Array#forEach can be used, as per your requirement.

An example with Array#forEach :

a.concat(b).forEach(function(e){
   k.push(e);
});

In case if you want to push an array of values to an existing array then use Array#push with Function#apply method.

[].push.apply(existingArray, arrayOfValuesToPush);

In your case it would be :

[].push.apply(k, a.concat(b));
// or
[].push.apply(k, a);
[].push.apply(k, b);

Upvotes: 3

brk
brk

Reputation: 50291

You need to refer to the element instead of index of the array

for ( n in _m=x.concat(y)) {
 k.push(_m[n]); 
}

JSFIDDLE

Upvotes: 1

Brad
Brad

Reputation: 163282

You're pushing the index, not the actual elements. Try something like this:

var x = [1,2];
var y = [3,4];
var k = [];

var z = x.concat(y);
for (var n in z) {
  k.push(z[n]);
}

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Upvotes: 0

Related Questions