0

可能重复:
JavaScript 等价于 printf/string.format

是否有一种更像 C 的方式在 javascript 中打印复杂的字符串,最好是不需要大量+符号和伴随的字符串""

我要这个:

console.log ( "Name: %s Age: %s Sex %s Wieght %s Height %s", name, age, sex, weight, height );

而不是这个:

console.log ( "Name: " + name + " Age: " + age + " Sex: " + sex + " Weight: " + weight " Height: " + height );
4

3 回答 3

2

如果您不介意使用第三方,这个库似乎可以满足您的需求。

JavaScript sprintf

来自文章

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
于 2012-07-18T21:16:13.223 回答
1

你说的是标准window.console吗?它具有完全相同的功能(在 Firefox 上测试):

console.log( "Name: %s Age: %s Sex %s Wieght %s Height %s", name, age, sex, weight, height);

或者:

console.log( "Name: ", name, " Age: ", sex, " Sex ", sex, " Wieght ", weight", " Height ", height);
于 2012-07-18T21:19:10.640 回答
0

使用 console.log 你总是可以这样做而不是串联:

console.log ( "Name: ", name, " Age: ", age, " Sex: ", sex, " Weight: ", weight, " Height: " , height );
于 2012-07-18T21:16:20.167 回答