gpt4 book ai didi

javascript - 将数组复制到 "this"变量上(创建类似数组的对象)

转载 作者:行者123 更新时间:2023-11-28 18:55:45 25 4
gpt4 key购买 nike

是否有更好的方法将数组复制到 this 变量

function obj(arr) {
for (var i=0, l=arr.length; i<l; ++i) {
this[i] = arr[i];
}
this.length = arr.length;
}

var o = new obj([1,2,3,4]);
console.log(o[0]); // Outputs 1

有没有其他方法可以做到这一点,而不是迭代整个arr

最佳答案

您可以使用Array#push这样:

function obj(arr) {
Array.prototype.push.apply(this, arr);
}

这会将 this 视为数组,添加 arr 中的所有元素并正确设置 length。另请参阅Function#apply .

但是当然仍然存在内部循环。您无法将集合值复制/移动到另一个集合而不迭代它(除非,我猜,集合使用 structural sharing )

关于javascript - 将数组复制到 "this"变量上(创建类似数组的对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33656210/

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