如何替换数组中的项目? [英] How to replace item in array?
问题描述
此数组的每个项目都是一个数字:
Each item of this array is some number:
var items = Array(523,3452,334,31, ...5346);
如何用新物品代替某些物品?
How to replace some item with a new one?
例如,我们要将3452
替换为1010
,我们将如何做?
For example, we want to replace 3452
with 1010
, how would we do this?
推荐答案
var index = items.indexOf(3452);
if (index !== -1) {
items[index] = 1010;
}
此外,建议您不要使用构造方法初始化数组.而是使用文字语法:
Also it is recommend you not use the constructor method to initialize your arrays. Instead, use the literal syntax:
var items = [523, 3452, 334, 31, 5346];
如果您要使用简洁的JavaScript,并且想缩短-1
比较,也可以使用~
运算符:
You can also use the ~
operator if you are into terse JavaScript and want to shorten the -1
comparison:
var index = items.indexOf(3452);
if (~index) {
items[index] = 1010;
}
有时候,我什至喜欢编写一个contains
函数来抽象化此检查并使其更容易理解正在发生的事情.太棒了,这对数组和字符串都适用:
Sometimes I even like to write a contains
function to abstract this check and make it easier to understand what's going on. What's awesome is this works on arrays and strings both:
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提出,您可以更轻松地确定源是否包含另一个值:
Starting with ES6/ES2015 for strings, and proposed for ES2016 for arrays, you can more easily determine if a source contains another value:
if (haystack.includes(needle)) {
// do your thing
}
这篇关于如何替换数组中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!