Array.prototype.map() returns 空项目但 Array.prototype.forEach() 没有

Array.prototype.map() returns empty item but Array.prototype.forEach() doesn't

我遇到了 .map() 的奇怪行为。它 returns 是一个空项目,而 .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(),它 returns 一个包含第一项的对象数组是空的。其他项目与 .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>, {...}, {...}, ...]

你遇到过类似的事情吗?

处理稀疏数组时,mapforEach() 都会跳过从未分配或已删除的元素。

不过,不同之处在于 map 构造结果数组本身,而您的 forEach() 代码推入结果数组。 push() 永远不会在数组中创建空洞,因为它总是在当前长度处附加一个新元素,但 map() 可以。 MDN指出:

Due to the algorithm defined in the specification if the array which map was called upon is sparse, resulting array will also be sparse keeping same indices blank.

如果您将 forEach 代码更改为使用输入数组索引而不是使用 push,您将得到类似于 map 的结果,例如

const getDataForEach = (obj) => {
    let r = [];
    obj.forEach((i, index) => {
        const e = new Entry(i);
        r[index] = e.organised;
    });
    return r;
};