从MDN站点尝试以下代码
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
不分配以除去接头
['angel', 'clown', 'drum', 'mandarin', 'surgeon']
的预期输出,而是删除空数组[]
。 最佳答案
我认为您对splice
的返回值感到困惑。它不返回修改后的数组,但删除了元素。在这种情况下,您没有删除任何内容,因此如果登录removed
,则会得到一个空的Array
。
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
var removed = myFish.splice(2, 0, 'drum');
console.log(myFish);
console.log(removed);
输出:
Array [ "angel", "clown", "drum", "mandarin", "surgeon" ]
Array [ ]