简体   繁体   English

将javascript中的逻辑操作数与对象一起使用

[英]Using logical operands in javascript with objects

I came across the use of the logical operand && with objects however would like to know whether expressions are evaluated in the manner below only when dealing with objects. 我遇到了将逻辑操作数&&与对象一起使用的情况,但是想知道是否仅在处理对象时才按以下方式评估表达式。

Code Sample 代码样例

var sampleObject = {
            size: 10, 
            shoe: {
                make: "nike",
                model: "air jordon"
            },
            color: "red"
            }

    console.log(sampleObject.size && sampleObject.shoe.model);

The out of console.log(sampleObject.size && sampleObject.shoe.model); out of console.log(sampleObject.size && sampleObject.shoe.model); returns air jordon . 返回air jordon My understanding is that because the first condition ie sampleObject.size evaluated to true and isn't falsely it returns the value contained in the object sampleObbject.shoe.model . 我的理解是,因为第一个条件(即sampleObject.size评估为true且不是falsely所以它返回对象sampleObbject.shoe.model包含的值。

The Javascript && operator first evaluates its left operand. JavaScript &&运算符首先评估其左操作数。 If it's a falsey value, it is the value of the entire expression. 如果是假值,则为整个表达式的值。 If it's a truthy value, then the right operand is evaluated, and it is returned. 如果它是一个真实值,那么将评估正确的操作数,然后将其返回。

Zeros, empty strings, undefined, and false are all falsey values. 零,空字符串,未定义和false均为falsey值。 Your sampleObject.size value is 10, a truthy value, so the right operand is evaluated and used as the value of the entire expression. 您的sampleObject.size值为10,这是一个真实值,因此将评估正确的操作数并将其用作整个表达式的值。

Note that none of this depends on the values being objects. 请注意,这都不取决于作为对象的值。

The || || and && operators run from left to right. &&运算符从左到右运行。 In the case of || 对于|| , the first truthy value is returned. ,则返回第一个真实值。 For && , it's the first falsy value. 对于&& ,这是第一个虚假的值。 In both cases, the last one is returned if no suitable return value is found. 在这两种情况下,如果找不到合适的返回值,则返回最后一个。

So, in this case, the fact that it returned a truthy value for the expression means that both sampleObject.size and sampleObject.show.model are truthy values. 因此,在这种情况下,它为表达式返回了真实值,这意味着sampleObject.sizesampleObject.show.model均为真实值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM