Javascript 拼接给出不同的输出

Javascript splice gives different output

这是我在使用 splice 时遇到的一个奇怪行为。

const numbers = [1, 2, 3];
numbers.splice(0, 0, 4, 5);
console.log(numbers); // This gives output [4, 5, 1, 2, 3] 

console.log([1, 2, 3].splice(0, 0, 4, 5)) // Outputs []

这是为什么?

这是预期的行为。 splice returns 已删除项目的数组,在您的情况下,没有删除任何元素。 splice实际上修改了原数组。阅读文档 here

Array.splice 自身运行 returns 您拥有的元素范围,从第一个参数开始到第二个参数结束。第二个参数之后的所有内容都会自动添加到原始数组的末尾,但不会作为操作结果返回。

const numbers = [1, 2, 3];
console.log(numbers.splice(0, 0, 4, 5)) // <- prints nothing because your sequence is from 0 to 0.

splice 方法不会 return 输出,而是修改原始数组。

JavaScript数组拼接()替换原数组元素

array.splice(index, how_many_element, item1, ....., itemX);
const numbers = [1, 2, 3];


console.log(numbers.splice(0, 0, 4, 5)) // <- here index = 0, how_many_element = 0, deferent = 0, that is why prints nothing because your sequence is from 0 to 0.

index : The position to add/remove items; how_many_element : Number of items to be removed.