简体   繁体   English

为什么我看到使用string.split()创建的javascript数组?

[英]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 ignorance has anything to do with it. 我不认为懒惰或无知与它有任何关系。 This is out of jQuery 1.4.2 这是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(abcdefg) instead of ('a', 'b', 'c', 'd', 'e', 'f', 'g') . 同样,在perl中,许多人使用qw(abcdefg)而不是('a', 'b', 'c', 'd', 'e', 'f', 'g') So the benefit is twofold: 所以好处是双重的:

  1. It's faster and easier to write and modify (can obviously be debatted). 编写和修改更快更容易(显然可以被推销)。
  2. 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 VS

var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
// 91 characters

如果初始字符串在文本中有引号或双引号也可能有意义。

"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. “81个字符和91个字符”<< Nice观察但是它再次添加了很少的处理时间来将String转换为数组,如果有时需要添加其中包含2个单词的内容。

May be they like this coding style. 可能他们喜欢这种编码风格。

IDK IDK

您可以在20种语言中使用20个字符串的工作日名称,并使用单个拆分为用户返回正确的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM