我如何检查是否一个JavaScript数组值为空或空? [英] How do I check if a JavaScript array value is empty or null?

查看:144
本文介绍了我如何检查是否一个JavaScript数组值为空或空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将这项工作进行测试值在位置指数是否存在,或是否有更好的方式:

 如果(arrayName中的[指数] ==){
     // 做东西
}


解决方案

在Javascript中所有的数组包含 array.length 元素,从数组[ 0] 直到数组[array.length - 1] 。根据定义,索引数组元素 I 据说是数组的一部分,如果 I 是<$ C之间$ C> 0 和 array.length - 1

即,在Javascript阵列是线性的,从零开始并去一个最大值,阵列不具有用于从阵列排除某些值或范围的机构。因此,要找出是否一个值存在在给定位置索引(其中指数为0或正整数),你从字面上只需要使用

 如果(指数&LT; array.length){
  // 做东西
}

然而,它的的可能对某些数组值是null,未定义大,NaN,无穷远,0,或不同值的一大堆。例如,如果你通过增加 array.length 属性添加数组值,任何新的值将是不确定的。从这个问题,我怀疑你想不知道,如果一个给定的值被认为是阵列的一部分,但该值是否是有意义的事,或者已被定义。即,不是未定义,或者,不是未定义或空。

 如果(typeof运算阵列[指数] ==未定义){

 如果(typeof运算数组[索引] =='未定义'和;!&安培;!数组[索引] == NULL){

这取决于你想要达到的目标。

有趣的是,因为JavaScript的比较规则,我的最后一个例子可以优化到:

 如果(阵列[指数]!= NULL){
  //的==和!=运算符考虑空等于只null或undefined

Will this work for testing whether a value at position "index" exists or not, or is there a better way:

if(arrayName[index]==""){
     // do stuff
}

解决方案

All arrays in Javascript contain array.length elements, starting with array[0] up until array[array.length - 1]. By definition, an array element with index i is said to be part of the array if i is between 0 and array.length - 1 inclusive.

That is, arrays in Javascript are linear, starting with zero and going to a maximum, and arrays don't have a mechanism for excluding certain values or ranges from the array. Therefore, to find out if a value exists at a given position index (where index is 0 or a positive integer), you literally just use

if (index < array.length) {
  // do stuff
}

However, it is possible for some array values to be null, undefined, NaN, Infinity, 0, or a whole host of different values. For example, if you add array values by increasing the array.length property, any new values will be undefined. From the question, I suspect you want to know not if a given value is considered part of the array, but whether that value is something meaningful, or has been defined. That is, not "undefined", or perhaps, not "undefined or null".

if (typeof array[index] !== 'undefined') {

or

if (typeof array[index] !== 'undefined' && array[index] !== null) {

It depends on what you're trying to achieve.

Interestingly, because of Javascript's comparison rules, my last example can be optimised down to:

if (array[index] != null) {
  // The == and != operator consider null equal to only null or undefined

这篇关于我如何检查是否一个JavaScript数组值为空或空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆