Each item of this array is some number:
JavaScript
x
2
1
var items = Array(523,3452,334,31, 5346);
2
How to replace some item with a new one?
For example, we want to replace 3452
with 1010
, how would we do this?
Advertisement
Answer
JavaScript
1
6
1
var index = items.indexOf(3452);
2
3
if (index !== -1) {
4
items[index] = 1010;
5
}
6
Also it is recommend you not use the constructor method to initialize your arrays. Instead, use the literal syntax:
JavaScript
1
2
1
var items = [523, 3452, 334, 31, 5346];
2
You can also use the ~
operator if you are into terse JavaScript and want to shorten the -1
comparison:
JavaScript
1
6
1
var index = items.indexOf(3452);
2
3
if (~index) {
4
items[index] = 1010;
5
}
6
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:
JavaScript
1
9
1
var contains = function (haystack, needle) {
2
return !!~haystack.indexOf(needle);
3
};
4
5
// can be used like so now:
6
if (contains(items, 3452)) {
7
// do something else...
8
}
9
Starting with ES6/ES2015 for strings, and proposed for ES2016 for arrays, you can more easily determine if a source contains another value:
JavaScript
1
4
1
if (haystack.includes(needle)) {
2
// do your thing
3
}
4