【发布时间】:2011-09-25 03:56:37
【问题描述】:
我有数组var john = ['asas','gggg','ggg'];
如果我在索引 3 处访问 john,即。 john[3],失败了。
我如何显示一条消息或警报,指出该索引没有值?
【问题讨论】:
标签: javascript logging
我有数组var john = ['asas','gggg','ggg'];
如果我在索引 3 处访问 john,即。 john[3],失败了。
我如何显示一条消息或警报,指出该索引没有值?
【问题讨论】:
标签: javascript logging
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 catch
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
【讨论】: