Js-w3school(2020.2.5)【js类型转换】

十八、js类型转换

1 Number() 转换数值,String() 转换字符串,Boolean() 转换布尔值。
2.
5种值的数据类型:
• 字符串(string)
• 数字(number)
• 布尔(boolean)
• 对象(object)
• 函数(function)
3种对象类型:
• 对象(Object)
• 日期(Date)
• 数组(Array)
2种不能包含值的数据类型:
• null
• undefined
3. constructor 属性返回所有 JavaScript 变量的构造器函数。
“Bill”.constructor // 返回 “function String() { [native code] }”
(3.14).constructor // 返回 “function Number() { [native code] }”
false.constructor // 返回 “function Boolean() { [native code] }”
[1,2,3,4].constructor // 返回 “function Array() { [native code] }”
{name:‘Bill’, age:62}.constructor // 返回" function Object() { [native code] }"
new Date().constructor // 返回 “function Date() { [native code] }”
function () {}.constructor// 返回 “function Function(){ [native code] }”
您可以通过检查 constructor 属性来确定某个对象是否为数组(包含单词 “Array”):
function isArray(myArray) {
return myArray.constructor.toString().indexOf(“Array”) > -1;
}
"Array"可以换 "Date"检验是否为日期格式
4. JavaScript 变量能够被转换为新变量以及另一种数据类型:
• 通过使用 JavaScript 函数
• 通过 JavaScript 本身自动转换
5. 全局方法 String()和数字方法 toString() 同理。
6. 全局方法 Number() 可用于把日期转换为数字。日期方法 getTime() 同理。
7.自动类型转换
5 + null // 返回 5 因为 null 被转换为 0
“5” + null // 返回 “5null” 因为 null 被转换为 “null”
“5” + 2 // 返回 52 因为 2 被转换为 “2”
“5” - 2 // 返回 3 因为 “5” 被转换为 5
“5” * “2” // 返回 10 因为 “5” 和 “2” 被转换为 5 和 2
8. 自动字符串转换
document.getElementById(“demo”).innerHTML = myVar;
// 如果 myVar = {name:“Fjohn”} // toString 转换为 “[object Object]”
// 如果 myVar = [1,2,3,4] // toString 转换为 “1,2,3,4”
// 如果 myVar = new Date() // toString 转换为 “Wed Feb 05 2020 17:10:59 GMT+0800 (中国标准时间)”
9.转换类型表
在这里插入图片描述
在这里插入图片描述

发布了41 篇原创文章 · 获赞 4 · 访问量 1645

猜你喜欢

转载自blog.csdn.net/mus123/article/details/104186930