检查数组是否为空或为空 [英] Check if array is empty or null
问题描述
我想知道如何检查jQuery中的数组是空还是空.我尝试了array.length === 0
,但是没有用.它也没有引发任何错误.
I would like to know how to check if an array is empty or null in jQuery. I tried array.length === 0
but it didn't work. It did not throw any error either.
这是代码:
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
}
推荐答案
只要您的选择器实际上在工作,我就不会发现检查数组长度的代码有问题.那应该做你想要的.有很多方法可以使您的代码更简单,更易读.这是一个清理过的版本,其中包含有关我清理过的内容的注释.
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.
-
$(this)
始终是有效的jQuery对象,因此没有理由检查if ($(this))
.它内部可能没有任何DOM对象,但是您可以根据需要使用$(this).length
进行检查,但这在这里是不必要的,因为如果没有任何项目,则.each()
循环将不会运行,因此$(this)
您的.each()
循环永远都是东西. - 在同一函数中多次使用$(this)效率低下.最好一次将它放入一个局部变量,然后从该局部变量中使用它.
- 建议使用
[]
而不是new Array()
初始化数组. -
if (value)
当value预期为字符串时,将同时保护value == null
,value == undefined
和value == ""
,因此您不必执行if (value && (value != ""))
.您可以执行以下操作:if (value)
检查所有三个空条件. -
if (album_text.length === 0)
会告诉您该数组是否为空,只要它是有效的,已初始化的数组(就在此处)即可.
$(this)
is always a valid jQuery object so there's no reason to ever checkif ($(this))
. It may not have any DOM objects inside it, but you can check that with$(this).length
if 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.- 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.
- It's recommended to initialize arrays with
[]
rather thannew Array()
. if (value)
when value is expected to be a string will both protect fromvalue == null
,value == undefined
andvalue == ""
so you don't have to doif (value && (value != ""))
. You can just do:if (value)
to check for all three empty conditions.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).
您打算如何使用此选择器$("input[name='album_text[]']")
?
What are you trying to do with this selector $("input[name='album_text[]']")
?
这篇关于检查数组是否为空或为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!