角度将数组转换为字符串

时间:2019-03-07 08:36:16

标签: javascript arrays angular

我有以下数组(testArray),我希望将所有状态提取为字符串(“亚利桑那”,“阿拉斯加”,“佛罗里达”,“夏威夷”,“古吉拉特”,“果阿”,“旁遮普邦”。 ..)。有没有更简单的方法可以做到这一点?

let testArray: State[];
testArray = this.getStates();

getStates() {
 return [
  new State(1, 1, 'Arizona'),
  new State(2, 1, 'Alaska'),
  new State(3, 1, 'Florida'),
  new State(4, 1, 'Hawaii'),
  new State(5, 2, 'Gujarat'),
  new State(6, 2, 'Goa'),
  new State(7, 2, 'Punjab'),
  new State(8, 3, 'Queensland'),
  new State(9, 3, 'South Australia'),
  new State(10, 3, 'Tasmania'),
  new State(11, 4, 'Penang')
 ];
}

3 个答案:

答案 0 :(得分:3)

最简单的方法如下

getStates().map(x=>x.StateName).join(",")

示例如下

function State(id,val,StateName) {
  this.id = id;
  this.val = val;
  this.StateName = StateName;
}

function getStates() {
 return [
  new State(1, 1, 'Arizona'),
  new State(2, 1, 'Alaska'),
  new State(3, 1, 'Florida'),
  new State(4, 1, 'Hawaii'),
  new State(5, 2, 'Gujarat'),
  new State(6, 2, 'Goa'),
  new State(7, 2, 'Punjab'),
  new State(8, 3, 'Queensland'),
  new State(9, 3, 'South Australia'),
  new State(10, 3, 'Tasmania'),
  new State(11, 4, 'Penang')
 ];
}

//Simplest Way is as follows
console.log(getStates().map(x=>x.StateName).join(","))

答案 1 :(得分:1)

使用reduce的另一种解决方案。

getStates().reduce((current, value, index) => {
    if(index > 0)
        current += ',';

    return current + value.StateName;
}, '');

完整的代码段:

function State(id,val,StateName) {
  this.id = id;
  this.val = val;
  this.StateName = StateName;
}

function getStates() {
 return [
  new State(1, 1, 'Arizona'),
  new State(2, 1, 'Alaska'),
  new State(3, 1, 'Florida'),
  new State(4, 1, 'Hawaii'),
  new State(5, 2, 'Gujarat'),
  new State(6, 2, 'Goa'),
  new State(7, 2, 'Punjab'),
  new State(8, 3, 'Queensland'),
  new State(9, 3, 'South Australia'),
  new State(10, 3, 'Tasmania'),
  new State(11, 4, 'Penang')
 ];
}

var merged = getStates().reduce((current, value, index) => {
    if(index > 0)
        current += ',';

    return current + value.StateName;
}, '');

console.log(merged);

答案 2 :(得分:0)

array转换为逗号分隔的string的最简单方法是

var commaSeperatedString = arrayName.toString();