iT邦幫忙

3

JavaScript宣告上的一些問題(以解決)

jojo 2021-03-31 22:40:501451 瀏覽

程式碼來源

const weatherCode2Type = (weatherCode) => {
  const [weatherType] =
    Object.entries(weatherTypes).find(([weatherType, weatherCodes]) =>
      weatherCodes.includes(Number(weatherCode))
    ) || [];

  return weatherType;

問題

  1. 請問為什麼要用中括號宣告變數[weatherType]?
  2. 最後接 || [];是甚麼意思?
    求救
    /images/emoticon/emoticon06.gif
定義陣列的縮寫方法
new Array();
或者
[];
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

4
淺水員
iT邦大師 6 級 ‧ 2021-03-31 23:05:23
最佳解答
let [a, b] = ["aaa", "123"];
console.log(a); //輸出 "aaa"
console.log(b); //輸出 "123"
let a = false || '123';
let b = 0 || [];
let c = '123' || '456';
console.log(a); //輸出 "123"
console.log(b); //輸出 Array []
console.log(c); //輸出 "123" (因為 "123" 算是 true,所以不會往後執行)
jojo iT邦新手 5 級 ‧ 2021-04-01 14:42:23 檢舉

謝謝!
這樣我又產生了另一個疑問,"123"是字串為什麼是布林型別呀?
是因為當中又根據甚麼判斷式來決定嗎?
是不是後續設定的值只要不為空就是true?

jojo iT邦新手 5 級 ‧ 2021-04-01 15:10:37 檢舉

整理

在javascript有個叫Toboolean
ToBoolean
來源

解析

&& 與 || 運算子在判斷的時候,會先對左邊的數值進行檢查。

  • 如果是 Boolean 類型就再做後續的判斷,如果不是?那就會透過 ToBoolean 判斷是「falsy」或「truthy」來轉換成對應的 true 跟 false 。(這邊作者運用?條件 (三元) 運算子來敘述,好酷)
  • 對 || 運算子來說,若第一個數值轉換為 true,則回傳第一個數值,否則回傳第二個數值。
  • 對 && 運算子來說,若第一個數值轉換為 true,則回傳第二個數值,否則回傳第一個數值。

參考

感謝淺水員激發我的好奇心

淺水員 iT邦大師 6 級 ‧ 2021-04-01 18:24:04 檢舉

是我一開始寫得太簡略
本來想過要不要貼一下資料的
後來一忙忘記了

我要發表回答

立即登入回答