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

查看:87
本文介绍了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天全站免登陆