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

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

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

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 = [];
}

更新 在加载html之前,我有这样的东西:

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

当前回答

JavaScript

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

Lodash & Underscore

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

其他回答

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
}

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

if(typeof image_array === 'undefined') {
    // it is not defined yet
} else if (image_array.length > 0) {
    // you have a greater than zero length array
}

你可以使用jQuery的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/

这就是我用的。第一个条件包含true,它有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 (array1); console.log (array2); console.log (array3); console.log (array4); If (array1 && array1.length) { console.log(“array1 !有价值!”); } If (array2 && array2.length) { console.log(“array2 !有价值!”); } If (array3 && array3.length) { console.log(“array3 !有价值!”); } If (array4 && array4.length) { console.log(“array4 !有价值!”); }

这也证明了if(array2 && array2.length)和if(array2 && array2.length)长度> 0)完全相同

对我来说,当我把它们放入jsfiddle时,一些高评级的答案“工作”,但当我有一个动态生成的数组列表时,答案中的很多代码对我来说并不工作。

这就是对我有效的方法。

var from = [];

if(typeof from[0] !== undefined) {
  //...
}

注意,在undefined周围没有引号,我没有考虑长度。