格式数组以在node.js中输出

var toFormat = [[1, "one", "unu"], [2, "two", "du"], [3, "three", "tri"], [4, "four", "kvar"]]; 

我需要输出数组toFormat所以它应该看起来像这样:

 1 (one) 2 (two) 3 (three) 4 (four) 

(每个子数组的第三个元素不被使用)如何做到这一点?

编辑:循环在这里

 var res = []; for(var i=0;i<toFormat.length;i++){ res.push(toFormat[i][1]+" ("+toFormat[i][2]+")"); } console.log(res.join("\n")) 

有很多方法可以做到。 我个人build议使用for...of循环,就像这样

 // defining the array to loop over const toFormat = [ [1, 'one', 'unu'], [2, 'two', 'du'], [3, 'three', 'tri'], [4, 'four', 'kvar'] ]; for (let i of toFormat) { console.log(i[0] + " (" + i[1] + ")"); } 
 const toFormat = [ [1, "one", "unu"], [2, "two", "du"], [3, "three", "tri"], [4, "four", "kvar"]]; const result = toFormat.map(([val, string]) => `${val} (${string})`).join('\n'); console.log(result); 

首先,你已经省略了最后一个数组中最后一个索引的结尾引用。

但是,除此之外, [Array.prototype.forEach()]方法可以做到这一点 :

 var toFormat = [[1, "one", "unu"], [2, "two", "du"], [3, "three", "tri"], [4, "four", "kvar"]]; toFormat.forEach(function(item, index, arry){ console.log(item[0] + " (" + item[1] + ")"); });