我正在尝试使用反引号和美元符号打印数组中的变量,但不知何故它没有从数组中检索数据。
var buz = {
fog: 'stack',
snow: 'white'
};
for (var key in buz) {
if (buz.hasOwnProperty(key)) {
console.log(`this is fog {$key} for sure. Value: {$buz[key]}`);
} else {
console.log(key); // toString or something else
}
}
这打印:
this is fog {$key} for sure. Value: {$buz[key]}
this is fog {$key} for sure. Value: {$buz[key]}
如何打印:
this is fog fog for sure. Value: stack
this is fog snow for sure. Value: white
?
最佳答案
你需要${expression}
。有关详细信息,请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
var buz = {
fog: 'stack',
snow: 'white'
};
for (var key in buz) {
if (buz.hasOwnProperty(key)) {
console.log(`this is fog ${key} for sure. Value: ${buz[key]}`);
} else {
console.log(key); // toString or something else
}
}
关于javascript - 使用带反引号和美元符号的 console.log() 打印变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47891305/