indexOf() ,它允许我们快速,轻松地检查数组中元素的存在。 indexOf()接受一个元素作为参数,并在调用时返回该元素的位置或索引,如果该元素在数组中不存在,则返回-1 。例如: 让水果= ['苹果','梨','橙子','桃子','梨子'];
fruits.indexOf('dates')//返回-1
fruits.indexOf('oranges')//返回2
fruits.indexOf('pears')//返回1,元素所在的第一个索引
indexOf()对于快速检查数组中是否存在元素非常有用。我们定义了一个函数quickCheck ,它将一个数组和一个元素作为参数。使用indexOf()修改函数,以便在传递的元素存在于数组时返回true如果不存在则返回false 。 quickCheck(["squash", "onions", "shallots"], "mushrooms")应该返回false'
testString: 'assert.strictEqual(quickCheck(["squash", "onions", "shallots"], "mushrooms"), false, "quickCheck(["squash", "onions", "shallots"], "mushrooms") should return false");'
- text: 'quickCheck(["squash", "onions", "shallots"], "onions")应该返回true'
testString: 'assert.strictEqual(quickCheck(["squash", "onions", "shallots"], "onions"), true, "quickCheck(["squash", "onions", "shallots"], "onions") should return true");'
- text: 'quickCheck([3, 5, 9, 125, 45, 2], 125)应该返回true'
testString: 'assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true, "quickCheck([3, 5, 9, 125, 45, 2], 125) should return true");'
- text: 'quickCheck([true, false, false], undefined)应返回false'
testString: 'assert.strictEqual(quickCheck([true, false, false], undefined), false, "quickCheck([true, false, false], undefined) should return false");'
- text: quickCheck函数应该使用indexOf()方法
testString: 'assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1, "The quickCheck function should utilize the indexOf() method");'
```