【问题标题】:Split() function on a single character returns an array with 2 empty strings?单个字符上的 Split() 函数返回一个包含 2 个空字符串的数组?
【发布时间】:2020-02-12 23:43:29
【问题描述】:

我在(基于动态/用户输入的)字符串上调用split(),并对返回数组中的每个元素执行操作。有时我会得到一个只有一个字符('/')的字符串,这会产生一些意想不到的结果(至少对我来说)。

如果我这样称呼:

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

splitString 返回值["", ""]。我预计只会收到[""]

我在返回的数组中得到 2 个空字符串是否有原因?我找不到任何文档或示例说明为什么会发生这种情况。另外,如果我想在这个例子中只接收一个空字符串,最好的方法是什么?只删除最后一个空字符串?

谢谢

【问题讨论】:

  • 在/之前是一个空字符串,在/之后是一个空字符串我想这就是为什么
  • 是的,split 返回一个包含 2 个元素的数组(1 个在拆分字符之前,1 个在之后)。你想在这里做什么?至于为什么要使用拆分?
  • 在 Python 中也会发生同样的事情。你基本上是把绳子切成两半。由于只有一个元素开头,因此您会得到两个空字符串。
  • @GlenK 谢谢,我想这是有道理的。我正在使用窗口路径 (window.location.path) 并生成面包屑 UI。内容本身是基于路径的动态
  • split(needle) 如果没有找到 needle 将返回一个字符串,并为它找到的每个针返回每个附加字符串。因此,如果找到一根针,它将返回 2 个字符串,找到 2 个针返回 3 个字符串,依此类推。我在这里得到你想要完成的事情。为什么你期望得到一个空字符串?

标签: javascript string split


【解决方案1】:

我在返回的数组中得到 2 个空字符串是否有原因?

字符串在'/' 处拆分,因此.split() 返回'/' 之前和之后的任何内容。

如果字符串是var randomString = 'Joe/Bill',那么它将返回["Joe", "Bill"]

在您的情况下,拆分前后没有字符,因此您得到["", ""]

正如 Oussail 所说,如果您随后添加 .filter(Boolean),那么它将删除所有空字符串,留下一个空数组 []

.filter(Boolean) 将从数组中删除所有空字符串,请参见此处:https://stackoverflow.com/a/54623591/12825520

然后您可以通过以下方式检查:

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
}

【讨论】:

    【解决方案2】:

    要弄清楚该方法为什么会这样做,一个好的策略是考虑它是如何实现的。

    我不知道 JS 的 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;
        }
    

    显然String.prototype.split() 方法不是这样实现的,但我认为它应该遵循相同的逻辑(注意考虑更复杂的分隔符,例如单词或正则表达式)。

    我希望这能澄清为什么返回的结果是 2 个空字符串(在你的情况下),因为:

    • substring 默认以空字符串开头 ("")
    • 找到separator后,substring(为空字符串)被保存到results数组中,然后再次设置为空字符串。
    • 最后,在检查了整个string(在这种情况下只有1个字符"/")之后,剩余的substring(也是一个空字符串)被保存到results

    注意:split() 不限于两个元素数组,并且可能返回与原始字符串长度相同的数组(例如,使用空字符串分隔符调用它时)。

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 2011-09-04
      • 2015-02-20
      • 2012-03-30
      相关资源
      最近更新 更多