Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript基本类型的装拆箱操作 #80

Open
HuYuee opened this issue Dec 16, 2019 · 0 comments
Open

JavaScript基本类型的装拆箱操作 #80

HuYuee opened this issue Dec 16, 2019 · 0 comments

Comments

@HuYuee
Copy link
Owner

HuYuee commented Dec 16, 2019

装拆箱操作主要是基于基本包装类型来进行的。ECMAScript 提供了3 个基本包装类型类型:Boolean、Number和String。这个三种基本包装类型是3个特殊的引用类型,属于Object类型。

装箱操作

所谓的装箱,是指将基本数据类型转换为对应的引用类型的操作。

new Boolean(true); // 装箱
typeof new Boolean(true) === 'object'; 
typeof new Number(1) === 'object'; 
typeof new String('abc') === 'object';

拆箱操作

所谓的拆箱,是指将引用类型对象转换为对应的值类型对象。它是通过引用类型的valueOf()或者toString()方法来实现的。

var objNum = new Number(123); 
console.log( typeof objNum ); //object
console.log( typeof objNum.valueOf() ); //number
console.log( typeof objNum.toString() ); // string 

var objStr =new String("123");  
console.log( typeof objStr ); //object
console.log( typeof objStr.valueOf() ); //string
console.log( typeof objStr.toString() ); // string

注意事项

Number(1)和new Number(1)是不一样的,这个是基本字符串和字符串对象的区别,详情参考基本MDN链接

typeof new String('abc') === 'object';//字符串对象
typeof String('abc') === 'string';//基本字符串
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant