javascript 如果变量未定义,防止出错?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8916279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:58:50  来源:igfitidea点击:

Prevent getting error if variable is undefined?

javascript

提问by lisovaccaro

I need to replace imagesrc with the value stored in this object. However when I run:

我需要用存储在这个对象中的值替换 imagesrc。但是,当我运行时:

if(data['results'][res]['entities']['media']["0"]["media_url"]) {
    imagesrc = data['results'][res]['entities']['media']["0"]["media_url"];
}

I get the error:

我收到错误:

Cannot read property '0' of undefined

How can I run my condition so that I don't get errors if something is undefined?

如果未定义某些内容,我如何运行我的条件以便我不会出错?

回答by Web User

if (data['results'][res]['entities']['media']["0"] == undefined
    || data['results'][res]['entities']['media']["0"] == null) {

    ...
}

回答by Arian

you can place your code inside a try catchblock and examin error message.

您可以将代码放在try catch块中并检查错误消息。

回答by Frédéric Hamidi

You could write a function that walks the object tree and returns undefinedas soon as it hits an undefined property:

您可以编写一个函数来遍历对象树并undefined在遇到未定义的属性时立即返回:

function safeGetData(obj, names)
{
    for (var i = 0; i < names.length; ++i) {
        if (typeof obj === "undefined") {
            return undefined;
        }
        obj = obj[names[i]];
    }
    return obj;
}

You can use it like this:

你可以这样使用它:

var imagesrc = safeGetData(data,
    ["results", res, "entities", "media", "0", "media_url"]);

回答by NicolaBaldi

It's an old topic, I know. It's just to add my 2 cents. I'm definitely not a javascript "guru", but here's one of my old attempts. It relies upon a couple of new ecmascript 6 features and it's going to approach the problem in a more "functional" way:

这是一个古老的话题,我知道。这只是为了增加我的 2 美分。我绝对不是 javascript“大师”,但这是我的旧尝试之一。它依赖于几个新的 ecmascript 6 特性,它将以一种更“实用”的方式来解决这个问题:

const prop = (...arr) => obj => arr.reduce((acc, v) => acc && acc.hasOwnProperty(v) ? acc[v] : undefined, obj)

And some tests in order to show how it should work:

以及一些测试以展示它应该如何工作:

describe('unit - prop', () => {
    const event = {
            record: {
                sns: {
                    subject: 'Hello',
                    message: '<div>Welcome!</div>'
                }
            }
        }

    it('property exists', done => {
        const value = prop('record', 'sns', 'subject')(event)
        expect(value)
            .to
            .be
            .equal('Hello')
        done()
    })

    it('property does not exist', done => {
        const value = prop('record', 'bad', 'subject')(event)
        expect(value)
            .to
            .be
            .undefined
        done()
    })
})

Does it make sense?

是否有意义?

回答by Rob

I'm a fan of using short circuit evaluation for these kinds of situations:

我很喜欢在这些情况下使用短路评估:

items && items[val] && doSomething(items[val])

Some people might be repulsed by this, but I think it's a nice and readable way to express something that should only be evaluated if certain conditions are met.

有些人可能对此感到反感,但我认为这是一种很好且易读的方式来表达仅在满足某些条件时才应评估的内容。

In this case, we're actually chaining two short circuit evaluations. First, we determine whether itemshas a defined value. If it undefined, then the rest of the expression is moot, so we won't even bother to evaluate it. AND if it is defined, then let's check for the existence of some property that we're interested in. If it's undefined, then bail out. AND if it's true, we can go ahead and evaluate the rest of the expression.

在这种情况下,我们实际上是在链接两个短路评估。首先,我们确定是否items具有定义的值。如果未定义,则表达式的其余部分没有实际意义,因此我们甚至不会费心评估它。如果它已定义,那么让我们检查一些我们感兴趣的属性是否存在。如果它未定义,则退出。如果它是真的,我们可以继续评估表达式的其余部分。

I think it's a lot easier to reason through at a glance than:

我认为一目了然比以下更容易推理:

if (items) {
   if (items[val]) {
     doSomething(items[val])
   }
}

Ternary operators work similarly:

三元运算符的工作原理类似:

 items 
     ? items[val] 
         ? doSomething(items[val])
         :  alert(‘The property “‘ + val + ‘“ has not yet been defined.')
     : alert(‘You have not yet defined any items!')