【问题标题】:Why does String.prototype.split return the full string为什么 String.prototype.split 返回完整的字符串
【发布时间】:2016-03-13 22:49:49
【问题描述】:

为什么String.prototype.split在被分割的字符串是串联的情况下返回完整的字符串?

// Single line
var x = "foo,bar,boo,far".split(",");

// Concatenation
var y = "foo,bar," + 
          "boo,far".split(",");

// Output
document.write("<pre>");
document.write(x + " :" + typeof x + "\n");
document.write(y + " :" + typeof y + "\n");
document.write("</pre>");

在我的实际代码中,字符串很长,并在最后以.split(",") 连接多行。

那么为什么这会产生完整的字符串而不是预期的数组呢?

【问题讨论】:

    标签: javascript string split concatenation


    【解决方案1】:

    事实证明,问题是运算符优先级之一。没关系,它是在不同的行上。重要的是.() 的优先级高于+,因此.split() 仅在最后一个块上执行。

    所以分手后发生的事情是这样的:

    var y = "foo,bar," + ["boo", "far"];
    

    由于数组被转换为字符串,并且因为默认的.toString() 只是使用, 连接数组,所以我们最终得到以下结果:

    var y = "foo,bar," + "boo,far";
    

    导致看起来像原始字符串。

    添加括号解决了这个问题。

    var y = ("foo,bar," + 
              "boo,far").split(",");
    

    【讨论】:

    • 就是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多