数组中的每一项都是一个数字:

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

如何用新物品替换旧物品?

例如,我们想用1010替换3452,该怎么做呢?


当前回答

首先,像这样重写数组:

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

接下来,通过索引号访问数组中的元素。确定索引号的公式为:n-1

要替换数组中的第一项(n=1),写:

items[0] = Enter Your New Number;

在您的示例中,数字3452位于第二个位置(n=2)。所以确定索引号的公式是2-1 = 1。因此,编写下面的代码将3452替换为1010:

items[1] = 1010;

其他回答

var index = Array.indexOf(Array value);
        if (index > -1) {
          Array.splice(index, 1);
        }

从这里,您可以根据相同的索引从数组中删除特定的值 你可以在数组中插入值。

 Array.splice(index, 0, Array value);

Array.indexOf()方法将替换第一个实例。获取每个实例使用Array.map():

a = a.map(function(item) { return item == 3452 ? 1010 : item; });

当然,这会创建一个新数组。如果你想在适当的地方做,使用Array.forEach():

a.forEach(function(item, i) { if (item == 3452) a[i] = 1010; });

我建议的解决方案是:

items.splice(1, 1, 1010);

拼接操作将从索引1开始,删除数组中的一项(即3452),并将其替换为新的项1010。

我用for循环解决了这个问题,遍历原始数组,并将匹配arreas的位置添加到另一个数组,然后遍历该数组,并在原始数组中更改它,然后返回它,我使用了一个箭头函数,但一个常规函数也可以工作。

var replace = (arr, replaceThis, WithThis) => {
    if (!Array.isArray(arr)) throw new RangeError("Error");
    var itemSpots = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == replaceThis) itemSpots.push(i);
    }

    for (var i = 0; i < itemSpots.length; i++) {
        arr[itemSpots[i]] = WithThis;
    }

    return arr;
};
presentPrompt(id,productqty) {
    let alert = this.forgotCtrl.create({
      title: 'Test',
      inputs: [
        {
          name: 'pickqty',
          placeholder: 'pick quantity'
        },
        {
          name: 'state',
          value: 'verified',
          disabled:true,
          placeholder: 'state',

        }
      ],
      buttons: [
        {
          text: 'Ok',
          role: 'cancel',
          handler: data => {

            console.log('dataaaaname',data.pickqty);
            console.log('dataaaapwd',data.state);


          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
                this.cottonLists[i].real_stock = data.pickqty;

            }
          }

          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
              this.cottonLists[i].state = 'verified';   

          }
        }
            //Log object to console again.
            console.log("After update: ", this.cottonLists)
            console.log('Ok clicked');
          }
        },

      ]
    });
    alert.present();
  }

As per your requirement you can change fields and array names.
thats all. Enjoy your coding.