首页 > 解决方案 > js控制台日志字符串格式化起点

问题描述

let amounts = [1,10,100]
let animals = [cat,dog,horse]
for (let n = 0; n<3; n++){
console.log("I have " + amounts[n] + " of " + animals[n] + " in total" )
} 

目前我得到:

I have 1 cat in total
I have 10 dog in total
I have 100 horse in total

有没有办法用“列”格式化这个日志(它们是一个一个传入的,我不能将它们记录为表格)

I have 1    cat    in total
I have 10   dog    in total
I have 100  horse  in total

标签: loggingconsoleformatting

解决方案


let amounts = [1, 10, 100]
let animals = ['cat', 'dog', 'horse']
for (let n = 0; n < 3; n++){
console.log("I have\t" + amounts[n] + "\t" + animals[n] + "\tin total" )
}

另一种解决方案是使用Array.forEach()

let amounts = [1, 10, 100]
let animals = ['cat', 'dog', 'horse']

amounts.forEach((amount, index) => {console.log(`I have\t${amount}\t${animals[index]}\tin total`)})


推荐阅读