简体   繁体   English

如何使用提示输入遍历对象数组并显示属性

[英]How to use prompt input to loop through an array of objects and display a property

First thank you in advance for any responses to this problem I am having. 首先,首先感谢您对我遇到的这个问题的任何答复。 I am new to JS and feel that this code should be pretty straight forward, but it is not working as intended. 我是JS的新手,觉得这段代码应该很简单,但是没有按预期工作。

I want to search through these objects in the array by name, and if the name (that is obtained through the prompt) is found in the array, I want to display the id of that object. 我想按名称搜索数组中的这些对象,如果在数组中找到了名称(通过提示符获得),则想显示该对象的ID。

if I type 'Jef' into the prompt, I get the ID; 如果我在提示中输入“ Jef”,我会得到ID; but if I type 'Steve' or 'Ryan' I get nothing. 但是如果我输入“ Steve”或“ Ryan”,我什么也没得到。 I also noticed that the loop seems to end no matter what I type without a break being added. 我还注意到,无论我键入什么内容而没有添加中断,循环似乎都结束了。 I think the loop is breaking, but I don't know what is causing it to break before the 'If' condition is met. 我认为循环正在中断,但是我不知道是什么原因导致了在满足“ If”条件之前中断循环。 Please help! 请帮忙!

 var array = [{ name: 'Jef', age: 29, id: '000' }, { name: 'Steve', age: 28, id: '001' }, { name: 'Ryan', age: 28, id: '002' } ]; var i; for (i = 0; i < array.length; i++) { if (prompt() == array[i].name) { console.log(array[i].id) } } 

The way you are doing it is close. 您的操作方式已接近完成。 You just need to put the prompt() outside the loop. 您只需要将hint()放在循环之外即可。 Once you have the input to search, you then loop through your whole array of objects. 输入了要搜索的内容后,便可以遍历整个对象数组。

For example: 例如:

var nameInput = prompt();
for (i =0; i < array.length; i++){
    if (nameInput == array[i].name) {
       console.log(array[i].id)
    }
}

Small explanation 小说明

Since your prompt is in a loop that also loops your array of objects, there can only be 1 "correct" answer at that given prompt point - whatever index ( array[i].name ) the loop is currently on. 由于您的提示处于还会循环对象数组的循环中,因此在给定的提示点只能有1个“正确”的答案-循环当前处于的任何索引( array[i].name )。

To see more of what I mean run your current code and type jef the first time the prompt comes up, Steve the second time, and Ryan the third time- this way gets your IDs, but is probably not your intended outcome. 要查看更多我的意思,请在第一次出现提示时运行当前代码并键入jef ,第二次输入Steve ,第三次输入Ryan ,这种方式可以获取您的ID,但可能不是您想要的结果。

Try this. 尝试这个。 You need to sort through your array and perform a strong match, then return the ID. 您需要对数组进行排序并执行强匹配,然后返回ID。

function NameExists(strName,objectArray)
{
    //convert to lower for type sensitive
    strName = strName.toLowerCase();
    for(var i = 0; i <objectArray.length; i++)
    {
        //convert to lower for type sensitive
        var comparison = objectArray[i].Name.toLowerCase();

        if(comparison.match(strName)==comparison)
            return objectArray[i].id;
    }
}

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

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