admin管理员组

文章数量:1293769

I often notice when people split a string of substrings instead of just declare an array of the necessary strings.

Example in moment.js:

langConfigProperties = 'months|monthsShort|weekdays|weekdaysShort|weekdaysMin|longDateFormat|calendar|relativeTime|ordinal|meridiem'.split('|'),

Example in jQuery

 "Boolean Number String Function Array Date RegExp Object".split(" ")

What is a reason to prefer such way ?

I often notice when people split a string of substrings instead of just declare an array of the necessary strings.

Example in moment.js:

langConfigProperties = 'months|monthsShort|weekdays|weekdaysShort|weekdaysMin|longDateFormat|calendar|relativeTime|ordinal|meridiem'.split('|'),

Example in jQuery

 "Boolean Number String Function Array Date RegExp Object".split(" ")

What is a reason to prefer such way ?

Share edited Jan 30, 2013 at 12:42 Eugene Gluhotorenko asked Jan 30, 2013 at 12:21 Eugene GluhotorenkoEugene Gluhotorenko 3,1642 gold badges35 silver badges52 bronze badges 4
  • I do it to avoid having to match all the quotes of the in the array declartion. – Subir Kumar Sao Commented Jan 30, 2013 at 12:24
  • 3 This doesn't belong on Stack Overflow. A short answer though: minification. These libraries are squeezed into minified versions with minimal whitespace and short variable names. As it turns out, splitting is shorter (in characters) than writing a array literal. – Mattias Buelens Commented Jan 30, 2013 at 12:25
  • 10 @MattiasBuelens Struggling to see how it isn't on topic for SO. – lonesomeday Commented Jan 30, 2013 at 12:27
  • 1 This definitely belongs on SO – Gerard Simpson Commented Apr 19, 2017 at 6:03
Add a ment  | 

1 Answer 1

Reset to default 15

It's way slower to use the .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'];

In this example, the difference isn't huge, but if you have 100 variables, the difference gets more significant.

The length added by the delimiter in the split version is 11 + 1 * n, where n is the number of elements, the 11 is for the .split('|')
For the array version, that's 2 + 3 * (n - 1), the 2 for the [].

That means that as soon as you have 6 elements, the .split version is shorter:

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

本文标签: javascriptUsing string split instead of array declaration array with substringsStack Overflow