在 JavaScript 中,你可以使用 indexOf() 方法或 includes() 方法來搜索數組中的元素。
使用 indexOf() 方法:
indexOf() 方法返回指定元素在數組中首次出現的索引,如果不存在則返回 -1。你可以通過檢查返回值是否為 -1 來確定元素是否存在于數組中。
const array = [1, 2, 3, 4, 5];
if (array.indexOf(3) !== -1) {
// 元素存在于數組中
} else {
// 元素不存在于數組中
}
使用 includes() 方法:
includes() 方法返回一個布爾值,表示數組是否包含指定元素。如果存在,返回 true;如果不存在,返回 false。
const array = [1, 2, 3, 4, 5];
if (array.includes(3)) {
// 元素存在于數組中
} else {
// 元素不存在于數組中
}
以上兩種方法可以根據你的需求選擇使用,它們在不同的場景下可能會更加適用。請注意,indexOf() 和 includes() 方法在檢索對象或復雜數據類型時可能不適用,因為它們會比較引用而不是具體的值。