数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
当前回答
当你的数组有很多旧项替换新项时,你可以这样使用:
函数replaceArray(数组,oldItem, newItem) { 对于(设I = 0;I < array.length;我+ +){ const index = array.indexOf(oldItem); If (~index) { array[index] = newItem; } } 返回数组 } console.log(replaceArray([1,2,3,2,2,8,1,9], 2,5)); console.log (replaceArray([1、2、3、2、2、8、1,9],2,“嗨”));
其他回答
var items = Array(523,3452,334,31,5346);
如果你知道它的价值,
items[items.indexOf(334)] = 1010;
如果你想知道这个值是否存在,那么使用,
var point = items.indexOf(334);
if (point !== -1) {
items[point] = 1010;
}
如果你知道地点(位置),那么直接使用,
items[--position] = 1010;
如果你想替换一些元素,你知道起始位置只意味着,
items.splice(2, 1, 1010, 1220);
有关.splice的更多信息
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.
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。
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
}