Javascript类型转换详解
时间:2022-05-09 09:40:35|栏目:JavaScript代码|点击: 次
类型转换
1.String->Number
const string = "99"; // 隐式转换 console.log(string * 1 + 77); // 显式转换 console.log(Number(string) + 77);
2.Number->String
const number = 66; console.log(typeof number); // 隐式转换 console.log(typeof (number + "")); // 显式转换 console.log(typeof String(number));
3.混合String->Number
把位于开头的数值字符串转为数值型
const string = "66.66alison"; console.log(parseInt(string)); console.log(parseFloat(string));
4.String->Array
const name = "alison"; console.log(name.split(""));
5.Array->String
const array = ["yooo", "alison", "ruby", "andy"]; console.log(array.join("")); console.log(array.join("&"));
6.Array->Number
空数组为0,x单元素数组为x,多元素数组为NaN
console.log(Number([])); console.log(Number([3])); console.log(Number([1, 2, 3]));
7.toString()
主要用于将Array(由逗号隔开)、Boolean、Date、Number等对象转换成String。
const array = ["yooo", "alison", "ruby", "andy"]; console.log(array.toString()); const number = 99; console.log(typeof number.toString());
8.Boolean隐式转换
比较和运算是两件事
(1)比较
在将boolean与number、string比较时,会隐式地将boolean中的true转为1、false转为0
let number = 99; console.log(number == true);
let hd = '0'; let hd2 = "1"; let hd3 = "99"; console.log(hd == false); console.log(hd2 == true); console.log(hd3 == true);
(2)运算
在运算中string和number会被隐式转换为boolean
let number = 99; if (number) console.log("number");
(3)其他类型转换为Boolean
console.log(Boolean([])); console.log(Boolean({}));
假 | 真 | |
---|---|---|
数值类型 | 0 | 其他 |
字符串类型 | 空串 | 其他 |
引用类型 | 数组和对象 |
9.Boolean显式转换
(1)!!
!先将number转换为boolean类型,然后再取反
!!相当于把数值转为布尔
(2)构造函数 Boolean()
// 数值 let number = 0; number = !!number; console.log(Boolean(number)); // 字符串 let string = "Alison"; console.log(!!string); console.log(Boolean(string)); // 数组 let array = []; console.log(!!array); console.log(Boolean(array)); // 对象 let object = {}; console.log(!!object); console.log(Boolean(object)); // 日期 let date = new Date(); console.log(!!date); console.log(Boolean(date));
总结
栏 目:JavaScript代码
下一篇:React.Js添加与删除onScroll事件的方法详解
本文标题:Javascript类型转换详解
本文地址:http://www.codeinn.net/misctech/201403.html