Javascript类型转换
yooo* 人气:0类型转换
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));
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!
加载全部内容