0

The following code produces (in Chrome javascript console)

a: (3) [1, 2, 3] b: (4) [1, 2, 3, 99] c: 4

I expected c to look like b. Why doesn't it?

function snafu(){
    var a = [1,2,3];
    var b = a.slice();
    var c = a.slice().push(99);
    b.push(99);
    console.log("a:",a,"  b:",b,"  c:",c);
}
1
  • you can replace push with concat and it should work Commented Jul 15, 2020 at 9:32

2 Answers 2

2

Array.push() gives you value of Array.length and not array itself

var a = [];
var b = a.push(8); /* returns length of array after pushing value into array */
console.log('a = ', a, ', b = ', b);

Sign up to request clarification or add additional context in comments.

Comments

1

Well, remember Array.slice() will return you new Array. So while pushing it on slice(), it'll return you length of the array.

function snafu(){
    var a = [1,2,3];
    var b = a.slice();
    var c = a.slice();
    c.push(99);
    b.push(99);
    console.log("a:",a,"  b:",b,"  c:",c);
}

snafu();

variable c will give you new Array so you can do whatever you want with c.

That's it. Easy!!!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.