在这段 JavaScript 代码中,如果变量 data
没有那个字符 .
那么 split 会返回什么?
x = data.split('.');
它会是原始字符串的数组吗?
最佳答案
是的,根据 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.
如果您不喜欢这样推断,可以按照底部相当多的步骤进行操作,您会看到它的作用。
测试它,如果你输入代码:
alert('paxdiablo'.split('.')[0]);
您会看到它输出 paxdiablo
,这是第一个(也是唯一的)数组元素。运行:
alert('pax.diablo'.split('.')[0]);
alert('pax.diablo'.split('.')[1]);
另一方面会给你两个警报,一个是pax
,一个是diablo
。
关于javascript - 如果字符串不匹配,.split() 返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27688120/