如何测试变量在JavaScript中是否具有值? [英] How can I test whether a variable has a value in JavaScript?
问题描述
我想测试一个JavaScript变量是否有值。
I want to test whether a JavaScript variable has a value.
var splitarr = mystring.split( " " );
aparam = splitarr [0]
anotherparam = splitarr [1]
//.... etc
但是字符串可能没有足够的条目,所以稍后我想测试它。
However the string might not have enough entries so later I want to test it.
if ( anotherparm /* contains a value */ )
我该怎么做?
推荐答案
一般来说,这是一个灰色地带......你的意思是有价值?值 null
和 undefined
是您可以分配给变量的合法值...
In general it's sort of a gray area... what do you mean by "has a value"? The values null
and undefined
are legitimate values you can assign to a variable...
String函数 split()
总是返回一个数组,所以使用 length
属性找出哪些指数存在的结果。超出范围的指数将具有未定义
的值。
The String function split()
always returns an array so use the length
property of the result to figure out which indices are present. Indices out of range will have the value undefined
.
但技术上(在 String.split()
)你可以这样做:
But technically (outside the context of String.split()
) you could do this:
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
这篇关于如何测试变量在JavaScript中是否具有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!