How to replace an item in an array with JavaScript?

后端 未结 26 2228
执笔经年
执笔经年 2020-11-29 15:33

Each item of this array is some number.

var items = Array(523,3452,334,31, ...5346);

How do I replace some number in with array with a new on

26条回答
  •  再見小時候
    2020-11-29 15:54

    ES6 way:

    const items = Array(523, 3452, 334, 31, ...5346);
    

    We wanna replace 3452 with 1010, solution:

    const newItems = items.map(item => item === 3452 ? 1010 : item);
    

    Surely, the question is for many years ago and for now I just prefer to use immutable solution, definitely, it is awesome for ReactJS.

    For frequent usage I offer below function:

    const itemReplacer = (array, oldItem, newItem) =>
      array.map(item => item === oldItem ? newItem : item);
    

提交回复
热议问题