在数组 JavaScript 中的每个值的中间插入值

javascriptweb developmentobject oriented programming更新于 2025/10/3 3:56:17

我们有一个像这样的数字数组 −

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 }
]

相关文章


有用资源