使用 .split
是更慢的,但是它有一个优点,代码可以更短(字符更少):
.split
, but it has the advantage that the code can be shorter (Less characters):var array = 'months|monthsShort|weekdays|weekdaysShort|weekdaysMin|longDateFormat|calendar|relativeTime|ordinal|meridiem'.split('|');
var array = ['months','monthsShort','weekdays','weekdaysShort','weekdaysMin','longDateFormat','calendar','relativeTime','ordinal','meridiem'];
在这个例子中,差别不是很大,但如果你有100个变量,差异就更加明显。
用分隔符进行拆分版本的长度增加量为11 + 1 * n
,其中 n
是元素的数量,11
是由于使用 .split('|')
而产生的。
对于数组版本,则为 2 + 3 * (n - 1)
,2
是由于使用了 []
。
这意味着一旦你有6个元素,.split
版本就会更短:
for(var i = 5; i < 8; i++){
console.log('Elements:', i, 'split:', 11 + (i-1), 'array:', 2 + 3 * (i-1));
}
// Elements: 5 split: 15 array: 14
// Elements: 6 split: 16 array: 17
// Elements: 7 split: 17 array: 20