javascript逻辑分配如何工作? [英] How does javascript logical assignment work?

查看:128
本文介绍了javascript逻辑分配如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中,如果我们有一些代码,例如

  var a =one; 
var b = q ||一个;
alert(b);

逻辑OR运算符将为b分配值,警报将为1。 / p>

这仅限于作业,还是我们可以在任何地方使用它?



似乎空字符串被视为与undefined相同。这是对吗?



这如何与AND变量一起使用?它们的组合怎么样?



什么时候使用这些习语,或什么时候不用?

解决方案

对于 q || a 评估为 a q 应为'falsy'值。你做的是短路评估。



回答你的问题:


  1. 逻辑运算符(如和 - && 或 - || )可以是也用于其他情况。更常见的是条件语句,如 if 此处更多内容


  2. 空字符串不被视为 undefined 。两者都是虚假的价值观。还有一些虚假的价值观。 更多信息


  3. <$ JavaScript中的c $ c> AND 或&& 不是变量。这是一个运营商


  4. 你使用的习惯用法很常见。



    var x = val || '默认'; //通常是的替代



    var x = val? val:'default'//或



    if(val)
    var x = val;
    else
    var x ='default';



In javascript, if we have some code such as

var a = "one";
var b = q || a;
alert (b);

The logical OR operator will assign a's value to b, and the alert will be "one."

Is this limited to assignments only or can we use it everywhere?

It seems an empty string is treated the same as undefined. Is this right?

How does this work with AND variables? What about combinations of them?

What is a good example of when to use these idioms, or when not to?

解决方案

For your q || a to evaluate to a, q should be a 'falsy' value. What you did is called "Short circuit evaluation".

Answering your questions:

  1. The logical operators (like and - &&, or - ||) can be used in other situations too. More generally in conditional statements like if. More here

  2. Empty string is not treated as undefined. Both are falsy values. There are a few more falsy values. More here

  3. AND, or && in JavaScript, is not a variable. It is an operator

  4. The idiom you have used is quite common.

    var x = val || 'default'; //is generally a replacement for

    var x = val ? val : 'default' //or

    if (val) var x = val; else var x = 'default';

这篇关于javascript逻辑分配如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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