我在尝试在单个 console.log 语句中记录对象的多个属性时遇到了类似的问题,但在多行中设置了样式。
我想以 name --> value 格式记录属性,并将值设为红色以便于阅读。
所以我最终构建的是这个函数:
//Function to transform an object to a formated string and params
var generateColouredLogObject = obj => {
var formatedString = ""
var arrayParams = []
Object.keys(obj)
.map(key => {
obj[key]
.map(item => {
formatedString += "%c %s --> %c %s %c"
arrayParams.push("", item.tag, "color:red", item.value, "")
})
formatedString += " \n"
})
return {text: formatedString, params: arrayParams}
}
这样的对象是这样的:
//the data we want to print
//Its built one 'line' property as an array containing each of the items (pair tag-vaule) you want to print
var objToLog = {
line1: [{ tag: "domain", value: window.document.domain }],
line2: [{ tag: "protocol", value: window.document.location.protocol }, { tag: "pahtname", value: window.document.location.pathname }],
}
执行此代码时会产生如下输出:
var output = generateColouredLogObject(objToLog)
console.log(output.text, ...output.params)
Dev Console output when executing code on this same page
对于您的示例,您应该构建适合您的场景的“formatedString”和“arrayParams”
希望对你有帮助