gpt4 book ai didi

javascript - Array.prototype.map.bind 与对象一起使用是否可靠?

转载 作者:行者123 更新时间:2023-11-30 17:14:40 26 4
gpt4 key购买 nike

我喜欢 Array.prototype.map 方法,前段时间我遇到了一个我没想到的用法。

    var xargByID = { a: 1, b: 2 };

Array.prototype.map.bind(xargByID)(function (xarg) {

});

我不知道 Array.prototype.map 内部是如何工作的所以我不得不问,它可靠吗?它可能会随着时间的推移而破裂吗?

最佳答案

根本行不通。您只能对具有以 0 开头的数字属性并具有相应长度属性的对象调用 Array.map。所以只有这个会起作用:

var xargByID = {0: 'first', 1: 'second', 2: 'third', length: 3};

Array.prototype.map.bind(xargByID)(function (xarg) {
console.log(xarg);
});

这是因为 .map() 在内部做了类似下面的模拟:

function simulateMap(callback, thisArg) {
var ret = [], length = this.length, that = thisArg || this;
for (var i = 0; i < length; i++) {
ret.push(callback.call(that, this[i], i, this));
}
return ret;
}

.forEach().some()等也是一样

编辑但是如果你非常喜欢.map(),你可以这样做:

var xargByID = { a: 1, b: 2, c: 3};

Object.getOwnPropertyNames(xargByID).map(function(xarg, i, arr) {
console.log(xarg, arr[i]);
});

关于javascript - Array.prototype.map.bind 与对象一起使用是否可靠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26335428/

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