下麵是Array includes()方法的示例。
- 例:
<script> var name = [ 'gfg', 'cse', 'geeks', 'portal' ]; a = name.includes('gfg') // Printing result of includes() document.write(a); </script>
- 輸出:
true
array.includes()方法用於知道數組中是否存在特定元素,因此,它返回true或false,即,如果該元素存在,則返回true,否則返回false。
用法:
array.includes(searchElement, start)
參數:此方法接受上麵提到和下麵描述的兩個參數:
- searchElement:此參數保存將要搜索的元素。
- start:此參數是可選的,它保存數組的起點,從此處開始搜索,默認值為0。
返回值:它返回一個布爾值,即True或False。
以下示例說明了JavaScript中的Array includes()方法:
- 範例1:在此示例中,該方法將在該數組中搜索元素2。
Input:[1, 2, 3, 4, 5].includes(2); Output:true
- 範例2:在此示例中,該方法將在該數組中搜索元素9。
Input:[1, 2, 3, 4, 5].includes(9); Output:false
下麵提供了上述方法的代碼:
程序1:
<script>
// Taking input as an array A
// having some elements.
var A = [ 1, 2, 3, 4, 5 ];
// includes() method is called to
// test whether the searching element
// is present in given array or not.
a = A.includes(2)
// Printing result of includes().
document.write(a);
</script>
輸出:
true
程序2:
<script>
// Taking input as an array A
// having some elements.
var name = [ 'gfg', 'cse', 'geeks', 'portal' ];
// includes() method is called to
// test whether the searching element
// is present in given array or not.
a = name.includes('cat')
// Printing result of includes()
document.write(a);
</script>
輸出:
false
支持的瀏覽器:下麵列出了JavaScript數組includes()方法支持的瀏覽器:
- 穀歌瀏覽器47.0
- Microsoft Edge 14.0
- Mozilla Firefox 43.0
- Safari 9.0
- Opera 34.0
相關用法
- Javascript String includes()用法及代碼示例
- Javascript String includes()用法及代碼示例
- Javascript typedArray.includes()用法及代碼示例
- Lodash _.includes()用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 JavaScript Array includes() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。