简体   繁体   English

Javascript将数组连接到字符串

[英]Javascript Concatenate Array to String

I am using D3.js and often find myself dynamically building transform attributes (or d attributes on path elements). 我正在使用D3.js,并经常发现自己动态构建transform属性(或path元素上的d属性)。 Both of these often require multiple comma-separated numbers. 这两者通常需要多个以逗号分隔的数字。

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? 我知道调用join()比手动连接逗号要慢,但这是浏览器将数组连接到字符串时的作用吗?
  • 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. 就个人而言,我认为第一种格式更具可读性。

Is there one way that is definitively better than the other? 有没有一种方式明显优于另一种方式? Or am I just being nitpicky? 或者我只是在挑剔?

When JavaScript coerces an array to a string, it actually call: .join(',') on the array. 当JavaScript将数组强制转换为字符串时,它实际上会在数组上调用: .join(',') 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. 因此,您实际上将使用.join(',')手动获得更好的性能,而不是将其留给解释器以注意您正在强制执行数组。 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. 所以: x + ',' + y是最快的, [x, y].join(',')是最好的做法(因为它可以更容易地修改行为), [x, y]是一个很小的比手动调用.join慢一点,有时可能不可读,但它更方便。

the short answer: use array.join. 简短的回答:使用array.join。

the long answer: 答案很长:

First off, concatenation isn't faster than using array.join(), it's slower. 首先,连接并不比使用array.join()更快,它更慢。 this is because each time you concatenate you destroy two strings and create a new one. 这是因为每次连接时都会销毁两个字符串并创建一个新字符串。

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. 并将其粘贴到html文件中。 Then profile it. 然后对其进行分析 On my machine (core i7EE, 16GB RAM, SSD disks, IE9), arr() takes 0ms and concat() takes 12ms. 在我的机器上(核心i7EE,16GB RAM,SSD磁盘,IE9),arr()需要0ms而concat()需要12ms。 Keep in mind this is over a million iterations (this same test would be quite different on IE6, concat() would take seconds). 请记住,这是超过一百万次迭代(相同的测试在IE6上会有很大不同,concat()需要几秒钟)。

Second, concatenation will take the same as array.join when having only two values. 其次,当只有两个值时,连接将与array.join相同。 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. 如果您使用上面的代码并将1000000更改为4,则concat和arr都需要0ms才能执行。 this means the difference for your particular flow is either inexistent or so negligible it doesn't show up in a profile. 这意味着您的特定流量的差异要么不存在,要么可忽略不计,不会显示在配置文件中。

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). 就个人而言,我不会使用第一种形式,因为我不喜欢手动连接字符串(当你有2个变量时,它相当简单,但是如果你有10个变量呢?那将会产生很长的代码。如果你收到一个带有n个值的数组,那么会出现一个for循环)。 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? 我知道现在阵列在强制时用逗号连接,但是如果规范发生变化,或者某些天才决定在代码库中更改Array.prototype的toString实现会发生什么? just for fun run this in jsfiddle: 只是为了好玩,在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(','); 如果你使用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. 通过声明:1)无论toString实现如何,您的数组都将被连接,并且2)它将以逗号连接,您将会对代码进行改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM