【发布时间】:2019-02-22 21:33:27
【问题描述】:
我遇到了来自 .map() 的奇怪行为。它返回一个空项,而 .forEach() 不返回。
代码如下:
class Entry {
constructor(data) {
this.name = data[0],
this.age = data[1],
this.school = data[2]
};
get organised() {
return this.organise();
};
organise() {
const data = {
name: this.name,
school: this.school
};
return data;
}
}
const getDataForEach = (obj) => {
let r = [];
obj.forEach((i) => {
const e = new Entry(i);
r.push(e.organised);
});
return r;
};
getDataForEach(input); // return normal object array [{...}, {...}, ...]
但如果我使用.map(),它会返回一个对象数组,其中第一项为空。其他项与.forEach()的结果相同。
const getDataMap = (obj) => {
return obj.map((i) => {
const e = new Entry(i);
console.log(e) // return normal [{...}]
console.log(e.organised) // return normal {...}
return e.organised;
});
};
getDataMap(input); // return an object array with the first item empty [<1 empty item>, {...}, {...}, ...]
你有过类似的经历吗?
【问题讨论】:
-
您确定
e.organized没有返回任何内容吗? -
这似乎是sparse arrays 的预期行为
-
是的,它们是使用正整数键的对象。例如
[, 2]类似于{ "1": 2, "length": 2 } -
更多详细信息请参见此处的第二个示例codereview.stackexchange.com/questions/180204/…
-
另一种选择是
Object.values(obj).map(但在 IE 中不可用)stackoverflow.com/a/41802221/1383168
标签: javascript arrays object foreach array.prototype.map