admin管理员组

文章数量:1327116

I am trying to print variables in an array using back ticks and dollar sign, but somehow it doesn't retrieve data from the array.

    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
      }
    }

I am trying to print variables in an array using back ticks and dollar sign, but somehow it doesn't retrieve data from the array.

    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 prints:

this is fog {$key} for sure. Value: {$buz[key]}
this is fog {$key} for sure. Value: {$buz[key]}

How can I print:

this is fog fog for sure. Value: stack
this is fog snow for sure. Value: white

?

Share Improve this question edited Oct 18, 2018 at 15:50 Barry 3,3287 gold badges25 silver badges43 bronze badges asked Dec 19, 2017 at 16:34 bombom 831 silver badge9 bronze badges 1
  • ah thank you all so much! – bom Commented Dec 19, 2017 at 16:39
Add a ment  | 

4 Answers 4

Reset to default 8

You need ${expression}. For more info, see https://developer.mozilla/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
  }
}

Change {$key} to ${key} and {$buz[key]} to ${buz[key]} like following:

console.log(`this is fog ${key} for sure. Value: ${buz[key]}`);

I think you're looking for:

console.log(`this is fog ${key} for sure. Value: ${buz[key]}`);

you are doing it wrong

it should be like this

abc ${something}

本文标签: javascriptprint variables using consolelog() with back ticks and dollar signStack Overflow