Get the index of a matching element from an array:
Method 1: using without any method (Original code)-
let cars = ["BMW", "Volvo", "Mini"];
let element = 'Volvo';
for( let i= 0; i <= cars.length; i++){
if(cars[i] === element){
console.log(i);
return i;
} else {
console.log(-1);
return -1;
}
}
Output:
1
Method 2: using indexOf method -
let cars = ["BMW", "Volvo", "Mini"];
let element = 'Volvo';
if(cars.indexOf(element) == -1){
console.log("-1");
} else {
console.log(cars.indexOf(element));
}
Output:
1
Method 3: using indexOf & includes method -
let cars = ["BMW", "Volvo", "Mini"];
let element = 'Volvo';
if(!cars.includes(element)){
console.log("-1");
} else {
console.log(cars.indexOf(element));
}
Output:
1
Betway Casino - Login | JtmHub
ReplyDeleteIf you have questions, please visit the Betway site. The website 서울특별 출장샵 is 영천 출장샵 safe, reliable and has the best odds on all 동해 출장샵 games. Betway has 서울특별 출장마사지 a 구리 출장샵 wide range of games.