簡體   English   中英

在javascript中typeof的用法是什么?

[英]What is the usage of typeof in javascript?

typeof返回原始數據類型,但我不明白為什么它在javascript中使用?

我不知道為什么它在javascript中使用?

typeof習慣了

返回[s]原始數據

例如,如果我想知道某些內容是否未定義,我可以這樣做

if (typeof object === 'undefined')

檢查,因為如果它是未定義的,則沒有數據類型(因為它是未定義的)。 這通常是為什么typeof將用於記錄目的,查看通過ajax接收的內容,或者用於接受可以具有不同類型的參數的函數以及使用typeof檢查該類型等的原因。

typeof是一個一元運算符,放在單個操作數之前,可以是任何類型。 它的值是一個字符串,它指定操作數的類型。

   - x                             typeof x

   undefined                        "undefined"
   null                             "object"
   true or false                    "boolean"
   any number or NaN                "number"
   any string                       "string"
   any function                     "function"
   any non function native object   "object"

typeof與原始值一起工作得很好,除了null.typeof無法區分null和object,因為null是假的,對象是真實的。這里很少有案例研究可能有用。 typeof運算的計算結果為對象比function.How以外的所有對象和數組值typeof與功能的交易可能是超出了這個問題的范圍。

希望這會幫助你。

typeof運算符返回一個表示操作數類型的字符串。 我們可以使用它來以下列方式檢查值的類型:

 let nr = 5; if (typeof nr === 'number') { console.log('nr is number'); } let str = 'hi'; if (typeof str === 'string') { console.log('str is string'); } 

當變量可以有多個值時,這尤其有用。 例如, nullundefinednumber 在這種情況下,我們可以將typeof運算符與if語句結合使用,以便為給定方案執行正確的代碼。

您可以使用JavaScript typeof運算符來查找JavaScript變量的類型。 它也用於驗證變量或輸入。更好地解釋=> http://www.w3schools.com/js/js_datatypes.asp 示例 typeof“John”//返回字符串typeof 3.14 //返回數字typeof false //返回boolean typeof [1,2,3,4] //返回對象typeof {name:'John',age:34} //返回對象

在javascript中輸入為什么使用它?

有時您可能需要檢查變量中存儲的數據類型,例如,typeof是一個運算符而不是一個函數,它與停止執行函數並從該函數返回值的return語句完全不同。

typeof運算符返回一個字符串,指示未評估的操作數的類型。

console.log(typeof 'name');
// expected output: "string"
console.log(typeof 74);
// expected output: "number"
console.log(typeof true);
// expected output: "boolean"
console.log(typeof declaredButUndefinedVariable);
// expected output: "undefined";

類型的MDN Web文檔

typeof運算符后面始終是其操作數:

typeof UnaryExpression =>請記住,括號是可選的,但請記住:括號對於確定表達式的數據類型非常有用。

var data = 100;
typeof data + ' Bye'; // return 'number Bye'
typeof (data + 'Bye'); // return 'string'

其他例子:

// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof(42) === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number('1') === 'number'; // Number tries to parse things into numbers


// Strings
typeof '' === 'string';
typeof 'bla' === 'string';
typeof `template literal` === 'string';
typeof '1' === 'string'; // note that a number within a string is still typeof string
typeof (typeof 1) === 'string'; // typeof always returns a string
typeof String(1) === 'string'; // String converts anything into a string, safer than toString


// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(1) === 'boolean'; // Boolean will convert values based on if they're truthy or falsy, equivalent to !!


// Symbols
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'


// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined'; 


// Objects
typeof {a: 1} === 'object';

// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === 'object';

typeof new Date() === 'object';
typeof /regex/ === 'object'; // See Regular expressions section for historical results

以下是一個常見的黑客類型,有點問題::

const type = obj => Object.prototype.toString.call(obj);

type("abc");// [object String]
type(123);// [object Number]// What's with all the objects?
type([]);// [object Array]
type({});// [object Object]
type(Object.create(null));// [object Object]
type(-1/0);// [object Number] Not exactly a true number
type(NaN);// [object Number] WTF?

正如您所看到的,它有一些問題。 它總是返回兩個用括號括起來的類型,第一個總是一個“對象”。 如果總是返回第一類無用信息,這將使其成為無用信息。 其次,它的區別在於它的局限性。 它無法告訴我們對象是作為文字(普通)還是使用Object.create()創建的,在調用時需要關鍵字“new”。 它也很簡單地稱無限和NaN為數字。

我希望分享一個更好的類型功能,修復所有這些事情。 它適用於所有基元,包括符號,異常(錯誤,未定義,null和NaN),本機對象和函數的最常見情況(數組,映射,對象,函數,數學,日期,承諾等等),以及它甚至可以在用戶制作的對象(標識為Plain)和DOM元素(標識為HTML)之間進行檢測。 它適用於所有現代和較舊的瀏覽器。 它分為幾個函數,使代碼更加用戶友好:

const isDOM = obj => (obj.nodeType && !isPlain(obj)) ? true : false;
const isPlain = obj => obj ? obj.constructor === {}.constructor : false;
const sanString = str => str.replace(/[^a-zA-Z ]/g, "");
const isNaN = obj => (Object.is(obj, NaN) === true) ? true : false;

function objType(obj){
if(obj === undefined) return undefined;
if(obj === Infinity) return Infinity;
if(obj === -Infinity) return -Infinity;
if(isDOM(obj)) return 'HTML';
let str = Object.prototype.toString.call(obj);
if(str === '[object Object]' && isPlain(obj)) return 'Plain';
str = sanString(str).split(' ');
if(str[1] === 'Number' && isNaN(obj)) return NaN;
return str[1];}
}

使用這樣:

objType(null);// Null
objType(undefined);// undefined
objType("abc");// String
objType(123);// Number
objType([]);// Array
objType({});// Plain not [object Object]
objType(Object.create(null));// Object is what we want
objType(document.body);// HTML
objType(-1/0);// -Infinity
objType(NaN);// NaN

如果您發現任何錯誤或錯誤或有更好的解決方案(不是來自liberaries或freameworks),請告訴我。 我很樂意解決這個問題。

暫無
暫無

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

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