检查数组是否为空或存在

时间:2012-07-31 15:17:28

标签: javascript jquery

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

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

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

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 在加载html之前,我有类似的东西:

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

23 个答案:

答案 0 :(得分:415)

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
}

答案 1 :(得分:123)

检查数组是否为空

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

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

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

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

案例空数组
现在,由于我们测试了所有其他可能性,我们正在讨论Array的实例。为了确保它不是空的,我们询问它所持有的元素数量,并确保它具有多于零的元素。

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

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

答案 2 :(得分:61)

如何(ECMA 5.1):

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

答案 3 :(得分:16)

这就是我使用的。第一个条件包括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(数组1); 的console.log(数组2); 的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!");
}

然后结果:

未定义

[]

[“one”,“two”,“three”]

和显示的最终测试

if(array2 && array2.length){

相同

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

<强> ARRAY3!有价值!

答案 4 :(得分:15)

您应该使用:

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

答案 5 :(得分:8)

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

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 :(得分:8)

optional chaining

随着可选链接建议进入第4阶段并获得广泛支持,有一种非常优雅的方式实现此目的

if(image_array?.length){

  // image_array is defined and has at least one element

}

答案 7 :(得分:6)

您可以使用jQuery&#39; 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/

答案 8 :(得分:5)

的JavaScript

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

Lodash&amp;下划线

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

答案 9 :(得分:3)

对我来说,确定一些高评价的答案&#34;工作&#34;当我把它们放到jsfiddle中时,但是当我有一个动态生成的数组列表时,答案中的很多代码对我来说都不起作用。

这就是IS为我工作的。

{{1}}

注意,未定义周围没有引号,我没有打扰长度。

答案 10 :(得分:3)

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

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

答案 11 :(得分:2)

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

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

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

答案 12 :(得分:2)

使用undescorelodash

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

答案 13 :(得分:0)

一种简单的方法,如果不存在则不会导致异常并转换为boolean:

!!array

示例:

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

答案 14 :(得分:0)

你应该这样做

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

答案 15 :(得分:0)

  

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

这是我用来研究此问题的小提琴(source

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

答案 16 :(得分:0)

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

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

您可以查看my fiddle here,查看最有可能检查数组的方法。

答案 17 :(得分:0)

我认为这个简单的代码会起作用:

#!/usr/bin/env python3
import os

for file in os.listdir(os.getcwd()):
    if file.endswith(".py"):
        if ((len(os.path.splitext(file)[0])) > 2 and (len(os.path.splitext(file)[0])) < 7):
            print(file)

答案 18 :(得分: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"]);

答案 19 :(得分:0)

最好是像这样检查:

int

查看完整的样本列表: code sample results

答案 20 :(得分:0)

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

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

进行比较

答案 21 :(得分:-1)

以ts

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

以html

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

答案 22 :(得分:-2)

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

如下面的评论中所述,我根据此question's answer)编辑我的答案:

var image_array = []
在else括号内的

不会改变之前在代码

中定义的image_array
相关问题