我为什么从这个简单的splice命令获得此输出?
作者:互联网
我在理解为什么获得此输出方面有一个小问题.
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);
输出是:
[ 'a', 'b', '1', 'c', 'd', 'e', 'f' ]
[]
为什么输出的第二行不是:
[ 'a', 'b', '2', 'c', 'd', 'e', 'f' ]
是分配问题还是什么?
解决方法:
阅读约splice方法.它返回
An array containing the removed elements. If only one element is removed, an array of one element is returned.
所以这样做
arr2 = arr2.splice(2,0,"2");
您可以使用splice返回的空数组[]覆盖初始数组arr.
标签:javascript,variable-assignment,splice 来源: https://codeday.me/bug/20191012/1900155.html