判斷一個數(shù)組中是否包含某個元素:
- 使用indexOf
const testArr=['Amy','Jhony','Henry','Tony'];
let index=testArr.indexOf('Jack');
console.log("index",index);
控制臺結(jié)果為-1酷师,表示數(shù)組中未包含此元素讶凉,否則會返回元素在數(shù)組中的index。
- 使用includes
testArr.inlcudes()直接返回布爾值山孔,true或false懂讯。
注意:對象數(shù)組不能使用includes方法來檢測,空數(shù)組也無法調(diào)用includes台颠。舉例 如下:
const objArr=[{a:1,b:2,c:3}];
objArr.includes({a:1})
不能得到期望的true