SMILET
您的代码可能会执行您想要的操作,但概念不正确。newArray是一个数组,您将数组的元素设置为 indexes 1,2并35生成一个长度为 36 的数组,其中包含许多未定义的元素:console.log(newArray);// results in [undefined, { id: 1, name: "name 1"}, { id: 2, name: "name 2"}, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, { id: 35, name: "name 35"}]使用forEachor之类的数组函数map只会遍历您设置的三个元素,但for (let i = 0; i < newArray.length; i++)循环会导致意外结果。如果你想通过一些 id 索引一个数组,那么你将需要一个映射(Record<number, any>在 Typescript 中),在 Javascript 的情况下它只是一个对象。无需更改大部分代码,您只需使用let newArray = {}.在不使用循环的情况下,您需要的是array.reduce函数:const indexed = array.reduce( (result, current) => ({ ...result, // spread current result [current.id]: current // add the current element at current.id }), {}); // initialize with an empty object当然,您不能像使用数组那样遍历对象,但可以使用for ... in和for ... of循环:for (let index in indexed) { console.log(indexed[index])}for (let element of indexed) { console.log(element)}