JavaScript is a weakly typed (or dynamically typed) language, meaning that the type of a variable is indeterminate. This article will share a summary of javascript conversions, including explicit and implicit conversions
The typeof operator
Use the Typeof operator to view the data types of JavaScript variables
typeof myCar // return undefined (if myCar is not declared)
typeof "John" / / return a string
typeof 3.14 / / return number
typeof NaN / / return number
typeof false / / returns a Boolean
typeof null / / return the object
typeof [1.2.3.4] / / return the object
typeof {name:'John'.age:34} / / return the object
typeof new Date(a)/ / return the object
typeof function () {} / / return function
Copy the code
Note: If the object is JavaScript Array or JavaScript Date, we cannot passtypeofTo determine their type, because they all return object
- The data type of an undefined variable is undefined
- The data type for NaN is number
- The data type of an Array is Object
- The data type of a Date is Object
- The data type of NULL is Object
The constructor property
The constructor property returns the constructors for all JavaScript variables
"John".constructor // Return function String() {[native code]}
(3.14).constructor Number() {[native code]}
false.constructor Boolean() {[native code]}
function () {}.constructor Function(){[native code]}
[1.2.3.4].constructor // Return Array() {[native code]}
{name:'John'.age:34}.constructor Object() {[native code]}
new Date().constructor Date() {[native code]}
Copy the code
Simple judgment type chunk function encapsulation
function isType(type) {
return function (obj) {
return obj.constructor.toString().indexOf(type) > -1; }}// You can use the constructor attribute to check whether the object is an Array (containing the string "Array"):
var isArray = isType("Array")
console.log(isArray([1.2.3])) //true
// You can use the constructor attribute to check whether the object is a Date (containing the string "Date"):
var isDate = isType("Date")
console.log(isDate(new Date())) //true
Copy the code
The instanceof operator is dissected in depth
In JavaScript, we use the typeof operator to determine the typeof a variable. The problem with using the typeof operator is that it returns “object” no matter what typeof object it refers to. ECMAScript introduces another Java operator, Instanceof, to solve this problem. The instanceof operator is similar to the typeof operator and is used to identify the typeof object being processed. Unlike the Typeof method, the Instanceof method requires the developer to explicitly identify the object as a particular type. Such as:
var oStringObject = new String("hello world")
console.log(oStringObject instanceof String) / / output "true"
Copy the code
This code asks “Is the variable oStringObject an instance of String?” OStringObject is indeed an instance of String, so the result is “true”. Although not as flexible as typeof methods, instanceof methods can be useful in cases where typeof methods return “object.
Instanceof is a common usage
// Determine if foo is an instance of class foo
function Foo(){}
var foo = new Foo();
console.log(foo instanceof Foo)//true
Copy the code
Instanceof in relation to inheritance
// Determine if foo is an instance of class foo and of its parent type
function Aoo(){}
function Foo(){}
Foo.prototype = new Aoo();//JavaScript prototype inheritance
var foo = new Foo();
console.log(foo instanceof Foo)//true
console.log(foo instanceof Aoo)//true
Copy the code
Instanceof complex usage
console.log(Object instanceof Object) //true
console.log(Function instanceof Function) //true
console.log(Number instanceof Number) //false
console.log(String instanceof String) //false
console.log(Function instanceof Object) //true
function Foo() {}console.log(Foo instanceof Function) //true
console.log(Foo instanceof Foo) //false
Copy the code
Is the code above confusing you again? Why do Object and Function instanceof themselves equal true, but other classes instanceof themselves do not? How to explain? To get to the bottom of instanceof’s mystery, you need to start in two ways:
- How is this operator defined in the language specification
- JavaScript prototype inheritance mechanism
JavaScript instanceof operator code
function instance_of(L, R) {//L represents the left expression, R represents the right expression
var O = R.prototype;// take the display prototype of R
L = L.__proto__;// take the implicit prototype of L
while (true) {
if (L === null)
return false;
if (O === L)// Return true if O is strictly L
return true; L = L.__proto__; }}Copy the code
JavaScript prototype inheritance mechanism
Object instanceof Object
// For convenience, first distinguish between left and right expressions
ObjectL = Object, ObjectR = Object;
// Follow the rules step by step
O = ObjectR.prototype = Object.prototype
L = ObjectL.__proto__ = Function.prototype
// First judgmentO ! = L// loop to see if L still has __proto__
L = Function.prototype.__proto__ = Object.prototype
// Second judgment
O == L
/ / return true
Copy the code
Function instanceof Function
// For convenience, first distinguish between left and right expressions
FunctionL = Function, FunctionR = Function;
// Follow the rules step by step
O = FunctionR.prototype = Function.prototype
L = FunctionL.__proto__ = Function.prototype
// First judgment
O == L
/ / return true
Copy the code
Foo instanceof Foo
// For convenience, first distinguish between left and right expressions
FooL = Foo, FooR = Foo;
// Follow the rules step by step
O = FooR.prototype = Foo.prototype
L = FooL.__proto__ = Function.prototype
// First judgmentO ! = L// Loop again to see if L still has __proto__
L = Function.prototype.__proto__ = Object.prototype
// Second judgmentO ! = L// Loop again to see if L still has __proto__
L = Object.prototype.__proto__ = null
// The third judgment
L == null
Copy the code
Multiple inheritance in Dojo
dojo.declare("Aoo".null{}); dojo.declare("Boo".null{}); dojo.declare("Foo",[Aoo,Boo],{});
var foo = new Foo();
console.log(foo instanceof Aoo);//true
console.log(foo instanceof Boo);//false
console.log(foo.isInstanceOf(Aoo));//true
console.log(foo.isInstanceOf(Boo));//true
Copy the code
Object.prototype.toString
ToString () is a prototype method for Object that, by default, returns the current Object’s [[Class]]. This is an internal property of the form [object Xxx], where Xxx is the type of the object. For object objects, toString() returns [Object object]. For other objects, you need to call call Apply to return the correct type information
Object.prototype.toString.call(' ') // [object String]
Object.prototype.toString.call(1) // [object Number]
Object.prototype.toString.call(true) // [object Boolean]
Object.prototype.toString.call(Symbol()) // [object Symbol]
Object.prototype.toString.call(undefined) // [object Undefined]
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(new Function()) // [object Function]
Object.prototype.toString.call(new Date()) // [object Date]
Object.prototype.toString.call([]) // [object Array]
Object.prototype.toString.call(new RegExp()) // [object RegExp]
Object.prototype.toString.call(new Error()) // [object Error]
Object.prototype.toString.call(window) // [object global] window is a reference to global
Object.prototype.toString.call(document) // [object HTMLDocument]
Copy the code
function isType(type) {
return function(data) {
return Object.prototype.toString.call(data) == type //true}}var isArray = isType("[object Array]")
var isDate = isType("[object Date]")
console.log(isArray([1.2.3]));
console.log(isDate(new Date()));
Copy the code
JavaScript type conversion
JavaScript variables can be converted to new variables or other data types:
- By using JavaScript functions
- Automatically converts through JavaScript itself
Convert other types to strings
The global method String() converts numbers to strings. This method can be used with any type of numbers, letters, variables, expressions:
var x = 10
String(x) // Convert variable x to a string and return
String(123) // Converts the number 123 to a string and returns
String(100 + 23) // Converts a numeric expression to a string and returns it
Copy the code
The Number method toString() has the same effect
x.toString()
(123).toString()
(100 + 23).toString()
Copy the code
You can find more ways to convert numbers to strings in the Number method section
methods | describe |
---|---|
toExponential() | Converts the value of an object to an exponential notation |
toFixed() | To convert a Number to a string with the specified Number of digits behind the decimal point |
toPrecision() | Formats a number to the specified length |
The global method String() converts a Boolean value to a String
String(false) / / return "false"
String(true) / / return "true"
Copy the code
The Boolean method toString() has the same effect
false.toString() / / return "false"
true.toString() / / return "true"
Copy the code
The global method String() converts a date object to a String
Date(a)Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)
String(new Date()) Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)
Copy the code
The Date method toString() has the same effect
obj = new Date()
obj.toString() Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)
Copy the code
You can see more about the date-to-string function in the Date method section:
methods | describe |
---|---|
getDate() | Returns the day of the month from the Date object (1 to 31) |
getDay() | Returns a day of the week from the Date object (0 to 6) |
getFullYear() | Returns the year as four digits from the Date object |
getHours() | Return the hour of the Date object (0 to 23) |
getMilliseconds() | Return the milliseconds of the Date object (0 to 999) |
getMinutes() | Return the minutes of the Date object (0 to 59) |
getMonth() | Returns the month (0 to 11) from the Date object |
getSeconds() | Return the number of seconds of the Date object (0 to 59) |
getTime() | Returns the number of milliseconds from January 1, 1970 to the present |
The unary Operator + can be used to convert a variable to a number:
var y = "5"; // y is a string
var x = + y; // x is a number
Copy the code
If the variable cannot be converted, it will still be a number, but with a value of NaN (not a number):
var y = "John"; // y is a string
var x = + y; // x is a number (NaN)
Copy the code
Convert other types to numbers
The global method Number() converts strings to numbers strings containing numbers (such as “3.14”) to numbers (such as 3.14) empty strings are converted to 0 other strings are converted to NaN (not a Number)
Number("3.14") / / return 3.14
Number("") / / returns 0
Number("") / / returns 0
Number("99, 88") / / returns NaN
Copy the code
You can see more about how strings can be converted to numbers in the Number method section:
methods | describe |
---|---|
parseFloat() | Parse a string and return a floating point number |
parseInt() | Parse a string and return an integer |
Js round to preserve two decimal places, and not complement 0
function fomatFloat(n, pos) {
var num = parseFloat(n)
if (isNaN(num)) return false
num = Math.round(num * Math.pow(10, pos)) / Math.pow(10, pos) / power/pow
// num = Math.round(num * 10 ** pos) / 10 ** pos
var str = num.toString()
var str_l = str.indexOf('. ')
if (str_l < 0 && pos > 0) {
str_l = str.length
str += '. '
}
while (str.length <= str_l + pos) { str += '0' }
return str
}
console.log("3.10159267 Reserving 2 decimal places:" + fomatFloat(3000.5005.10))
Copy the code
The global method Number() converts a Boolean value to a Number
Number(false) / / returns 0
Number(true) / / returns 1
Number(26.3 "aaa") NaN / / results
Copy the code
The global method Number() converts dates to numbers
d = new Date(a);Number(d) / / back to 1404568027739
Copy the code
The date method getTime() has the same effect
d = new Date(a); d.getTime()/ / back to 1404568027739
Copy the code
Converts other types to Booleans
Boolean(1) //true
Boolean(11) //true
Boolean(-10) //true
Boolean("Ha ha") //true
Boolean("000") //true
Boolean("0"); //true
Boolean("") //flase
Boolean(-0) //flase
Boolean(0) //flase
Boolean(null) //flase
Boolean(undefined) //flase
Copy the code
Automatic conversion type
When JavaScript tries to operate on an “incorrect” data type, it automatically converts to the “correct” data type. The following output is not what you expect:
5 + null // returns 5. Null converts to 0
"5" + null // return "5null" null to "null"
"5" + 1 // return "51" 1 to "1"
"5" - 1 // return 4 "5" to convert to 5
Copy the code
JavaScript automatically calls the toString() method of the variable when you try to output an object or a variable:
document.getElementById("demo").innerHTML = myVar;
myVar = {name:"Fjohn"} // toString converts to "[object object]"
myVar = [1.2.3.4] // toString converts to "1,2,3,4"
myVar = new Date(a)// toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200"
Copy the code
Numbers and Booleans are also frequently converted to each other:
myVar = 123 // toString converts to "123"
myVar = true // toString converts to true
myVar = false // toString converts to "false"
Copy the code
The following table shows how to convert different numeric values to numbers (Number), strings (String), and Booleans (Boolean):
The original value | Convert to numbers | Convert to string | Converts to a Boolean value | The instance |
---|---|---|---|---|
false | 0 | “false” | false | Try it » |
true | 1 | “true” | true | Try it » |
0 | 0 | “0” | false | Try it » |
1 | 1 | “1” | true | Try it » |
“0” | 0 | “0” | true | Try it » |
“000” | 0 | “000” | true | Try it » |
“1” | 1 | “1” | true | Try it » |
NaN | NaN | “NaN” | false | Try it » |
Infinity | Infinity | “Infinity” | true | Try it » |
-Infinity | -Infinity | “-Infinity” | true | Try it » |
“” | 0 | “” | false | Try it » |
“20” | 20 | “20” | true | Try it » |
“Runoob” | NaN | “Runoob” | true | Try it » |
[] | 0 | “” | true | Try it » |
[20] | 20 | “20” | true | Try it » |
[10] | NaN | “10, 20” | true | Try it » |
[“Runoob”] | NaN | “Runoob” | true | Try it » |
[“Runoob”,”Google”] | NaN | “Runoob,Google” | true | Try it » |
function(){} | NaN | “function(){}” | true | Try it » |
{} | NaN | “[object Object]” | true | Try it » |
null | 0 | “null” | false | Try it » |
undefined | NaN | “undefined” | false | Try it » |