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

当前回答

你应该使用:

  if (image_array !== undefined && image_array.length > 0)

其他回答

对我来说,当我把它们放入jsfiddle时,一些高评级的答案“工作”,但当我有一个动态生成的数组列表时,答案中的很多代码对我来说并不工作。

这就是对我有效的方法。

var from = [];

if(typeof from[0] !== undefined) {
  //...
}

注意,在undefined周围没有引号,我没有考虑长度。

如果你想测试图像数组变量是否已经定义,你可以这样做

if(typeof image_array === 'undefined') {
    // it is not defined yet
} else if (image_array.length > 0) {
    // you have a greater than zero length array
}

下面是我的解决方案包装在一个函数,也抛出 错误来管理对象范围和所有类型的几个问题 传递给函数的可能数据类型。

这是我用来研究这个问题的小提琴(来源)

var jill = [0];
var jack;
//"Uncaught ReferenceError: jack is not defined"

//if (typeof jack === 'undefined' || jack === null) {
//if (jack) {
//if (jack in window) {
//if (window.hasOwnP=roperty('jack')){
//if (jack in window){

function isemptyArray (arraynamed){
    //cam also check argument length
  if (arguments.length === 0) { 
    throw "No argument supplied";
  }

  //console.log(arguments.length, "number of arguments found");
  if (typeof arraynamed !== "undefined" && arraynamed !== null) {
      //console.log("found arraynamed has a value");
      if ((arraynamed instanceof Array) === true){
        //console.log("I'm an array");
        if (arraynamed.length === 0) {
            //console.log ("I'm empty");
            return true;
        } else {
          return false;
        }//end length check
      } else {
        //bad type
        throw "Argument is not an array";
      } //end type check
  } else {
    //bad argument
    throw "Argument is invalid, check initialization";;
  }//end argument check
}

try {
  console.log(isemptyArray(jill));
} catch (e) {
    console.log ("error caught:",e);
}

这个怎么样?检查未定义数组的长度可能会抛出异常。

if(image_array){
//array exists
    if(image_array.length){
    //array has length greater than zero
    }
}

我在Javascript中遇到过很多这样的问题。对我来说,最好的方法是在检查长度之前进行广泛的检查。我在这个问答中看到了一些其他的解决方案,但我希望能够检查null或未定义或任何其他假值。

if(!array || array.length == 0){
    console.log("Array is either empty or does not exist")
}

这将首先检查未定义、空值或其他假值。如果其中任何一个为真,它将完成布尔值,因为这是一个OR。然后是更危险的数组检查。长度,如果数组是未定义的,可能会出错,可以检查。如果数组未定义或为空,这将永远不会达到,因此条件的顺序非常重要。