▲TOPへ戻る

【javascript】バッククォート内のドルマークの使い方 ` ${ } `

array

` ${ } `の意味

  1. `文字列${ 変数 }文字列`と書くことで、 変数文字列ではなく変数として認識してくれます。
  2. シングルクォーテーションではなく、バッククォートです。
バッククォート
  const weather = '晴れ';             
  console.log(`今日の天気は${weather}です。`);
  //  結果 => 今日の天気は晴れです。

'文字列' + 変数 + '文字列' と書き換え可

ここでの点は、シングルクォーテーションでもOK!

  const weather = '晴れ';             
  console.log('今日の天気は' + weather  + 'です。');
  //  結果 => 今日の天気は晴れです。

以下のように値を変えて表示できます。

今日の天気は?
 const weatherSelect = document.getElementById("weatherSelect");
  function changeWeather() {
    const weatherText = document.getElementById("text");
    const weather = '<span class="blue">' + weatherSelect.value + '</span>';
    weatherText.innerHTML = `今日の天気は${weather}です。`;
  }
  weatherSelect.onchange = changeWeather;

アニメーションさせる

ボックスをクリックしてみてください。

  const box = document.querySelector(".box");
  let count = 100;
  box.addEventListener("click", ()=>{
    let rotate = setInterval(()=>{
      count++;
      box.style.width = `${count}px`
      if(count>360){
        clearInterval(rotate)
      }
    },10)
  })

参考

ここでも` ${ } `を使い、アニメーションさせています。

js
【CSS】【javascript】conic-gradientで1分カウンターを作る方法
point

`文字列${ 変数 }文字列`

シングルクォーテーションではなく、バッククォート

'文字列' + 変数 + '文字列' と書き換えることができる。

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ