我们有一个这样的数字数组-
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 }
]