简体   繁体   English

JavaScript字符串indexOf无法正常工作

[英]Javascript String indexOf not working as expected

I must be missing something .. not sure why my JavaScript is failing or not working 我必须缺少一些东西..不确定为什么我的JavaScript失败或无法正常工作

var discount = 10;
var newTemp;

if (discount != null) {
    if (discount.indexOf("%") > -1) {
        newTemp = discount.substring(0, 2) + '%';
    } else {
        newTemp = discount;
    }
 } //end of outer if

Above script works when discount = "10.0%" But fails when discount = 10 上面的脚本在Discount =“ 10.0%”时有效,但在Discount = 10时失败

maynot be best way, but all I am trying to do is if discount value contains % sign then setting newTemp variable with new value. 可能不是最好的方法,但是我要做的就是如果折扣值包含%符号,然后将newTemp变量设置为新值。 Else just keep it as is. 否则,保持原样。

Any idea, why control fails when discount value is = 10 任何想法,为什么折扣值= 10时控制失败

because "10%" is a string, therefore it has a indexOf method, and 10 is probably an integer or number. 因为“ 10%”是字符串,所以它具有indexOf方法,而10可能是整数或数字。

Try discount.toString().indexOf('%') 尝试discount.toString().indexOf('%')

It's because you're not appending the '%' in the else branch. 这是因为您没有在else分支中附加'%'。

var newTemp;
if (discount != null) {
    if (discount.indexOf("%") > -1) {
        newTemp = discount.substring(0, 2);
    } else {
        newTemp = discount;
    }
 } //end of outer if
 newTemp += '%';

also as Hugo said, the number 10 does not have the indexOf method, which is a string method. 也正如Hugo所说,数字10没有indexOf方法,它是字符串方法。

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

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