【问题标题】:substring doesn't seem to be working子字符串似乎不起作用
【发布时间】:2014-09-27 05:56:55
【问题描述】:
getProductType = function (product) {
    var productType = '';
    if (product.standardVariable) {
        productType += 'Standard Variable, ';
    }
    if (product.basic) {
        productType += 'Basic, ';
    }
    if (product.intro) {
        productType += 'Intro, ';
    }
    if (product.fixed) {
        productType += 'Fixed, ';
    }
    if (product.equity) {
        productType += 'Equity';
    } else {
        alert(productType);
        productType.substring(0, productType.length - 2);
        alert(productType);
    }
    return productType;
};

我的测试用例是 product.fixed = true,其他都是 false。

为什么我的两个警报都打印出“已修复”?为什么子字符串不起作用?

【问题讨论】:

    标签: javascript string substring


    【解决方案1】:

    尝试将值赋给变量,因为 substring 返回一个新字符串。

    var newstr = productType.substring(0, productType.length - 2);
    alert(newstr);
    

    【讨论】:

    • +1, substring 从原始字符串中创建一个副本,而不是修改
    【解决方案2】:

    字符串在 JavaScript 中是不可变的。此外,.substring 返回一个新字符串。您需要将子字符串的结果分配给一个变量。您可以为此重用 productType,所以这应该可以完成工作:

    productType = productType.substring(0, productType.length - 2);
    

    【讨论】:

      猜你喜欢
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多