【问题标题】:Create a function that has two parameters, parameter a will be a array and parameter b will find a element within the array创建一个有两个参数的函数,参数 a 将是一个数组,参数 b 将在数组中找到一个元素
【发布时间】:2019-04-23 15:38:56
【问题描述】:

得到以下开始,但似乎无法弄清楚如何完成。本质上,如果我要调用myTest([one, two, three], 2);,它应该返回元素three。必须使用 for-loops 来找到我的解决方案。

function myTest(a, b){
  for (let i = 0; i < a.length; i++)

如果我调用myTest([one, two, three], 2);,它应该返回元素three

假设上面是正确的调用方式。

【问题讨论】:

标签: javascript arrays function for-loop


【解决方案1】:
function myTest(a, b){
  for (let i = 0; i < a.length; i++) {
     if (a[i] == a[b]) {return a[i]}
  }
}

这应该可行。

【讨论】:

  • OP 对如何访问数组中的索引值一无所知。
  • 或者可能有一些代码每次都需要执行,直到找到元素。
  • 如果是这种情况,函数find 是一个更好的解决方案。第二个参数是一个索引,所以return a[b];是最好的方法。
【解决方案2】:

您可以将数组的索引设为property accessor

function myTest(array, index) {
    return array[index];
}

console.log(myTest(['one', 'two', 'three'], 2));

【讨论】:

    【解决方案3】:

    如果我收到你的问题,那么你可以简单地 return a[b]; 而不使用任何 for 循环。

    【讨论】:

      【解决方案4】:

      因此,您必须将第一个参数“强制”为数组或至少检查它:

      function myTest(arrayParam, arrayIndex) {
          if (typeof arrayParam != typeof[]) {
              console.log('wrong parameter ' + arrayParam + ' must be an Array');
              return;
          }
          return arrayParam[arrayIndex]; /** eventualy you've to check index is in array range so check the length of the array too*/
      }
      

      JavaScript 没有类型变量,因此必须添加每个检查才能使用类型值。 wo 的 typeof 返回类型也可以是 object。

      编辑:甚至更简单并保证所有类型都具有“正确”类型:

      myTest(arr, idx) {
          if (arr[idx]) {
              return arr[idx];
          } //-- will simply return nothing if parameter not fit or idx out of array size
      }
      

      更简单但不太准确,因为你可以拥有这个并且仍然有一个返回值(没有什么可以确定第一个参数是一个数组,第二个参数是一个整数值作为索引):

      myTest({test:'some value'}, 'test'); //-- who will return 'some value'
      

      在第二个示例中,我想强调其他响应不可能是错误,也不会使用数组。

      【讨论】:

        猜你喜欢
        • 2020-01-02
        • 2023-04-08
        • 2016-01-23
        • 2012-08-09
        • 1970-01-01
        • 2013-09-27
        • 2014-06-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多