typeof
returns the primitive data type but I am not getting why it is used in javascript?
问题:
回答1:
I am not getting why it is used in javascript?
typeof
is used to
return[s] the primitive data
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 typeof
would 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.
回答2:
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.
- 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 studies which may be useful. typeof evaluates to object for all object and array values other than function.How typeof
deals with function is probably beyond the scope of this question.
Hope this will help you.
回答3:
The typeof
operator 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:
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 typeof
operator in conjunction with an if
statement in order to execute the right code for a given scenario.
回答4:
You can use the JavaScript typeof
operator 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.asp
Example
typeof "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
回答5:
typeof in javascript why it is used?
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.
The typeof operator returns a string indicating the type of the unevaluated operand.
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
The typeof operator is always followed by its operand:
typeof UnaryExpression => keep in mind that parentheses are optional but remember that: Parentheses are very useful to determine the data type for expressions.
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
回答6:
The following is a common typeof hack which is somewhat problematic::
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.
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:
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.