Javascript 关于从输出中隐藏文本字符串的代码的几个问题

Javascript 关于从输出中隐藏文本字符串的代码的几个问题,javascript,loops,for-loop,if-statement,Javascript,Loops,For Loop,If Statement,您好,我开始学习JavaScript,昨天我要求帮助我从输出中隐藏数组的NaN字符串。有些人帮了我。。但我有新问题 对于此代码 if(typeof(degFahren[loopCounter])==“string”)继续 那里发生了什么事?正如我所看到的,若degFahren等于文本字符串,那个么脚本将继续运行,但它以另一种方式工作,并处理输出的数字 对于此代码 if(parseInt(degFahren[loopCounter])!=“NaN”) 它根本不隐藏字符串。显示数组中的所有字符串。

您好,我开始学习JavaScript,昨天我要求帮助我从输出中隐藏数组的NaN字符串。有些人帮了我。。但我有新问题

  • 对于此代码

    if(typeof(degFahren[loopCounter])==“string”)继续

  • 那里发生了什么事?正如我所看到的,若degFahren等于文本字符串,那个么脚本将继续运行,但它以另一种方式工作,并处理输出的数字

  • 对于此代码

    if(parseInt(degFahren[loopCounter])!=“NaN”)

  • 它根本不隐藏字符串。显示数组中的所有字符串。为什么?

    这里是一段不起作用的代码

    for (loopCounter = 0; loopCounter <=6; loopCounter++){   
    
       if (parseInt(degFahren[loopCounter]) != "NaN") 
    
       degCent[loopCounter] = convertToCentigrade(degFahren[loopCounter]);
       document.write ("Value " + loopCounter + " was " + degFahren[loopCounter] + " degrees Fahrenheit");
       document.write (" which is " + degCent[loopCounter] +  " degrees centigrade<br />");
    
      }
    

    for(loopCounter=0;loopCounter您的假设是正确的,但是代码失败了,因为您错过了大括号。您应该在
    if
    条件之后添加大括号

    for (loopCounter = 0; loopCounter <=6; loopCounter++){   
    
       if (parseInt(degFahren[loopCounter]) != "NaN") {
    
           degCent[loopCounter] = convertToCentigrade(degFahren[loopCounter]);
           document.write ("Value " + loopCounter + " was " + degFahren[loopCounter] + " degrees Fahrenheit");
           document.write (" which is " + degCent[loopCounter] +  " degrees centigrade<br />");
       }
    
    }
    
    for(loopCounter=0;loopCounter
    正如我所看到的,若degFahren等于文本字符串,脚本将继续执行

    degFahren
    显然应该是一个数组。它不测试
    degFahren
    是否为字符串,而是测试正在迭代的当前元素(位于数组内部)是否为字符串

    它根本不隐藏NaN字符串。显示数组中的所有字符串。为什么

    NaN不是字符串;它是一个基本值。但是NaN!==NaN;您应该改用isNaN()函数

    您还应避免隐式创建全局变量。如果您提取温度,而不是混淆标记,则更易于阅读:

    for (loopCounter = 0; loopCounter <=6; loopCounter++){
      const tempF = degFahren[loopCounter];
      if (isNaN(tempF)) continue;
      const tempCentigrade = convertToCentigrade(tempF);
      document.write ("Value " + loopCounter + " was " + tempF + " degrees Fahrenheit");
      document.write (" which is " + tempCentigrade +  " degrees centigrade<br />");
    }
    
    for(loopCounter=0;loopCounter