用逗号 angularjs 在单个字符串中显示数组

Displaying array in single string with comma angularjs

我需要表示给定的数组:

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

作为以逗号分隔的单个字符串:

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

使用这个,

var a = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado"];
var string = a.join(",");
console.log(string);

使用join函数:

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

我还差得远 Angular,但你就不能写一个 js 函数帮你做吗?

我假设你换了两个句子?既然你想从数组转到字符串,但你的第一行代码是一个字符串而你的第二行代码是一个数组?

无论如何,我会这样做:

var string = "";

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