jQuery 检查数组是否为空或空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7198197/
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-26 23:31:57  来源:igfitidea点击:

Check if array is empty or null

jqueryarraysis-empty

提问by input

I would like to know how to check if an array is empty or null in jQuery. I tried array.length === 0but it didn't work. It did not throw any error either.

我想知道如何在 jQuery 中检查数组是空的还是空的。我试过了,array.length === 0但没有用。它也没有抛出任何错误。

This is the code:

这是代码:

var album_text = new Array();

$("input[name='album_text[]']").each(function(){
  if( $(this).val() &&  $(this).val() != '') {
    album_text.push($(this).val());
  }
});
if (album_text.length === 0) {
  $('#error_message').html("Error");
}

else {
  // send data
}

回答by jfriend00

As long as your selector is actually working, I see nothing wrong with your code that checks the length of the array. That should do what you want. There are a lot of ways to clean up your code to be simpler and more readable. Here's a cleaned up version with notes about what I cleaned up.

只要您的选择器实际工作,我认为您检查数组长度的代码没有任何问题。那应该做你想做的。有很多方法可以清理您的代码,使其更简单、更具可读性。这是一个清理版本,其中包含有关我清理内容的注释。

var album_text = [];

$("input[name='album_text[]']").each(function() {
    var value = $(this).val();
    if (value) {
        album_text.push(value);
    }
});
if (album_text.length === 0) {
    $('#error_message').html("Error");
}

else {
  //send data
}

Some notes on what you were doing and what I changed.

关于你在做什么和我改变了什么的一些笔记。

  1. $(this)is always a valid jQuery object so there's no reason to ever check if ($(this)). It may not have any DOM objects inside it, but you can check that with $(this).lengthif you need to, but that is not necessary here because the .each()loop wouldn't run if there were no items so $(this)inside your .each()loop will always be something.
  2. It's inefficient to use $(this) multiple times in the same function. Much better to get it once into a local variable and then use it from that local variable.
  3. It's recommended to initialize arrays with []rather than new Array().
  4. if (value)when value is expected to be a string will both protect from value == null, value == undefinedand value == ""so you don't have to do if (value && (value != "")). You can just do: if (value)to check for all three empty conditions.
  5. if (album_text.length === 0)will tell you if the array is empty as long as it is a valid, initialized array (which it is here).
  1. $(this)始终是有效的 jQuery 对象,因此没有理由检查if ($(this)). 它里面可能没有任何 DOM 对象,但是$(this).length如果需要,您可以检查它,但这在这里不是必需的,因为.each()如果没有项目,循环将不会运行,因此$(this)您的.each()循环内部将始终存在。
  2. 在同一个函数中多次使用 $(this) 是低效的。最好将它放入一个局部变量,然后从该局部变量中使用它。
  3. 建议使用[]而不是初始化数组new Array()
  4. if (value)当值预计将是一个字符串将两者保护value == nullvalue == undefined而且value == ""这样你就不必做if (value && (value != ""))。您可以这样做:if (value)检查所有三个空条件。
  5. if (album_text.length === 0)只要它是一个有效的初始化数组(它在这里),就会告诉你数组是否为空。

What are you trying to do with this selector $("input[name='album_text[]']")?

你想用这个选择器做$("input[name='album_text[]']")什么?

回答by Mayank Raipure

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

回答by Daniel A. White

You should check for ''(empty string) before pushing into your array. Your array has elements that are empty strings. Then your album_text.length === 0will work just fine.

''在推入数组之前,您应该检查(空字符串)。您的数组具有为空字符串的元素。那么你的album_text.length === 0将工作得很好。

回答by rhinoxi

I think it is dangerous to use $.isEmptyObject from jquery to check whether the array is empty, as @jesenko mentioned. I just met that problem.

正如@jesenko 提到的,我认为使用 jquery 中的 $.isEmptyObject 来检查数组是否为空是危险的。我刚遇到那个问题。

In the isEmptyObject doc, it mentions:

isEmptyObject 文档中,它提到:

The argument should always be a plain JavaScript Object

参数应该总是一个普通的 JavaScript 对象

which you can determine by $.isPlainObject. The return of $.isPlainObject([])is false.

您可以通过 确定$.isPlainObject。的返回$.isPlainObject([])是假的。