V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
fqxufo
V2EX  ›  问与答

Javascript 权威指南中关于"或运算"的一个问题

  •  
  •   fqxufo · 2019-06-29 00:43:34 +08:00 · 1174 次点击
    这是一个创建于 1735 天前的主题,其中的信息可能已经有所发展或是发生改变。

    javascript the definitive guide 第六版第四章 77 页有这么一个例子:

    4.10.2 Logical OR (||)

    An idiomatic usage of this operator is to select the first truthy value in a set of alternatives:

    // If max_width is defined, use that. Otherwise look for a value in the preferences object. If that is not defined use a hard-coded constant.

    var max = max_width || preferences.max_width || 500;

    https://s2.ax1x.com/2019/06/29/ZQiv8S.png

    也就是可以利用或运算的特性,从一堆值里面选择出来第一个真值( truthy value)

    但是无论是在 chrome 的 console 里运行这段代码,抑或者新建一个包含该代码的 html,都会产生出这个错误:

    Uncaught ReferenceError: max_width is not defined

    https://s2.ax1x.com/2019/06/29/ZQAS7n.png

    变量 max 不会被成功赋值,依然是 undefined

    为什么这个例子现在不能有效了呢?

    fqxufo
        1
    fqxufo  
    OP
       2019-06-29 01:15:38 +08:00
    不好意思,我理解错了书里面所指的含义
    还是自己基础知识不牢固,实在是抱歉了

    var max_width; var preferences = {}; var max = max_width || preferences.max_width || 500;
    => max = 500
    cutpictureboyxx
        2
    cutpictureboyxx  
       2019-06-29 01:19:13 +08:00 via iPhone   ❤️ 1
    或运算符可以做通过短路的方式做默认值,但也得遵守语法规则啊,你这个变量没定义就使用肯定报错啊
    sunjourney
        3
    sunjourney  
       2019-06-29 12:51:38 +08:00
    你看报错啊
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1129 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 18:46 · PVG 02:46 · LAX 11:46 · JFK 14:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.