平均,最低和最高温度 - JavaScript

时间:2017-10-08 01:55:44

标签: javascript performance debugging

此计算器旨在接受用户输入,以计算和报告平均温度。我已经完成了大部分工作,但是我遇到了一个问题,其中低温的数字位数与高位不同,例如:9和10或95和110,脚本是重视低于高温的低温。在neath下面是我正在使用的javascript。不幸的是我还没有添加屏幕截图,但是在输入9和10的高点时输出响应是:

请输入低于高温的低温。

(function(){
var temperatures = [];
var lowest = 150;
var highest = 0;
var lowestDate;
var highestDate;
var lAverage = 0;
var hAverage = 0;

var table = $('table');

function addTemps() {
    'use strict';
    var table = "<table><tr><th style='width:110px'>Date</th><th>Low Temperature</th><th>High Temperature</th></tr>";
    var lTemp = $('lTemp').value;
    var hTemp = $('hTemp').value;
    if (((parseFloat(lTemp) != parseInt(lTemp, 10)) || isNaN(lTemp) ||
    (parseFloat(hTemp) != parseInt(hTemp, 10)) || isNaN(hTemp)) ||
    (lTemp > 150) || (hTemp < 0) || (lTemp>hTemp)) {
        if ((parseFloat(lTemp) != parseInt(lTemp, 10)) || isNaN(lTemp)){
            table += '<tr><td colspan="3">Please enter a number for low temperature.</td></tr></table>';
        }
        if ((parseFloat(hTemp) != parseInt(hTemp, 10)) || isNaN(hTemp)){
            table += '<tr><td colspan="3">Please enter a number for high temperature.</td></tr></table>';           
        }
        if ((lTemp > 150) || (hTemp < 0)) {
            table += '<tr><td colspan="3">Please enter a number below 150 for low, or a number greater than 0 for high temperature.</td></tr></table>';
        } 
        if (lTemp>hTemp) {
            table += '<tr><td colspan="3">Please enter a low temperature less than the high temperature.</td></tr></table>';            
        }
        $('output').innerHTML = table;          
    }
    else {
        lTemp = parseInt(lTemp);
        hTemp = parseInt(hTemp);
        var newDate = new Date((new Date().getTime())-(temperatures.length * 86400000));
        temperatures.push([newDate,lTemp,hTemp]);
        table = createTable(table);
        $('output').innerHTML = table;          
    }
    return false;
}

function init() {
    'use strict';
    $('theForm').onsubmit = addTemps;
}

function createTable(tbl){
    lAverage=0; hAverage=0;
    for (var i = 0; i<temperatures.length; i++) {
        var date = ''+(temperatures[i][0].getMonth()+1)+"/"+temperatures[i][0].getDate()+"/"+temperatures[i][0].getFullYear();
        var low = temperatures[i][1];
        var high = temperatures[i][2];
        tbl += '<tr><td>'+date+'</td><td style="text-align: right">'+low+'</td><td style="text-align: right">'+high+'</td></tr>';
        if (low < lowest){
            lowest = low;
            lowestDate = date;
        } 
        if (high > highest){
            highest = high;
            highestDate = date; 
        }
        lAverage+=temperatures[i][1];
        hAverage+=temperatures[i][2];
    }
    lAverage=(lAverage/temperatures.length).toFixed(1);
    hAverage=(hAverage/temperatures.length).toFixed(1);
    tbl+='<tr class="summaryRow"><td>Averages</td><td style="text-align: right">'+lAverage+'</td><td style="text-align: right">'+hAverage+'</td></tr>';
    tbl+='<tr class="summaryRow"><td colspan="3">The lowest temperature of '+lowest+' occured on '+lowestDate+'.</tr>';
    tbl+='<tr class="summaryRow"><td colspan="3">The highest temperature of '+highest+' occured on '+highestDate+'.</tr>';
    tbl+='</table>';
    return tbl;
}

function $(elementID){ 
    if (typeof(elementID) == 'string') { 
        return document.getElementById(elementID);
    }
}

window.onload = init;
})();

我假设这是使用parseFloat或parseInt的addTemps函数中的错误,但我仍然坚持要实际修改的内容以避免此问题。

1 个答案:

答案 0 :(得分:0)

以下是一些想法。我无法在repl.it中测试此代码,因此它可能有一些粗糙的边缘 如果我正确理解了这段代码应该做什么..

两个主要问题是:

  1. 您正在将字符串与多个位置的数字进行比较。
  2. 您的addTemps()函数始终返回false - 这是正确的吗?
    我实际上不记得onSubmit是如何工作的,因为我多年没有使用过JQuery或表格 如果我将该部分混淆,请适当调整addTemps的返回值。
  3. 技术上没有错,但您可以使用“便利变量”来缓存计算/转换。它们在JS中基本上是“免费的”。这可以使代码更容易阅读,并且编译器不必继续重复执行相同的计算。
  4. (function(){
    // could avoid "magic numbers" in code with:
    var min_valid_hiTemp = 0;
    var max_valid_loTemp = 150;
    
    // initialize vars
    var temperatures = [];
    var lowest  = 150;    // max_valid_loTemp;
    var highest = 0;      // min_valid_hiTemp;
    var lowestDate  = '';
    var highestDate = '';
    var lAverage = 0;
    var hAverage = 0;
    
    var table = $('table');
    
    function addTemps() {
        'use strict';
    
        var table = "<table><tr><th style='width:110px'>Date</th><th>Low Temperature</th><th>High Temperature</th></tr>";
        var lTemp = $('lTemp').value;
        var hTemp = $('hTemp').value;
    
        // convenience variables
        loTemp_float = parseFloat(lTemp);
        loTemp_int   = parseInt(lTemp, 10);
        hiTemp_float = parseFloat(hTemp);
        hiTemp_int   = parseInt(hTemp, 10);
        loTemp_isNAN = isNaN(lTemp);
        hiTemp_isNAN = isNaN(hTemp);
    
    
        // print error message if input was invalid
        if ( (loTemp_float != loTemp_int) ||
             (hiTemp_float != hiTemp_int) ||
             loTemp_inNaN || hiTemp_isNan ||
             (loTemp_int > hiTemp_int) ||
             (loTemp_int > 150) || 
             (hiTemp_int < 0)
            ){
              if ((loTemp_float != loTemp_int) || loTemp_isNAN){
                  table += '<tr><td colspan="3">Please enter a number for low temperature.</td></tr></table>';
              }
              if ((hiTemp_float != hiTemp_int) || hiTemp_isNAN){
                  table += '<tr><td colspan="3">Please enter a number for high temperature.</td></tr></table>';           
              }
              // uses "magic numbers"
              if ((loTemp_int > 150) || (hiTemp_int < 0)) {
                  table += '<tr><td colspan="3">Please enter a number below 150 for low, or a number greater than 0 for high temperature.</td></tr></table>';
              } 
              if (loTemp_int > hiTemp_int) {
                  table += '<tr><td colspan="3">Please enter a low temperature less than the high temperature.</td></tr></table>';            
              }
    
            // don't call createTable() ?  
            $('output').innerHTML = table;  
    
            // shouldn't this block return false? - To not submit the form
            return false
    
        }
        // input is valid: store the temperature data
        else {
            // not necessary now - we already have variables with this info: loTemp_int, hiTemp_int
            // lTemp = parseInt(lTemp);
            // hTemp = parseInt(hTemp);
    
            //  curious how the number of stored temps is related to the date..? 
            var newDate = new Date((new Date().getTime())-(temperatures.length * 86400000));
    
            // just use the variables we already have
            //temperatures.push([newDate, lTemp, hTemp]);
            temperatures.push([newDate, loTemp_int, hiTemp_int]);
    
            table = createTable(table);
            $('output').innerHTML = table; 
    
            // shouldn't this block return true? - To submit the form
            return true
        }
    
        // ?? No matter what, return false?
        // I suspect you want to return false if input was invalid, and true if it was valid.
        // if so, the return values should be inside the "if" and the "else" blocks.
        // Not outside both blocks, as it is here.
        //return false;
    }
    
    function init() {
        'use strict';
        $('theForm').onsubmit = addTemps;
    }
    
    function createTable(tbl){
        lAverage=0; 
        hAverage=0;
    
        for (var i = 0; i<temperatures.length; i++) {
    
            var date = ''+(temperatures[i][0].getMonth()+1)+"/"+temperatures[i][0].getDate()+"/"+temperatures[i][0].getFullYear();
            var low  = temperatures[i][1];
            var high = temperatures[i][2];
    
            tbl += '<tr><td>'+date+'</td><td style="text-align: right">'+low+'</td><td style="text-align: right">'+high+'</td></tr>';
    
            if (low < lowest){
                lowest = low;
                lowestDate = date;
            } 
            if (high > highest){
                highest = high;
                highestDate = date; 
            }
    
            // you already have variables "low" and "high" - may as well use them
            // lAverage+=temperatures[i][1];
            // hAverage+=temperatures[i][2];
            lAverage += low;
            hAverage += high;
        }
    
        lAverage=(lAverage/temperatures.length).toFixed(1);
        hAverage=(hAverage/temperatures.length).toFixed(1);
    
        tbl+='<tr class="summaryRow"><td>Averages</td><td style="text-align: right">'+lAverage+'</td><td style="text-align: right">'+hAverage+'</td></tr>';
        tbl+='<tr class="summaryRow"><td colspan="3">The lowest temperature of '+lowest+' occured on '+lowestDate+'.</tr>';
        tbl+='<tr class="summaryRow"><td colspan="3">The highest temperature of '+highest+' occured on '+highestDate+'.</tr>';
        tbl+='</table>';
    
        return tbl;
    }
    
    function $(elementID){ 
        if (typeof(elementID) == 'string') { 
            return document.getElementById(elementID);
        }
    }
    
    window.onload = init;
    })();
    

    我实际上不记得onSubmit是如何工作的,因为我多年没有使用过JQuery或表格。
    如果我将该部分混淆了,请适当调整addTemps的返回值。

    这是一个repl version,它还纠正了上述代码中存在的几个拼写错误 注意:除非您使用y以外的其他内容回复“添加另一个临时”提示,否则不会显示任何“打印”语句。因此部分功能并不完美,但是你可以看到逻辑的主要粘点已被正确解决。

    // could avoid "magic numbers" in code with:
    var min_valid_hiTemp = 0;
    var max_valid_loTemp = 150;
    
    // initialize vars
    var temperatures = [];
    var lowest  = 150;    // max_valid_loTemp;
    var highest = 0;      // min_valid_hiTemp;
    var lowestDate  = '';
    var highestDate = '';
    var lAverage = 0;
    var hAverage = 0;
    
    // var table = $('table');
    // non html version
    var table = 'table\n';
    
    function addTemps() {
        'use strict';
    
        var table = 'Date' + '        ' + 'Low Temperature' + '         ' + 'High Temperature' + '\n';
    
        // var lTemp = $('lTemp').value;
        // var hTemp = $('hTemp').value;
    
        // non html version:
        var lTemp = prompt('enter low temp');
        var hTemp = prompt('enter high temp');
    
        // convenience variables
        var loTemp_float = parseFloat(lTemp);
        var loTemp_int   = parseInt(lTemp, 10);
        var hiTemp_float = parseFloat(hTemp);
        var hiTemp_int   = parseInt(hTemp, 10);
        var loTemp_isNAN = isNaN(lTemp);
        var hiTemp_isNAN = isNaN(hTemp);
    
    
        // print error message if input was invalid
        if ( (loTemp_float != loTemp_int) ||
             (hiTemp_float != hiTemp_int) ||
             loTemp_isNAN || hiTemp_isNAN ||
             (loTemp_int > hiTemp_int) ||
             (loTemp_int > 150) || 
             (hiTemp_int < 0)
            ){
              if ((loTemp_float != loTemp_int) || loTemp_isNAN){
                  table += 'Please enter a number for low temperature.' + '\n';
    
              }
              if ((hiTemp_float != hiTemp_int) || hiTemp_isNAN){
                  table += 'Please enter a number for high temperature.' + '\n';           
              }
              // uses "magic numbers"
              if ((loTemp_int > 150) || (hiTemp_int < 0)) {
                  table += 'Please enter a number below 150 for low, or a number greater than 0 for high temperature.' + '\n';
              } 
              if (loTemp_int > hiTemp_int) {
                  table += 'Please enter a low temperature less than the high temperature.' + '\n';            
              }
    
            // does't call createTable() ?  
            // $('output').innerHTML = table;
            // without html:
            console.log(table);
            console.log();
    
            // shouldn't this block return false? - To not submit the form
            return false
    
        }
        // input is valid: store the temperature data
        else {
    
            //  curious how the number of stored temps is related to the date..? 
            var newDate = new Date((new Date().getTime()) - (temperatures.length * 86400000));
    
            temperatures.push([newDate, loTemp_int, hiTemp_int]);
    
            table = createTable(table);
            //$('output').innerHTML = table; 
            // non html version
            console.log(table);
            console.log();
    
            // shouldn't this block return true? - To submit the form
            return true
        }
    
        // ?? No matter what, return false?
        // I suspect you want to return false if input was invalid, and true if it was valid.
        // if so, the return values should be inside the "if" and the "else" blocks.
        // Not outside both blocks, as it is here.
        //return false;
    }
    
    function init() {
        'use strict';
    
        //$('theForm').onsubmit = addTemps;
    
        // non html / jquery version
        if (addTemps()){
            console.log("submitted");
        }
        else {
            console.log('not submitted');
        }
    }
    
    function createTable(tbl){
        lAverage=0; 
        hAverage=0;
    
        for (var i = 0; i< temperatures.length; i++) {
    
            var date = '' + (temperatures[i][0].getMonth()+1) + 
                       "/" + temperatures[i][0].getDate() + 
                       "/" + temperatures[i][0].getFullYear();
            var low  = temperatures[i][1];
            var high = temperatures[i][2];
    
    
            tbl += date + '\t' + low + '\t\t\t' + high + '\n';
    
            if (low < lowest){
                lowest = low;
                lowestDate = date;
            } 
            if (high > highest){
                highest = high;
                highestDate = date; 
            }
    
            lAverage += low;
            hAverage += high;
        }
    
        lAverage = (lAverage/temperatures.length).toFixed(1);
        hAverage = (hAverage/temperatures.length).toFixed(1);
    
        tbl += 'Averages' + '\t' + lAverage + ' low, ' + '\t\t' + hAverage + ' high' + '\n';
        tbl += 'The lowest temperature of  ' + lowest   + ' occured on ' + lowestDate +'.\n';
        tbl += 'The highest temperature of ' + highest  + ' occured on ' + highestDate+'.\n';
        tbl += '\n';
    
        return tbl;
    }
    
    
    // window.onload = init;
    
    var addAnother = 'y'
    while (addAnother == 'y') {
      init();
      addAnother = prompt('press "y" to add another');
    }