使用javascript的陣列(array)或物件(object)時,常常會需要去判斷陣列或物件的key值是否存在,避免出現undefined的情況

至於要怎麼判斷呢?


判斷陣列(array)鍵值:

var arr = ["a","b","c","d"];
//使用 indexOf 來判斷
var isExist = arr.indexOf("a");

//不存在會得到 -1
if(isExist == -1){
 console.log('不存在');
}else{
 console.log('存在');
}

判斷物件(object)鍵值:

var obj = {
 'a':'john',
 'b':'aidec',
 'c':'ken',
};
//使用 hasOwnProperty 來判斷
var isExist = obj.hasOwnProperty('a');

//不存在會得到 false
if(!isExist){
 console.log('不存在');
}else{
 console.log('存在');
}



文章轉載或引用,請先告知並保留原文出處與連結!!(單純分享或非營利的只需保留原文出處,不用告知)

原文連結:
https://blog.aidec.tw/post/javascript-array-object-key-exist