当前位置: 动力学知识库 > 问答 > 编程问答 >

md autocomplete - Displaying array in single string with comma angularjs

问题描述:

I need to represent Given array :

 ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado"]

as single string separated by commas:

 'Alabama, Alaska, Arizona, Arkansas, California, Colorado'

网友答案:

Use the join function:

var myArray = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado"];
var myString = myArray.join(', ');
console.log(myString);
网友答案:

I'm nowhere near being really good at Angular, but couldn't you just write a js function to do it for you?

And I'm assuming you switched your 2 sentences? Since you want to go from array to string but your first line of code is a string and your second one is an array?

Anyway, this is how I would do it:

var string = "";

myStates.forEach(function (state, index, array) {
    if (index === array.length - 1) {
        string += state;
    } else {
        string += state + ", ";
    }
});
网友答案:

Use this,

var a = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado"];
var string = a.join(",");
console.log(string);
分享给朋友:
您可能感兴趣的文章:
随机阅读: