gpt4 book ai didi

javascript - 使用 arr.push 与 arr.push.apply(arr, element)

转载 作者:行者123 更新时间:2023-11-29 19:07:52 26 4
gpt4 key购买 nike

我主要是这样使用的:

arr.push(element)

但我见过有人这样使用:

arr.push.apply(arr, element)

这两种方法有什么区别?

最佳答案

我认为在使用“列表”时更常见。使用 apply 时,您可以将数组分解为单独的参数。

例如:

arr.push(0,1,2,3)

就像这样做,但初始值在数组中:

arr.push.apply(this, [0,1,2,3])

这是一个运行示例:

var original = [1,2,3];
var arr = [];

arr.push(0);
arr.push.apply(arr, original); // pushes all the elements onto the array

console.log(arr); // 0,1,2,3

但是,在 ES6 中,您甚至不需要使用 apply

let original = [1,2,3];
let arr = [];

arr.push(0, ...original);

console.log(arr); // 0,1,2,3

关于javascript - 使用 arr.push 与 arr.push.apply(arr, element),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41405252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com