在 JavaScript 中复制数组
在本文中,我们将学习如何将数组的元素复制到新的 JavaScript 数组中。
在 JavaScript 中,数组是包含所需键中的值的普通对象,可以是数字。
数组是具有固定数字键和动态值的 JavaScript 对象,在单个变量中包含任意数量的数据。数组是一维或多维的。
JavaScript 数组可以存储任何东西,例如直接值或存储 JavaScript 对象。与不同的语言相比,JavaScript 数组可以在相同数组的不同索引上保存不同的数据。
slice()
方法是 JavaScript 提供的内置方法。此方法将数组拆分为两个位置。
通过采用两个输入(开始索引和结束索引)来执行此切割。基于此,该部分将在索引上返回一个数组。
如果只指定起始索引,则返回最后一个元素。使用 slice
而不是 splice
的优点是它不会用 splice
改变原始数组。
语法:
slice()
slice(start)
slice(start, end)
start
和 end
索引处的任何元素(包括 end 之前的 start 和 stop 元素)都将插入到新数组中。结束索引是一个完全可选的参数。
你可以在 slice()
的文档中找到有关 slice
函数的更多信息。
const inputArray = ["Kiwi","Orange","Apple","Banana"];
const outputArray1 = inputArray.slice();
console.log(outputArray1);
当我们调用 slice()
时,所有元素都从原始数组复制,即 inputArray
到 outputArray1
。整个数组被复制,因为我们不传递开始或结束索引。
如果起始索引大于数组的长度,则返回空,空数组也将作为输出返回。有趣的部分是,如果你指定负索引,输入参数将被视为从序列末尾开始的更改。
一旦你在任何浏览器中运行上面的代码,它就会打印出类似这样的内容。
输出:
["Kiwi","Orange","Apple","Banana"]
spread
(...
) 语法允许扩展可迭代对象,例如,期望零个或多个参数(用于函数调用)或元素(用于数组字面量)的表达式或数组或扩展对象在需要零个或多个键值对的地方表达(对于对象文字)。
语法:
const newArray = [...oldArray];
当对象或数组的所有元素必须包含在某个列表中时,可以使用 spread
语法。
它通常用于将新项目添加到本地数据存储或查看所有已保存的项目和新增内容。此类操作的一个非常简单的版本可能如下所示。
const inputArray = ["Kiwi","Orange","Apple","Banana"];
const outputArray1 = [...inputArray, 'Grapes'];
console.log(outputArray1);
在上面的示例中,你可以尽可能多地执行最后一行,以将更多葡萄添加到数组的末尾。
输出:
["Kiwi","Orange","Apple","Banana"]
["Kiwi","Orange","Apple","Banana", "Grapes"]
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。