Why am I getting this output from this simple splice command?

寵の児 提交于 2019-12-20 02:29:13

问题


I have a small issue with understanding why I'm getting this output.

var arr = ["a", "b", "c", "d", "e", "f"];
arr.splice(2,0,"1");
console.log(arr);  

var arr2 = ["a", "b", "c", "d", "e", "f"];
arr2 = arr2.splice(2,0,"2");
console.log(arr2);

ouput is:

[ 'a', 'b', '1', 'c', 'd', 'e', 'f' ]
[]  

Why is the second line of output not:

[ 'a', 'b', '2', 'c', 'd', 'e', 'f' ]  

Is it an issue of assignment or what?


回答1:


Reading about splice method. It returns

An array containing the removed elements. If only one element is removed, an array of one element is returned.

So by doing

arr2 = arr2.splice(2,0,"2");

you overwrite initial array arr with empty array [] returned by splice.




回答2:


1 - The splice method Changes the content of an array

2 - The splice method returns the element removed - ** Not original Array **



来源:https://stackoverflow.com/questions/16382414/why-am-i-getting-this-output-from-this-simple-splice-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!