字符串分割返回有两个元素,而不是一个数组 [英] String split returns an array with two elements instead of one

查看:147
本文介绍了字符串分割返回有两个元素,而不是一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白这种行为:

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

但我得到这样的:

but I get this:

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 works?

有另一种方式来做到这一点?

Is there another way to do this?

推荐答案

这是正确的和预期的行为。既然你已经包含字符串中的分离,分割功能(简体)主罚部分的分隔符左侧(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.

如果你真的好奇拆分()是如何工作的,你可以检查出148和ECMA规范的149(ECMA 262)的<一个页面href=\"http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf\">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天全站免登陆