本文主要給大家介紹了關于利用JavaScript查詢某個值是否數組內的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹:
問題
> var b = ["aa", "bb"]> "aa" in b
我要查詢字符串aa是否在數組里面,in可行么?
in
首選說in操作符
用過python的都想是不是可以用in,可惜不能用,先看看python的效果:
>>> a = ["aa" , "bb"]>>> "aa" in aTrue>>>
但是JavaScript不一樣,in操作的對象要是一個對象,在MDN的官網有說:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
簡言之就是:
1.數組得搜下標
2.對象可以為key in obj這種,實例:
// Arraysvar trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];0 in trees // returns true3 in trees // returns true6 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 bfalse> b.indexOf("aa")0> b.indexOf("aaa")
最簡單粗暴的辦法
就是做一個for 循環這種,一個個比較吧
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林網的支持
新聞熱點
疑難解答