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

Is Array.prototype.map.bind reliable to use with objects?

本文关键字:是否 一起 对象 prototype map bind Array      更新时间:2023-09-26

我喜欢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]);
});

首先,.bind绝对不是编写示例的最佳方式,最好是Array.prototype.map.call(xargByID, function (xarg) {

只要对象是类似数组的,它就会工作:它有一个整数>=0的length属性,并且要迭代的元素位于整数>=0和<长度。这不是一个黑客,它是故意的;Array.prototype.map可以用于非Array对象,只要它们具有类似Array的形式

在您的示例中,它不起作用,因为属性不在数字索引处,并且没有长度属性。但是,如果xArgByID是,例如,这个:{0: 'a', 1: 'b', length: 2},它就会起作用。

我知道这并不能回答您问题的可靠性方面,但如果您可以访问像lodash这样的库,那么您可以使用它的map函数来迭代对象。此可靠的。

_.map(集合,[iteratee=_.identity])

通过iteratee运行集合中的每个元素来创建一个值数组。iteratee由三个参数调用:(值,索引|键,集合)。

根据您想要做的具体操作,您可能还需要考虑_.forOwn()_.forIn()_.forEach()方法。它们还迭代对象中的属性。

编辑:根据cortopy在下面的评论,我已经更新了这个答案,使其对lodash 4.x准确