代码之家  ›  专栏  ›  技术社区  ›  justintime

如何在JavaScript中测试变量是否有值?

  •  6
  • justintime  · 技术社区  · 17 年前

    var splitarr =  mystring.split( " " );
    aparam = splitarr [0]
    anotherparam = splitarr [1]
    //.... etc
    

    但是字符串可能没有足够的条目,所以稍后我想测试它。

    if ( anotherparm /* contains a value */ )
    

    6 回复  |  直到 17 年前
        1
  •  15
  •   James Curran    17 年前
     if (typeof anotherparm == "undefined")
    
        2
  •  3
  •   James    17 年前

    在JavaScript中,空字符串的计算结果为FALSE,因此您可以执行以下操作:

    if (anotherparam) {...}
    
        3
  •  2
  •   Jason S    17 年前

    null 和 undefined 是可以分配给变量的合法值。。。

    split() 始终返回一个数组,因此使用 length 未定义

    但技术上(在 String.split()

    js>z = ['a','b','c',undefined,null,1,2,3]
    a,b,c,,,1,2,3
    js>typeof z[3]
    undefined
    js>z[3] === undefined
    true
    js>z[3] === null
    false
    js>typeof z[4]
    object
    js>z[4] === undefined
    false
    js>z[4] === null
    true
    
        4
  •  2
  •   JD Isaacks    17 年前

    您可以通过以下方式检查字符串中的字符数:

    var string_length = anotherparm.length;
    
        5
  •  1
  •   Diodeus - James MacFarlane    17 年前

    一个技巧是使用 or true “或” false "

    var splitarr =  mystring.split( " " );
    aparam = splitarr [0]||''
    anotherparam = splitarr [1]||''
    

    这可以防止在变量不存在时抛出错误,并允许您将其设置为默认值或您选择的任何值。

        6
  •  1
  •   Real Red.    17 年前

    上面有这么多答案,你们应该知道如何检查变量的值,这样我就不会重复了。

    但是,您尝试编写的逻辑可能更好地使用不同的方法编写,即通过查看拆分数组的长度,而不是将数组的内容分配给变量,然后进行检查。

    即 if(splitarr.length < 2) 那么显然 anotherparam 肯定是“不包含值”。

    因此,与其这样做,

    if(anotherparam /* contains a value */ )
    {
       //dostuff
    }
    

    if(splitarr.length >= 2)
    {
       //dostuff
    }