包装类
1. 说明
- 在 JS 中为我们提供了三个包装类,通过这三个包装类可以将基本数据类型的数据转化为对象
- String()
- 可以将基本数据类型字符串转换为 String 对象
- Number()
- 可以将基本数据类型的数字转换为 Number 对象
- Boolean()
- 可以将基本数据类型的布尔值转换为 Boolean 对象
- 但是注意,在实际开发中不会使用基本数据类型的对象
- 如果使用基本数据类型的对象,在做一些比较时可能会带来一些不可预期的结果
2. 用基本数据类型调用方法
- 方法和属性之能添加给对象,不能添加给基本数据类型
- 当我们对一些基本数据类型的值去调用属性和方法时
- 浏览器会临时使用包装类将其转换为对象,然后在调用对象的属性和方法
- 调用完以后,在将其转换为基本数据类型
var num = new Number(3);
var num2 = new Number(3);
var str = new String("hello");
var bool = new Boolean("true");
var bool2 = new Boolean("true");
num.hello = "abacdefg";
var a = 3;
a.hello = "你好";
console.log(bool === bool2);
var b = new Boolean(false);
if (b) {
alert("我运行了");
}
var s = 123;
s = s.toString();
s.hello = "你好";
console.log(s.hello);
console.log(typeof s);
![请添加图片描述](https://img-blog.csdnimg.cn/4c5114b11bf447e0a05d022c3f3a48d7.png)
![请添加图片描述](https://img-blog.csdnimg.cn/fcca816f886945d5977fcb42f9cc1429.png)