如何在JavaScript中记录超出绑定的ArrayIndex
How can I log an ArrayIndex out of bound in JavaScript?
我有数组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
相关文章:
- 在VanillaJS中模拟模型双向数据绑定
- 无法通过数组映射绑定
- 主干-不管怎样,检查事件以前是否绑定过
- 用于搜索的聚合物嵌套绑定
- Angular:更新一次性绑定的数据
- 如何使用ngrepeat和双向绑定获得指令的隔离范围
- react.js中的密钥绑定
- 使用regex的jquery keydown绑定不会验证撇号和句点
- 将事件处理程序绑定到任何可能的事件
- AngularJS指令只识别双向绑定类型
- Telerik rad组合框多列数据绑定
- 对API数据使用声明性绑定
- 如何销毁/删除/取消绑定SnapSVG.js
- 在D3.js中,有没有任何方法可以将x和y方向上的滚动事件绑定到平移svg
- 数据绑定:'系统Char'不包含名为'xxxxx'
- react组件中的绑定方法
- 如何将ngrepeat下的ngmodel绑定到$scope
- WinJS内联绑定语法
- ng绑定和ng href问题.ng href未从控制器加载数据
- 如何在JavaScript中记录超出绑定的ArrayIndex