“未定义"检查“未定义"时出错在 if 语句中 [英] "undefined" error when checking "undefined" in an if statement

查看:51
本文介绍了“未定义"检查“未定义"时出错在 if 语句中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查 Object(如关联数组)以查看其中是否有部分数据可用,但我收到了 undefined 错误完全在 if 语句中,我正在检查它是否是 undefined

I'm checking an Object (like an Associative Array) to see if a portion of data is available there or not, but I'm getting an undefined error exactly in the if statement where I'm checking if it is undefined or not!

我有一个像这样的 Object:

var data = {
    1: {
        2: {
            3: [
                ["a","b"],
                ["c","d"],
            ],
        }
    }
}

我也尝试过使用 双引号,例如:var data = { "1": { "2": { ...

I have also tried with double-quotes like: var data = { "1": { "2": { ...

这些是我已经尝试过的 if 语句.所有这些都失败了,Firebug 正在生成 TypeError: data[1][2][3] is undefined 正好在 if 语句中:

These are the if statements which I've already tried. All of them failed, Firebug is generating TypeError: data[1][2][3] is undefined exactly in the if statement:

if (typeof data[1][2][3] == "undefined") {
if (data[1][2][3] === undefined) { 
// when I have double quotes
if (typeof data["1"]["2"]["3"] == "undefined") {
if (data["1"]["2"]["3"] === undefined) { 

我在 jsfiddle.net 中检查过,它工作正常.我尝试了所有我能想到的事情,但我仍然不知道为什么它在 if 语句中失败.

I checked that in jsfiddle.net and it works fine. I tried all the things I could imagine of, however I still don't have any idea why it fails in the if statement.

更新

看看这个,天哪:

推荐答案

一些备注,也许解决方案介于两者之间:

some remarks, maybe the solution is in between:

也许你想使用否定版本

if (typeof data[1][2][3] !== "undefined") {

因为您似乎在处理条件主体中的数据,所以您想确保它确实定义在您的 if 条件中?Atm,代码被执行如果数据未定义.

since you seem to work on that data in the condition body, so you want to make sure it actually is defined inside your if condition? Atm, the code gets executed if the data is undefined.

您是在代码中完全使用这个对象还是仅用于演示目的?因为如果检查 data[1][2][3] 并且 data[1][2] 已经未定义,则尝试访问 data[1][2][3] 会抛出一个错误,因为你试图访问一个不存在的对象的属性.

Are you using exactly this object in your code or was this only for demonstration purposes? Because if you check data[1][2][3] and data[1][2] is already undefined, trying to access data[1][2][3] will throw an error because you are trying to access a property of a non existing object.

旁注:如果您有数字索引,使用数组而不是对象可能更合适?

Sidenote: It might be more appropriate to use an array instead of a object if you have numeric indices?

这篇关于“未定义"检查“未定义"时出错在 if 语句中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆