前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >17 - JavaScript :类型转换​

17 - JavaScript :类型转换​

作者头像
前端黑板报
发布2022-12-01 16:57:10
3530
发布2022-12-01 16:57:10
举报
文章被收录于专栏:前端黑板报前端黑板报

原文地址:https://dev.to/bhagatparwinder/javascript-type-conversion-14eg

转为 Boolean

JavaScript 中 Boolean 值有两个:truefalse。但是,JavaScript 还会把特定的值视为 truthyfalsy。除了 0undefined""falseNaN 其它值都为 truthy

我们可以使用取反操作符 ! 在 true 和 false 之间来回切换。这种转换也把数据类型转为了 boolean

代码语言:javascript
复制
const a = null;
const b = undefined;
const c = "";
const d = 0;

console.log(typeof a); // object
console.log(typeof b); // undefined
console.log(typeof c); // string
console.log(typeof d); // number

const w = !a;
const x = !b;
const y = !c;
const z = !d;

console.log(typeof w); // boolean
console.log(typeof x); // boolean
console.log(typeof y); // boolean
console.log(typeof z); // boolean

不仅把类型转为了 boolean ,还改变了变量的值。如果你需要转换 boolean 类型同时保持对应的 truthyfalsy 使用 !!

代码语言:javascript
复制
const a = null;
const b = undefined;
const c = "";
const d = 0;

console.log(typeof a); // object
console.log(typeof b); // undefined
console.log(typeof c); // string
console.log(typeof d); // number

const w = !!a;
const x = !!b;
const y = !!c;
const z = !!d;

console.log(typeof w); // boolean
console.log(typeof x); // boolean
console.log(typeof y); // boolean
console.log(typeof z); // boolean

// Let's check if they are all false though and haven't switched to true!

console.log(w); // false
console.log(x); // false
console.log(y); // false
console.log(z); // false

转为 String

使用 toString() 方法。

代码语言:javascript
复制
const num = 7;
console.log(typeof num); // number
const numString = num.toString();
console.log(typeof numString); // string

或使用便捷方式在后面添加 ""

代码语言:javascript
复制
const num = 7;
console.log(typeof num); // number
const numString = num + "";
console.log(typeof numString); // string

转为 Number

parseInt() 解析一个字符串为整数,你传递给它的字符串作为第一个参数,第二个参数作为基数。它指定使用哪个进制类型:hexadecimal (16), octal (8), or decimal (10)。

代码语言:javascript
复制
console.log(parseInt("0xF", 16)); // 15
console.log(parseInt("321", 10)); // 321

或者使用便捷方法在字符串之前添加 +!

代码语言:javascript
复制
console.log(+"0xF"); // 15
console.log(+"321"); // 321

有些情况下 + 可能被用于字符串链接。在那种情况下,使用按位运算操作符 ~ 两次:

代码语言:javascript
复制
console.log(~~"0xF"); // 15
console.log(~~"321"); // 321
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-08-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端黑板报 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 转为 Boolean
  • 转为 String
  • 转为 Number
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档