簡體   English   中英

何時使用 Boolean(var1)?

[英]When to use Boolean(var1)?

redux 教程中它說:

const canSave = Boolean(title) && Boolean(content) && Boolean(userId)
  • 但是 userId = 0 然后會轉換為 false
  • 你不能只使用以下內容嗎?
const canSave = title && content && userId

是的,您可以想象一下,對於某些標題值,您會得到奇怪的結果。 想象一下有人在他們的標題或內容中添加了false信息。 雖然不確定 userId

在(可能有點不尋常)不檢查結果的真假,而是檢查另一個 boolean 的情況下,必須明確轉換為 Boolean。 為了說明,以下邏輯失敗:

 const title = ''; const content = 'content'; const userId = 'foo'; const canSave = title && content && userId; if (canSave === false) { console.log('cant save'); throw new Error(); } console.log('saving...');

canSave轉換為 boolean 將解決該問題。

但更干燥的方法是在整個結果上調用Boolean ,而不是在每個單獨的表達式上。

const canSave = Boolean(title && content && userId);

但是 userId = 0 然后會轉換為 false

不知道你在做什么。 如果這是一個問題,也許您想要的邏輯是typeof userId === 'number'

如果你使用 TypeScript 和title && content && userId表達式,表達式評估是一個string ,TSC 會拋出錯誤,見下例:

import React, { useState } from 'react';

export default function Test() {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [userId, setUserId] = useState('');

  return <button disabled={title && content && userId}>click me</button>;
}

錯誤:

類型 'string' 不可分配給類型 'boolean'.ts(2322) index.d.ts(2054, 9):預期類型來自屬性 'disabled',它在類型 'DetailedHTMLProps<ButtonHTMLAttributes, HTMLButtonElement> 上聲明'

所以你需要將字符串轉換為 boolean。 來自文檔Boolean

不要使用Boolean object 將非布爾值轉換為 boolean 值。 要執行此任務,請改為使用Boolean作為 function 或雙非運算符:

var x = Boolean(expression);     // use this...
var x = !!(expression);          // ...or this

所以代碼應該是:

const canSave = Boolean(title) && Boolean(content) && Boolean(userId);
// or
const canSave = !!title && !!content && !!userId;

他們兩個都很好。

除了使用 Boolean 之外,您始終可以使用此快捷方式:

const canSave = !!(title && content && userId)

但是!! 將其轉換為 Boolean。

例如,您需要將 boolean 從服務器傳遞到客戶端,並且您不希望字符串字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM