JavaScript OR (||) variable assignment explanation

后端 未结 12 2424
北恋
北恋 2020-11-21 06:41

Given this snippet of JavaScript...

var a;
var b = null;
var c = undefined;
var d = 4;
var e = \'five\';

var f = a || b || c || d || e;

alert(f); // 4
         


        
12条回答
  •  遥遥无期
    2020-11-21 07:13

    According to the Bill Higgins' Blog post; the Javascript logical OR assignment idiom (Feb. 2007), this behavior is true as of v1.2 (at least)

    He also suggests another use for it (quoted): "lightweight normalization of cross-browser differences"

    // determine upon which element a Javascript event (e) occurred
    var target = /*w3c*/ e.target || /*IE*/ e.srcElement;
    

提交回复
热议问题