简体   繁体   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;
};

My test case is that product.fixed = true, everything else is false. 我的测试用例是product.fixed = true,其他所有东西都是false。

Why is it that both my alerts print out 'Fixed, '? 为什么我的两个警报都打印“固定”? Why is substring not working? 为什么子字符串不起作用?

try Assinging the value to variable because,substring returns a new string. 尝试将值关联到变量,因为substring返回一个新字符串。

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

Strings are immutable in JavaScript. 字符串在JavaScript中是不可变的。 Also, .substring returns a new string. 此外, .substring返回一个新字符串。 You'll need to assign the results of the substring to a variable. 您需要将子字符串的结果分配给变量。 You can reuse productType for this, so this should do the job: 您可以为此重复使用productType,因此应该可以完成以下工作:

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

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

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