JavaScript判斷字符在不在數(shù)組里面的5種方式實例
在 JavaScript 中,想要判斷一個字符是否存在于數(shù)組中。
1. 使用 Array.prototype.includes
includes 方法返回一個布爾值,表示數(shù)組是否包含指定的元素。
const array = ['a', 'b', 'c', 'd']; const char = 'b'; if (array.includes(char)) { console.log(`${char} 存在于數(shù)組中`); } else { console.log(`${char} 不存在于數(shù)組中`); }
2. 使用 Array.prototype.indexOf
indexOf 方法返回指定元素在數(shù)組中的索引,如果不存在則返回 -1。
const array = ['a', 'b', 'c', 'd']; const char = 'b'; if (array.indexOf(char) !== -1) { console.log(`${char} 存在于數(shù)組中`); } else { console.log(`${char} 不存在于數(shù)組中`); }
3. 使用 Array.prototype.some
some 方法測試數(shù)組中是否有至少一個元素通過提供的函數(shù)測試。如果有一個元素滿足條件,則返回 true,否則返回 false。
const array = ['a', 'b', 'c', 'd']; const char = 'b'; if (array.some(element => element === char)) { console.log(`${char} 存在于數(shù)組中`); } else { console.log(`${char} 不存在于數(shù)組中`); }
4. 使用 Set
如果你需要頻繁檢查元素是否存在,可以考慮使用 Set
const array = ['a', 'b', 'c', 'd']; const char = 'b'; const set = new Set(array); if (set.has(char)) { console.log(`${char} 存在于數(shù)組中`); } else { console.log(`${char} 不存在于數(shù)組中`); }
5. 使用 Array.prototype.find
find 方法返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的值。否則返回 undefined。
const array = ['a', 'b', 'c', 'd']; const char = 'b'; if (array.find(element => element === char) !== undefined) { console.log(`${char} 存在于數(shù)組中`); } else { console.log(`${char} 不存在于數(shù)組中`); }
根據(jù)場景,選擇適合用的方式
總結
到此這篇關于JavaScript判斷字符在不在數(shù)組里面的5種方式的文章就介紹到這了,更多相關js判斷字符在不在數(shù)組內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javascript實現(xiàn)的一個帶下拉框功能的文本框
這篇文章主要介紹了javascript實現(xiàn)的一個帶下拉框功能的文本框,需要的朋友可以參考下2014-05-05JavaScript新特性structuredClone()深拷貝策略詳解
structuredClone()是瀏覽器和Node.js的原生API,底層使用更高效的 C++ 實現(xiàn),比起JS層的JSON.stringify/parse 組合,性能通常更好,這篇文章給大家介紹JavaScript新特性structuredClone()深拷貝策略,感興趣的朋友一起看看吧2025-06-06