如何替换数组中的项目? [英] 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?
例如,我们想用1010
替换3452
,我们该怎么做?
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屋!