+ 1
Specific vaule in varibles?
I want to have an if statment that is able to run if a vaule has one particular vaule in a way that can be used for many different vaules E.g.. Var people= ["Josh", "Philip", "Karan"] If (people === "Philip) { } Note I need it to not have an array number so that code can run efficiently (so if people[1] === Philip is not a good answer)
5 Réponses
+ 3
If i got you right, you want to know if a particular string exist in an array?
check this out
https://code.sololearn.com/Wc8w3zNBjBem/?ref=app
+ 5
Array has an includes() method, it will return a boolean(true/false) depending on whether the value in question is present in the array.
If (people.includes("Philip")) {
}
JavaScript Array includes() Method - https://www.w3schools.com/jsref/jsref_includes_array.asp
JavaScript Array Methods - https://www.w3schools.com/js/js_array_methods.asp
JavaScript Array Reference - https://www.w3schools.com/jsref/jsref_obj_array.asp
+ 4
var people = ["Josh","Philip ","Karan "];
if(people.indexOf("Philip") != -1){
console.log("found");
}else{
console.log("not found");
}
if what you want is to check if the value exists in array
you can use IndexOf() it returns the index of element if found or -1 if not found.
+ 4
Adding to Bahha🐧's example, you can write a function which returns true and false depending on if value is there or not.
function isValueInArray(arr, value) {
return arr.indexOf(value) >= 0;
}
Notice how you have to pass both array and value to the function? Using prototypes we can solve that problem.
Learn about prototypes: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes
https://code.sololearn.com/WLqeZp3H9gHi/?ref=app
0
Thank you everyone!