String split 返回一个元素比预期多的数组(空元素) [英] String split returns an array with more elements than expected (empty elements)

查看:54
本文介绍了String split 返回一个元素比预期多的数组(空元素)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白这种行为:

var string = 'a,b,c,d,e:10.';
var array = string.split ('.');

我希望:

console.log (array); // ['a,b,c,d,e:10']
console.log (array.length); // 1

但我明白了:

console.log (array); // ['a,b,c,d,e:10', '']
console.log (array.length); // 2

为什么返回两个元素而不是一个?split 是如何工作的?

Why two elements are returned instead of one? How does split work?

还有其他方法可以做到这一点吗?

Is there another way to do this?

推荐答案

这是正确且预期的行为.鉴于您已在字符串中包含分隔符,split 函数(简化)将分隔符左侧的部分(a,b,c,d,e:10")作为第一个元素,并将部分作为分隔符的其余部分(空字符串)作为第二个元素.

This is the correct and expected behavior. Given that you've included the separator in the string, the split function (simplified) takes the part to the left of the separator ("a,b,c,d,e:10") as the first element and the part to the rest of the separator (an empty string) as the second element.

如果您真的对 split() 的工作原理感到好奇,可以在 http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

If you're really curious about how split() works, you can check out pages 148 and 149 of the ECMA spec (ECMA 262) at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

这篇关于String split 返回一个元素比预期多的数组(空元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆