如何格式化数组中的元素?

时间:2016-11-02 09:02:41

标签: javascript arrays

我有三个数组:

var name = ["wheel", "rectangle", "moon"];
var type = ["car", "shape", "sky"];
var all = [];
var temp = " ";

for (var i = 0; i < name.length; i++) {
    temp = name[i] + " " + type[i];
    all.push(temp);
}

for (var i = 0; i < name.length; i++) {
    // I call here function to display all element of array `all`
}

输出结果为:

wheel car
rectangle shape
moon sky

但输出的格式并不好。我想在将数组添加到数组type之前移位数组all的元素,所以我希望输出如下:

wheel       car
rectangle shape
moon        sky

我的问题是:如何移动数组的元素以将它们添加到另一个数组并以允许我显示上述形式的元素的方式存储它们?

6 个答案:

答案 0 :(得分:2)

  

但输出的形式不太好

如果您只想更好地格式化输出,请尝试console.table

var name1 = [ "wheel","rectangle","moon" ];
var type = [ "car" , "shape", "sky"];
var all=[];
for (var i = 0; i< name1.length; i++)
{
      all.push({ name : name1[i], type: type[i] });
}
console.table(all);

尝试使用此{{3}}查看实际输出,因为stack-snippet会改变console api的行为

答案 1 :(得分:1)

您应该计算哪个是第一个数组中最长的字符串,以便事先知道需要附加多少空格才能正确填充字符串

var n = ["wheel", "rectangle", "moon"];
var t = ["car", "shape", "sky"];
var all = [];

/* sorting the values of the first array by length desc,
 * then get the length of the first element 
 */
var padding = n.sort(function(a, b) {
  return a.length <= b.length;
})[0].length + 1; 

n.forEach(function(el, i) {
  all.push(el + " ".repeat(padding - el.length) + t[i]);
});

输出

"rectangle car"
"wheel     shape"
"moon      sky"
  

codepen demo

答案 2 :(得分:1)

首先遍历数组并找到最大长度。然后再循环并添加空格。

<script >
  var name=["wheel","rectangle","moon"];
  var type=["car","shape","sky"];
  var all=[];
  var i=0;
  var maxLength=0;

  string temp=" ";

  String.prototype.padLeft= function(len, c){
      var r = '';
      while(r.length < len) r += c;
      return s+r;
  }
  for (i = 0; i< name.length; i++)
  {
      maxLength = Math.max(maxLength, name[i].length+type[i].length+1;
  }

  for (i = 0; i< name.length; i++)
  {
      temp=name[i]+type[i].padLeft(maxLength-name[i].length-type[i].length);
      all.push(temp);
  }
 </script >

答案 3 :(得分:1)

我会这样做;

&#13;
&#13;
var id = ["wheel","rectangle","moon"],
  type = ["car","shape","sky"];
id.longestStringLength = Math.max(...id.map(s => s.length));
type.longestStringLength = Math.max(...type.map(s => s.length));
id = id.map((s,_,a) => s + " ".repeat(a.longestStringLength-s.length));
type = type.map((s,_,a) => " ".repeat(a.longestStringLength-s.length) + s);
console.log(id,type);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

连接时使用\t代替空格以使其对齐。

答案 5 :(得分:0)

为什么不直接添加标签'\ t',它会为您提供所需的输出。或者,您可以在两个数组项之间附加固定数量的空格。