JavaScript程序,用于检查数组是否包含值
在此示例中,您将学习编写一个JavaScript程序,该程序将检查数组是否包含值。
示例1:使用includes()检查数组
// program to check if an array contains a 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 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不同。
下一篇: JavaScript程序来检查Le年
总计 0 评论