本文主要給大家介紹了關于利用JavaScript查詢某個值是否數(shù)組內(nèi)的相關內(nèi)容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹:
問題
> var b = ["aa", "bb"] > "aa" in b
我要查詢字符串a(chǎn)a是否在數(shù)組里面,in可行么?
in
首選說in操作符
用過python的都想是不是可以用in,可惜不能用,先看看python的效果:
>>> a = ["aa" , "bb"] >>> "aa" in a True >>>
但是JavaScript不一樣,in操作的對象要是一個對象,在MDN的官網(wǎng)有說:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
簡言之就是:
1.數(shù)組得搜下標
2.對象可以為key in obj這種,實例:
// Arraysvar trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; 0 in trees // returns true 3 in trees // returns true 6 in trees // returns false 'bay' in trees // returns false (you must specify the // index number, not the value at that index) 'length' in trees // returns true (length is an Array property) Symbol.iterator in trees // returns true (arrays are iterable, works only in ES2015+) // Predefined objects'PI' in Math // returns true // Custom objectsvar mycar = {make: 'Honda', model: 'Accord', year: 1998}; 'make' in mycar // returns true 'model' in mycar // returns true
indexOf
這是個好東西,可以直接使用,如果是前端使用要確保瀏覽器支持,nodejs支持沒有問題的。
實例:
> var b = ["aa", "bb"] undefined > "aa" in b false > b.indexOf("aa") 0 > b.indexOf("aaa")
最簡單粗暴的辦法
就是做一個for 循環(huán)這種,一個個比較吧
總結
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com