如何在JavaScript字符串中插入变量? [英] How to insert variables in JavaScript strings?

查看:137
本文介绍了如何在JavaScript字符串中插入变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中的字符串中插入变量的最佳方法是什么?我猜这不是这个:

What's the best way to do insert variables in a string in JavaScript? I'm guessing it's not this:

var coordinates = "x: " + x + ", y: " + y;

在Java中, String s是不可变的,做上面这样的事情会不必要地创建并扔掉 String s。 Ruby是类似的,有一个很好的方法来做上述事情:

In Java, Strings are immutable and doing something like the above would unnecessarily create and throw away Strings. Ruby is similar and has a nice way of doing the above:

coordinates = "x: #{x}, y: #{y}"

JavaScript有类似的东西吗?

Does something similar exist for JavaScript?

推荐答案

在ES6中作为模板字符串引入

Introduced in ES6 as "template strings"

MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

const name = "Nick"
const greeting = `Hello ${name}`  // "Hello Nick"

这篇关于如何在JavaScript字符串中插入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆