Coding - 碼農筆記 / Coding 101 / JavaScript

JavaScript – Array裡 indexOf的運用

Array.prototype.indexOf()

indexOf()方法返回在數組中中可以找到一個给定元素的第一個索引,如果不存在,則返回-1

var family = ['Shane','Sally','Isaac','Kittie'];
console.log(family.indexOf('Kittie'));

輸出:3


var family2 = ['Shane','Sally','Isaac'];
console.log(family2.indexOf('Kittie'));

輸出:-1(找不到)



// indexOf('比對的字串',由索引值第幾個後開始找)
var family3 = ['Shane','Kittie','Sally','Isaac'];
console.log(family3.indexOf('Kittie',2)); 

輸出:-1(找不到),因為Kittie在第1個,索引值第2個後開始找

 

查詢某字串是否在Array裡

var family3 = ['Shane','Sally','Isaac','kittie'];
var kittieExist = family3.indexOf('kittie') > -1 // 回傳 true or false

console.log(kittieExist);

回傳: true


// 判斷如果不存在,則直接加上kittie進Array
if(!kittieExist) {
 family3.push('kittie');
}
console.log(family3);

 

© 2024 胡同筆記 | WordPress Theme: Cosimo by CrestaProject.