JavaScript >> Javascript 文檔 >  >> Tags >> string

JavaScript:檢查變量是否為字符串

簡介

JavaScript 支持多種數據類型,例如字符串、數字、浮點數等。string 是“John Doe”等角色的集合。通常,您通過將字符括在雙引號或單引號中來創建它們。或者,您可以使用 new String() 創建一個字符串 構造函數:

let myString = 'John Doe';
let myString2 = new String("John Doe");

標準解決方案 - 使用 typeof 運算符

在 JavaScript 中,typeof 運算符是檢查任何變量類型的最常用方法。或者,您可以使用 typeof() 方法:

let myString = 'John Doe';

typeof myString;  // string
typeof(myString); // string

如果與字符串一起使用,typeof 運算符返回 "string" .讓我們創建一個簡單的示例來確認這一點:

let myString = "John Doe";

if (typeof myString === "string") {
    console.log("This variable is a string");
} else {
    console.log("This variable is not a string");
}

事實上,myString 是一個字符串:

This variable is a string

注意: 即使變量包含用單引號/雙引號括起來的數字,它仍然會被視為字符串。

typeof 的一個有趣問題 運算符是它不能識別使用 new String() 創建的字符串 構造函數。 new 關鍵字創建一個新的 JavaScript object 那是 String 的實例 類型。因此,typeof 運算符無法正確識別使用 new String() 創建的字符串 構造函數:

let myString = new String('John Doe');

console.log(typeof myString); // "object"

在這種情況下,而不是 typeof 運算符,我們需要使用 instanceof 運算符 - 它可以檢測到使用 new String() 創建的對象 構造函數是 String 的實例 類型:

let myString = new String("John Doe");

if (myString instanceof String) {
    console.log("This variable is a string");
} else {
    console.log("This variable is not a string");
}

myString 是一個字符串,這段代碼會產生如下輸出:

免費電子書:Git Essentials

查看我們的 Git 學習實踐指南,其中包含最佳實踐、行業認可的標準以及隨附的備忘單。停止谷歌搜索 Git 命令並真正學習 它!

This variable is a string

使用 Lodash 圖書館

如果您已經在使用 Lodash 項目中的庫,使用它來檢查變量是否為字符串沒有害處!如果我們不需要 Lodash 來做其他事情,那麼絕對不需要依賴,但是,如果我們已經有了依賴,我們可以使用 _.isString() 方法,返回 true 如果指定的值是字符串原語或 String 對象,使其適用於顯式和隱式創建的字符串:

let myString = new String("John Doe");

if (_.isString(myString)) {
    console.log("This variable is a string");
} else {
    console.log("This variable is not a string");
}

輸出:

This variable is a string

結論

在本文中,我們學習瞭如何在 JavaScript 中檢查變量是否為字符串。此外,我們還了解了它如何與 Lodash 等外部庫一起使用 .


Tutorial JavaScript 教程
  1. 向 Vue-Vite Chrome 擴展添加路由

  2. $(window).scrollTop() 與 $(document).scrollTop()

  3. 我重新創建了我的 VSCode 主題🔥

  4. 將字符串轉換為整數數組

  5. 修復花哨的字體挫折

  6. React Context API 簡單設置

  7. 跨框架組件

  1. Mongoose 更新子文檔

  2. 重新拋出 promise catch 中的錯誤

  3. 如何將行號添加到 Google Prettify 中的所有行?

  4. Javascript:將數組轉換為對象

  5. 通知 API 簡介

  6. 如何將 URL 解析為 javascript 中的主機名和路徑?

  7. 使用 SASS 和 CSS 變量對 React 應用程序進行白標

  1. 如何使用極小極大算法讓您的井字遊戲無與倫比

  2. SailsJS+GraphQL 應用程序的結構

  3. Console.log(this) JavaScript |示例代碼

  4. React Native Mobx 教程 - 第 2 部分