简体   繁体   English

我的嵌套循环无法遍历对象数组

[英]My Nested Loops Fails To Iterate through the Object Array

I'm working on a free code camp question which is listed below:我正在研究下面列出的免费代码营问题:

FCC Question URL: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup FCC 问题网址: https : //www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup

We have an array of objects representing different people in our contacts lists.我们有一组对象代表我们的联系人列表中的不同人。

A lookUpProfile function that takes name and a property (prop) as arguments has been pre-written for you.已经为您预先编写了一个以名称和属性 (prop) 作为参数的 lookUpProfile 函数。

The function should check if name is an actual contact's firstName and the given property (prop) is a property of that contact.该函数应该检查 name 是否是实际联系人的 firstName 并且给定的属性 (prop) 是该联系人的属性。

If both are true, then return the "value" of that property.如果两者都为真,则返回该属性的“值”。 If name does not correspond to any contacts then return "No such contact".如果姓名与任何联系人都不对应,则返回“无此类联系人”。 If prop does not correspond to any valid properties of a contact found to match name then return "No such property".如果 prop 与找到的与姓名匹配的联系人的任何有效属性不对应,则返回“无此类属性”。

Here is the object:这是对象:

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"]
    }
];

My Approach:我的方法:

I am attempting to solve this problem by iterating through the arrays.我试图通过遍历数组来解决这个问题。 So, we begin by iterating through the object (elements 0-3).因此,我们首先遍历对象(元素 0-3)。 If the firstName matches with name then we know it is in the Contacts[i] array.如果 firstName 与 name 匹配,那么我们知道它在 Contacts[i] 数组中。 To find the property for the contacts[i] array, I will iterate through the array again to find Contacts[i].j === property.为了找到contacts[i] 数组的属性,我将再次遍历数组以找到Contacts[i].j === 属性。

Below is the code:下面是代码:

function lookUpProfile(name, prop){
// Only change code below this line

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


// Only change code above this line
}

// Change these values to test your function
console.log(lookUpProfile("Bob", "number"));

For some reason, every time I run the function it says No such contact.出于某种原因,每次我运行该功能时,它都会说没有此类联系。 I know that my outer loop works fine, but for some reason my inner loop doesn't?我知道我的外循环工作正常,但由于某种原因我的内循环没有?

I know that solutions include replacing my inner loop with the following statement:我知道解决方案包括用以下语句替换我的内部循环:

if (contacts[x].hasOwnProperty(prop))

Or replacing the inner loop with this:或者用这个替换内循环:

 if (prop in contacts[i]) {

However, I'm curious on why this method doesn't work?但是,我很好奇为什么这种方法不起作用? Any help would be much appreciated.任何帮助将非常感激。

Here is the jsfiddle: https://jsfiddle.net/7u13cbm5/这是 jsfiddle: https ://jsfiddle.net/7u13cbm5/

// Only change code below this line

    for (var i = 0; i < contacts.length; i++){
         if (name === contacts[i].firstName){
             var val = contacts[i];
             for(var j in val) {
                if (val.hasOwnProperty(j) && prop === j){
                    return val[j]; 
                }
             }
             return "No such property";
         }
    }
    return "No such contact";


// Only change code above this line

Carefully consider what you're actually doing inside that inner loop.仔细考虑您在内部循环中实际执行的操作。

What you're actually doing is using the dot notation to access the length and j property of the the contact that has a matching name.您实际上正在做的是使用点表示法访问具有匹配名称的联系人的lengthj属性。

In this cases particular case, you can try debugging by looking at what happens during each iteration of the loop by printing the values to console.在这种特殊情况下,您可以通过将值打印到控制台来查看循环每次迭代期间发生的情况,从而尝试调试。 For instance,例如,

console.log(val.length) // ( => undefined) which means the loop wouldn't even run.

// Next let's look at val.j
for (var j = 0; j <val.length; j++){ 
  // If you added the following line to debug, 
  // you'll see that nothing would print because (j < val.length) is never true. 
  console.log(val.j) 
  if (prop === val.j){
    return val.j; 
  }else {
    return  "No such property";
  }
}

The reason why the console.log would not print is because you first try to access the length property of val, which does not exist for any contacts. console.log不会打印的原因是因为您首先尝试访问 val 的length属性,该属性对于任何联系人都不存在。

Try to pick up debugging in the future, even if it's just console.log and it would make your life a lot easier.尝试在未来进行调试,即使它只是console.log ,它会让你的生活更轻松。 Here's a great read if you have some time:https://medium.com/@mattburgess/beyond-console-log-2400fdf4a9d8 .如果您有时间,阅读以下内容:https ://medium.com/@mattburgess/beyond-console-log-2400fdf4a9d8

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

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