fqxufo
V2EX  ›  问与答

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

  •  
  •   fqxufo · Jun 29, 2019 · 2109 views
    This topic created in 2511 days ago, the information mentioned may be changed or developed.

    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
       Jun 29, 2019
    不好意思,我理解错了书里面所指的含义
    还是自己基础知识不牢固,实在是抱歉了

    var max_width; var preferences = {}; var max = max_width || preferences.max_width || 500;
    => max = 500
    cutpictureboyxx
        2
    cutpictureboyxx  
       Jun 29, 2019 via iPhone   ❤️ 1
    或运算符可以做通过短路的方式做默认值,但也得遵守语法规则啊,你这个变量没定义就使用肯定报错啊
    sunjourney
        3
    sunjourney  
       Jun 29, 2019
    你看报错啊
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3734 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 10:37 · PVG 18:37 · LAX 03:37 · JFK 06:37
    ♥ Do have faith in what you're doing.