923 B
923 B
title, localeTitle
| title | localeTitle |
|---|---|
| Check For The Presence of an Element With indexOf() | 使用indexOf()检查元素是否存在 |
使用indexOf()检查元素是否存在
- 可以使用简单的
if-statement来检查indexOf()函数返回的值是否小于0。 - 一旦发现了值,您就可以返回
true或false。 Solution-1演示了一个简单的if-statement如何返回正确的结果。
方案1:
function quickCheck(arr, elem) {
if(arr.indexOf(elem)>=0) {
return true;
}
return false;
}
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
Solution-2演示如何使用? : (conditional)解决问题? : (conditional)运算符。
方案2:
function quickCheck(arr, elem) {
return arr.indexOf(elem) >= 0 ? true : false;
}
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));