【问题标题】:Couple of questions about code that hides text strings from output关于从输出中隐藏文本字符串的代码的几个问题
【发布时间】:2018-04-23 03:58:07
【问题描述】:

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

Here the link to answers

  1. 对于这段代码,

    if (typeof(degFahren[loopCounter]) === 'string') continue;

里面发生了什么?如我所见,如果 degFahren 等于文本字符串,脚本将继续执行,但它以另一种方式工作并处理输出数字。

  1. 对于这个代码

    if (parseInt(degFahren[loopCounter]) != "NaN")

它根本不隐藏 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 />");

  }

【问题讨论】:

    标签: javascript loops for-loop if-statement


    【解决方案1】:

    您的假设是正确的,但是代码失败了,因为您错过了大括号。您应该在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 />");
       }
    
    }
    

    【讨论】:

      【解决方案2】:

      我可以看到如果 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 />");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-25
        • 2011-07-24
        • 2020-07-16
        • 2015-04-26
        • 2013-01-24
        相关资源
        最近更新 更多