如何在JavaScript中记录一个ArrayIndex?

Joh*_*per 9 javascript logging

我有阵列 var john = ['asas','gggg','ggg'];

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

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

Mic*_*ski 6

if (typeof yourArray[undefinedIndex] === "undefined") {
  // It's undefined
  console.log("Undefined index: " + undefinedIndex;
}
Run Code Online (Sandbox Code Playgroud)

  • 他的问题是:**我怎样才能显示一条消息或警告,说明所传的索引没有价值.** (2认同)

Nea*_*eal 6

function checkIndex(arrayVal, index){
    if(arrayVal[index] == undefined){
        alert('index '+index+' is undefined!');
        return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)
//use it like so:
if(checkIndex(john, 3)) {/*index exists and do something with it*/}
else {/*index DOES NOT EXIST*/}
Run Code Online (Sandbox Code Playgroud)

  • 不要试图施放类型!使用===而不是==!它也会更快(以纳秒为单位,但是嘿!:) (2认同)