JavaScript String.concat() 方法
String concat()
是 JavaScript 中的内置方法,可在不改变任何字符串的情况下将两个或多个字符串连接到另一个字符串的末尾。
JavaScript string.concat() 的语法:
baseString.concat(string_1, string_2, ..., string_N);
参数
- baseString 这是强制字符串类型调用对象
- string_1 要与基本字符串连接的字符串
- string_N N是要拼接的字符串的个数
返回值
按照与参数中传递的字符串相同的顺序连接字符串后,将返回一个新的结果字符串。
使用 JavaScript String concat() 方法连接两个字符串
让我们从一个简单的例子开始,其中 JavaScript String concat()
方法组合两个字符串并在控制台上打印结果。
const baseString= "I am a ";
const string_1= "programmer.";
console.log(baseString.concat(string_1))
输出:
I am a programmer.
调用 String concat()
方法时会创建一个新字符串。 调用 concat()
方法的字符串对象 baseString 中的字符将首先填充这个新数组。
然后将 string_1 的字符连接到新字符串的末尾,而不改变两个字符串。
使用 JavaScript string.concat() 方法连接多个字符串
在此示例中,JavaScript concat() 方法组合了多个字符串,并在一个新数组 - resultString 中返回串联的四个字符串。
const baseString = "Welcome"; //compulsory string
const string_1 = " ";
const string_2 = "to";
const string_3 = " Hello World!";
const resultString = baseString.concat(string_1, string_2, string_3)
console.log(resultString)
输出:
Welcome to Hello World!
在上面的例子中,concat() 创建了一个新数组。 然后将每个参数字符串的元素首尾相连地连接到新数组中。
新数组被复制到一个常量字符串对象 resultString。
使用 JavaScript String concat() 方法用逗号连接字符串
下面的示例使用 concat()
在中间用逗号连接字符串,并在控制台上打印结果。
var s_1 = "Roses"
var s_2 = "sunflowers"
var s_3 = "and lilies."
console.log(s_1.concat( ", ", s_2, ", ", s_3))
输出:
Roses, sunflowers, and lilies.
当调用字符串 concat()
函数时,字符串“,”
被初始化。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。