How to replace an item in an array with JavaScript?

后端 未结 26 2218
执笔经年
执笔经年 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 16:02

    First, rewrite your array like this:

    var items = [523,3452,334,31,...5346];
    

    Next, access the element in the array through its index number. The formula to determine the index number is: n-1

    To replace the first item (n=1) in the array, write:

    items[0] = Enter Your New Number;
    

    In your example, the number 3452 is in the second position (n=2). So the formula to determine the index number is 2-1 = 1. So write the following code to replace 3452 with 1010:

    items[1] = 1010;
    

提交回复
热议问题