开发者

What are the advantages of splitting a string to initiliase a javascript array? [closed]

开发者 https://www.devze.com 2023-03-04 11:53 出处:网络
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references,or expertise, but this question will likely solicit debate, a
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 10 years ago.

This pattern is quite common; I've seen it in a few places including the jQuery source code:

var arr = "word1 word2 word3".split(" ");

as an alternative to the 'normal' methods of array initiliasation:

var arr1 = [ "word1", "word2", "word3" ];

var arr2 = new Array( "word1", "word2", "word3" );
开发者_开发技巧

What are the benefits of the string-splitting approach?


From John Resig (creator of jQuery):

"the only benefit i see is character count in the source and one string rather than numerous." Bingo!

Now that I think about, I think Closure may optimize this point (don't think YUIMin did). I can check in to it again.

Also, the Google JavaScript Style Guide recommends avoiding new Array() because "Array constructors are error-prone due to their arguments." The guide has a more thorough explanation.


The first is shorter. In JS libs these days that's an issue. It's also easier to write: less , and '. It's also harder to mistype.

0

精彩评论

暂无评论...
验证码 换一张
取 消