Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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. 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:

<?php if(count($images) != 0): ?> <script type="text/javascript">     <?php echo "image_array = ".json_encode($images);?> </script> <?php endif; ?> 
like image 912
user1564141 Avatar asked Jul 31 '12 15:07

user1564141


People also ask

How do you check the array is empty or not?

The array can be checked if it is empty by using the array. length property. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true.

How check list is empty or not in Javascript?

length) // array null or empty check; if(array && ! array. length) // array exists, but empty check; if(str) // string not null and not empty.

How do you check if an array of objects is empty in Javascript?

Use the Object. entries() function. It returns an array containing the object's enumerable properties. If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.


1 Answers

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:

<?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 } 
like image 173
jbabey Avatar answered Oct 05 '22 04:10

jbabey