javascript Javascript将数组连接到字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19040826/
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
Javascript Concatenate Array to String
提问by Towler
I am using D3.js and often find myself dynamically building transform
attributes (or d
attributes on path
elements). Both of these often require multiple comma-separated numbers.
我使用 D3.js 并且经常发现自己动态构建transform
属性(或元素上的d
属性path
)。这两者通常都需要多个逗号分隔的数字。
Sometimes I build my strings by concatenating an array to string:
有时我通过将数组连接到字符串来构建我的字符串:
var x = 0,
y = 1,
path = 'M0,0 L' + [x, y];
And sometimes I build my strings by manually adding the comma:
有时我通过手动添加逗号来构建我的字符串:
var x = 0,
y = 1,
path = 'M0,0 L' + x + ',' + y;
I've decided that I should try to stick to one method or the other, and am wondering which approach is the better one to take.
我已经决定我应该尝试坚持一种方法或另一种方法,并且想知道采用哪种方法更好。
Here are a few things I've considered:
以下是我考虑过的几点:
- I know that calling
join()
is slower than manually concatenating the commas, but is that what the browser does when it concatenates an array to a string? - The second format will work in any browser. Are there any browsers that don't support the first format?
- The first format uses less characters (keeping file sizes low is always a plus).
- Personally, I believe the first format is more readable.
- 我知道调用
join()
比手动连接逗号慢,但是浏览器在将数组连接到字符串时会这样做吗? - 第二种格式适用于任何浏览器。是否有不支持第一种格式的浏览器?
- 第一种格式使用较少的字符(保持较小的文件大小总是一个优点)。
- 就个人而言,我认为第一种格式更具可读性。
Is there one way that is definitively better than the other? Or am I just being nitpicky?
有没有一种方法绝对比另一种更好?还是我只是挑剔?
回答by TenorB
When JavaScript coerces an array to a string, it actually call: .join(',')
on the array. So you're actually going to be getting better performance with .join(',')
manually as opposed to leaving it up to the interpreter to notice you're coercing the array. So: x + ',' + y
is the fastest, [x, y].join(',')
is the best practice(since it makes it easier to modify the behavior), and [x, y]
is a tiny bit slower than manually calling .join
and can be unreadable at times, but it's more convenient.
当 JavaScript 将数组强制转换为字符串时,它实际上是.join(',')
在数组上调用:。因此,您实际上将通过.join(',')
手动获得更好的性能,而不是让解释器注意到您正在强制使用数组。所以:x + ',' + y
是最快的,[x, y].join(',')
是最佳实践(因为它可以更容易地修改行为),并且[x, y]
比手动调用慢一点.join
,有时可能无法读取,但更方便。
回答by Nicolás Straub
the short answer: use array.join.
简短的回答:使用array.join。
the long answer:
长答案:
First off, concatenation isn't faster than using array.join(), it's slower. this is because each time you concatenate you destroy two strings and create a new one.
首先,连接并不比使用 array.join() 快,它更慢。这是因为每次连接时都会破坏两个字符串并创建一个新字符串。
take the following code:
取以下代码:
<script>
function concat(){
var txt = '';
for (var i = 0; i < 1000000; i++){
txt =+ i + ',';
}
}
function arr(ar){
var txt = 'asdf' + ar;
}
ar = [];
for (var i = 0; i < 1000000; i++) {
ar.push(i);
}
concat();
arr(ar);
alert('done!');
</script>
and paste it into an html file. Then profile it. On my machine (core i7EE, 16GB RAM, SSD disks, IE9), arr() takes 0ms and concat() takes 12ms. Keep in mind this is over a million iterations (this same test would be quite different on IE6, concat() would take seconds).
并将其粘贴到 html 文件中。然后对其进行概要分析。在我的机器上(核心 i7EE、16GB RAM、SSD 磁盘、IE9),arr() 需要 0ms,concat() 需要 12ms。请记住,这是超过一百万次迭代(同样的测试在 IE6 上会大不相同,concat() 需要几秒钟)。
Second, concatenation will take the same as array.join when having only two values. So for your example, from a performance perspective, they're both equivalent. if you take the above code and change the 1000000 to 4, both concat and arr take 0ms to execute. this means the difference for your particular flow is either inexistent or so negligible it doesn't show up in a profile.
其次,当只有两个值时,连接将与 array.join 相同。所以对于你的例子,从性能的角度来看,它们都是等价的。如果把上面的代码把1000000改成4,concat和arr都需要0ms执行。这意味着您的特定流程的差异要么不存在,要么可以忽略不计,它不会出现在配置文件中。
Third, modern browsers optimize string concatenation using array.join() anyways, so the discussion is probably moot from a performance point of view.
第三,现代浏览器无论如何都使用 array.join() 优化字符串连接,因此从性能的角度来看,讨论可能没有实际意义。
That leaves us with style. Personally, I wouldn't use the first form because I don't like manually concatenating strings (when you've got 2 vars it's rather straightforward, but what if you have 10 vars? that'll make a really long line of code. And what if you receive an array with n values, in comes a for loop). I wouldn't use the second form either because, as pointed out in another answer, the value is coerced to a string, and that means some implicit transformation is going on. The problem here is the implicit part. I know now arrays are joined with a comma when coerced, but what happens if the spec changes, or some genius decides to change the toString implementation of Array.prototype in your codebase? just for fun run this in jsfiddle:
这给我们留下了风格。就我个人而言,我不会使用第一种形式,因为我不喜欢手动连接字符串(当你有 2 个变量时,它相当简单,但如果你有 10 个变量呢?那会产生很长的代码行。如果您收到一个包含 n 个值的数组,则会出现一个 for 循环)。我也不会使用第二种形式,因为正如另一个答案中指出的那样,该值被强制转换为字符串,这意味着正在进行一些隐式转换。这里的问题是隐式部分。我知道现在数组在强制时用逗号连接,但是如果规范发生变化,或者某些天才决定更改代码库中 Array.prototype 的 toString 实现会发生什么?只是为了好玩,在 jsfiddle 中运行它:
Array.prototype.toString = function() {
return 'not the expected result!';
}
alert([1, 2]);
Can you guess what the answer will be? (the above code will execute the same kind of conversion for the array as your code. coercion via the toString() method)
你能猜出答案是什么吗?(上面的代码将对数组执行与您的代码相同类型的转换。通过 toString() 方法强制转换)
if you use array.join(','); you'll be futureproofing your code by stating that 1) your array will be joined regardless of the toString implementation and 2) it will be joined with a comma.
如果你使用 array.join(','); 您将通过声明 1) 无论 toString 实现如何都将加入您的数组,以及 2) 它将用逗号连接,从而使您的代码面向未来。