javascript - 使用带反引号和美元符号的 console.log() 打印变量

标签 javascript arrays

我正在尝试使用反引号和美元符号打印数组中的变量,但不知何故它没有从数组中检索数据。

    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/

相关文章:

javascript - angularjs ng-repeat按数字顺序排序字符串数组

Javascript:原型(prototype)中的初始方法存储

javascript - 将数组拆分为给定范围内随机长度的 block

ios - Swift:创建具有不同自定义类型的数组

arrays - 从三矩阵算法中找到给定的和 "total"

c# - javascript和C#服务器通信

javascript - 如何在 Next.js 的事件页面上设置链接组件的样式

javascript - 将所有字段加在一起或返回原始总和

arrays - 查找总和为 0 的数组的所有子集

c++ - 为什么我在 ‘]’ token 之前得到数组绑定(bind)不是整数常量,即使全局声明了大小?