亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JavaScript:如何通過三元條件的邊緣情況

JavaScript:如何通過三元條件的邊緣情況

智慧大石 2022-01-20 20:39:52
我如何在這里實現一些可能發生的邊緣情況。//邊緣情況下,如果mediaType是undefined,它應該返回undefined或者infinity,如果mediaType是xs它應該返回xs與當前實現。//編碼當前實現function getCurrentBreakpoint(mediaType) {  const mediaTypes = ["xs", "sm", "md", "lg", "xl", "infinity"];  return mediaTypes[mediaTypes.indexOf(mediaType) - 1];}這里有任何幫助。
查看完整描述

3 回答

?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

您可以使用Array#find:


function getCurrentBreakpoint(mediaType) {

  const mediaTypes = ["xs", "sm", "md", "lg", "xl", "infinity"];

  return mediaTypes.find(mt => mt === mediaType);

}


console.log(getCurrentBreakpoint('xs'));

console.log(getCurrentBreakpoint('foo'));

console.log(getCurrentBreakpoint());


如果你真的想使用三元運算符,你可以使用它來代替。


return mediaTypes.includes(mediaType) ? mediaType : undefined


查看完整回答
反對 回復 2022-01-20
?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

您可以通過簡單地檢查 mediaType 是否未定義


if (!mediaType) {

/* ... */

}

目前尚不清楚您調用該函數的上下文,但如果您想返回 undefined (我認為這不是一個好的做法),您可以這樣做:


if (!mediaType) {

    return mediaType

}

編輯:用戶將帖子和標題更改為與三元一起使用。


那么它將是


return !mediaType ? mediaType : /* whatever */

如果是另一種方式,并且您希望始終定義它,則可以使用二進制條件:


return mediaType && /* whatever */


查看完整回答
反對 回復 2022-01-20
?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

可能的解決方案:


      function getCurrentBreakpoint(mediaType) {

          const mediaTypes = ["xs", "sm", "md", "lg", "xl", "infinity"];

          return mediaType=="xs"?"xs":mediaTypes[mediaTypes.indexOf(mediaType) - 1]?mediaTypes[mediaTypes.indexOf(mediaType) - 1]:"infinity";

       }


查看完整回答
反對 回復 2022-01-20
  • 3 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號