JavaScript | 如何对字符串、数字、布尔类型进行转换

1 概述

我们在编写 JavaScript 代码时,经常碰到类型转换问题。比如如何将字符串转换为数字,或者如何将数字转换为字符串。

本文将详细介绍它们之间是如何进行转换的。

2 字符串

String 是 JavaScript 提供的内置对象。先看下面的代码:

/* 
 * Creates a Primitive Wrapper Object. 
 */

new String()

// String {""}

/* 
 * This Primitive Wrapper Object contains 
 * a set of built-in methods you can call. 
 */

new String("Hello").valueOf()

// "Hello"

... 

/* Creates a string */
String("Hello")

// "Hello"


String 对象可以将布尔型,数字转化为字符串,如下图所示:
在这里插入图片描述

3 布尔型

先看下布尔对象如何使用:

在这里插入图片描述
布尔对象将把false转换为true,把true转换为false。举个例子:

const differentTypes = [NaN, 0, 1, true, "1234" null, undefined]

differentTypes.filter(Boolean) // same as array.filter(x => Boolean(x))

// [1, true, "1234"]

differentTypes.filter(x => !!x)

// [1, true, "1234"]

4 数字

先看下面的代码:

console.log("0" + 1 )
// 输出:01

console.log(Number("0") + 1 )
// 输出:02

4.1 Number 与 parseInt / parseFloat 区别

Number 对于简单的字符串到数字的转换非常有用。但是如果转换带有单位的值时,就要用 parseInt parseFloat了。

parseInt("100px") // 100
parseFloat("100.23") // 100.23

Number("100px") // NaN

注意:parseInt/parseFloat 只会解析数字,碰到非数字就会停止。

// parseInt and parseFloat yield the same results in this example

parseInt("a100") // NaN
parseInt("1a00") // 1

Number("a100") // NaN
Number("1a00") // NaN

如果碰到十六进制或者八进制,则需要启用第二个参数。

// Both function calls should return a binary representation of the number, 4

// Works as expected 
parseInt("100", 2) //4

// Does not work as expected
parseInt("0b100", 2) // 0 

猜你喜欢

转载自blog.csdn.net/alexwei2009/article/details/125341686