数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
用for循环很容易完成。
for (var i = 0; i < items.length; i++)
if (items[i] == 3452)
items[i] = 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
}
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; });
最简单的方法是使用一些库,如下划线和映射方法。
var items = Array(523,3452,334,31,...5346);
_.map(items, function(num) {
return (num == 3452) ? 1010 : num;
});
=> [523, 1010, 334, 31, ...5346]
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的更多信息
首先,像这样重写数组:
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;
下面是一个可重用函数的基本答案:
function arrayFindReplace(array, findValue, replaceValue){
while(array.indexOf(findValue) !== -1){
let index = array.indexOf(findValue);
array[index] = replaceValue;
}
}
我用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;
};
如果使用一个复杂的对象(甚至是一个简单的对象),你可以使用es6, Array.prototype.findIndex是一个很好的选择。对于OP的数组,他们可以这样做,
const index = items.findIndex(x => x === 3452)
items[index] = 1010
对于更复杂的对象,这真的很管用。例如,
const index =
items.findIndex(
x => x.jerseyNumber === 9 && x.school === 'Ohio State'
)
items[index].lastName = 'Utah'
items[index].firstName = 'Johnny'
替换可以在一行中完成:
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(项目);
使用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']
var index = Array.indexOf(Array value);
if (index > -1) {
Array.splice(index, 1);
}
从这里,您可以根据相同的索引从数组中删除特定的值 你可以在数组中插入值。
Array.splice(index, 0, Array value);
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);
var replaceWhat = 3452, replaceWith = 1010;
if ( ( i = items.indexOf(replaceWhat) ) >=0 ) items.splice(i, 1, replaceWith);
console.log(items);
>>> (5) [523, 1010, 334, 31, 5346]
第一个方法
在一行中替换或更新数组项的最佳方法
array.splice(array.indexOf(valueToReplace), 1, newValue)
Eg:
let items = ['JS', 'PHP', 'RUBY'];
let replacedItem = items.splice(items.indexOf('RUBY'), 1, 'PYTHON')
console.log(replacedItem) //['RUBY']
console.log(items) //['JS', 'PHP', 'PYTHON']
第二种方法
另一种简单的方法是:
items[items.indexOf(oldValue)] = newValue
如果有人对如何从数组的下标替换一个对象感兴趣,这里有一个解决方案。
通过id查找对象的索引:
const index = items.map(item => item.id).indexOf(objectId)
使用object .assign()方法替换该对象:
Object.assign(items[index], newValue)
ES6道:
const items = Array(523, 3452, 334, 31, ...5346);
我们想用1010替换3452,解决方案:
const newItems = items.map(item => item === 3452 ? 1010 : item);
当然,这个问题是很多年前的问题了,现在我更喜欢使用不可变的解决方案,当然,这对ReactJS来说是很棒的。
为了经常使用,我提供以下功能:
const itemReplacer = (array, oldItem, newItem) =>
array.map(item => item === oldItem ? newItem : item);
这里有一句话。它假设项将在数组中。
var项= [523,3452,334,31,5346] var替换= (arr, oldVal, newVal) => (arr[arr.indexOf(oldVal)] = newVal, arr) 控制台。日志(替换项,3452,1010)
如果你想要一个简单的糖纸,你可以:
(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);
来自@gilly3的回答很棒。
替换数组中的对象,保持数组顺序不变
当我从服务器获取数据时,我更喜欢以下方式将新的更新记录更新到我的记录数组中。它保持秩序完整,相当直截了当的一行。
Users =用户。map(u => u.id !== editedUser。)id吗?u: editedUser);
Var用户= [ {id: 1,姓:'John',姓:'Ken'}, {id: 2,姓:'Robin',姓:'Hood'}, {id: 3,名:“威廉”,姓:“库克”} ]; var editedUser = {id: 2,名字:'Michael',姓:'Angelo'}; Users =用户。map(u => u.id !== editedUser。)id吗?u: editedUser); Console.log ('users -> ', users);
items[items.indexOf(3452)] = 1010
非常适合简单的交换。试试下面的代码片段
const items =数组(523,3452,334,331,5346); console.log(物品) items[items. indexof (3452)] = 1010 console.log(物品)
javascript中替换数组元素的函数式方法:
Const replace = (array, index,…items) =>[…数组。Slice (0, index),…项目,…数组。Slice (index + 1)];
当你的数组有很多旧项替换新项时,你可以这样使用:
函数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,“嗨”));
这个就行了
Array.prototype.replace = function(a, b) {
return this.map(item => item == a ? b : item)
}
用法:
let items = ['hi', 'hi', 'hello', 'hi', 'hello', 'hello', 'hi']
console.log(items.replace('hello', 'hi'))
输出:
['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi']
好处是,每个数组都有.replace()属性。
const items =数组(1,2,3,4,5); console.log(物品) items[items. indexof (2)] = 1010 console.log(物品)