遍历数组并替换为某个值

Iterate over Array and replacing at a certain value

我对我的代码的可行性有疑问。我确信有更好更有效的方法来编写我编写的函数。

这是函数:

let i;
for (i = 0; i < ns.length; i++) {
  if (ns[i] > 1) {
    ns[i] = 3;
    const place = ns[i];
    ns.splice(place + 2, 1, 4);
    ns.splice(place, 1, 2);
    ns.splice(place - 1, 1, 1);
  }
}

初始数组(此数组的长度最多为 20 项):

ns = [1 , 1 , 1 , 1 , 2 , 0]

结果数组:

ns = [1 , 1 , 1 , 2 , 3 , 4]

信不信由你,但这将满足我的需要。但是有没有比仅仅加起来三次拼接更好的方法呢?如果初始数组的第二个在末尾或开头,它还会扩展我的数组。我知道我可以将它包装在另一个条件中,但这对我来说似乎很笨拙。


提前致谢!
此致

您可以将拼接替换为删除单个值并在索引处添加具有简单赋值的单个值。

为了防止在未给定的索引处更新值,您可以使用一个函数来检查所需的索引并仅更新给定的索引。

function update(array, index, value) {
    if (index >= 0 && index < array.length) {
        array[index] = value;
    }
}
var ns = [1, 1, 1, 1, 2, 0],
    length = ns.length,
    i,
    place = 3;
    
for (i = 0; i < length; i++) {
    if (ns[i] > 1) {
        ns[i] = place;
        update(ns, place - 1, 1);
        update(ns, place, 2);
        update(ns, place + 2, 4);
    }
}

console.log(ns);

在 Nina Scholz 和一位朋友的帮助下,我得到了正确的答案:

初始数组:

["1", "1", "1", "1", "1", "2", "0", "0"]

所需数组:

["1", "1", "1", "1", "2", "3", "4", "0"]

函数:

   isSibling() {
    const siblings = this.props.data.map(item => (
      item.progress
    ));
    let i;
    const place = '3';
    for (i = 0; i < siblings.length; i++) {
      if (siblings[i] === '2') {
        const num = i;
        siblings[i] = place;
        this.update(siblings, i - 1, '2');
        this.update(siblings, i + 1, '4');
        return siblings;
      }
    }
    return siblings;
   }

更新函数:
确保数组不被拉长或缩短:

  update(array, index, value) {
    if (index >= 0 && index < array.length) {
      array[index] = value;
    }
  }

感谢您的帮助! :D