解释下面的代码,因为我不理解逻辑或的目的

Explain code below, as i dont understand purpose of logical or

本文关键字:不理解 因为 代码 解释      更新时间:2023-09-26

我在我的项目中使用此代码,但不理解代码中操作符(||)的目的

window.jQuery || document.write('<script src="js/libs/jquery-1.9.0.min.js">'x3C/script>')

如果全局对象中没有定义jQuery,那么编写一个脚本元素从服务器加载jQuery。

这是一个条件包含。它只是

的简写。
if ( window.jQuery ) {
} else {
    document.write('<script src="js/libs/jquery-1.9.0.min.js">'x3C/script>')
}

在这种情况下||操作符用来检查,如果窗口。jquery是真的(存在的)就使用它,否则调用document.write(''x3C/script>')来附加它。

var name = newName || 'Mike';
console.log(name) // will display Mike 

因为newName变量确实存在,但是如果我这样做

var newName = 'John';
var name = newName || 'Mika';
console.log(name) // will display John

因为newName变量存在并且它的值是'John'