【问题标题】:Function with for loop: Why is 1 not overwritten by 5?带有 for 循环的函数:为什么 1 不被 5 覆盖?
【发布时间】:2020-06-30 06:34:15
【问题描述】:

我的 for 循环有问题。控制台日志输出为1,不明白为什么函数不返回5?据我了解,1 应该被 5 覆盖?哪里错了?

非常感谢您的帮助。

const hallo = {
  1: {"name": "Hallo"}, 
  2: {"name": "Frage", "id": 1}, 
  3: {"name": "Frage", "id": 5}, 
  4:  {"name": "Endpunkt"}
}
const inputcontext = () => {
  console.log(hallo[1]);
  var i;

  var l = Object.keys(hallo).length;
  for (i = 1; i < l; i++) {
    if (hallo[i].name === "Frage") {
      let inputcontext = hallo[i].id;
      return inputcontext;
    }
  }
}
const s = inputcontext()
console.log(s)

【问题讨论】:

  • return 在第一次出现后立即退出函数。它只迭代到“2”

标签: javascript for-loop object


【解决方案1】:

一旦获得第一个匹配项,您就会从函数中返回。您需要完成循环的所有迭代,然后返回。

const hallo = {
  1: {"name": "Hallo"}, 
  2: {"name": "Frage", "id": 1}, 
  3: {"name": "Frage", "id": 5}, 
  4:  {"name": "Endpunkt"}
}
const inputcontext = () => {
  console.log(hallo[1]);
  var i;
  let inputcontext = "";
  var l = Object.keys(hallo).length;
  for (i = 1; i < l; i++) {
    if (hallo[i].name === "Frage") {
      inputcontext = hallo[i].id;
    }
  }
  return inputcontext;
}
const s = inputcontext()
console.log(s)

【讨论】:

    【解决方案2】:

    return 语句只是中断迭代,return 语句的位置很重要。我希望这些示例对您有所帮助。

    function example(){
        for(i = 0; i < 10; i++) {
            if(i == 5) {
                return i;
            }
        }
    }
    console.log(example());     // returns 5
    
    function example2(){
        for(i = 0; i < 10; i++) {
            if(i == 5) {
                console.log('Hello world')
            }
        }
        return i;
    }
    console.log(example2());    // returns 10

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      相关资源
      最近更新 更多