Reputation: 187
For example i have an array with 100 values, let it be a[1,2,3...100]
Can I create a if check that will be suitable for any value from the array?
like:
if(value === a[any index]){
//do smth
}
almost sure that it can be done but don't know how, can you help me with that?
Upvotes: 0
Views: 42
Reputation: 11
You should use the ES7 array.includes()
. If it finds a given value in your array it will return a True
boolean, else it will return False
.
Example:
console.log([1,2,3].includes(2)) //True
console.log([1,2,3,4,5].includes(6)) //False
Upvotes: 1
Reputation: 9228
You can use an Object
or Array
to hold functions as values and then lookup a specific function depending on a given value to run different code based on that value.
function doSomething(){console.log("Something")}
function doSomethingElse(){console.log("Something else")}
function doAnotherThing(){console.log("Another thing")}
// specify value when to run a certain function and the function to run
const whatToDo = {
"x": doSomething,
"y": doSomethingElse,
"z": doAnotherThing
}
// depending on some value the appropriate function will be run
const someValue = "z";
whatToDo[someValue]();
// or when using indices
const whatToDoArray = [doSomething, doSomethingElse, doAnotherThing];
// choose a function randomly
const randomValue = Math.floor(Math.random() * whatToDoArray.length);
whatToDoArray[randomValue]();
Upvotes: 0
Reputation: 2486
// for of
for (const item of a) {
if (value === item) {
}
}
// traditional for loop
for (let i = 0; i < a.length; i++) {
if (value === array[i]) {
}
}
// forEach
a.forEach(item => {
if (value === array[i]) {
}
});
Upvotes: 1
Reputation: 5566
You can use forEach:
a.forEach(element => {
if (value === element) {
// do something
}
});
Upvotes: 1