How to replace an item in an array with JavaScript?

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

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

    If you know the value then use,

    items[items.indexOf(334)] = 1010;
    

    If you want to know that value is present or not, then use,

    var point = items.indexOf(334);
    
    if (point !== -1) {
        items[point] = 1010;
    }
    

    If you know the place (position) then directly use,

    items[--position] = 1010;
    

    If you want replace few elements, and you know only starting position only means,

    items.splice(2, 1, 1010, 1220);
    

    for more about .splice

提交回复
热议问题