1.创建对象
/*直接创建*/ var person = new Object(); person.name = "宝宝"; person.age = 3; var person2 = {name:"宝宝",age:3};/*与new Object()等价*/ /*使用对象构造器的方法,即函数*/ function person3(name,age,height){ this._name = name; this._age = age; this._height = height; this.sleeping = sleep; function sleep(){ alert("is sleeping"); } } var baby = new person3("宝宝",3,70); /*调用*/ baby.sleeping(); /*遍历*/ for(var temp in baby){ document.write(baby[temp]); }
2.String字符串对象
/*两种方法创建*/ var str = new String("hello"); var str = "hello"; var str = 'hello'; /*1.获取长度*/ document.write(str.length+"<br/>"); /*2.大小写转换*/ document.write(str.toUpperCase()+"<br/>"); document.write(str.toLowerCase()+"<br/>"); /*3.替换*/ var msg = str.replace("hello","你好"); document.write(msg+"<br/>"); /*4.分割*/ var abc="a,s,d,f,g"; var arr = abc.split(","); for(var temp in arr){ document.write(arr[temp]+"<br/>"); } /*5.连接两个或更多字符*/ var str1 = "aa"; var str2 = ","; var str3 = "你好!"; var str4 = str1.concat(str2,str3); document.write(str4+"<br/>"); /*6.查找*/ var str1 = "Oh,Hello Jack,Hello Mery !";/*索引下标从0开始*/ document.write(str1.indexOf("Hello"));//返回3 document.write("<br/>"); document.write(str1.lastIndexOf("Hello"));//返回14 document.write("<br/>"); /*7.截取*/ //substring(fromIndex,toIndex) var str2 = str1.substring(3,8);//包括from,不包括to document.write(str2+"<br/>"); //substr(fromIndex,length) var str3 = str1.substr(3,5); document.write(str3+"<br/>"); var idx = str1.indexOf("Hello"); var temp = str1.substring(idx); document.write(temp+"<br/>"); /*8.去掉两边的空格*/ var msg = " abc, asd, ddd, "; document.write(msg.trim().length); document.write("<br/>");
3.Array数组对象
/*常规定义*/ var arr = new Array(); arr[0] = "a"; arr[1] = "b"; arr[2] = "c"; /*简洁方法*/ var arr = new Array("a","b","c"); /*直接赋值方法*/ var arr = ["a","b","c"]; /*1.length属性*/ document.write(arr.length+"<br/>"); /*2.toString()方法*/ document.write(arr.toString()+"<br/>"); document.write(arr+"<br/>");//打印数组会默认调用toString()方法 /*3.indexOf()搜索数组中的元素并返回他的位置*/ var idx = arr.indexOf("b"); document.write(idx+"<br/>"); /*4.concat()数组合并*/ var arr2 = ["d","e","f"]; var arr3 = arr.concat(arr2); document.write(arr3+"<br/>"); /*5.join(separator)把数组所有元素放入一个字符串,可以指定分隔符,默认为逗号*/ var tpArr = arr3.join("-"); document.write(tpArr+"<br/>"); /*6.map()方法,通过指定函数处理数组的每个元素,并返回处理后的数组*/ var tmpMapArr = arr.map(function(item, index, arry){//后两个参数可以省略 return item+"--"; }) document.write(tmpMapArr+"<br/>"); /*7.forEach()方法:遍历*/ arr.forEach(function(item, index, arry){//后两个参数可以省略 document.write(item+"<br/>"); }) /*8.reverse()方法,反转*/ document.write(arr.reverse()+"<br/>"); /*9.sort()方法,排序*/ var arr4 = ["o","b","f"]; document.write(arr4.sort()+"<br/>"); /*数字排序*/ var arr5 = [4,19,2]; document.write(arr5.sort(function(a,b){ return a-b;//升序 })+"<br/>"); document.write(arr5.sort(function(a,b){ return b-a;//降序 })+"<br/>");