You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

JavaScript字符串插值疑问:单引号写法为何无法生效?

Why String Interpolation Isn't Working with Single Quotes in JavaScript

Hey there! Let's break down why your first approach didn't work and how template literals actually function in JavaScript.

The Core Issue: Wrong Quote Type

JavaScript has three ways to define strings, but only one supports interpolation:

  • Single quotes (') and double quotes ("): These create regular string literals. Any ${variable} inside them gets treated as plain text—JavaScript won’t parse or replace it with the variable’s actual value.
  • Backticks (`): These create template literals, which are built specifically for interpolation. They let you embed variables directly using ${variable} syntax, and JavaScript will automatically replace the placeholder with the variable’s content.

Let’s Analyze Your Code

Your non-working interpolation code uses single quotes, so ${topping} stays as literal text instead of being replaced:

const takeOrder = (topping) => { 
  console.log('Order: pizza topped with ${topping}'); 
}; 
takeOrder("mushrooms"); // 输出: Order: pizza topped with ${topping}

Your string concatenation works because you’re manually combining a regular string with the variable using the + operator—this works with single/double quotes, but it’s less clean than interpolation.

The Fix: Swap Single Quotes for Backticks

Just replace the single quotes with backticks, and your interpolation will work as expected:

const takeOrder = (topping) => { 
  console.log(`Order: pizza topped with ${topping}`); 
}; 
takeOrder("mushrooms"); // 输出: Order: pizza topped with mushrooms

Bonus: Extra Perks of Template Literals

Template literals also simplify multi-line strings—no need for \n escape characters:

const takeOrder = (topping, size) => { 
  console.log(`Order:
  ${size} pizza
  Topped with ${topping}`); 
}; 
takeOrder("mushrooms", "large");
// 输出格式化的多行文本

内容的提问来源于stack exchange,提问作者Cause

火山引擎 最新活动