从位于数组内部的数组中删除逗号

我有以下数组,其中包含较小的数组:

var fruits = [["Bananas", "2"], ["Apples", "4"], ["Oranges", "5"]];

我想这样显示它们,删除较小数组中的逗号并添加连字符:

香蕉-2

苹果-4

橘子-5

我已经尝试了以下方法,但是仍然无法正常工作:

var fruits = [
  ["Bananas", "2"],
  ["Apples", "4"],
  ["Oranges", "5"]
];
var fruitsToday = [];
for (i = 0; i < fruits.length; i++) {
  fruitsToday += fruits[i].join(" - ");
}
document.getElementById("today").innerHTML = fruitsToday.join("<br>");

任何帮助将不胜感激!

评论
琴和雅
琴和雅

Your code works well. Problem is fruitsToday.join("<br>"); because fruitsToday is string and join() works only with array.

var fruits = [["Bananas", "2"], ["Apples", "4"], ["Oranges", "5"]];
var fruitsToday = [];
for (i=0; i < fruits.length; i++) {
  fruitsToday += (fruits[i].join(" - ") + '<br/>');
}
document.getElementById("today").innerHTML = fruitsToday;
<div id=today></div>
点赞
评论
请,带走
请,带走

您可以映射联接的项目,并将数组用于输出。

var fruits = [["Bananas", "2"], ["Apples", "4"], ["Oranges", "5"]],
    fruitsToday = fruits.map(a => a.join(' - '));

document.getElementById("today").innerHTML = fruitsToday.join('<br>');
<div id="today"></div>
点赞
评论
asaepe
asaepe

You need to use an array and push to it. Using the + operator will coerce the array into a string and concatenate the strings.

var fruits = [["Bananas", "2"], ["Apples", "4"], ["Oranges", "5"]];
var fruitsToday = [];
  for (i=0; i < fruits.length; i++) {
    fruitsToday.push(fruits[i].join(" - "));
  }
  document.getElementById("today").innerHTML = fruitsToday.join("<br>");
<div id="today"></div>
点赞
评论
命*
命*

应该在一行就可行:)

var fruits = [["Bananas", "2"], ["Apples", "4"], ["Oranges", "5"]];

document.getElementById("today").innerHTML = fruits.map(f => f.join(" - ")).join("<br>");
<span id="today"><span>
点赞
评论