本文介绍了在 JavaScript 中连接字符串的最有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中,我有一个包含多次迭代的循环,并且在每次迭代中,我都会创建一个包含许多 += 运算符的巨大字符串.有没有更有效的方法来创建字符串?我正在考虑创建一个动态数组,在其中不断向其中添加字符串,然后进行连接.任何人都可以解释并举例说明最快的方法吗?

In JavaScript, I have a loop that has many iterations, and in each iteration, I am creating a huge string with many += operators. Is there a more efficient way to create a string? I was thinking about creating a dynamic array where I keep adding strings to it and then do a join. Can anyone explain and give an example of the fastest way to do this?

推荐答案

似乎基于 JSPerf 使用 += 是最快的方法,尽管不一定适用于所有浏览器.

Seems based on benchmarks at JSPerf that using += is the fastest method, though not necessarily in every browser.

为了在 DOM 中构建字符串,似乎更好连接字符串首先,然后添加到 DOM,而不是迭代地将其添加到 DOM.不过,您应该对自己的案例进行基准测试.

For building strings in the DOM, it seems to be better to concatenate the string first and then add to the DOM, rather then iteratively add it to the dom. You should benchmark your own case though.

(感谢@zAlbee 更正)

(Thanks @zAlbee for correction)

这篇关于在 JavaScript 中连接字符串的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:45