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

I want to clone a new array from an existing one and insert an element. Unfortunately, the existing array is empty, so it likes:

[].slice().push(65)

the output of the above expression is 1.

Why is this 1?

+4
source share
2 answers

Array#push()returns the length of the resulting array. Since you are pushing a single value on an empty array, the length of the result will indeed be 1.

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

var arr = [].slice();
arr.push(65);
console.log(arr); // [ 65 ]
+6
source

Editing my comment on the answer:

MDN push(): push() .

, .

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

, concat()

var a = [1,2,3];
var b = [].concat(a,64);
console.log(b);
+2

Source: https://habr.com/ru/post/1539768/


All Articles