简体   繁体   English

单个字符上的 Split() 函数返回一个包含 2 个空字符串的数组?

[英]Split() function on a single character returns an array with 2 empty strings?

I am calling split() on a (dynamic/user input based) string and performing an operation on each element in the returned array.我在(基于动态/用户输入的)字符串上调用split()并对返回的数组中的每个元素执行操作。 Occasionally I will have a string with only a single character ('/') and this has produced some unexpected results (to me at least).有时我会有一个只有一个字符 ('/') 的字符串,这会产生一些意想不到的结果(至少对我来说)。

If I call this:如果我这样称呼:

var randomString = '/';
var splitString = randomString.split('/');

splitString returns a value of ["", ""] . splitString返回值["", ""] I expected to receive just [""] .我希望只收到[""]

Is there a reason I am getting 2 empty strings in the returned array?我在返回的数组中得到 2 个空字符串是否有原因? I couldn't find any documentation or examples of why this is happening.我找不到任何文档或示例说明为什么会发生这种情况。 Additionally, if I want to receive just a single empty string in this example, what would be the best way?另外,如果我想在这个例子中只接收一个空字符串,最好的方法是什么? Just remove the last empty string?只是删除最后一个空字符串?

Thanks谢谢

Is there a reason I am getting 2 empty strings in the returned array?我在返回的数组中得到 2 个空字符串是否有原因?

The string is split at '/' , so the .split() returns whatever is before and after the '/' .字符串在'/'处拆分,因此 .split() 返回'/'之前和之后的任何内容。

If the string were var randomString = 'Joe/Bill' then it would return ["Joe", "Bill"] .如果字符串是var randomString = 'Joe/Bill'那么它会返回["Joe", "Bill"]

In your case, there are no characters before or after the split, so you get ["", ""] .在您的情况下,拆分之前或之后没有任何字符,因此您会得到["", ""]

As Oussail said, if you then add .filter(Boolean) then it will remove all empty strings, leaving you with an empty array [] .正如 Oussail 所说,如果你再添加.filter(Boolean)那么它会删除所有空字符串,留下一个空数组[]

( .filter(Boolean) will remove any empty strings from the array, see here: https://stackoverflow.com/a/54623591/12825520 ) .filter(Boolean)将从数组中删除任何空字符串,请参见此处: https : .filter(Boolean)

You could then check for this with:然后你可以检查这个:

var randomString = '/';
var splitString = randomString.split('/');

// Remove any empty strings from the results
splitString = splitString.filter(Boolean);

if (splitString.length === 0) {
   // do something here
   //
   // This might be a special case so you might
   // want to handle it in a specific way
}

To figure out why the method does what it does, a good strategy is to think about how it's implemented.要弄清楚该方法为什么会这样做,一个好的策略是考虑它是如何实现的。

I don't know the native implementation of the split() method for JS, but it occurs to me that the algorithm traverses the string looking for the passed separator, stores the left portion of the string and then continues until done.我不知道 JS 的split()方法的本机实现,但我突然想到该算法遍历字符串寻找传递的分隔符,存储字符串的左侧部分,然后继续直到完成。

This is a rudimentary version of a split function, with the condition that it matches a single character separator:这是 split 函数的基本版本,条件是它匹配单个字符分隔符:

    function split(string, separator) {
      let substring = '';
      const results = [];
      // Iterate over the characters of the string
      for (let index = 0; index < string.length; index++) {
        const character = string[index];
        // Check if we found the separator
        if (character === separator) {
          // Save the current stored substring
          results.push(substring);
          // Set the new substring as empty
          substring = '';
        } else {
          // Add the character to the substring
          substring += character;
        }
      }
      results.push(substring);
      return results;
    }

Obviously the String.prototype.split() method is not implemented like this, but I think it should follow the same logic (having care to consider more complex separators, such as words or regexes).显然String.prototype.split()方法不是这样实现的,但我认为它应该遵循相同的逻辑(注意考虑更复杂的分隔符,例如单词或正则表达式)。

I hope this clarifies why the returned result is 2 empty strings (in your case), because:我希望这可以澄清为什么返回的结果是 2 个空字符串(在您的情况下),因为:

  • The substring starts by default as an empty string ( "" ) substring默认以空字符串 ( "" ) 开头
  • After finding the separator , the substring (which is an empty string) is saved to the results array and then set to an empty string again.找到separator ,将substring (空字符串)保存到results数组中,然后再次设置为空字符串。
  • Finally, after checking the whole string (in this case the only 1 character "/" ), the remaining substring (also an empty string) is saved to the results .最后,在检查整个string (在这种情况下只有 1 个字符"/" )之后,剩余的substring (也是一个空字符串)被保存到results

NOTE: split() is not restricted to a two element array, and potentially can return an array the same length of the original string (for example, when calling it with an empty string separator).注意: split()不限于两个元素的数组,并且有可能返回与原始字符串长度相同的数组(例如,使用空字符串分隔符调用它时)。

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

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