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

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

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

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


当前回答

如果你想要一个简单的糖纸,你可以:

(elements = elements.filter(element => element.id !== updatedElement.id)).push(updatedElement);

如:

let elements = [ { id: 1, name: 'element one' }, { id: 2, name: 'element two'} ];
const updatedElement = { id: 1, name: 'updated element one' };

如果你没有id,你可以像这样字符串化元素:

(elements = elements.filter(element => JSON.stringify(element) !== JSON.stringify(updatedElement))).push(updatedElement);

其他回答

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.

最简单的方法是使用一些库,如下划线和映射方法。

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

_.map(items, function(num) {
  return (num == 3452) ? 1010 : num; 
});
=> [523, 1010, 334, 31, ...5346]

const items =数组(1,2,3,4,5); console.log(物品) items[items. indexof (2)] = 1010 console.log(物品)

var index = items.indexOf(3452);

if (index !== -1) {
    items[index] = 1010;
}

另外,建议不要使用构造函数方法来初始化数组。相反,使用文字语法:

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

如果你喜欢简洁的JavaScript,想缩短-1的比较,你也可以使用~操作符:

var index = items.indexOf(3452);

if (~index) {
    items[index] = 1010;
}

有时我甚至喜欢写一个包含函数来抽象这个检查,使它更容易理解发生了什么。令人惊叹的是,这对数组和字符串都有效:

var contains = function (haystack, needle) {
    return !!~haystack.indexOf(needle);
};

// can be used like so now:
if (contains(items, 3452)) {
    // do something else...
}

从字符串的ES6/ES2015开始,到数组的ES2016建议,你可以更容易地确定一个源是否包含另一个值:

if (haystack.includes(needle)) {
    // do your thing
}

我建议的解决方案是:

items.splice(1, 1, 1010);

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