判斷方法:1、使用“arr.includes(元素值)”語句,如果返回值為true,則數(shù)組中有某一項;2、使用“arr.findIndex((v)=>{return v==元素值;})”語句,如果返回值不為“-1”,則數(shù)組中包含某一項。
本教程操作環(huán)境:windows7系統(tǒng)、ECMAScript 6版、Dell G3電腦。
es6判斷數(shù)組是否有某一項值
方法1:利用includes()方法
includes() 方法用來判斷一個數(shù)組是否包含一個指定的值,返回 true或 false。語法:
array.includes(searchElement, fromIndex);
-
searchElement:要查找的元素;
-
fromIndex:開始查找的索引位置,可省略,默認(rèn)值為0。
示例:
var arr=[2, 9, 7, 8, 9]; if(arr.includes(9)){ console.log("數(shù)組中有指定值"); } else{ console.log("數(shù)組中沒有指定值"); }
方法2:利用findIndex()方法
findIndex()方法返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的索引。否則返回-1
。
var arr=[2, 9, 7, 8, 9]; var ret = arr.findIndex((v) => { return v == 1; }); if(ret!=-1){ console.log("數(shù)組中有指定值"); } else{ console.log("數(shù)組中沒有指定值"); }
【