如何在JavaScript中记录超出绑定的ArrayIndex

How can I log an ArrayIndex out of bound in JavaScript?

本文关键字:绑定 ArrayIndex 记录 JavaScript      更新时间:2023-09-26

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

如果我访问索引3处的john,即john[3],它将失败。

如何显示消息或警报,说明该索引中没有值?

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*/}
if (typeof yourArray[undefinedIndex] === "undefined") {
  // It's undefined
  console.log("Undefined index: " + undefinedIndex;
}

Javascript已尝试捕获

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

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

var john = ['asas','gggg','ggg'];
var index=3;
if (john[index] != undefined ){
 console.log(john[index]);
}

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

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

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