当页面第一次加载时,我需要检查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; ?>

当前回答

使用uncore或lodash:

_isarray (image_array) && ! ipad (image_array)

其他回答

当你创建image_array时,它是空的,因此你的image_array。长度为0

正如下面的评论所述,我根据这个问题的答案编辑了我的答案):

var image_array = []

在else括号内,不会对前面代码中定义的image_array进行任何更改

JavaScript

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

Lodash & Underscore

( _.isArray(myArray) && myArray.length > 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');
}

你可以检查我的提琴这里显示最可能的方法来检查数组。

你应该使用:

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

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

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