How to replace an item in an array with JavaScript?

后端 未结 26 2242
执笔经年
执笔经年 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:51

    If using a complex object (or even a simple one) and you can use es6, Array.prototype.findIndex is a good one. For the OP's array, they could do,

    const index = items.findIndex(x => x === 3452)
    items[index] = 1010
    

    For more complex objects, this really shines. For example,

    const index = 
        items.findIndex(
           x => x.jerseyNumber === 9 && x.school === 'Ohio State'
        )
    
    items[index].lastName = 'Utah'
    items[index].firstName = 'Johnny'
    

提交回复
热议问题