子串似乎没有工作
问题描述:
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,其他都是错误的。子串似乎没有工作
为什么我的警报打印出“固定”?为什么子串不工作?
答
尝试将值赋予变量,因为substring返回一个新字符串。
var newstr = productType.substring(0, productType.length - 2);
alert(newstr);
答
字符串在JavaScript中是不可变的。另外,.substring返回一个新的字符串。您需要将子字符串的结果分配给一个变量。您可以重复productType这一点,所以这应该做的工作:
productType = productType.substring(0, productType.length - 2);
+1,'substring'创建一个副本** **出原始字符串,不** **修改它 – slezica 2014-09-27 06:01:14