数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
数组中的每一项都是一个数字:
var items = Array(523,3452,334,31, ...5346);
如何用新物品替换旧物品?
例如,我们想用1010替换3452,该怎么做呢?
当前回答
最简单的方法是这样。
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]
其他回答
items[items.indexOf(3452)] = 1010
非常适合简单的交换。试试下面的代码片段
const items =数组(523,3452,334,331,5346); console.log(物品) items[items. indexof (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;
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
}
如果你想要一个简单的糖纸,你可以:
(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);
使用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']