问题描述
第一次加载页面时,我需要检查image_array
中是否有图片并加载最后一张图片.
When the page is loading for the first time, I need to check if there is an image in image_array
and load the last image.
否则,我会禁用预览按钮,提醒用户按下新图像按钮并创建一个空数组来放置图像;
Otherwise, I disable the preview buttons, alert the user to push new image button and create an empty array to put the images;
问题是 else
中的 image_array
一直触发.如果数组存在 - 它只是覆盖它,但警报不起作用.
The problem is that image_array
in the else
fires all time. If an array exists - it just overrides it, but alert doesn't work.
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 之前,我有这样的事情:
UPDATEBefore loading html, I have something like this:
<?php if(count($images) != 0): ?>
<script type="text/javascript">
<?php echo "image_array = ".json_encode($images);?>
</script>
<?php endif; ?>
推荐答案
if (typeof image_array !== 'undefined' && image_array.length > 0) {
// the array is defined and has at least one element
}
您的问题可能是由于隐式全局变量和变量提升的混合而发生的.确保在声明变量时使用 var
:
Your problem may be happening due to a mix of implicit global variables and variable hoisting. Make sure you use var
whenever declaring a variable:
<?php echo "var image_array = ".json_encode($images);?>
// add var ^^^ here
然后确保您以后不会意外地重新声明该变量:
And then make sure you never accidently redeclare that variable later:
else {
...
image_array = []; // no var here
}
这篇关于检查数组是否为空或存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!