474

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

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

问题是一直image_arrayelse火灾中。如果存在数组 - 它只是覆盖它,但警报不起作用。

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; ?>
4

23 回答 23

630
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
}
于 2012-07-31T15:30:42.330 回答
283

检查数组是否为空

现代方式,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

为什么?

案例未定义
未定义变量是您尚未为其分配任何内容的变量。

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

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

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

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

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

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

Case Empty Array
现在,由于我们测试了所有其他可能性,我们正在讨论Array. 为了确保它不是空的,我们询问它所持有的元素数量,并确保它有多个元素。

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

secondArray = [1,2,3];
secondArray.length > 0; // => true
于 2014-01-05T22:43:18.750 回答
76

怎么样(ECMA 5.1):

if(Array.isArray(image_array) && image_array.length){
  // array exists and is not empty
}
于 2016-02-22T19:27:09.363 回答
53

这就是我使用的。第一个条件涵盖了truthy,它同时具有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! has a value!");
}

if (array2 && array2.length) {
  console.log("array2! has a value!");
}

if (array3 && array3.length) {
  console.log("array3! has a value!");
}

if (array4 && array4.length) {
  console.log("array4! has a value!");
}

这也证明了这一点if(array2 && array2.length)并且if(array2 && array2.length > 0)完全相同

于 2016-06-21T20:04:11.543 回答
32

可选链

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

if(image_array?.length){

  // image_array is defined and has at least one element

}
于 2020-03-19T07:21:16.220 回答
16

你应该使用:

  if (image_array !== undefined && image_array.length > 0)
于 2012-07-31T15:21:48.113 回答
9

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

if(typeof image_array === 'undefined') {
    // it is not defined yet
} else if (image_array.length > 0) {
    // you have a greater than zero length array
}
于 2012-07-31T15:22:31.700 回答
8

JavaScript

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

Lodash & 下划线

( _.isArray(myArray) && myArray.length > 0 )
于 2018-06-08T10:38:23.243 回答
6

您可以使用 jQueryisEmptyObject()来检查数组是否包含元素。

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/

于 2014-06-02T16:26:05.440 回答
4

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

!!array

例子:

if (!!arr) {
  // array exists
}
于 2017-09-24T14:35:43.810 回答
3

最好的检查是:

    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);

查看完整的示例列表: 代码示例 结果

于 2020-09-21T23:52:53.387 回答
3

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

if(image_array){
//array exists
    if(image_array.length){
    //array has length greater than zero
    }
}
于 2018-03-07T16:24:34.073 回答
3

使用undescorelodash

_.isArray(image_array) && !_.isEmpty(image_array)

于 2017-06-03T09:25:22.277 回答
2

我在 Javascript 中经常遇到这个问题。对我来说,最好的方法是在检查长度之前进行非常广泛的检查。我在此问答中看到了其他一些解决方案,但我希望能够检查其中一个nullundefined任何其他错误值。

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

这将首先检查undefinednull或其他错误值。如果其中任何一个为真,它将完成布尔值,因为这是一个OR. 然后可以检查风险更大的检查array.length,如果数组未定义,可能会出错。如果arrayisundefined或将永远无法达到null,因此条件的顺序非常重要。

于 2017-04-03T17:46:47.200 回答
1

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

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');
}

您可以在此处查看我的小提琴,其中显示了检查数组的最可能方法。

于 2015-01-29T10:47:29.777 回答
1

对我来说,当我将一些高评价的答案放入 jsfiddle 时,它​​们肯定“有效”,但是当我有一个动态生成的数组列表数量时,答案中的很多代码对我不起作用。

这就是为我工作的。

var from = [];

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

请注意,未定义周围没有引号,我不在意长度。

于 2015-07-13T23:36:44.227 回答
1

以下是我包装在一个函数中的解决方案,该函数还会引发错误,以管理对象范围和传递给函数的所有可能数据类型的几个问题。

这是我用来检查这个问题的小提琴(来源

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);
}
于 2019-07-15T04:29:15.503 回答
0

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

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

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

//then check
if(isEmpty(yourArray.length)==true){
            //its empty
        } else {
            //not empty
        }
于 2022-01-29T10:01:43.430 回答
0

你应该做这个

    if (!image_array) {
      // image_array defined but not assigned automatically coerces to false
    } else if (!(0 in image_array)) {
      // empty array
      // doSomething
    }
于 2016-03-16T08:45:30.400 回答
0

在我的情况下,array_.length总是返回 0,即使它里面有值。可能是因为非默认索引。

因此,要检查数组是否已定义,我们使用typeof _array !== 'undefined' 然后检查它是否包含任何日期,我只需将其与空数组进行比较_array !== []

于 2021-04-02T17:27:40.343 回答
0

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

if(image_array instanceof Array && image_array.length)

function test(image_array) {
  if(image_array instanceof Array && image_array.length) { 
    console.log(image_array,'- it is not empty array!')
  } else {
    console.log(image_array,'- it is empty array or not array at all!')
  }
}

test({length:5});
test('undefined');
test([]);
test(["abc"]);

于 2020-09-07T21:08:26.137 回答
-1

在 ts

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

在 HTML 中

(照片 == 未定义 || !(isArray(photos) && photos.length > 0) )

于 2018-08-13T11:36:19.487 回答
-5

当您创建 image_array 时,它是空的,因此您的 image_array.length 为 0

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

var image_array = []

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

于 2012-07-31T15:20:07.647 回答