时间:2022-05-09 09:40:35 | 栏目:JavaScript代码 | 点击:次
const string = "99"; // 隐式转换 console.log(string * 1 + 77); // 显式转换 console.log(Number(string) + 77);
const number = 66; console.log(typeof number); // 隐式转换 console.log(typeof (number + "")); // 显式转换 console.log(typeof String(number));
把位于开头的数值字符串转为数值型
const string = "66.66alison"; console.log(parseInt(string)); console.log(parseFloat(string));
const name = "alison"; console.log(name.split(""));
const array = ["yooo", "alison", "ruby", "andy"]; console.log(array.join("")); console.log(array.join("&"));
空数组为0,x单元素数组为x,多元素数组为NaN
console.log(Number([])); console.log(Number([3])); console.log(Number([1, 2, 3]));
主要用于将Array(由逗号隔开)、Boolean、Date、Number等对象转换成String。
const array = ["yooo", "alison", "ruby", "andy"]; console.log(array.toString()); const number = 99; console.log(typeof number.toString());
比较和运算是两件事
在将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);
在运算中string和number会被隐式转换为boolean
let number = 99; if (number) console.log("number");
console.log(Boolean([])); console.log(Boolean({}));
假 | 真 | |
---|---|---|
数值类型 | 0 | 其他 |
字符串类型 | 空串 | 其他 |
引用类型 | 数组和对象 |
!先将number转换为boolean类型,然后再取反
!!相当于把数值转为布尔
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));