当页面第一次加载时,我需要检查image_array中是否有图像,并加载最后一张图像。

否则,我禁用预览按钮,提醒用户按新的图像按钮,并创建一个空数组来放置图像;

问题是else中的image_array一直被触发。如果一个数组存在-它只是覆盖它,但警报不工作。

if(image_array.length > 0)
    $('#images').append('<img src="'+image_array[image_array.length-1]+'" class="images" id="1" />');
else{
    $('#prev_image').attr('disabled', 'true');
    $('#next_image').attr('disabled', 'true');
    alert('Please get new image');
    var image_array = [];
}

更新 在加载html之前,我有这样的东西:

<?php if(count($images) != 0): ?>
<script type="text/javascript">
    <?php echo "image_array = ".json_encode($images);?>
</script>
<?php endif; ?>

当你创建image_array时,它是空的,因此你的image_array。长度为0

正如下面的评论所述,我根据这个问题的答案编辑了我的答案):

var image_array = []

在else括号内,不会对前面代码中定义的image_array进行任何更改


你应该使用:

  if (image_array !== undefined && image_array.length > 0)

如果你想测试图像数组变量是否已经定义,你可以这样做

if(typeof image_array === 'undefined') {
    // it is not defined yet
} else if (image_array.length > 0) {
    // you have a greater than zero length array
}

if (typeof image_array !== 'undefined' && image_array.length > 0) {
    // the array is defined and has at least one element
}

您的问题可能是由于混合使用了隐式全局变量和变量提升。确保在声明变量时使用var:

<?php echo "var image_array = ".json_encode($images);?>
// add var  ^^^ here

然后确保以后不会意外地重新声明该变量:

else {
    ...
    image_array = []; // no var here
}

检查数组是否为空

一个现代的方式,ES5+:

if (Array.isArray(array) && array.length) {
    // array exists and is not empty
}

老派方法:

typeof array != "undefined"
    && array != null
    && array.length != null
    && array.length > 0

一种紧凑的方式:

if (typeof array != "undefined" && array != null && array.length != null && array.length > 0) {
    // array exists and is not empty
}

CoffeeScript方式:

if array?.length > 0

Why?

情况下定义 未定义变量是一个你还没有给它赋值的变量。

let array = new Array();     // "array" !== "array"
typeof array == "undefined"; // => true

情况下空 一般来说,null是缺少值的状态。例如,当您错过或未能检索某些数据时,变量为空。

array = searchData();  // can't find anything
array == null;         // => true

Case不是数组 Javascript有一个动态类型系统。这意味着我们不能保证变量持有什么类型的对象。有可能我们不是在与Array的实例对话。

supposedToBeArray =  new SomeObject();
typeof supposedToBeArray.length;       // => "undefined"

array = new Array();
typeof array.length;                   // => "number"

Case空数组 现在,由于我们测试了所有其他可能性,我们正在与Array的一个实例对话。为了确保它不是空的,我们询问它所持有的元素的数量,并确保它的元素大于0。

firstArray = [];
firstArray.length > 0;  // => false

secondArray = [1,2,3];
secondArray.length > 0; // => true

你可以使用jQuery的isEmptyObject()来检查数组是否包含元素。

var testArray=[1,2,3,4,5]; 
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true 

来源:https://api.jquery.com/jQuery.isEmptyObject/


如果你没有一个变量声明为数组,你可以创建一个检查:

if(x && x.constructor==Array && x.length){
   console.log("is array and filed");
}else{
    var x= [];
    console.log('x = empty array');
}

它检查变量x是否存在,如果存在,则检查它是否是一个已填充的数组。否则它会创建一个空数组(或者你可以做其他事情);

如果你确定创建了一个数组变量,有一个简单的检查:

var x = [];

if(!x.length){
    console.log('empty');
} else {
    console.log('full');
}

你可以检查我的提琴这里显示最可能的方法来检查数组。


对我来说,当我把它们放入jsfiddle时,一些高评级的答案“工作”,但当我有一个动态生成的数组列表时,答案中的很多代码对我来说并不工作。

这就是对我有效的方法。

var from = [];

if(typeof from[0] !== undefined) {
  //...
}

注意,在undefined周围没有引号,我没有考虑长度。


(ECMA 5.1)如何:

if(Array.isArray(image_array) && image_array.length){
  // array exists and is not empty
}

你应该这样做

    if (!image_array) {
      // image_array defined but not assigned automatically coerces to false
    } else if (!(0 in image_array)) {
      // empty array
      // doSomething
    }

这就是我用的。第一个条件包含true,它有null和undefined。第二个条件检查空数组。

if(arrayName && arrayName.length > 0){
    //do something.
}

或者感谢tsemer的评论,我添加了第二个版本

if(arrayName && arrayName.length)

然后我在Firefox中使用Scratchpad对第二个条件进行了测试:

var array1; Var array2 = []; Var array3 = ["one", "two", "three"]; Var array4 = null; console.log (array1); console.log (array2); console.log (array3); console.log (array4); If (array1 && array1.length) { console.log(“array1 !有价值!”); } If (array2 && array2.length) { console.log(“array2 !有价值!”); } If (array3 && array3.length) { console.log(“array3 !有价值!”); } If (array4 && array4.length) { console.log(“array4 !有价值!”); }

这也证明了if(array2 && array2.length)和if(array2 && array2.length)长度> 0)完全相同


我在Javascript中遇到过很多这样的问题。对我来说,最好的方法是在检查长度之前进行广泛的检查。我在这个问答中看到了一些其他的解决方案,但我希望能够检查null或未定义或任何其他假值。

if(!array || array.length == 0){
    console.log("Array is either empty or does not exist")
}

这将首先检查未定义、空值或其他假值。如果其中任何一个为真,它将完成布尔值,因为这是一个OR。然后是更危险的数组检查。长度,如果数组是未定义的,可能会出错,可以检查。如果数组未定义或为空,这将永远不会达到,因此条件的顺序非常重要。


使用uncore或lodash:

_isarray (image_array) && ! ipad (image_array)


一个简单的方法,不会导致异常,如果不存在,并转换为布尔值:

!!array

例子:

if (!!arr) {
  // array exists
}

这个怎么样?检查未定义数组的长度可能会抛出异常。

if(image_array){
//array exists
    if(image_array.length){
    //array has length greater than zero
    }
}

JavaScript

( typeof(myArray) !== 'undefined' && Array.isArray(myArray) && myArray.length > 0 )

Lodash & Underscore

( _.isArray(myArray) && myArray.length > 0 )

在ts

 isArray(obj: any) 
{
    return Array.isArray(obj)
  }

在html中

(isArray(photos) && photos. isArray == undefined || !长度> 0))


下面是我的解决方案包装在一个函数,也抛出 错误来管理对象范围和所有类型的几个问题 传递给函数的可能数据类型。

这是我用来研究这个问题的小提琴(来源)

var jill = [0];
var jack;
//"Uncaught ReferenceError: jack is not defined"

//if (typeof jack === 'undefined' || jack === null) {
//if (jack) {
//if (jack in window) {
//if (window.hasOwnP=roperty('jack')){
//if (jack in window){

function isemptyArray (arraynamed){
    //cam also check argument length
  if (arguments.length === 0) { 
    throw "No argument supplied";
  }

  //console.log(arguments.length, "number of arguments found");
  if (typeof arraynamed !== "undefined" && arraynamed !== null) {
      //console.log("found arraynamed has a value");
      if ((arraynamed instanceof Array) === true){
        //console.log("I'm an array");
        if (arraynamed.length === 0) {
            //console.log ("I'm empty");
            return true;
        } else {
          return false;
        }//end length check
      } else {
        //bad type
        throw "Argument is not an array";
      } //end type check
  } else {
    //bad argument
    throw "Argument is invalid, check initialization";;
  }//end argument check
}

try {
  console.log(isemptyArray(jill));
} catch (e) {
    console.log ("error caught:",e);
}

可选的链接

随着可选链接提议达到了第4阶段,并得到了更广泛的支持,有一种非常优雅的方式可以做到这一点

if(image_array?.length){

  // image_array is defined and has at least one element

}

可能你的image_array不是数组,而是一些对象的长度属性(如字符串)-尝试

if(image_array instanceof Array && image_array.length)

函数测试(image_array) { if(image_array instanceof Array && image_array.length) { Console.log (image_array,'-它不是空数组!') }其他{ Console.log (image_array,'-它是空数组或根本不是数组!') } } 测试({长度:5}); 测试(“定义”); 测试([]); 测试((“abc”));


最好是这样检查:

    let someArray: string[] = [];
    let hasAny1: boolean = !!someArray && !!someArray.length;
    let hasAny2: boolean = !!someArray && someArray.length > 0; //or like this
    console.log("And now on empty......", hasAny1, hasAny2);

查看完整的样本列表:


在我的例子中,是array_。长度总是返回0,即使它里面有值。可能是因为非默认索引。

为了检查数组是否定义了我们使用typeof _array !== 'undefined' 然后检查它是否包含任何日期,我只是简单地将它与一个空数组_array !== []


我发现工作的方法(来自另一种语言)是做一个简单的函数来测试。

创建一个函数,检查数组的大小,并通过参数传递长度。

isEmpty(size){
        if(size==0) {
            return true;
        } else  {
            return false;
        }
    }

//then check
if(isEmpty(yourArray.length)==true){
            //its empty
        } else {
            //not empty
        }