这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
这将用于测试一个值在位置索引是否存在,或者有更好的方法:
if(arrayName[index]==""){
// do stuff
}
当前回答
我在使用laravel数据表时遇到了这个问题。我在活动日志中存储了一个名为properties的JSON值,并希望根据该值是否为空来显示一个按钮。
好吧,数据表是解释这作为一个数组,如果它是空的,和一个对象,如果它不是,因此,下面的解决方案为我工作:
render: function (data, type, full) {
if (full.properties.length !== 0) {
// do stuff
}
}
对象没有长度属性。
其他回答
使用Lodash,你可以做到:
if(_.has(req,'documents')){
if (req.documents.length)
_.forEach(req.documents, function(document){
records.push(document);
});
} else {
}
if(_.has(req,'documents'))是检查我们的请求对象是否有一个名为documents的属性,如果它有prop,下一个if(req.documents.length)是验证它是否不是一个空数组,这样其他的东西,如forEach可以继续。
我们就不能这样做吗
if(arrayName.length > 0){
//or **if(arrayName.length)**
//this array is not empty
}else{
//this array is empty
}
从概念上讲,JavaScript中的数组包含数组。长度元素,从数组[0]开始,直到数组[array. array.]长度- 1]。如果i在0和array之间,则索引为i的数组元素定义为数组的一部分。长度-包括1。如果i不在这个范围内,它就不在数组中。
因此,从概念上讲,数组是线性的,从0开始,一直到最大值,没有任何机制在这个范围内存在没有条目的“间隙”。要找出一个值是否存在于给定的位置索引(其中索引为0或正整数),您只需使用
if (i >= 0 && i < array.length) {
// it is in array
}
Now, under the hood, JavaScript engines almost certainly won't allocate array space linearly and contiguously like this, as it wouldn't make much sense in a dynamic language and it would be inefficient for certain code. They're probably hash tables or some hybrid mixture of strategies, and undefined ranges of the array probably aren't allocated their own memory. Nonetheless, JavaScript the language wants to present arrays of array.length n as having n members and they are named 0 to n - 1, and anything in this range is part of the array.
然而,您可能想要知道数组中的值是否实际上是有定义的—也就是说,它不是未定义的。也许你甚至想知道它是否有定义而不是null。可以在不设置数组值的情况下向数组添加成员:例如,如果您通过增加数组来添加数组值。属性,任何新值将是未定义的。
确定给定的值是否有意义,或者是否已定义。即非undefined或null:
if (typeof array[index] !== 'undefined') {
or
if (typeof array[index] !== 'undefined' && array[index] !== null) {
有趣的是,由于JavaScript的比较规则,我的最后一个例子可以优化为:
if (array[index] != null) {
// The == and != operators consider null equal to only null or undefined
}
我认为这个决定适合那些喜欢声明式函数编程而不是命令式OOP或过程式编程的人。如果你的问题是“里面有价值吗?”(一个真实或虚假的值)”你可以使用。some方法来验证里面的值。
[].some(el => el || !el);
它并不完美,但它不需要应用任何包含相同逻辑的额外函数,如function isEmpty(arr){…}。 当我们这样做[]时,它听起来仍然比“它是零长度吗?”要好。长度导致0,在某些情况下是危险的。 甚至是这个[]。length > 0表示它的长度是否大于0 ?
先进的例子:
[ ].some(el => el || !el); // false
[null].some(el => el || !el); // true
[1, 3].some(el => el || !el); // true
if(!arrayName[index]){
// do stuff
}