繁体   English   中英

子字符串似乎不起作用

[英]substring doesn't seem to be working

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。

为什么我的两个警报都打印“固定”? 为什么子字符串不起作用?

尝试将值关联到变量,因为substring返回一个新字符串。

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

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

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

暂无
暂无

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

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