【问题标题】:How can I log an ArrayIndex out of bound in JavaScript?如何在 JavaScript 中记录超出范围的数组索引?
【发布时间】:2011-09-25 03:56:37
【问题描述】:

我有数组var john = ['asas','gggg','ggg'];

如果我在索引 3 处访问 john,即。 john[3],失败了。

我如何显示一条消息或警报,指出该索引没有值?

【问题讨论】:

    标签: javascript logging


    【解决方案1】:
    function checkIndex(arrayVal, index){
        if(arrayVal[index] == undefined){
            alert('index '+index+' is undefined!');
            return false;
        }
        return true;
    }
    

    //use it like so:
    if(checkIndex(john, 3)) {/*index exists and do something with it*/}
    else {/*index DOES NOT EXIST*/}
    

    【讨论】:

    • 不要尝试强制转换类型!使用 === 而不是 == !它也会更快(以纳秒为单位,但是嘿!:)
    • “数组索引超出范围”和“数组有'未定义'元素”应该以不同方式处理。见这里:stackoverflow.com/questions/6728424/…
    【解决方案2】:
    if (typeof yourArray[undefinedIndex] === "undefined") {
      // It's undefined
      console.log("Undefined index: " + undefinedIndex;
    }
    

    【讨论】:

    • 他的问题:我怎样才能显示一条消息或警报,指出传递的索引没有值。
    • “数组索引超出范围”和“数组有'未定义'元素”应该以不同方式处理。见这里:stackoverflow.com/questions/6728424/…
    【解决方案3】:

    Javascript 有 try catch

    try
      {
      //your code
      }
    catch(err)
      {
      //handle the error - err i think also has an exact message in it.
    alert("Error");
      }
    

    【讨论】:

    • 或者检查数组的长度。
    • if(somearray.length
    • 从错误中捕获索引并吞下它是一个糟糕的解决方案。这种编程会导致错误。最好只检查数组的长度!
    【解决方案4】:

    Javascript 数组从 0 开始。因此您的数组包含内容 0 - 'asas'、1 - 'gggg'、2 - 'ggg'。

    【讨论】:

      【解决方案5】:
      var john = ['asas','gggg','ggg'];
      var index=3;
      if (john[index] != undefined ){
       console.log(john[index]);
      }
      

      【讨论】:

        【解决方案6】:

        数组的索引从 0 开始,而不是 1。

        数组中有3个元素;他们是:

        john[0] // asas
        john[1] // gggg
        john[2] // ggg
        

        【讨论】:

          猜你喜欢
          • 2021-10-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多