gpt4 book ai didi

javascript - 这两段代码有什么区别? (javascript)

转载 作者:行者123 更新时间:2023-12-03 07:55:20 24 4
gpt4 key购买 nike

我试图找出以下两个代码片段之间的区别。它们都展平子数组数组并且输出相同的内容。

Array.prototype.concatAll = function() {
var results = [];
this.forEach(function(subArray) {
subArray.forEach(function(element) {
results.push(element);
});
});

return results;
}; // [ [1,2,3], [4,5,6], [7,8,9] ] -> [1, 2, 3, 4, 5, 6, 7, 8, 9]

Array.prototype.concatAll = function() {
var results = [];
this.forEach(function(subArray) {
results.push.apply(results, subArray);
});

return results;
}; // [ [1,2,3], [4,5,6], [7,8,9] ] -> [1, 2, 3, 4, 5, 6, 7, 8, 9]

申请如何运作?为什么结果必须写入两次?

最佳答案

apply 是函数的一种方法,允许传递显式 this 参数(可能与函数所属的对象不同)和参数数组。在您的示例中, apply 用于接受参数数组的能力,作为 spread operator 的替代品。 .

关于javascript - 这两段代码有什么区别? (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34821935/

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