最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

logging - How can I log an ArrayIndex out of bound in JavaScript? - Stack Overflow

programmeradmin4浏览0评论

I have the array var john = ['asas','gggg','ggg'];

If I access john at index 3, ie. john[3], it fails.

How can I display a message or alert saying that there is no value at that index?

I have the array var john = ['asas','gggg','ggg'];

If I access john at index 3, ie. john[3], it fails.

How can I display a message or alert saying that there is no value at that index?

Share Improve this question edited Dec 30, 2016 at 19:52 Michael Piefel 20k12 gold badges90 silver badges122 bronze badges asked Jun 29, 2011 at 13:19 John CooperJohn Cooper 7,63133 gold badges83 silver badges102 bronze badges 0
Add a comment  | 

6 Answers 6

Reset to default 6
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 has try catch

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

Javascript arrays start at 0. so your array contains contents 0 - 'asas', 1 - 'gggg', 2 - 'ggg'.

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

Arrays are indexed starting with 0, not 1.

There are 3 elements in the array; they are:

john[0] // asas
john[1] // gggg
john[2] // ggg
发布评论

评论列表(0)

  1. 暂无评论