freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../basic-data-structures/check-for-the-presence-of-a...

3.3 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7b7b367417b2b2512b14 Check For The Presence of an Element With indexOf() 1 使用indexOf检查元素是否存在

Description

由于数组可以随时更改或变异 因此无法保证特定数据在特定数组中的位置或者该元素是否仍然存在。幸运的是JavaScript为我们提供了另一种内置方法indexOf() ,它允许我们快速,轻松地检查数组中元素的存在。 indexOf()接受一个元素作为参数,并在调用时返回该元素的位置或索引,如果该元素在数组中不存在,则返回-1 。例如:
让水果= ['苹果''梨''橙子''桃子''梨子'];

fruits.indexOf'dates'//返回-1
fruits.indexOf'oranges'//返回2
fruits.indexOf'pears'//返回1元素所在的第一个索引

Instructions

indexOf()对于快速检查数组中是否存在元素非常有用。我们定义了一个函数quickCheck ,它将一个数组和一个元素作为参数。使用indexOf()修改函数,以便在传递的元素存在于数组时返回true如果不存在则返回false

Tests

tests:
  - text: '<code>quickCheck([&quot;squash&quot;, &quot;onions&quot;, &quot;shallots&quot;], &quot;mushrooms&quot;)</code>应该返回<code>false</code>'
    testString: 'assert.strictEqual(quickCheck(["squash", "onions", "shallots"], "mushrooms"), false, "<code>quickCheck(["squash", "onions", "shallots"], "mushrooms")</code> should return <code>false</code>");'
  - text: '<code>quickCheck([&quot;squash&quot;, &quot;onions&quot;, &quot;shallots&quot;], &quot;onions&quot;)</code>应该返回<code>true</code>'
    testString: 'assert.strictEqual(quickCheck(["squash", "onions", "shallots"], "onions"), true, "<code>quickCheck(["squash", "onions", "shallots"], "onions")</code> should return <code>true</code>");'
  - text: '<code>quickCheck([3, 5, 9, 125, 45, 2], 125)</code>应该返回<code>true</code>'
    testString: 'assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true, "<code>quickCheck([3, 5, 9, 125, 45, 2], 125)</code> should return <code>true</code>");'
  - text: '<code>quickCheck([true, false, false], undefined)</code>应返回<code>false</code>'
    testString: 'assert.strictEqual(quickCheck([true, false, false], undefined), false, "<code>quickCheck([true, false, false], undefined)</code> should return <code>false</code>");'
  - text: <code>quickCheck</code>函数应该使用<code>indexOf()</code>方法
    testString: 'assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1, "The <code>quickCheck</code> function should utilize the <code>indexOf()</code> method");'

Challenge Seed

function quickCheck(arr, elem) {
  // change code below this line

  // change code above this line
}

// change code here to test different cases:
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));

Solution

// solution required