如何应对" undefined"和" NaN"在简单的JavaScript计算?

时间:2016-12-06 00:55:23

标签: javascript

所以有两个下拉菜单和一些javascript函数来选择价格并设置一个国家(附带税率)。然后在付款单上显示价格+税率=总额给用户。

如果选择了价格和国家/地区(税率),那么javascript和总和就会起作用:

£49.99 + 10% VAT = £54.99

如果选择了价格但没有选择国家(税率),则会发生这种情况:

Total: £49.99 + undefined% VAT = £NaN

如果没有选择价格或国家(税率),那么我们得到:

£undefined + undefined% VAT = £NaN

所以问题是:我们如何处理来自javascript的丑陋错误?对undefinedNaN if / else处理javascript的方法是什么?

感谢。

更新2: NaN检查有效,但我在哪里放置未定义的检查。添加了TaxPrice功能,以便您可以看到它的来源。

// First grab the tax rate from a drop down

function TaxPrice()
{
var taxprice=0;
var theForm = document.forms["payment-form"];
var selectedrate = theForm.elements["country_vat"];
taxprice = tax_rates[selectedrate.value];
return taxprice;
}

// Then calculate the total, including the NaN checks

function calculateTotal()
{
var TaxRate = TaxPrice() / 100;
var TotalPrice = PlanPrice() + (TaxRate * PlanPrice());
var TotalTax = (TaxRate * PlanPrice())

if(isNaN(TotalPrice)) {
    // check NaN
    TotalPrice = 0
}

if(isNaN(TotalTax)) {
    // check NaN
    TotalTax = 0
}

//display the price
var divobj = document.getElementById('p');
divobj.innerHTML = "£" + PlanPrice();

//display the tax rate
var divobj = document.getElementById('r');
divobj.innerHTML = "£" + TotalTax.toFixed(2) + " (" + TaxPrice() + "% VAT)";

//display the total
var divobj = document.getElementById('t');
divobj.innerHTML = "£" + TotalPrice.toFixed(2);    

}

5 个答案:

答案 0 :(得分:1)

使用

专门检查undefined
if(typeof price === "undefined"){}

使用

专门检查NaN
if(isNaN(price)){} 

通常你也可以简单地做

if(price){}

如果falsepriceNaNundefined,if语句的内部将返回null,但是{{1}或者你可能不想要的空字符串,所以你需要在条件中指定它。

特别是在您的情况下,最好不要在未定义任何部分时执行计算,因为结果只会创建0undefined值:

NaN

然后你不必检查function calculateTotal(){ //first check all you need for the calculation is defined if (typeof TaxPrice() != 'undefined' && typeof PlanPrice() != 'undefined'){ //perform the calculation and output the result }else{ //output an error message or a default ouput } } ,因为那些是由NaN制造算术造成的。

答案 1 :(得分:1)

请将值转换为有限数字,例如:

function toNumber(value) {
    if(typeof  value !== 'number') {
        // covert type to number
        // void 0, null, true, false, 'abc', [], {} => NaN
        // [0] => 0
        value = parseFloat(value)
    }
    if(isNaN(value)) {
        // check NaN
        value = 0
    }
    if(!isFinite(value)) {
        // check Infinity and -Infinity
        value = Number.MAX_SAFE_INTEGER * Math.sign(value)
    }
    return value
}

答案 2 :(得分:0)

制作与此相似的功能

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

# Random data
data = np.random.rand(10, 10)

# Plot data
levels = np.linspace(0., 1., 100)
plot = ax.contourf(data, levels=levels)

# Create colorbar
cbar = plt.colorbar(plot)
cbar_ticks = np.linspace(0., 1., num=6, endpoint=True)
cbar.ax.set_autoscale_on(True)
cbar.set_ticks(cbar_ticks)

plt.show(block=False)

def update():
    global cbar

    cbar.remove()
    fig.clear()

    # Create new data and plot
    new_data   = 2.*np.random.rand(10, 10)
    new_levels = np.linspace(0., 2., 200)
    ax = fig.add_subplot(111)
    plot = ax.contourf(new_data, levels=new_levels )

    cbar = plt.colorbar(plot)
    cbar_ticks = np.linspace(0., 2., num=21, endpoint=True)
    cbar.set_ticks(cbar_ticks)    
    plt.draw()

update()

然后在需要使用可能的未定义值进行计算时使用它。例如

function get_value(input, default_value) {
    return input === undefined || isNaN(input) ? default_value : input;
}

答案 3 :(得分:0)

使用isNaN()函数检查变量是否为NaN。

e.g。见这里:http://www.w3schools.com/jsref/jsref_isnan.asp

您还可以跟踪在其他变量中设置的变量。 ;)

答案 4 :(得分:0)

如果您只想在选择了两个计算时进行计算,那么只需在代码前检查这些错误:

if(typeof (your_price_variable) !== undefined && typeof (your_country_variable) !== undefined)

并使该功能仅在满足此条件时运行。然后输出不会是" NaN。"