You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何JavaScript中${i}和${colors[i]}无法在控制台输出实际值?

为什么我的JavaScript循环里控制台输出的是模板字面量而非变量值?

你遇到的问题很典型,咱们先看一下你的代码和输出:

原代码

const colors = ['Red', 'Green', 'Blue'] 
for(let i=0, max = colors.length; i < max; i++) { 
  console.log('Color at position ${i} is ${colors[i]}'); 
}

原输出

Color at position ${i} is ${colors[i]}


问题原因

这是因为你用了**单引号(' ')来包裹字符串,而JavaScript的模板字符串(支持${变量}语法的字符串)必须使用反引号( )**来定义。单引号/双引号只会把里面的内容当作普通的字符串字面量,不会解析其中的${}占位符,自然就直接输出了${i}和${colors[i]}这些文本。

解决方法

把包裹字符串的单引号换成反引号就可以了,修改后的代码如下:

const colors = ['Red', 'Green', 'Blue'] 
for(let i=0, max = colors.length; i < max; i++) { 
  console.log(`Color at position ${i} is ${colors[i]}`); 
}

修改后的输出

Color at position 0 is Red
Color at position 1 is Green
Color at position 2 is Blue

这样控制台就会正确解析变量,输出每个索引对应的颜色值啦~

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:19:30