如何正确检查两个条件?

时间:2019-09-07 11:55:19

标签: javascript loops conditional-statements

我正在处理家庭作业问题。 我希望调用此函数: numberConverter([1,2,3,'4','5',{},33])

返回此字符串:“ 2已转换为数字:4,5; 1无法转换”

这意味着该功能: -遍历数组 -计算所有可以转换为数字的字符串 -将这些实例推送到数组中 -计算所有无法转换为数字的值 -如果所有值都是数字,则返回“无需转换”

当我运行我的代码时,它返回: “ 1转换为数字:NaN; 0不能转换”

我在调试器中浏览了代码,但并没有将“ 4”和“ 5”保留为可以转换为数字的字符串。

为什么?

我的尝试

function numberConverter(arr) {
    var countConverted = 0;
    var converted = [];
    var countNotConverted = 0;
    var countNumbers = 0;

    for (var x of arr) {
        if (isNaN(x) == true && typeof parseInt(x)=="number") {
            converted.push(parseInt(x));
            countConverted++
        } else if (isNaN(x) == true && typeof parseInt(x)!="number") {
            countNotConverted++
        } else if (isNaN(x) == false) {
            countNumbers++
        }
    }

    if (arr.length+1 == countNumbers) {
        return `no need for conversion`
    } else {
        return `${countConverted} were converted to numbers: ${converted}; ${countNotConverted} couldn't be converted`
    }
}

正确的代码:

function numberConverter(arr) {

    var converted = []
    var counterConverted = 0
    var counterNotConverted = 0

    for (var c of arr) {

    if(typeof(c) != "number") { 
        if (isNaN(c)) {
            counterNotConverted++;
        } else {
            // c = parseInt(c); done in line 16
            counterConverted++;
            converted.push(parseInt(c))
        }
    }
    }
    if (counterConverted == 0) {
        return "no need for conversion"
    } else {
        //return counterConverted+" were converted to numbers: "+ converted + "; "+counterNotConverted+" couldn't be converted"
        return `${counterConverted} were converted to numbers: ${converted}; ${counterNotConverted} coudln't be converted`
    }
}

编辑-几乎可以更改

function numberConverter(arr) {
    var countConverted = 0;
    var converted = [];
    var countNotConverted = 0;
    var countNumbers = 0;

    for (var x of arr) {
        if (typeof(x) != "number" && typeof parseInt(x)=="number") {
            converted.push(parseInt(x));
            countConverted++
        } else if (typeof(x) != "number" && typeof parseInt(x)!="number") {
            countNotConverted++
        } else if (isNaN(x) == false) {
            countNumbers++
        }
    }

    if (arr.length+1 == countNumbers) {
        return `no need for conversion`
    } else {
        return `${countConverted} were converted to numbers: ${converted}; ${countNotConverted} couldn't be converted`
    }
}

奇怪的是,它像这样NaN来转换,推送和返回{}

“ 3转换为数字:4,5,NaN; 0不能转换”

而不是将其视为无法转换。为什么?快到了!

评论::刚发现parseInt({})的类型为“数字”。

1 个答案:

答案 0 :(得分:1)

您正步入正轨。只需检查三个条件: 第一个条件:是数字吗?

if (typeof(x) === 'number') {
    countNumbers++;
}

第二个条件:可以转换为数字吗?

 else if(!isNaN(x)) {
     countConverted++;
     converted.push(parseInt(x));
 }

最后一个条件:还有什么不能转换

else {
    countNotConverted++;
}

其余的代码很不错... 工作示例:JsFiddle