简体   繁体   English

如何检测JS变量是否未定义?

[英]How to detect if a JS variable is undefined?

// mystring contains dynamic text. Sometimes can be
// null
var a = mystring.split(" ");
var proc = a[0] + " " + a[1];

If a does not contain text, after split proc is undefined. 如果a不包含文本,则在split proc后未定义。 If I try to assing its value to a textbox the result is "undefined": 如果我尝试将其值赋给文本框,则结果为“未定义”:

mytextbox.val(proc);

在此处输入图片说明

So I need a way to make that proc has always a value, at least an empty string. 因此,我需要一种使proc始终具有值,至少为空字符串的方法。

You can just use 你可以用

(mystring || " ")

which will evaluate to mystring if it is not null , or " " if it is. 如果不为null ,则结果为mystring否则为" "

Or, you can just put an if statement around the whole thing: 或者,您可以在整个事情上放一个if语句:

if (mystring != null) {
    // stuff
} else {
    var proc = "";
}
var proc = "";
if (mystring !== null) { // omit this if you're sure it's a string
    var a = mystring.split(" ");
    if (a.length > 1) {
        proc = a[0] + " " + a[1];
    }
}

I'm quite sure your proc is not undefined , but the string " undefined" . 我非常确定您的proc不是undefined ,而是字符串" undefined"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM