javascript - 操作 Array.map 中的前一项?

标签 javascript arrays

我正在使用 Array.prototype.map() 转换我的数组,如果当前项目符合某些条件,我想更改其上一个项目。

下面的代码似乎不起作用,如果没有 for 我该怎么做?循环?

var nums = [1, 2, 3, 4, 5];

var res = nums.map((item, index, array) => {
  if (item > 3) {
    array[index - 1] += 1;
  }
  return item;
});

console.log(res); // [ 1, 2, 3, 4, 5 ], I want [1, 2, 4, 5, 5]

最佳答案

您可以使用 reducer

var res = [1, 2, 3, 4, 5]
  .reduce((reduced, item, i) => {
     i && (reduced[i-1] += item > 3 ? 1 : 0);
     return [...reduced, item];
   }, []);

console.log(res); 

关于javascript - 操作 Array.map 中的前一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52399750/

相关文章:

javascript - 当我在 $watch 中更改观察者模式时,Angular Watch 不会触发

javascript - Sencha Touch 2 对接标签面板

javascript结合公共(public)和私有(private)window.onload

javascript - 将 JavaScript 对象 trim 为具有匹配值的指定属性

arrays - 从文件创建字节数组?

javascript - php json_encode 创建未转义的换行符

javascript - 为什么我的带有生成器函数的 setTimeout 没有触发?

c++ - 对结构数组使用构造函数

c++ - 在本地 spoj 上的 "Edit distance"中声明二维数组会产生运行时错误?

python - 我如何设计一个 Python 函数来打印仅将前向对角线元素设置为 True 的矩阵?