简体   繁体   English

使用 for 循环进行数组迭代 - 使用条件语句和返回

[英]Array iteration with for loop - use of conditional statements and returns

For this array of objects:对于这个对象数组:

var contacts = [
  {
      "firstName": "Akira",
      "lastName": "Laine",
      "number": "0543236543",
      "likes": ["Pizza", "Coding", "Brownie Points"]
  },
  {
      "firstName": "Harry",
      "lastName": "Potter",
      "number": "0994372684",
      "likes": ["Hogwarts", "Magic", "Hagrid"]
  },
  {
      "firstName": "Sherlock",
      "lastName": "Holmes",
      "number": "0487345643",
      "likes": ["Intriguing Cases", "Violin"]
  },
  {
      "firstName": "Kristian",
      "lastName": "Vos",
      "number": "unknown",
      "likes": ["JavaScript", "Gaming", "Foxes"]
  }
];

There is then a for loop that iterates over the array of objects, and the arguments to lookup against the object.然后有一个for循环遍历对象数组,以及查找对象的参数。 I understand that we are iterating and that the function will stop running after it returns something.我知道我们正在迭代并且该函数在returns某些内容后将停止运行。 I have included a console.log(i);我已经包含了一个console.log(i); to see the value of the iterator variable, to see how many times the loop occurs.查看迭代器变量的值,查看循环发生了多少次。

function lookUpProfile(name, prop) {  

    for (var i = 0; i < contacts.length; i++) {  
      console.log(i);
      if (contacts[i].firstName === name) {  
        if (contacts[i].hasOwnProperty(prop)) {         
          return contacts[i][prop]   
        } else {
          return "No such property"; 
        }
      }

    } //end of loop
  return "No such contact"; 
  }


   console.log(lookUpProfile("Kristian", "lastName")); // Vos

So I run the code and look at my console output and get what I expect, we iterate 4 times, and then we return the current objects property.所以我运行代码并查看我的控制台输出并得到我期望的结果,我们迭代了 4 次,然后我们return当前对象属性。

在此处输入图片说明

Why is that the code does not work when I refactor the function, so that rather than having two nested if conditions, I use the logical AND operator && which combines the two test conditions into one if statement - like so:为什么当我重构函数时代码不起作用,所以我没有使用两个嵌套的if条件,而是使用逻辑 AND 运算符&&将两个测试条件组合成一个if语句 - 如下所示:

function lookUpProfile(name, prop) { 
  for (var i = 0; i < contacts.length; i++) {  
    console.log(i);
    if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {                 
      return contacts[i][prop]   
    } else {
      return "No such property"; 
    }

  } //end of loop
  return "No such contact"; 
}

 console.log(lookUpProfile("Kristian", "lastName")); // Expected output: Vos

Now when I run the code, no iteration seems to occur as console.log(i);现在,当我运行代码时, console.log(i);似乎没有发生迭代console.log(i); seems to output undefined once and not multiple times, so we don't seem to be looping and I don't understand why.似乎输出undefined一次而不是多次,所以我们似乎没有循环,我不明白为什么。 Secondly even though our test conditions are met we return 'no such property'.其次,即使满足我们的测试条件,我们也会返回“没有这样的属性”。

在此处输入图片说明

What I need to understand if why this simple refactor has broken the function.我需要了解为什么这个简单的重构破坏了功能。 I understand that once a function returns something that function execution ends and iteration would stop, I think this issue has something to do with being outside of the loop and the control flow breaking but I don't understand why.我知道一旦函数返回一些函数执行结束并且迭代将停止的东西,我认为这个问题与在循环之外和控制流中断有关,但我不明白为什么。 Please can someone clearly explain why this is happening in my specific case.请有人清楚地解释为什么在我的具体情况下会发生这种情况。

when you have nested if condition当您嵌套 if 条件时

if (contacts[i].firstName === name)

this checks for name if name doesn't matches it doesn't do anything如果名称不匹配,则检查名称,它不会执行任何操作

but in second one you have return in else statement after if so in case name doesn't matches it return from function但是在第二个中,如果名称不匹配,则在 else 语句之后返回,如果名称不匹配,则从函数返回

 if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {                 
      return contacts[i][prop]   
    } else {                           // problem is here
  return "No such property"; 
 }

just remove the else condition from loop只需从循环中删除 else 条件

 var contacts = [{"firstName": "Akira","lastName": "Laine","number": "0543236543","likes": ["Pizza", "Coding", "Brownie Points"]},{"firstName": "Harry","lastName": "Potter","number": "0994372684","likes": ["Hogwarts", "Magic", "Hagrid"]},{"firstName": "Sherlock","lastName": "Holmes","number": "0487345643","likes": ["Intriguing Cases", "Violin"]},{"firstName": "Kristian","lastName": "Vos","number": "unknown","likes": ["JavaScript", "Gaming", "Foxes"]}]; function lookUpProfile(name, prop) { for (var i = 0; i < contacts.length; i++) { if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) { return contacts[i][prop] } } //end of loop return "No such contact"; } console.log(lookUpProfile("Kristian", "lastName"));

Because in your previous code, "No such property" was returned only if contacts[i].hasOwnProperty(prop) was false .因为在您之前的代码中,仅当contacts[i].hasOwnProperty(prop)false时才返回"No such property" Now, it is also returned if contacts[i].firstName === name is false.现在,如果contacts[i].firstName === name为false,它也会返回。 You want to keep those 2 if blocks separated.您希望将这两个if块分开。

Also, the reason why your console.log(i) prints undefined is because it is above your for loop, before the declaration of the i variable.此外,您的console.log(i)打印undefined的原因是因为它在您的for循环之上,在i变量的声明之前。 Move it down 1 line.将其向下移动 1 行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM