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

当前回答

(ECMA 5.1)如何:

if(Array.isArray(image_array) && image_array.length){
  // array exists and is not empty
}

其他回答

在ts

 isArray(obj: any) 
{
    return Array.isArray(obj)
  }

在html中

(isArray(photos) && photos. isArray == undefined || !长度> 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
}

在我的例子中,是array_。长度总是返回0,即使它里面有值。可能是因为非默认索引。

为了检查数组是否定义了我们使用typeof _array !== 'undefined' 然后检查它是否包含任何日期,我只是简单地将它与一个空数组_array !== []

可选的链接

随着可选链接提议达到了第4阶段,并得到了更广泛的支持,有一种非常优雅的方式可以做到这一点

if(image_array?.length){

  // image_array is defined and has at least one element

}

你应该这样做

    if (!image_array) {
      // image_array defined but not assigned automatically coerces to false
    } else if (!(0 in image_array)) {
      // empty array
      // doSomething
    }