- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > web開(kāi)發(fā) > JavaScript >
- js中不常見(jiàn)的運算符與操作符總結
空值合并運算符: ??
當左側的操作數為 null 或者 undefined 時(shí),返回其右側操作數,否則返回左側操作數。
null ?? 'huli' // huli undefined ?? 'huli' // undefined '' ?? 'huli' // '' [] ?? 'huli' // [] ({}) ?? 'huli' // {} NaN ?? 'huli' // NaN false ?? 'huli' // false 0 ?? 'huli' // 0
邏輯空賦值: ??=
邏輯空賦值運算符 (x ??= y) 僅在 x 是 nullish (null 或 undefined) 時(shí)對其賦值。
const a = { duration: 50 }; a.duration ??= 10; console.log(a.duration); // expected output: 50 a.speed ??= 25; console.log(a.speed); // expected output: 25
邏輯或: ||
存在真則為真, , 以前面的為準
const a = 3; const b = -2; console.log(a > 0 || b > 0); // true
可以是false的值
null
undefined
NaN
"" 與 ''
0
false
邏輯或賦值: ||=
有則返回,沒(méi)有則賦值
const a = { duration: 50, title: '' }; a.duration ||= 10; console.log(a.duration); // expected output: 50 a.title ||= 'title is empty.'; console.log(a.title); // expected output: "title is empty"
邏輯與: &&
都存在則為真, 以后面的為準
const a = 3; const b = -2; console.log(a > 0 && b > 0); // expected output: false
邏輯與賦值: &&=
存在則賦值
let a = 1; let b = 0; a &&= 2; console.log(a); // expected output: 2 b &&= 2; console.log(b); // expected output: 0
可選鏈操作符: ?.
可選鏈操作符( ?. )允許讀取位于連接對象鏈深處的屬性的值,而不必明確驗證鏈中的每個(gè)引用是否有效。?. 操作符的功能類(lèi)似于 . 鏈式操作符,不同之處在于,在引用為空(nullish ) (null 或者 undefined) 的情況下不會(huì )引起錯誤,該表達式短路返回值是 undefined。與函數調用一起使用時(shí),如果給定的函數不存在,則返回 undefined。
const adventurer = { name: 'Alice', cat: { name: 'Dinah' } }; const dogName = adventurer.dog?.name; console.log(dogName); // expected output: undefined console.log(adventurer.someNonExistentMethod?.()); // expected output: undefined
到此這篇關(guān)于js中不常見(jiàn)的運算符與操作符的文章就介紹到這了,更多相關(guān)js運算符與操作符內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站