Javascript Array.prototype.map.bind与对象一起使用是否可靠?
我喜欢Array.prototype.map方法,不久前我遇到了一个意想不到的用法Javascript Array.prototype.map.bind与对象一起使用是否可靠?,javascript,Javascript,我喜欢Array.prototype.map方法,不久前我遇到了一个意想不到的用法 var xargByID = { a: 1, b: 2 }; Array.prototype.map.bind(xargByID)(function (xarg) { }); 我不知道Array.prototype.map在内部是如何工作的,所以我不得不问,它可靠吗?它会随着时间的推移而中断吗?它根本不起作用。只能对具有以0开头的数字属性且具有相应长度属性的对象调用Array.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;
}
首先,
.bind
绝对不是编写示例的最佳方式,最好是Array.prototype.map.call(xargByID,function(xarg){
只要对象像数组一样,它就可以工作:它有一个length
属性,该属性是一个整数>=0,并且您要迭代的元素的属性是integers>=0和array.prototype.map
可以在非array
对象上使用,只要它们具有类似于数组的形式
在您的示例中,它将不起作用,因为属性不在数字索引处,并且没有长度属性。但是,如果xArgByID是,例如:
{0:'a',1:'b',length:2},它将起作用
我知道这并不能回答您问题的可靠性方面,但是如果您可以访问库,例如,那么您可以使用它来迭代对象。这是可靠的
_.map(集合,[iteratee=..identity])
通过iteratee运行集合中的每个元素来创建值数组。iteratee由三个参数调用:
(值、索引|键、集合)
根据您想做什么,您也可以考虑“<代码> > .FOWN())/>代码> <代码> > .FIN()/<代码>和<代码> >前额(<)/>代码>方法。它们还遍历对象中的属性。
编辑:根据cortopy下面的评论,我已将此答案更新为lodash 4.x的正确答案(之前的答案对lodash 3.x的正确答案)哪个版本的lodash?4.6.1.不接受thisArg。我想您可能会将其与支持[thisArg]的本机数组.prototype.map()混淆@cortopy是的,这在lodash 4.x中已更改。我已更新了答案。
var xargByID = { a: 1, b: 2, c: 3};
Object.getOwnPropertyNames(xargByID).map(function(xarg, i, arr) {
console.log(xarg, arr[i]);
});