Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

javascript - 检查数组是否为空或存在(Check if an array is empty or exists)

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.

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

Otherwise, I disable the preview buttons, alert the user to push new image button and create an empty array to put the images;

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

The problem is that image_array in the else fires all time.

(问题是, image_arrayelse火灾所有的时间。)

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

UPDATE Before loading html, I have something like this:

(更新在加载html之前,我有类似以下内容:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
if (typeof image_array !== 'undefined' && image_array.length > 0) {
    // the array is defined and has at least one element
}

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:

(确保在声明变量时使用var :)

<?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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...