indexOf()
。这个方法让我们可以便捷地检查某个元素是否存在于一个数组中。indexOf()
方法接受一个元素作为输入参数,并返回该元素在数组中的位置(索引);若该元素不存在于数组中则返回-1
。
例如:
```js
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
fruits.indexOf('dates'); // 返回 -1
fruits.indexOf('oranges'); // 返回 2
fruits.indexOf('pears'); // 返回 1,即第一个出现的 'pears' 元素在数组中的索引为 1
```
indexOf()
在快速检查一个数组中是否存在某个元素时非常有用。我们已经定义了一个quickCheck
函数,它接受一个数组和一个元素作为输入参数。请修改这个函数,利用indexOf()
方法,使得当输入的数组中含有输入的元素时,函数返回true
;不含有输入的元素时,函数返回false
。
quickCheck(["squash", "onions", "shallots"], "mushrooms")
应该返回false
'
testString: assert.strictEqual(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'), false);
- text: 'quickCheck(["squash", "onions", "shallots"], "onions")
应该返回true
'
testString: assert.strictEqual(quickCheck(['onions', 'squash', 'shallots'], 'onions'), true);
- text: 'quickCheck([3, 5, 9, 125, 45, 2], 125)
应该返回true
'
testString: assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true);
- text: 'quickCheck([true, false, false], undefined)
应返回false
'
testString: assert.strictEqual(quickCheck([true, false, false], undefined), false);
- text: quickCheck
函数应该使用indexOf()
方法
testString: assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1);
```