javascript javascript中typeof的用法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33663747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:45:45  来源:igfitidea点击:

What is the usage of typeof in javascript?

javascripttypeof

提问by Rohit Goyal

typeofreturns the primitive data type but I am not getting why it is used in javascript?

typeof返回原始数据类型,但我不明白为什么在 javascript 中使用它?

回答by Cilan

I am not getting why it is used in javascript?

我不明白为什么在 javascript 中使用它?

typeofis used to

typeof习惯于

return[s] the primitive data

返回[s]原始数据

For example, if I wanted to know if something was undefined, I could do

例如,如果我想知道某事是否未定义,我可以这样做

if (typeof object === 'undefined')

to check because if it is undefined there is no datatype (because it's undefined). This is generally why typeofwould be used other than for logging purposes, to see what is received through ajax, or for making functions that accept a parameter that can have different types and checking that type with typeof, etc.

要检查,因为如果它未定义,则没有数据类型(因为它未定义)。这通常是为什么typeof除了用于日志记录目的,查看通过 ajax 接收到的内容,或者用于制作接受可以具有不同类型的参数并使用typeof等检查该类型的函数之外的原因。

回答by Willem van der Veen

The typeofoperator returns a string which represents the type of the operand. We can use this to check the type of a value in the following manner:

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');
}

This can be especially useful when a variable can have multiple values. For example, null, undefined, or a number. In this case we can use the typeofoperator in conjunction with an ifstatement in order to execute the right code for a given scenario.

当一个变量可以有多个值时,这尤其有用。例如,nullundefined,或number。在这种情况下,我们可以将typeof运算符与if语句结合使用,以便为给定的场景执行正确的代码。

回答by brk

typeof is an unary operator that is placed before a single operand which can be of any type. Its value is a string that specifies the type of operand.

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"

The typeof works sufficiently well with primitive values except null.typeof cannot distinguish between null & object because null is falsy & objects are truthy.Here are few case studieswhich may be useful. typeof evaluates to object for all object and array values other than function.How typeofdeals with function is probably beyond the scope of this question.

除了 null.typeof 不能区分 null 和 object,因为 null 是假的,而对象是真值,typeof 对原始值工作得很好。这里有 一些可能有用的案例研究。typeof 对除函数typeof以外的所有对象和数组值计算为对象。如何处理函数可能超出了这个问题的范围。

Hope this will help you.

希望这会帮助你。

回答by booluw

You can use the JavaScript typeofoperator to find the type of a JavaScript variable. It is also use to validate a variable or input.Explain better => http://www.w3schools.com/js/js_datatypes.aspExampletypeof "John" // Returns string typeof 3.14 // Returns number typeof false // Returns boolean typeof [1,2,3,4] // Returns object typeof {name :'John', age:34} // Returns object

您可以使用 JavaScripttypeof运算符来查找 JavaScript 变量的类型。它还用于验证变量或输入。更好地解释 => http://www.w3schools.com/js/js_datatypes.asp Exampletypeof "John" // 返回字符串 typeof 3.14 // 返回数字 typeof false // 返回boolean typeof [1,2,3,4] // 返回对象 typeof {name :'John', age:34} // 返回对象

回答by Savino9

typeof in javascript why it is used?

javascript中的typeof为什么使用它?

Sometimes you might need to check what kind of data is stored in a variable for example, typeof is an operator not a function and it's completely different from the return statement that stops the execution of a function and returns a value from that function.

有时您可能需要检查存储在变量中的数据类型,例如 typeof 是一个运算符而不是一个函数,它与停止执行函数并从该函数返回值的 return 语句完全不同。

The typeofoperator returns a string indicating the type of the unevaluated operand.

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";

typeof MDN web docs

类型 MDN 网络文档

The typeof operator is always followed by its operand:

typeof 运算符总是跟在它的操作数之后:

typeof UnaryExpression=> keep in mind that parentheses are optional but remember that: Parentheses are very useful to determine the data type for expressions.

typeof UnaryExpression=> 请记住括号是可选的,但请记住:括号对于确定表达式的数据类型非常有用。

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

Other examples:

其他例子:

// 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

回答by Jules Manson

The following is a common typeof hack which is somewhat problematic::

以下是一种常见的 hack 类型,它有点问题:

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?

As you can see there are a few problems with it. It always returns two types wrapped in brackets with the first always an "object". This makes the first type useless information if it is always returned. Secondly it is somehat limited in what it distinguishes. It cannot tell us if an object was created as a literal (plain) or with Object.create() which would require the keyword "new" when called. It also falesly calls infinity and NaN a number.

如您所见,它存在一些问题。它总是返回用括号括起来的两种类型,第一种总是“对象”。如果总是返回第一种类型的信息,这将使其成为无用信息。其次,它的区别在某种程度上是有限的。它无法告诉我们一个对象是作为文字(普通)创建的还是使用 Object.create() 创建的,后者在调用时需要关键字“new”。它还错误地将无穷大和 NaN 称为数字。

I wish to share a better typeof function that fixes all of those things. It works for all primitives including symbols, anomalies (errors, undefined, null, and NaN), most common cases of native objects and functions (Array, Map, Object, Function, Math, Date, Promise, and many more), and it can even detect between user made objects (identified as Plain) and DOM elements (identified as HTML). It should work for all modern and somewhat older browsers. It is broken down into several functions to make the code more user friendly:

我希望分享一个更好的 typeof 函数来修复所有这些问题。它适用于所有原语,包括符号、异常(错误、未定义、空值和 NaN)、本机对象和函数的最常见情况(数组、映射、对象、函数、数学、日期、承诺等),并且它甚至可以检测用户创建的对象(标识为普通)和 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];}
}

Use like this:

像这样使用:

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

Please let me know if you find any errors or bugs or have a better solution (not from liberaries or freameworks). I will gladly promply fix it.

如果您发现任何错误或错误或有更好的解决方案(不是来自 liberaries 或 freameworks),请告诉我。我会很乐意及时修复它。