Javascript将数组连接到字符串 [英] Javascript Concatenate Array to String

查看:26
本文介绍了Javascript将数组连接到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 D3.js 并且经常发现自己动态构建 transform 属性(或 path 元素上的 d 属性).这两者通常都需要多个逗号分隔的数字.

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.

有时我通过将数组连接到字符串来构建字符串:

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:

  • 我知道调用 join() 比手动连接逗号要慢,但是浏览器在将数组连接到字符串时会这样做吗?
  • 第二种格式适用于任何浏览器.是否有不支持第一种格式的浏览器?
  • 第一种格式使用较少的字符(保持较小的文件大小总是一个优点).
  • 就我个人而言,我认为第一种格式更具可读性.
  • 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.

有没有一种方法绝对比另一种更好?还是我太挑剔了?

Is there one way that is definitively better than the other? Or am I just being nitpicky?

推荐答案

当 JavaScript 将数组强制转换为字符串时,它实际上是在数组上调用:.join(',').因此,您实际上将通过 .join(',') 手动获得更好的性能,而不是让解释器注意到您正在强制转换数组.所以: x + ',' + y 是最快的, [x, y].join(',') 是最佳实践(因为它更容易修改行为​​),并且 [x, y] 比手动调用 .join 慢一点,有时可能不可读,但更方便.

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将数组连接到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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