简体   繁体   English

Iterables 表现不佳

[英]Iterables behaving badly

I have a bizarro issue which I just ran into... when passed an array of objects, the for..of iterator has no problem iterating over the objects and giving me the "name" property of each.我有一个我刚刚遇到的奇怪问题......当传递一个对象数组时, for..of迭代器迭代对象并给我每个对象的“名称”属性没有问题。 However, array.forEach completely fails to iterate.但是, array.forEach完全无法迭代。

The main function is found in Database.ts :主要的 function 在Database.ts中找到:

import { ITableDefinition } from "./Table";

export function Database(...tables: ITableDefinition<any>[]) {
  const names: string[] = [];
  for (const table of tables) {
    names.push(table.name);
  }

  return {
    tables,
    tableNames: tables.forEach((table) => table.name),
    tableNamesWithForOf: names,
  };
}

As you can see the function reflexively passes the array of tables it receives but also passes the name property of each table and it does it twice .如您所见,function 反射性地传递了它接收到的数组,但也传递了每个表的name属性,并且它执行了两次 Once using forEach and once using for..of .一次使用forEach和一次使用for..of

When running the following Jest tests, 2 of the 3 pass but the forEach test fails:运行以下 Jest 测试时,3 个测试中有 2 个通过但 forEach 测试失败:

describe("Trouble with iterables => ", () => {
  // db.tables is received as an array
  it("tables property is an array", () => {
    const db = Database(Table(Song), Table(Playlist));
    expect(Array.isArray(db.tables)).toBe(true);
    expect(typeof db.tables[0]).toBe("object");
  });

  // for..of iterates over the array correctly and extracts the "name" prop
  it("for ... of returns the names of the tables correctly", () => {
    const db = Database(Table(Song), Table(Playlist));

    expect(db.tableNamesWithForOf).toHaveLength(2);
    expect(db.tableNamesWithForOf).toContain("Song");
    expect(db.tableNamesWithForOf).toContain("Playlist");
  });

  // shockingly, forEach doesn't iterate at all and returns `undefined`!
  it("forEach returns the names of the tables correctly", () => {
    const db = Database(Table(Song), Table(Playlist));

    expect(db.tableNames).toHaveLength(2);
    expect(db.tableNames).toContain("Song");
    expect(db.tableNames).toContain("Playlist");
  });
});

My mind is blown but I'd love to hear from you if you can make some sense of it.我的想法很震惊,但如果你能理解的话,我很想听听你的意见。

Note: I tagged as both javascript and typescript but i doubt this has to with transpiling so if folks think I should take off the TS tag let me know and I'll do so.注意:我标记为javascripttypescript但我怀疑这与转译有关,所以如果人们认为我应该取消 TS 标记,请告诉我,我会这样做。

forEach in tables.forEach((table) => table.name) doesn't return anything i.e. returns undefined , you can use .map instead tables.forEach((table) => table.name)中的 forEach 不返回任何内容,即返回 undefined ,您可以改用.map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM