简体   繁体   中英

Simplest Javascript If-statement not working

I want to check a php variable in javascript and create an Array accordingly.

I tried this, but it's not working:

<script language="Javascript" type="text/javascript">
            var phpvar1_large = <?php echo $var1_large ?>; 
            var phpvar2_large = <?php echo $var2_large ?>; 
            var phpvar3_large = <?php echo $var3_large ?>; 
            var phpvar4_large = <?php echo $var4_large ?>; 

            if(!phpvar1_large){
            var imgArray = new Array(
                '<?=$main_img; ?>'
                );
            }else if(!phpvar2_large){
                var imgArray = new Array(
                '<?=$main_img; ?>',
                '<?=$var1_large; ?>'
                );
            }else if(!phpvar3_large){
            var imgArray = new Array(
                '<?=$main_img; ?>',
                '<?=$var1_large; ?>',
                '<?=$var2_large; ?>',
                '<?=$var3_large; ?>'
                );
            }else if(!phpvar4_large){
                var imgArray = new Array(
                '<?=$main_img; ?>',
                '<?=$var1_large; ?>',
                '<?=$var2_large; ?>',
                '<?=$var3_large; ?>'
                );
            }else if(phpvar4_large){
            var imgArray = new Array(
                '<?=$main_img; ?>',
                '<?=$var1_large; ?>',
                '<?=$var2_large; ?>',
                '<?=$var3_large; ?>',
                '<?=$var4_large; ?>'
            );
            }
</script>

However, if I don't use an if-statement, the array is created correctly:

<script language="Javascript" type="text/javascript">
            var imgArray = new Array(
                '<?=$main_img; ?>',
                '<?=$var1_large; ?>',
                '<?=$var2_large; ?>',
                '<?=$var3_large; ?>',
                '<?=$var4_large; ?>'
            );
</script>

I appreciate your help very much!

I strongly recommend simply JSON-encoding your array.

$imgArray = array('img1.jpg', 'img2.jpg', etc);
echo 'var imgArray = ' . json_encode($imgArray);

I'm pretty sure your problem is that the boolean values you are writing via php are not being interpreted as boolean but strings, that is why it is always evalued as false.

you should write var phpvar1_large = <?php echo json_encode($var1_large); ?>; var phpvar1_large = <?php echo json_encode($var1_large); ?>;

You are welcome!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM