
数据类型:
String Number Boolean Null UndefinedObject在JS中为我们提供了三个包装类,通过这三个包装类可以将基本数据类型转换为对象
String()
- 可以将基本数据类型字符串转换为String对象
Number()
- 可以将基本数据类型的数字转换为Number对象
Boolean()
- 可以将基本数据类型的布尔值转换为Boolean对象
但是请注意!!! 我们在实际应用中不会使用基本数据类型的对象,如果我们使用基本数据类型的对象,在做一些比较的时候可能会带来一些不可预期的结果。(看bool的例子) 包装类浏览器底层自己使用的
var str="hello world";
console.log(typeof str);
var str1=new String("hello world");
console.log(typeof str1);
var num=new Number(3);
var bl=new Boolean(false);
console.log(bl);
console.log(typeof bl);
if(bl){//前面03_JavaScript类型转换的时候说过
alert("hello everyone!!");
}方法和属性只能添加给对象,不能添加给基本数据类型 当我们对一些基本数据类型的值去调用属性和方法时,浏览器会临时使用包装类将其转换对象,然后在调用对象的属性和方法,调用完以后,再将其转换为基本数据类型
var num=123;
//将基本数据类型转换为Number对象,然后通过对象调用toString()方法
num=num.toString();
console.log(num);
console.log(typeof num);var str="hello world";
console.log(typeof str);
/*
在底层字符串中以数组的形式保存
["h","e","l","l","o"....]
*/
console.log(str[4]);//o
//字符串的长度
console.log(str.length);//String 对象的属性lengthconsole.log(str.charAt(4));console.log(str.charCodeAt(0));//h 的Unicode编码为104var str1=String.fromCharCode(1234);//Ӓ
console.log(str1);indexOf() //“hello world”;
lastIndexof()
var result=str.indexOf("h");//0
result=str.indexOf("a");// -1
result=str.indexOf("l",6);//9
console.log(result);参数说明: 第一个参数:开始位置的索引(包括开始位置) 第二个参数:结束位置的索引(不包括结束位置)
result=str.slice(2,7);//包头不包尾
result=str.slice(2);//包头不包尾
console.log(str);
console.log(result);参数说明:
不同的是这个方法不能接收负值,如果传递负值,则默认为0 如果第二个参数小于第一个参数,则自动调换位置
result=str.substring(2,7);//包头不包尾
console.log(result);可以将一个字符串拆分称为一个数组
var str="his,him,history";
var arr=str.split(",");
console.log(str);
console.log(arr);toUpperCase()
toLowerCase()
str=str.toUpperCase();
console.log(str);
str=str.toLowerCase();
console.log(str);