javascript 变量在初始化后未定义

javascript variable is undefined after Initialized

本文关键字:未定义 初始化 变量 javascript      更新时间:2023-09-26

我有下面的代码,太简单了

var Height = <%= Height %>,
    _height;                       
console.log(Height); // in my test, I got 800
    if(Height > 800){      
        _height = 450;
    }
    else {
       _height = 330;
    }
    console.log(_height); // it will log 'undefined'

错误的部分是什么?

您在(缺少字母)有拼写错误

heigh = 450;

因此,请尝试以下代码:

var Height = <%= Height %>,
        _height;                       
    console.log(Height); // in my test, I got 800
        if(Height > 800){      
            _height = 450;
        }
        else {
           _height = 330;
        }
        console.log(_height);

使用if (parseInt(Height) > 800)而不是简单地检查if(Height > 800)。它工作正常。

Height转换为 int 或 float 然后比较

if(parseInt(Height)>800)

if(parseFloat(Height)>800)