Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does empty array.slice(0).push(anything) mean?

I want to clone a new array from an existing one and push in an element. Unfortunately, the existing array is an empty one, so it's like:

[].slice().push(65)

the output of above expression is 1.

Why is it 1?

like image 227
Aaron Shen Avatar asked Feb 14 '23 01:02

Aaron Shen


2 Answers

Array#push() returns the length of the resultant array. Since you're pushing a single value onto an empty array, the length of the result will indeed be 1.

If you want to see the updated array as output, you'll need to save a reference to it since push() does not return a reference:

var arr = [].slice();
arr.push(65);
console.log(arr); // [ 65 ]
like image 89
BoltClock Avatar answered Feb 15 '23 14:02

BoltClock


Changing my comment to an answer:

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

You need to do it in two steps, not one with that pattern.

var temp = [].slice();
temp.push(65);
console.log(temp);

If you want to do it in one line, look into concat()

var a = [1,2,3];
var b = [].concat(a,64);
console.log(b);
like image 24
epascarello Avatar answered Feb 15 '23 13:02

epascarello