我只是好奇,为什么这段代码能工作...
function slasher(arr, howMany) {
arr.splice(0, howMany);
return arr;
}
slasher([1, 2, 3], 2);
但这不是吗?我想要的结果是 "[3]"
function slasher(arr, howMany) {
return arr.splice(0, howMany);
}
slasher([1, 2, 3], 2);
最佳答案
回答此类问题只需查阅一份好的文档即可。我推荐 Mozilla 的 MDN - Array.splice() :
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
Return value
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
它告诉我们这个方法就地改变了数组,即 myArray.splice()
直接变异/改变 myArray
而不是构建一个新数组并返回它.返回值实际上是 已删除 元素的列表。
关于javascript - 为什么这现在作为一个返回声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44207800/