数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
当前回答
使用ES6扩展操作符和.slice方法替换列表中元素的不可变方法。
const arr = ['fir', 'next', 'third'], item = 'next'
const nextArr = [
...arr.slice(0, arr.indexOf(item)),
'second',
...arr.slice(arr.indexOf(item) + 1)
]
验证它是否有效
console.log(arr) // [ 'fir', 'next', 'third' ]
console.log(nextArr) // ['fir', 'second', 'third']
其他回答
const items =数组(1,2,3,4,5); console.log(物品) items[items. indexof (2)] = 1010 console.log(物品)
替换可以在一行中完成:
var items =数组(523,3452,334,331,5346); 项目(项目。Map ((e, i) => [i, e])。Filter (e => e[1] == 3452)[0][0]] = 1010 console.log(项目);
或者创建一个函数来重用:
Array.prototype.replace =函数(t, v) { 如果(this.indexOf (t) != 1) 这个(这个。Map ((e, i) => [i, e])。Filter (e => e[1] == t)[0][0]] = v; }; / /检查 var items =数组(523,3452,334,331,5346); 物品。替换(3452、1010); console.log(项目);
首先,像这样重写数组:
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;
items[items.indexOf(3452)] = 1010
非常适合简单的交换。试试下面的代码片段
const items =数组(523,3452,334,331,5346); console.log(物品) items[items. indexof (3452)] = 1010 console.log(物品)
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.