Jam*_*mes 1 javascript typeof undefined
我想在对它执行操作之前检查数组中的下一个元素是否存在,但我无法检查它是否未定义.例如:
// 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
Run Code Online (Sandbox Code Playgroud)
alert(typeof arr[1]); // This does nothing
Run Code Online (Sandbox Code Playgroud)
它没有做任何事情,因为它失败并出现错误:
ReferenceError: arr is not defined
Run Code Online (Sandbox Code Playgroud)
如果你这样尝试:
var arr = [];
alert(typeof arr[1]);
Run Code Online (Sandbox Code Playgroud)
然后你会得到你期望的.但是,更好的方法是使用.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!");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1141 次 |
| 最近记录: |