简体   繁体   English

如何分隔数组值

[英]How to Separate Array Values

Some Background Information 一些背景资料

There was a lesson on Codecademy that instructed me to create a contact list (features objects within objects). 在Codecademy上有一堂课,指导我创建一个联系人列表(在对象中包含对象)。 At the end, I was to make a function that could take an input and match it with any names on the contact list. 最后,我要做一个函数,可以接受输入并将其与联系人列表中的任何名称匹配。 If there was a match, it would log all of the contact information associated with that name to the console. 如果匹配,它将与该名称关联的所有联系信息记录到控制台。

So far, I have successfully done all of the above and wanted to go a little further. 到目前为止,我已经成功完成了上述所有工作,并希望进一步介绍。 I wanted the function to log the address of the person with spacing in between each value (like this: "One Microsoft Way, Redmond, WA, 98052" instead of "One Microsoft Way,Redmond,WA,98052"). 我希望该函数记录每个值之间带有空格的人的地址(例如:“ Microsoft Way,Redmond,WA,98052”,而不是“ Microsoft Way,Redmond,WA,98052”)。

I also wanted the function to log "No match." 我还希望该功能记录“不匹配”。 into the console (just once) if it searched through the entire contact list and found no matching names. 如果它在整个联系人列表中进行搜索但没有找到匹配的姓名,则将其放入控制台(仅一次)。 With my current code, it logs "No match." 使用我当前的代码,它记录为“ No match”。 for every single non-matching name, and I don't want that. 对于每个不匹配的名称,我都不想这样。

In short: How can I return and separate an array of values with spacing between each value? 简而言之:如何返回并分隔每个值之间有间距的值数组? How can I make the function return "No match." 如何使函数返回“不匹配”。 a single time after not finding any matches? 找不到任何匹配项后的单个时间?

Here is my code: 这是我的代码:

// Main object
var friends = {
    // Nested objects
    bill: {
        firstName: "Bill",
        lastName: "Pifheba",
        number: "1234567890",
        address: ["One Microsoft Way", "Redmond", "WA", "98052"]
    },

    steve: {
        firstName: "Steve",
        lastName: "Ajfiae",
        number: "1234512345",
        address: ["2 Stack Way", "Lazss", "WA", "12345"]
    },

    bob: {
        firstName: "Bob",
        lastName: "Dcfiwae",
        number: "8291047261",
        address: ["28 Stack Way", "What", "WA", "54321"]
    }
};

// Searches for matching name
var search = function(name) {
    // Iterates through nested objects
    for (var x in friends) {
        // If match is found
        if (friends[x].firstName === name) {
            // Print contact information
            console.log("First Name: " + friends[x].firstName + "\r\nLast Name: " + friends[x].lastName + "\r\nNumber: " + friends[x].number + "\r\nAddress: " + friends[x].address);
        } else {
            console.log("No match.");
        }
    }
};

// Asks for who to search for
search(prompt("Name?"));

You can .join an array to turn it into a space separated string. 您可以.join数组将其转换为以空格分隔的字符串。

["One Microsoft Way", "Redmond", "WA", "98052"].join(", ");
// "One Microsoft Way, Redmond, WA, 98052"

Rather than logging the value inside your function, you can return it and instead log the result of calling it. 您可以返回它,而不是记录函数内部的值,而记录调用它的结果。

if (friends[x].firstName === name) {
  return "First Name: " + friends[x].firstName + "\r\nLast Name: " + friends[x].lastName + "\r\nNumber: " + friends[x].number + "\r\nAddress: " + friends[x].address);
}

This will short circuit the loop as soon as it finds a match. 一旦找到匹配项,这将使环路短路。 To provide a fallback return value, simply add another return statement at the end of the function. 要提供后备返回值,只需在函数末尾添加另一个return语句。

var search = function(name) {
  // ...
  return "No match.";
}

This statement will only run if the loop completes without finding a match. 仅当循环完成但未找到匹配项时,此语句才会运行。

Finally you can directly log the result of the call. 最后,您可以直接记录通话结果。

console.log(search(prompt("Name?")));
var search = function(name) {
    // Iterates through nested objects
    var found = false;
    for (var x in friends) {
        // If match is found
        if (friends[x].firstName === name) {
            // Print contact information
            found = true;
            console.log("First Name: " + friends[x].firstName + "\r\nLast Name: " + friends[x].lastName + "\r\nNumber: " + friends[x].number + "\r\nAddress: " + friends[x].address.join(' '));
            break; // stop iteration
        }
    }
    if (!found) {
      console.log("No match.");
    }
};

You can use Array.prototype.join() , which joins the array elements together with the string supplied to the method (here ', ' ), to form a string: 您可以使用Array.prototype.join() ,它将数组元素与提供给方法的字符串(此处为', ' )连接在一起,形成一个字符串:

friends[x].address.join(', ')

References: 参考文献:

There is a couple of issues with your code. 您的代码有几个问题。

  • you should use an array so you can have multiple users with the same name 您应该使用一个数组,以便可以有多个具有相同名称的用户
  • you don't really need to loop through all your friends as each key is unique 您真的不需要遍历所有friends因为每个键都是唯一的

see comments in code below 查看下面代码中的注释

 // Main object var friends = { // Nested objects bill: { firstName: "Bill", lastName: "Pifheba", number: "1234567890", address: ["One Microsoft Way", "Redmond", "WA", "98052"] }, steve: { firstName: "Steve", lastName: "Ajfiae", number: "1234512345", address: ["2 Crap Way", "Lazss", "WA", "12345"] }, bob: { firstName: "Bob", lastName: "Dcfiwae", number: "8291047261", address: ["28 Crap Way", "What", "WA", "54321"] } }; // Searches for matching name var search = function(name) { // check to see if the friends name is a property of your object // if not return early if ( name in friends == false ) { console.log('not found'); return false; } // since you have already checked that the name exists you // can just use the name property instead of looping through // as all keys must be unique when using an object console.log( friends[name] ); console.log("First Name: " + friends[name].firstName + "\\r\\nLast Name: " + friends[name].lastName + "\\r\\nNumber: " + friends[name].number + "\\r\\nAddress: " + friends[name].address.join(' ')); // you can join an array with `.join` console.log(friends[name].address.join(' ')); }; // Asks for who to search for search(prompt("Name?")); 
 <script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script> 

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

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