检查数组是否为空或存在

时间:2021-08-12 11:13:27

For the first page load I need to check if there is image_array load last image, otherwise block preview buttons; alert user to push new image button; create empty array to put there images;

对于第一个页面加载,我需要检查是否有image_array加载最后一个图像,否则块预览按钮;提醒用户按新的图像按钮;创建空数组以放置图像;

The problem is that image_array in the else fires all time. If array exists - it just overrides it, but alert dosent work.

问题是,else中的image_array会一直触发。如果数组存在——它只是覆盖它,但是警告dosent工作。

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 = [];
}

UPDATE Before loading html i have something like this

在加载html之前进行更新

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

18 个解决方案

#1


312  

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

Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var whenever declaring a variable:

由于隐含的全局变量和变量提升的混合,您的问题可能正在发生。确保在声明变量时使用var:

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

And then make sure you never accidently redeclare that variable later:

然后确保你以后不会不小心重新声明这个变量:

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

#2


89  

To check if an array is either empty or not.

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

Compact Version

紧凑版本

  if(typeof array != "undefined" && array != null && array.length != null && array.length > 0){}

CoffeeScript Version

CoffeeScript版本

  if array?.length > 0

Note: Do not use this, there is a better way of finding if an array exists and it's non-empty.

注意:不要使用这个,有一个更好的方法来发现数组是否存在,并且它是非空的。


Why?

Case Undefined

Undefined variable is a variable that you haven't assigned anything to it yet.

未定义的变量是一个你还没有分配到它的变量。

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

Case Null

Generally speaking, null is state of lacking a value. For example a variable is null when you missed or failed to retrieve some data.

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

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

Case Not an Array

Javascript has a dynamic type system. This means we can't guarantee what type of object a variable holds.
There is a chance that we're not talking to an instance of Array.

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

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

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

Case Empty Array

Now since we tested all other possibilities, we're talking to an instance of Array.

既然我们已经测试了所有其他的可能性,我们正在与一个数组实例对话。

In order to make sure it's not empty, we ask about number of elements it's holding, and making sure it has more than zero elements.

为了确保它不是空的,我们询问它所包含的元素的数量,并确保它有超过零的元素。

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

#3


35  

How about (ECMA 5.1):

如何(ECMA - 5.1):

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

#4


11  

You should use:

你应该使用:

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

#5


9  

If you want to test whether the image array variable had been defined you can do it like this

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

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

#6


7  

This is what I use. The first condition covers truthy, which has both null and undefined. Second condition checks for an empty array.

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

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

or thanks to tsemer's comment I added a second version

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

if(arrayName && arrayName.length)

Then I made a test for the second condition, using Scratchpad in Firefox:

然后我对第二个条件进行了测试,在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);

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!");
}

Then the results:

结果:

undefined

未定义的

[]

[]

["one", "two", "three"]

(“1”,“2”,“3”)

null

and the final test that shows

最后一个测试。

if(array2 && array2.length){

如果(array2 & & array2.length){

is the same as

是一样的

if(array2 && array2.length > 0){

如果(array2 & & array2。长度> 0){

array3! has a value!

array3 !有价值!

#7


5  

User JQuery is EmptyObject to check whether array is contains elements or not.

用户JQuery是EmptyObject,用于检查数组是否包含元素。

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

#8


3  

For me sure some of the high rated answers "work" when I put them into jsfiddle, but when I have a dynamically generated amount of array list a lot of this code in the answers just doesn't work for ME.

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

This is what IS working for me.

这就是我要做的。

var from = [];

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

Notice, NO quotes around undefined and I'm not bothering with the length.

注意,没有未定义的引号,我不关心长度。

#9


1  

If you do not have a variable declared as array you can create a check:

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

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

This checks if variable x exists and if it is, checks if it is a filled array. else it creates an empty array (or you can do other stuff);

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

If you are certain there is an array variable created there is a simple check:

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

var x = [];

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

You can check my fiddle here with shows most possible ways to check array.

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

#10


1  

I come across this issue quite a lot in Javascript. For me the best way to do it is to put a very broad check before checking for length. I saw some other solutions in this Q&A, but I wanted to be able to check for either null or undefined or any other false value.

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

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

This will first check for undefined, null, or other false values. If any of those are true, it will complete the boolean as this is an OR. Then the more risky check of array.length, which could error us if array is undefined, can be checked. This will never be reached if array is undefined or null, so the ordering of conditions is very important.

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

#11


1  

Using undescore or lodash:

使用undescore或lodash:

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

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

#12


1  

How about this ? checking for length of undefined array may throw exception.

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

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

#13


0  

When you create your image_array, it's empty, therefore your image_array.length is 0

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

As stated in the comment below, i edit my answer based on this question's answer) :

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

var image_array = []

inside the else brackets doesn't change anything to the image_array defined before in the code

在其他括号内,不会对代码中定义的image_array进行任何更改。

#14


0  

You should do this

你应该这样做

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

#15


0  

Try below,

试下,

if(array.results != undefined) - specific to SharePoint

or

if(array.length > 0)

#16


0  

A simple way that doesn't result in exceptions if not exist and convert to boolean:

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

!!array

Example:

例子:

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

#17


0  

Here's mine to add to the long list of answers:

以下是我的答案:

first, checking for length is not enough to check the type, since

首先,检查长度不足以检查类型,因为

const fakeArray1 = { length: "very long" };
const fakeArray2 = { length: "1337", data: {} };
if (fakeArray1.length) {...} // is true
if (fakeArray2.length > 0) {...} // is also true

so you need to check for the real type, either

所以你也需要检查真正的类型

image_array.constructor === Array or Array.isArray(image_array)

image_array。===数组或数组(image_array)

Now the magic (note: using magic in JS is dangerous and require dexterity and responsibility), when using untyped comparison any pair of equality below is truthy

现在的魔法(注意:在JS中使用魔法是危险的,需要灵活性和责任感),当使用无类型比较时,下面的任何一对等式都是真实的

[] == false; [] == 0; [] == ''; [null] == false

[]= = false;[]= = 0;[]= =”;(空)= = false

So! this is getting exiting :P

如此!这是令人兴奋的:P

MY ANSWER

我的答案

if(Array.isArray(image_array) && image_array == false) {
  // handle the case where, either
  // - the array don't exist
  // - the array is empty
  // - it contains only one empty element
}

Note: (and advise)

注意:(建议)

using untyped check is considered bad practice in JS and someone might want to add the third =, changin the behaviour of your code. I advise then to wrap this check in a util function so it doesn't get in your logic and miss understood by peers.

在JS中使用无类型检查被认为是不好的做法,有些人可能想要添加第三个=,改变代码的行为。然后,我建议将这个检查封装到一个util函数中,这样它就不会进入您的逻辑,也不会被同行所理解。

#18


0  

JavaScript

JavaScript

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

Lodash & Underscore

Lodash &下划线

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

#1


312  

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

Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var whenever declaring a variable:

由于隐含的全局变量和变量提升的混合,您的问题可能正在发生。确保在声明变量时使用var:

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

And then make sure you never accidently redeclare that variable later:

然后确保你以后不会不小心重新声明这个变量:

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

#2


89  

To check if an array is either empty or not.

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

Compact Version

紧凑版本

  if(typeof array != "undefined" && array != null && array.length != null && array.length > 0){}

CoffeeScript Version

CoffeeScript版本

  if array?.length > 0

Note: Do not use this, there is a better way of finding if an array exists and it's non-empty.

注意:不要使用这个,有一个更好的方法来发现数组是否存在,并且它是非空的。


Why?

Case Undefined

Undefined variable is a variable that you haven't assigned anything to it yet.

未定义的变量是一个你还没有分配到它的变量。

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

Case Null

Generally speaking, null is state of lacking a value. For example a variable is null when you missed or failed to retrieve some data.

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

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

Case Not an Array

Javascript has a dynamic type system. This means we can't guarantee what type of object a variable holds.
There is a chance that we're not talking to an instance of Array.

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

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

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

Case Empty Array

Now since we tested all other possibilities, we're talking to an instance of Array.

既然我们已经测试了所有其他的可能性,我们正在与一个数组实例对话。

In order to make sure it's not empty, we ask about number of elements it's holding, and making sure it has more than zero elements.

为了确保它不是空的,我们询问它所包含的元素的数量,并确保它有超过零的元素。

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

#3


35  

How about (ECMA 5.1):

如何(ECMA - 5.1):

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

#4


11  

You should use:

你应该使用:

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

#5


9  

If you want to test whether the image array variable had been defined you can do it like this

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

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

#6


7  

This is what I use. The first condition covers truthy, which has both null and undefined. Second condition checks for an empty array.

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

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

or thanks to tsemer's comment I added a second version

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

if(arrayName && arrayName.length)

Then I made a test for the second condition, using Scratchpad in Firefox:

然后我对第二个条件进行了测试,在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);

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!");
}

Then the results:

结果:

undefined

未定义的

[]

[]

["one", "two", "three"]

(“1”,“2”,“3”)

null

and the final test that shows

最后一个测试。

if(array2 && array2.length){

如果(array2 & & array2.length){

is the same as

是一样的

if(array2 && array2.length > 0){

如果(array2 & & array2。长度> 0){

array3! has a value!

array3 !有价值!

#7


5  

User JQuery is EmptyObject to check whether array is contains elements or not.

用户JQuery是EmptyObject,用于检查数组是否包含元素。

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

#8


3  

For me sure some of the high rated answers "work" when I put them into jsfiddle, but when I have a dynamically generated amount of array list a lot of this code in the answers just doesn't work for ME.

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

This is what IS working for me.

这就是我要做的。

var from = [];

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

Notice, NO quotes around undefined and I'm not bothering with the length.

注意,没有未定义的引号,我不关心长度。

#9


1  

If you do not have a variable declared as array you can create a check:

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

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

This checks if variable x exists and if it is, checks if it is a filled array. else it creates an empty array (or you can do other stuff);

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

If you are certain there is an array variable created there is a simple check:

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

var x = [];

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

You can check my fiddle here with shows most possible ways to check array.

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

#10


1  

I come across this issue quite a lot in Javascript. For me the best way to do it is to put a very broad check before checking for length. I saw some other solutions in this Q&A, but I wanted to be able to check for either null or undefined or any other false value.

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

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

This will first check for undefined, null, or other false values. If any of those are true, it will complete the boolean as this is an OR. Then the more risky check of array.length, which could error us if array is undefined, can be checked. This will never be reached if array is undefined or null, so the ordering of conditions is very important.

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

#11


1  

Using undescore or lodash:

使用undescore或lodash:

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

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

#12


1  

How about this ? checking for length of undefined array may throw exception.

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

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

#13


0  

When you create your image_array, it's empty, therefore your image_array.length is 0

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

As stated in the comment below, i edit my answer based on this question's answer) :

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

var image_array = []

inside the else brackets doesn't change anything to the image_array defined before in the code

在其他括号内,不会对代码中定义的image_array进行任何更改。

#14


0  

You should do this

你应该这样做

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

#15


0  

Try below,

试下,

if(array.results != undefined) - specific to SharePoint

or

if(array.length > 0)

#16


0  

A simple way that doesn't result in exceptions if not exist and convert to boolean:

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

!!array

Example:

例子:

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

#17


0  

Here's mine to add to the long list of answers:

以下是我的答案:

first, checking for length is not enough to check the type, since

首先,检查长度不足以检查类型,因为

const fakeArray1 = { length: "very long" };
const fakeArray2 = { length: "1337", data: {} };
if (fakeArray1.length) {...} // is true
if (fakeArray2.length > 0) {...} // is also true

so you need to check for the real type, either

所以你也需要检查真正的类型

image_array.constructor === Array or Array.isArray(image_array)

image_array。===数组或数组(image_array)

Now the magic (note: using magic in JS is dangerous and require dexterity and responsibility), when using untyped comparison any pair of equality below is truthy

现在的魔法(注意:在JS中使用魔法是危险的,需要灵活性和责任感),当使用无类型比较时,下面的任何一对等式都是真实的

[] == false; [] == 0; [] == ''; [null] == false

[]= = false;[]= = 0;[]= =”;(空)= = false

So! this is getting exiting :P

如此!这是令人兴奋的:P

MY ANSWER

我的答案

if(Array.isArray(image_array) && image_array == false) {
  // handle the case where, either
  // - the array don't exist
  // - the array is empty
  // - it contains only one empty element
}

Note: (and advise)

注意:(建议)

using untyped check is considered bad practice in JS and someone might want to add the third =, changin the behaviour of your code. I advise then to wrap this check in a util function so it doesn't get in your logic and miss understood by peers.

在JS中使用无类型检查被认为是不好的做法,有些人可能想要添加第三个=,改变代码的行为。然后,我建议将这个检查封装到一个util函数中,这样它就不会进入您的逻辑,也不会被同行所理解。

#18


0  

JavaScript

JavaScript

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

Lodash & Underscore

Lodash &下划线

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