将值插入数组JavaScript内每个值的中间
我们有一个这样的数字数组-
const numbers = [1, 6, 7, 8, 3, 98];
我们必须将这个数字数组转换为对象数组,每个对象都将键作为“值”,并将其值作为数组元素的特定值。除此之外,我们还必须将对象插入两个已有的元素之间,并以键作为“操作”,并使用+,-*,/作为其值之一。
因此,对于数字数组,输出看起来像这样-
[
{ "value": 1 }, { "operation": "+" }, { "value": 6 }, { "operation": "-"},
{ "value": 7 }, { "operation": "*" }, { "value": 8 }, { "operation":"/" },
{ "value": 3 }, { "operation": "+" }, {"value": 98}
]因此,让我们为该函数编写代码-
示例
const numbers = [1, 6, 7, 8, 3, 98, 3, 54, 32];
const insertOperation = (arr) => {
const legend = '+-*/';
return arr.reduce((acc, val, ind, array) => {
acc.push({
"value": val
});
if(ind < array.length-1){
acc.push({
"operation": legend[ind % 4]
});
};
return acc;
}, []);
};
console.log(insertOperation(numbers));输出结果
控制台中的输出将为-
[
{ value: 1 }, { operation: '+' },
{ value: 6 }, { operation: '-' },
{ value: 7 }, { operation: '*' },
{ value: 8 }, { operation: '/' },
{ value: 3 }, { operation: '+' },
{ value: 98 }, { operation: '-' },
{ value: 3 }, { operation: '*' },
{ value: 54 }, { operation: '/' },
{ value: 32 }
]热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿