在没有+符号的javascript中打印复杂字符串

时间:2012-07-18 21:13:27

标签: javascript syntax printing

  

可能重复:
  JavaScript equivalent to 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 );

3 个答案:

答案 0 :(得分:2)

如果你不介意去第三方,这个图书馆似乎可以做你想要的。

JavaScript sprintf

来自文章

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);

答案 1 :(得分: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);

答案 2 :(得分:0)

使用console.log,您始终可以执行此操作而不是连接:

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