Why do I see javascript arrays getting created with string.split()?
I see code like this all over the web
var days= "Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" ");
Why do that instead of
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
I don't think laziness or ignor开发者_C百科ance has anything to do with it. This is out of jQuery 1.4.2
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" ")
They do it all over the place.
I think it's because you don't have to quote and separate every string of the array. Likewise, in perl, many people use qw(a b c d e f g)
instead of ('a', 'b', 'c', 'd', 'e', 'f', 'g')
. So the benefit is twofold:
- It's faster and easier to write and modify (can obviously be debatted).
- It's smaller bitwise, so you spare some bandwidth.
See the bit size:
var days= "Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" ");
// 81 characters
vs
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
// 91 characters
It may also make sense if initial strings have quotes or double quotes in text.
"81 characters and 91 characters" << Nice observation but it again adds few processing time to convert String to Array and what if sometimes there's need to add something which has 2 words in it.
May be they like this coding style.
IDK
You could have 20 strings of the week day names in 20 languages, and use a single split to return the correct array for the user.
精彩评论