我有一个数组,其值为 ['a', 'b', 'c', 'd', 'e']
现在我希望它成为一个具有它的值的对象,所以我做了一些数组映射
const arrs = ['a', 'b', 'c', 'd', 'e']
let arrObj = arrs.map(arr => {
return {value: arr}
})
现在 arrObj
的值是
[{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'd'}, {value: 'e'}]
但我想做的是在数组中每个对象的中间插入一个对象,该对象的值为{operator: '+'}
。所以 arrObj
的值将是
[{value: 'a'}, {operator: '+'}, {value: 'b'}, {operator: '+'}, {value: 'c'}, {operator: '+'}, {value: 'd'}, {operator: '+'}, {value: 'e'}]
现在,如果我在 array.map() 中设置 arrObj 的值,我该如何使用 javascript 实现该功能?
最佳答案
您可以创建一个双倍长度减一的新数组,并根据索引添加所需的值。
var values = ['a', 'b', 'c', 'd', 'e'],
result = Array.from(
{ length: values.length * 2 - 1 },
(_, i) => i % 2
? { operator: '+' }
: { value: values[i >> 1] }
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 在数组中每个值的中间插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56438854/