简体   繁体   English

String split 返回一个元素比预期多的数组(空元素)

[英]String split returns an array with more elements than expected (empty elements)

I don't understand this behaviour:我不明白这种行为:

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

I expect this:我期待这个:

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 work? split如何工作的?

Is there another way to do this?有没有另一种方法可以做到这一点?

You could add a filter to exclude the empty string.您可以添加一个过滤器来排除空字符串。

var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(function(el) {return el.length != 0});

一个稍微简单的@xdazz 版本,用于排除空字符串(使用ES6 箭头函数):

var array = string.split('.').filter(x => x);

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 函数(简化)将分隔符左侧的部分 ("a,b,c,d,e:10") 作为第一个元素,并将部分作为其余的分隔符(一个空字符串)作为第二个元素。

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如果您真的对 split() 的工作原理感到好奇,您可以在http://www.ecma-international.org/publications/files/ECMA-ST/ 查看ECMA 规范 (ECMA 262) 的第 148 页和第 149 页Ecma-262.pdf

Use String.split() method with Array.filter() method.String.split()方法与Array.filter()方法一起使用。

 var string = 'a,b,c,d,e:10.'; var array = string.split ('.').filter(item => item); console.log(array); // [a,b,c,d,e:10] console.log (array.length); // 1

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split

trim the trailing period first首先修剪尾随期

'a,b,c,d,e:10.'.replace(/\.$/g,''); // gives "a,b,c,d,e:10"

then split the string然后拆分字符串

var array = 'a,b,c,d,e:10.'.replace(/\.$/g,'').split('.');

console.log (array.length); console.log (array.length); // 1 // 1

That's because the string ends with the .那是因为字符串以. character - the second item of the array is empty.字符 - 数组的第二项为空。

If the string won't contain .如果字符串不包含. at all, you will have the desired one item array.总而言之,您将拥有所需的一项数组。

The split() method works like this as far as I can explain in simple words: split()方法的工作原理是这样的,我可以用简单的话解释一下:

  1. Look for the given string to split by in the given string.在给定的字符串中查找要拆分的给定字符串。 If not found, return one item array with the whole string.如果未找到,则返回一个包含整个字符串的项目数组。
  2. If found, iterate over the given string taking the characters between each two occurrences of the string to split by.如果找到,则迭代给定的字符串,取字符串的每两次出现之间的字符进行拆分。
  3. In case the given string starts with the string to split by, the first item of the result array will be empty.如果给定的字符串以要拆分的字符串开头,则结果数组的第一项将为空。
  4. In case the given string ends with the string to split by, the last item of the result array will be empty.如果给定的字符串以要拆分的字符串结尾,则结果数组的最后一项将为空。

It's explained more technically here , it's pretty much the same for all browsers. 这里有更技术性的解释,所有浏览器几乎都一样。

so; 所以; [String.prototype] split(separator, limit) return to the normal limit parameter is empty. [String.prototype] split(separator, limit)返回正常limit参数为空。

"".split(",") // [""]

"a,b,c.".split(".", 1) // ["a,b,c"]

If you could not have done this too, without limit parameter. 如果你不能这样做,没有限制参数。 I think this is a normal operation... 我认为这是正常的操作......

According to MDN web docs :根据MDN 网络文档

Note: When the string is empty, split() returns an array containing one empty string, rather than an empty array.注意:当字符串为空时,split() 返回一个包含一个空字符串的数组,而不是一个空数组。 If the string and separator are both empty strings, an empty array is returned.如果字符串和分隔符都是空字符串,则返回一个空数组。

const myString = '';
const splits = myString.split();

console.log(splits); 

// ↪ [""]

Well, split does what it is made to do, it splits your string.好吧, split 做了它应该做的事情,它分裂了你的字符串。 Just that the second part of the split is empty.只是拆分的第二部分是空的。

Because your string is composed of 2 part :因为您的字符串由两部分组成:

1 : a,b,c,d,e:10 1 : a,b,c,d,e:10

2 : empty 2:空

If you try without the dot at the end :如果你尝试在最后不加点:

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

output is :输出是:

["a,b,c:10"]

You have a string with one "."您有一个带有“.”的字符串。 in it and when you use string.split('.') you receive array containing first element with the string content before "."在其中,当您使用 string.split('.') 时,您会收到包含第一个元素的数组,该元素的字符串内容在 "." 之前。 character and the second element with the content of the string after the "."字符和字符串内容在“.”之后的第二个元素。 - which is in this case empty string. - 在这种情况下是空字符串。

So, this behavior is normal.所以,这种行为是正常的。 What did you want to achieve by using this string.split?你想通过使用这个 string.split 来实现什么?

try this试试这个

javascript gives two arrays by split function, then javascript通过split函数给出两个数组,然后

var Val = "abc@gmail.com";
var mail = Val.split('@');

if(mail[0] && mail[1])  {   alert('valid'); }
else    {   alert('Enter valid email id');  valid=0;    }

if both array contains length greater than 0 then condition will true如果两个数组的长度都大于 0,则条件为真

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM