string 如何在 JavaScript 字符串中插入变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19105009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert variables in JavaScript strings?
提问by at.
What's the best way to do insert variables in a string in JavaScript? I'm guessing it's not this:
在 JavaScript 中的字符串中插入变量的最佳方法是什么?我猜不是这个:
var coordinates = "x: " + x + ", y: " + y;
In Java, String
s are immutable and doing something like the above would unnecessarily create and throw away String
s. Ruby is similar and has a nice way of doing the above:
在 Java 中,String
s 是不可变的,执行上述操作会不必要地创建和丢弃String
s。Ruby 是类似的,并且有一个很好的方法来完成上述操作:
coordinates = "x: #{x}, y: #{y}"
Does something similar exist for JavaScript?
JavaScript 是否存在类似的东西?
回答by Nick Brady
Introduced in ES6 as "template strings"
在 ES6 中作为“模板字符串”引入
MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
MDN 文档:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const name = "Nick"
const greeting = `Hello ${name}` // "Hello Nick"
回答by Nicole
That's fine in JavaScript. There is no good built-in equivalent of an sprintf
or String.format
, however, you can build your own.
这在 JavaScript 中没问题。没有很好的内置sprintf
或等价物String.format
,但是,您可以构建自己的.
Don't worry about the "unnecessary" string objects. That's definitely micro-optimization. Address it if and when you need that extra tiny bit of performance or memory optimization, but in distributed software, you probably don't.
不要担心“不必要的”字符串对象。这绝对是微观优化。如果您需要额外的一点点性能或内存优化,请解决它,但在分布式软件中,您可能不需要。
回答by Wyatt
If for some reason you are doing this many times per second and referencing the strings many times per call, you can always store the strings themselvesas variables.
如果出于某种原因,您每秒多次执行此操作并在每次调用时多次引用字符串,您始终可以将字符串本身存储为变量。
var preX = 'x: '
, preY = 'y: '
, coords
;
coords = preX + x + preY + y;
This of course should be supported by benchmarking/profiling, but creating many strings per frame is often a source of unnecessary garbage which can result in jank down the line.
这当然应该得到基准测试/分析的支持,但是每帧创建许多字符串通常是不必要的垃圾来源,可能导致线路卡顿。
回答by tjcafferkey
https://www.npmjs.com/package/stringinject
https://www.npmjs.com/package/stringinject
https://github.com/tjcafferkey/stringinject
https://github.com/tjcafferkey/stringinject
I created this function to do exactly this, it will allow you to pass in a string, and an object with keys that will replace placeholder values in the string with their values like below:
我创建了这个函数来做到这一点,它允许你传入一个字符串和一个带有键的对象,这些键将用它们的值替换字符串中的占位符值,如下所示:
var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
// My username is tjcafferkey on Github