2014-09-27 93 views
0
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,其他都是錯誤的。子串似乎沒有工作

爲什麼我的警報打印出「固定」?爲什麼子串不工作?

回答

2

嘗試將值賦予變量,因爲substring返回一個新字符串。

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

+1,'substring'創建一個副本** **出原始字符串,不** **修改它 – slezica 2014-09-27 06:01:14

1

字符串在JavaScript中是不可變的。另外,.substring返回一個新的字符串。您需要將子字符串的結果分配給一個變量。您可以重複productType這一點,所以這應該做的工作:

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