javascript - 为什么 typeof array[0] == 'undefined' 不起作用?

标签 javascript undefined typeof

我想在对它执行操作之前检查数组中的下一个元素是否存在,但我无法检查它是否未定义。例如:

// Variable and array are both undefined
alert(typeof var1);   // This works
alert(typeof arr[1]); // This does nothing

var arr = [1,1];
alert(typeof arr[1]); // This works now

最佳答案

alert(typeof arr[1]); // This does nothing

它没有做任何事情,因为它因错误而失败:

ReferenceError: arr is not defined

如果您改用这种方式尝试:

var arr = [];
alert(typeof arr[1]);

然后你会得到你所期望的。但是,进行此检查的更好方法是使用数组的 .length 属性:

// Instead of this...
if(typeof arr[2] == "undefined") alert("No element with index 2!");

// do this:
if(arr.length <= 2) alert("No element with index 2!");

关于javascript - 为什么 typeof array[0] == 'undefined' 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14026352/

相关文章:

javascript - 为什么函数响应 .prototype 但常规对象不响应?

javascript - JavaScript 中使用字符串进行类型检测?

Javascript typeof 抛出引用错误

ruby 错误 : Not Finding Variable Defined in Loop

javascript - jQuery:如何获取外部图像的尺寸?

javascript - 如何结合js和bootstrap

javascript - 使用 javascript 后 css 悬停事件不起作用?

javascript - Sequelize 模型自定义方法返回未定义

javascript - 在 JavaScript 中获取真实的对象类型

javascript - Jquery 插件图像滚动器,上一张和下一张图像在侧面可见