考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
当前回答
我可以给你们举个例子:
函数fullName(first, last) { let fullName = first + " " + last; 返回fullName; } 函数fullNameStringInterpolation(first, last) { let fullName = ' ${first} ${last} '; 返回fullName; } console.log('Old School: ' + fullName('Carlos', 'Gutierrez')); console.log('New School: ' + fullNameStringInterpolation('Carlos', 'Gutierrez'));
其他回答
你可以很容易地使用ES6模板字符串,并使用任何可用的transpilar(如babel)编译到ES5。
const age = 3;
console.log(`I'm ${age} years old!`);
http://www.es6fiddle.net/im3c3euc/
从ES6开始,你可以使用模板文字:
Const age = 3 console.log(' I'm ${age} years old! ')
附注:注意反引号的使用:' '。
找不到我要找的东西,然后找到了
如果你使用的是Node.js,有一个内置的utipackage,它有一个format函数,工作方式是这样的:
util.format("Hello my name is %s", "Brent");
> Hello my name is Brent
巧合的是,在Node.js -中,这也被内置到console.log版本中
console.log("This really bad error happened: %s", "ReferenceError");
> This really bad error happened: ReferenceError
如果您想在console.log输出中插入,那么只需
console.log("Eruption 1: %s", eruption1);
^^
这里,%s是所谓的“格式说明符”。log内置了这种插值支持。
试试kiwi吧,它是一个轻量级的JavaScript模块,用于字符串插值。
你可以这样做
Kiwi.compose("I'm % years old!", [age]);
or
Kiwi.compose("I'm %{age} years old!", {"age" : age});