javascript - 为什么这现在作为一个返回声明?

标签 javascript function

我只是好奇,为什么这段代码能工作...

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/

相关文章:

javascript - 在 JavaScript 中快速重绘 unicode 符号数组

javascript - Node : Using fs. readFile 读取错误 : EISDIR: illegal operation on a directory,

r - 按名称合并多对列

javascript - VueJS - 将标记中的数据发送到 Vue 实例以在 mounted() 中使用

javascript - 用鼠标移动 jQuery 自定义工具提示

c - 为什么在库函数之前有一个序列点?

r - 计算数据集中因子水平的相对频率

python - 如何将字符串变量从 python 传递给 PowerShell 函数

javascript - 限制输入数字小数点前后的数字

javascript - 覆盖和恢复功能