有没有办法删除Javascript中数组之间的逗号?

时间:2019-05-23 20:02:57

标签: javascript arrays

我正在创建一个测验,该测验根据用户的答案打印俱乐部列表。但是,当我运行它时,我不需要的每个数组之间都有一个逗号。

我试图删除逗号,但是为了使代码正常工作,在每个项目之间都必须使用逗号。

我有以下列表: var clubs=[[" Fall Production"," Spring Musical", ""],["Student Government", ""],["Tricorn", ""],["FBLA", ""]...] //and it continues

然后使用此功能打印它们:

function eliminateClubs(){
for(h=0;h<=personChoices.length;h++){
   if (personChoices[h]==1){
     recClubs.push(clubs[h].join(', <br/>'));
   }
 }
}

打印时,它看起来像:

Fall Production,
Spring Musical,
, Student Government,
, Tricorn,
, FBLA,
etc...

我不知道如何消除出现在每个不同数组前面的逗号,但是每个项目后面的逗号都很好。

4 个答案:

答案 0 :(得分:2)

function eliminateClubs(){
 for(h=0;h<=personChoices.length;h++){
   if (personChoices[h]==1){
       if (clubs[h].indexOf(',') > -1)
       {
          clubs[h] = clubs[h].replace(',','');
       }
     recClubs.push(clubs[h].join(', <br/>'));
    }
  }
}

答案 1 :(得分:1)

我建议您执行以下操作:

var p=[1,0,1,0];
var clubs=[[" Fall Production"," Spring Musical", ""],["Student Government", ""],["Tricorn", ""],["FBLA", ""]];
console.log(clubs.filter((a, i) =>p[i]==1).flat().filter((a) =>a ).map(a=>a.trim()).join(',<br>'));

答案 2 :(得分:0)

尝试一下:

const clubs = [
    ["Fall Production"," Spring Musical", ""],
    ["Student Government", ""],
    ["Tricorn", ""],
    ["FBLA", ""]
];

// filter empty values of arrays of strings
const filteredClubs = clubs.map(arr => arr.filter(a => a));

// convert filteredClubs in a one level array
const oneLevelArrayClubs = filteredClubs.reduce((acc, next) => acc.concat(next));


// join them with what you wanted
const clubsString = oneLevelArrayClubs.join(', <br/>');

答案 3 :(得分:0)

您可以简单地Array.flatMap遍历数组并使用Array.filter

var clubs=[[" Fall Production"," Spring Musical", ""],["Student Government", ""],["Tricorn", ""],["FBLA", ""]]

let result = clubs.flatMap(x => x.filter(y => y))

console.log(result)

然后,如果要添加换行符和修剪等操作,则可以再执行一次Array.map。如果您的数据更干净,则可以跳过该步骤,因此,如果可能,请尝试纠正这些空白等

let result = clubs.flatMap(x => x.filter(y => y)).map(x => x.trim())

注意Array.flatArray.flatMap在IE中不支持,因此您需要使用polyfill

您可以使用Array.map / Array.reduce避免这种情况,

var clubs=[[" Fall Production"," Spring Musical", ""],["Student Government", ""],["Tricorn", ""],["FBLA", ""]]

let result = clubs.map(x => x.filter(y => y)).reduce((r,c) => [...r,...c], [])

console.log(result)