Javascript 如果字符串没有匹配项, .split() 会返回什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27688120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does .split() return if the string has no match?
提问by Vikram Anand Bhushan
In this JavaScript code if the variable datadoes not have that character .then what will split return?
在这段 JavaScript 代码中,如果变量data没有那个字符,.那么 split 会返回什么?
x = data.split('.');
Will it be an array of the original string?
它会是原始字符串的数组吗?
回答by paxdiablo
Yes, as per ECMA262 15.5.4.14 String.prototype.split (separator, limit), if the separator is not in the string, it returns a one-element array with the original string in it. The outcome can be inferred from:
是的,根据ECMA262 15.5.4.14 String.prototype.split (separator, limit),如果分隔符不在字符串中,则返回一个包含原始字符串的单元素数组。结果可以从以下推断:
Returns an Array object into which substrings of the result of converting this object to a String have been stored. The substrings are determined by searching from left to right for occurrences of separator; these occurrences are not part of any substring in the returned array, but serve to divide up the String value.
返回一个 Array 对象,其中存储了将此对象转换为 String 的结果的子字符串。通过从左到右搜索分隔符的出现来确定子字符串;这些出现不是返回数组中任何子字符串的一部分,而是用于分割字符串值。
If you're not happy inferring that, you can follow the rather voluminous steps at the bottom and you'll see that's what it does.
如果您对推断不满意,可以按照底部相当多的步骤进行操作,您会看到它的作用。
Testing it, if you type in the code:
测试一下,如果你输入代码:
alert('paxdiablo'.split('.')[0]);
you'll see that it outputs paxdiablo, the first (and only) array element. Running:
你会看到它输出paxdiablo第一个(也是唯一一个)数组元素。跑步:
alert('pax.diablo'.split('.')[0]);
alert('pax.diablo'.split('.')[1]);
on the other hand will give you two alerts, one for paxand one for diablo.
另一方面会给你两个警报,一个 forpax和一个 for diablo。

