示例 1:使用 includes() 检查数组
// program to check if an array contains a specified value
const array = ['you', 'will', 'learn', 'javascript'];
const hasValue = array.includes('javascript');
// check the condition
if(hasValue) {
console.log('Array contains a value.');
} else {
console.log('Array does not contain a value.');
}
输出
Array contains a value.
在上面的程序中,使用了 includes()
方法来检查数组是否包含指定的值。
- 如果数组中存在该值,
includes()
方法将返回true
。 - 使用
if...else
语句根据条件显示结果。
示例 2:使用 indexOf() 检查数组
// program to check if an array contains a specified value
const array = ['you', 'will', 'learn', 'javascript'];
const hasValue = array.indexOf('javascript') !== -1;
// check the condition
if(hasValue) {
console.log('Array contains a value.');
} else {
console.log('Array does not contain a value.');
}
输出
Array contains a value.
在上面的程序中,将 indexOf()
方法与 if...else
语句一起使用,以检查数组是否包含指定的 值。
indexOf()
方法搜索数组并返回第一个匹配项的位置。如果找不到该值,则返回 -1。
注意:includes()
和 indexOf()
都区分大小写。因此,J 和 j 是不同的。