字符串拆分返回一个数组,该数组包含比预期多的元素(空元素) [英] String split returns an array with more elements than expected (empty elements)

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

问题描述

我不了解这种行为:

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

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

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

还有另一种方法吗?

推荐答案

这是正确的预期行为.假设您已在字符串中包含分隔符,则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

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

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