每当读取一个基本类型值的时候,后台就会创建一个对应的基本类型的包装对象。
基本类型值不是对象 ,所以不该有方法。为了方便操作基本类型值,当读取基本类型值时,后台会进行一系列处理。eg.
var s1 = "str";
var s2 = s1.substring(2);
后台自动完成下列处理、
1. 创建String类型的一个实例
2. 在实例上调用指定方法
3. 销毁这个实例
引用类型和基本包装类型的区别就是对象的生存期。引用类型的实例在执行流离开前作用域一直保存在内存中。基本包装类型在执行完一行代码后即被销毁,不能在运行时给基本包装类型添加属性和方法。
*最好不要显示地创建基本包装类型的实例。
*对基本包装类型调用typeof返回object。
*基本包装类型转换为Boolean类型都为true。
*注意转型函数和基本包装类型构造函数的区别。
Boolean
类型
布尔表达式中所以的对象都会转化为true
typeof对基本类型返回”boolean”,对引用类型返回”true”
Number
类型
toFixed()
返回指定小数位的字符串表示
toExponential()
返回指数表示法
toPrecision()
返回固定大小格式或指数格式
var num = 99;
//1e+2
console.log(num.toExponential(0));
//9.9e+1
console.log(num.toExponential(1));
//1e+2
console.log(num.toPrecision(1));
//99
console.log(num.toPrecision(2));
//990
console.log(num.toPrecision(3));
String
类型
charAt()
返回指定位置字符的字符串形式
charCodeAt()
返回指定位置字符的编码
concat()
将一个或多个字符串扑街
slice()
摘取一个字符串区域,返回一个新的字符串。
substing()
返回在字符串中指定两个下标之间的字符。
substr()
通过指定字符数返回在指定位置开始的字符串中的字符。
var str = 'hello';
console.log(str.slice(3));//lo
console.log(str.substring(3));//lo
console.log(str.substr(3));//lo
console.log(str.slice(3, 4));//l
console.log(str.substring(3, 4));//l
console.log(str.substr(3, 4));//lo
//传入一个负值,将负值与字符串长度相加-3+5=2
console.log(str.slice(-3));//llo
//substring()将所有负值转为0
console.log(str.substring(-3));//hello
//传入一个负值,将负值与字符串长度相加-3+5=2
console.log(str.substr(-3));//llo
//slice()将第二个参数转化为1,slice(3, 1),返回包含0个字符的字符串
console.log(str.slice(3, -4));//
//substirng()将-4,转化为0,substring()会将较小的数作为开始位置,相当于substring(0, 3);
console.log(str.substring(3, -4));//hel
//substr()将第二个参数转换为0,suvstr(3, 0)返回包含0个字符的字符串
console.log(str.substr(3, -4));//
indexOf()
从字符串对象中返回首个被发现的给定值的索引值,如果没有找到则返回-1。
lastIndexOf()
从字符串对象中返回最后一个被发现的给定值的索引值,如果没有找到则返回-1。
trim()
从字符串的开始和结尾去除空格。
repalce()
被用来在正则表达式和字符串直接比较,然后用新的子串来替换被匹配的子串。
repalce()
第一个参数是字符串或RegExp对象,第二个参数是字符串或一个函数.
如果第一个参数是字符串,只会替换第一个字符,如果想替换整个字符串要指定全局(g)标志
var text = "cat, bat, sat, fat";
var result = text.replace("at", "ond");
//cond, bat, sat, fat
console.log(result);
result = text.replace("/at/g", "ond");
//cat, bat, sat, fat
console.log(result);
split()
通过分离字符串成字串,将字符串对象分割成字符串数组。