【发布时间】:2020-10-22 04:14:15
【问题描述】:
编辑 在我的问题中犯了一个错误。 let tempArr = splitArr 是错误的。这需要是: tempArr = 汽车。所以@Prime 和@sabbir.alam 的遮阳篷可以解决问题!
我有一个值数组,其中一个值(car[3])是一个由“,”分隔的字符串。我用 .split(", ") 创建了这些元素的新数组 (splitArr)。
现在我想创建 n 个数组并将 car[3] 替换为 splitArr 中的一个项目。但我的结果只有 splitArr 的最后一个值。
我尝试了 .map .forEach for 循环。 .arryafunction 或 for 循环内部和外部的 tempArr。但总是相同的结果,而 splitArr.forEach 中的 console.log 显示了 splitArr 的每一项。下面是一些视觉指导。
代码
const car = [
'BMW',
'Serie1',
'Gray',
'Wheels, Lights, Alarm' ]
const splitArr = car[3].split(", ");
const newArr = [];
splitArr.forEach(item => {
console.log(item);
let tempArr = splitArr; // This needs to be: car!
tempArr[3] = item;
newArr.push(tempArr);
});
console.log(newArr);
结果
Wheels
Lights
Alarm
[
[ 'Wheels', 'Lights', 'Alarm', 'Alarm' ],
[ 'Wheels', 'Lights', 'Alarm', 'Alarm' ],
[ 'Wheels', 'Lights', 'Alarm', 'Alarm' ]
]
想要的结果
Wheels
Lights
Alarm
[
[ 'BMW', 'Serie1', 'Gray', 'Wheels' ],
[ 'BMW', 'Serie1', 'Gray', 'Lights' ],
[ 'BMW', 'Serie1', 'Gray', 'Alarm' ]
]
提前致谢!
【问题讨论】:
-
请将想要的结果添加为数据结构。
-
@NinaScholz 你的意思是想要的结果?
标签: javascript node.js arrays