خرید بک لینک

Vote count: 0

var alph = ["a", "b", "c"];
var r = [];

for(var i = 0; i < 5; i += 1) {
    r.push(alph);
}

r[0].reverse();
console.log(r); 

/* Output

[ [ 'c', 'b', 'a' ],
  [ 'c', 'b', 'a' ],
  [ 'c', 'b', 'a' ],
  [ 'c', 'b', 'a' ],
  [ 'c', 'b', 'a' ] ]

*/

/* Expected output

[ [ 'c', 'b', 'a' ],
  [ 'a', 'b', 'c' ],
  [ 'a', 'b', 'c' ],
  [ 'a', 'b', 'c' ],
  [ 'a', 'b', 'c' ] ] 

*/

There are arrays in an array. The first array should be reversed. I thought r[0].reverse() would do this, but instead this reverses all arrays.

Can someone explain why this happens ?

asked 6 mins ago

2 Answers

Vote count: 2

You are pushing the reference to the array, so updating one will make changes to the rest. Instead push the copy of the original array for copying array use Array#slice method.

var alph = ["a", "b", "c"];
var r = [];

for (var i = 0; i < 5; i += 1) {
  r.push(alph.slice());
}

r[0].reverse();
console.log(r);
answered 4 mins ago

Vote count: 1

You're not creating an array of new arrays when you push onto r: you're pushing the same array onto r 5 times (it's being passed by reference, not by value). Therefore, any operation on r[0] is really updating alph, which causes all of the other references to be updated, too.

answered 3 mins ago

برچسب: نویسنده: استخدام کار تاريخ: پنجشنبه 27 خرداد 1395 ساعت: 21:03

صفحه بندی