【问题标题】:Get code to not return undefined after running获取代码在运行后不返回未定义
【发布时间】:2019-11-19 07:32:45
【问题描述】:

我创建了一个将数字插入整数数组的函数。我假设数组总是已经排序。我希望它返回可以插入数字的最低索引。我已经完成了,但是在它返回索引之后,当我在 repl.it 上运行它时它也返回未定义。想知道为什么会这样吗?

    function lowestIndexInsert(num,arr){
      for (i = 0; i<arr.length; i++){
          if (arr[i]>num){
             arr[i]=num;
          }
      }
     return arr.indexOf(num);
    }


    console.log(lowestIndexInsert(32,[8,9,15,30,35]));

【问题讨论】:

  • “未定义”消息来自 console.log。例如 console.log('test') 也会显示 undefined
  • 如果你在repl.it中删除console.log,然后调用这个函数,你就不会再看到undefined了,但是你会看到返回的值。

标签: javascript repl.it


【解决方案1】:

“未定义”消息来自 console.log。例如 console.log('test') 也将显示未定义。 尝试不使用console.log,你就完成了

    function lowestIndexInsert(num,arr){
  for (i = 0; i<arr.length; i++){
      if (arr[i]>num){
         arr[i]=num;
      }
  }
 return arr.indexOf(num);
}


lowestIndexInsert(32,[8,9,15,30,35])

【讨论】:

    【解决方案2】:

    如果console.log() 语句是您源代码的一部分,您将得到您想要的结果。但是,如果您实际上是从控制台执行console.log(),您将获得额外的undefined,因为在console 中,您不必要求console.log(),它本身没有返回值( undefined)。在这种情况下,您只需调用您的函数并返回其 return 值。

    【讨论】:

      【解决方案3】:

      简单的解决方案

      let arr = [1,2,32,35,56,68]
      let num = 30
      
      function lowestIndexInsert(num,arr){
        for(let i of arr){
          if(arr[i]>num)
          return i
        }
      }
      
      console.log(lowestIndexInsert(num,arr))

      【讨论】:

      • 这根本解决不了问题。您已经重新编写了循环,这不是问题。这甚至不能解决问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2019-07-05
      • 2015-12-16
      • 2021-07-10
      • 2022-11-11
      • 1970-01-01
      相关资源
      最近更新 更多