Javascript 检查数组是否为空或存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11743392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:56:10  来源:igfitidea点击:

Check if an array is empty or exists

javascriptjquery

提问by user1564141

When the page is loading for the first time, I need to check if there is an image in image_arrayand load the last image.

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

Otherwise, I disable the preview buttons, alert the user to push new image button and create an empty array to put the images;

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

The problem is that image_arrayin the elsefires all time. If an array exists - it just overrides it, but alert doesn't work.

问题是,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 = [];
}

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

回答by jbabey

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 varwhenever 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
}

回答by Pooyan Khosravi

To check if an array is either empty or not

检查数组是否为空

A modern way, ES5+:

一种现代方式,ES5+:

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

An old-school way:

一个老派的方式:

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

A compact way:

一种紧凑的方式:

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

A CoffeeScript way:

一种 CoffeeScript 方式:

if array?.length > 0


Why?

为什么?

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

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

let array = new Array();     // "array" !== "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.

Case Null
一般而言,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.

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

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.

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

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

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

回答by Queequeg

How about (ECMA 5.1):

怎么样(ECMA 5.1):

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

回答by James Drinkard

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

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

which also proves that if(array2 && array2.length)and if(array2 && array2.length > 0)are exactly doing the same

这也证明了,if(array2 && array2.length)并且if(array2 && array2.length > 0)正在做同样的事情

回答by Samson

You should use:

你应该使用:

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

回答by Mike Brant

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
}

回答by Mayank Raipure

You can use jQuery's isEmptyObject()to check whether the array contains elements or not.

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

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

Source: https://api.jquery.com/jQuery.isEmptyObject/

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

回答by Amit Bhagat

JavaScript

JavaScript

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

Lodash & Underscore

洛达什和下划线

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

回答by insign

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

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

!!array

Example:

例子:

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

回答by Nikul Patel

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
    }
}