前端之JavaScript对象
一 概述
在JavaScript中除了null和undefined以外其他的数据类型都被定义成了对象(对象名称首字母大写),也可以用创建对象的方法定义变量(如下)。String、Math、Array、Date、RegExp都是JavaScript中重要的内置对象,在JavaScript程序大多数功能都是基于对象实现的。在JavaScript中,几乎所有事物都是对象。
//利用数字对象获取可表示最大数
var a = Number.MAX_VALUE; // 1.7976931348623157e+308
//创建字符串对象
var b = new String("hello world");
//创建日期对象
var c = new Date(); // Thu Dec 28 2017 17:20:50 GMT+0800 (中国标准时间)
//创建数组对象
var d = new Array("星期一","星期二","星期三","星期四");
内置对象分类如下:

与py一样,js对象也具有属性和方法
//访问对象属性: 方式一:object.attr 方式二:object["attr"] //访问对象方法: object.func()
二 String对象
2.1 字符串的创建
- 变量 = "字符串" // 通过typeof 返回为string
- 字符串对象名称 = new String("字符串内容") // 通过typeof 返回为object
var str1 = "hello world";
var str2 = new String("hello word");
(str1 === str2) // 结果为 false,因为str1是字符串,str2是对象
注意:建议不要创建 String 对象。它会拖慢执行速度,并可能产生其他副作用。
2.2 字符串的属性及方法
str.length // 获取字符串的长度,仅有的属性
str.toLowerCase() // 转为小写
str.toUpperCase() // 转为大写
str.trim() // 去除字符串两边空格
//示例:
var str1 = " Hello World ";
document.write(str1.length+"<br>"); // 13
document.write(str1.toLowerCase()+"<br>"); // hello world
document.write(str1.toUpperCase()+"<br>"); // HELLO WORLD
document.write(str1.trim()+"<br>"); // Hello World
//字符串查询方法
str.charAt(index) // 获取指定位置字符,其中index为要获取的字符索引
str.indexOf(findstr,startindex) // 返回某个指定的字符串值在字符串中首次出现的位置,可以指定开始查询位置
str.lastIndexOf(findstr) // 从后向前搜索字符串,并从起始位置(0)开始计算返回字符串最后出现的位置
str.match(regexp) // match返回匹配字符串的数组,如果没有匹配则返回null
str.search(regexp) // search返回匹配字符串的首字符位置索引
//示例:
var str1 = "Hello World";
var str2 = str1.match("World");
var str3 = str1.search("World");
document.write(str1.charAt(4)+"<br>"); // o
document.write(str1.indexOf("l",5)+"<br>"); // 9
document.write(str1.lastIndexOf("l")+"<br>"); // 9
document.write(str2[0]+"<br>"); // World
document.write(str3+"<br>"); // 6
//子字符串处理方法
str.substr(start, length) // start表示开始位置,length表示截取长度
str.substring(start, end) // end是结束位置
str.slice(start, end) // 切片操作字符串
str.replace(searchvalue,newvalue) // 字符串替换
str.split(); // 把字符串分割为字符串数组
str.concat(addstr) // 连接两个或更多字符串,并返回新的字符串。
//示例:
str1 = "abcdefg";
str2 = "1,2,3,4,5";
document.write(str1.substr(1,3)+"<br>"); // bcd
document.write(str1.substring(1,3)+"<br>"); // bc
document.write(str1.slice(1,3)+"<br>"); // bc
document.write(str1.slice(1)+"<br>"); // bcdefg
document.write(str1.slice(-3,-1)+"<br>"); // ef
document.write(str1.replace("ab","AB")+"<br>"); // ABcdefg
document.write(str2.split(",")+"<br>"); // 1,2,3,4,5
document.write(str2.split(",")[0]+"<br>"); // 1
document.write(str1.concat(str2,"hello")+"<br>"); // abcdefg1,2,3,4,5hello
三 Array对象(数组)
3.1 数组的创建
//创建方式1(字面):
var arrname = [元素0,元素1,….];
示例: var newarr=[1,2,3];
//创建方式2(简洁方式):
var arrname = new Array(元素0,元素1,….);
示例: var newarr = new Array(100,"a",true);
//创建方式3(常规方式):
var arrname = new Array(长度);
示例:
var cnweek = new Array();
cnweek[0]="星期日";
cnweek[1]="星期一";
cnweek[2]="星期二";
cnweek[3]="星期三";
cnweek[4]="星期四";
cnweek[5]="星期五";
cnweek[6]="星期六";
创建二维数组:
var cnweek=new Array(7); for (var i=0;i<=6;i++){ cnweek[i]=new Array(2); } cnweek[0][0]="星期日"; cnweek[0][1]="Sunday"; cnweek[1][0]="星期一"; cnweek[1][1]="Monday"; ... cnweek[6][0]="星期六"; cnweek[6][1]="Saturday";
3.2 数组的属性及方法
length/indexOf()/toString()
x.length // 获取数组长度
x.indexOf() // 获取元素索引值
x.toString() // 转换数组到字符串
var arr = ["AC","C","AB","BC","a","ab","c"];
console.log(arr.length); // 7
console.log(arr.indexOf("C")); // 1
str1 = arr.toString();
console.log(str1); // AC,C,AB,BC,a,ab,c
console.log(typeof(str1)); // string
jion()
x.jion(bystr) // 用数组的元素组成字符串,可以指定拼接字符串
var arr = ["AC","C","AB","BC","a","ab","c"];
var str1 = arr.join("-");
console.log(str1); // AC-C-AB-BC-a-ab-c
concat()
x.concat(value,...) // 合并数组 var arr = ["AC","C","AB","BC","a","ab","c"]; var b = arr.concat(4,5); console.log(b.toString()); // AC,C,AB,BC,a,ab,c,4,5
数组排序 reverse()/sort()
x.sort() // 排序数组元素
x.reverse() // 颠倒数组元素
var arr = ["AC","C","AB","BC","a","ab","c"];
document.write(arr.sort()); // AB,AC,BC,C,a,ab,c
document.write(arr.reverse()); // c,ab,a,C,BC,AC,AB
var arr1 = [123,1,23,441,47,32];
document.write(arr1.sort()); // 1,123,23,32,441,47
document.write(arr1.reverse()); // 47,441,32,23,123,1
//如果就想按照数字比较呢?(就在定义一个函数)
//方式一
var arr1 = [123,1,23,441,47,32];
function intSort(a,b) {
if (a>b){
return 1;//-1 //1为正序排列,-1为反序排列
}
else if(a<b){
return -1;//1
}
else {
return 0
}
}
document.write(arr1.sort(intSort)) // 1,23,32,47,123,441
// 方式二
var arr1 = [123,1,23,441,47,32];
function Intsort(a,b) {
return a-b;
}
document.write(arr1.sort(intSort)) // 1,23,32,47,123,441
数组切片 slice()
x.slice(start, end) // start表示开始位置索引,end是结束位置下一数组元素索引编号
// 第一个数组元素索引为0; start、end可为负数,-1代表最后一个数组元素; end省略则相当于从start位置截取以后所有数组元素
var arr1 = ['a','b','c','d','e','f','g','h'];
var arr2 = arr1.slice(2,4);
var arr3 = arr1.slice(4);
var arr4 = arr1.slice(2,-1);
document.write(arr2.toString()); // c,d
document.write(arr3.toString()); // e,f,g,h
document.write(arr4.toString()); // c,d,e,f,g
删除子数组 splice()
x.splice(start, deleteCount, value, ...) // splice()的主要用途是对数组指定位置进行删除和插入 // start表示开始位置索引; deleteCount删除数组元素的个数; value表示在删除位置插入的数组元素,value参数可以省略 var arr1 = ['a','b','c','d','e','f','g','h']; arr1.splice(1,2); alert(arr1.toString()); //arr1变为 [a,e,f,g,h] arr1.splice(1,1); alert(arr1.toString()); //arr1变为 [a,f,g,h] arr1.splice(1,0,'aa','bb'); alert(arr1.toString()); //arr1变为 [a,aa,bb,f,g,h]
pop()/push()
//push()/pop()这两个方法模拟的是一个栈操作 x.push(value, ...) // 压栈,将value值添加到数组x的结尾,value可以为字符串、数字、数组等任何值 x.pop() // 弹栈,将数组x的最后一个元素删除 var arr1 = [1,2,3]; arr1.push(4,5); alert(arr1); // 1,2,3,4,5 arr1.push([6,7]); alert(arr1) // 1,2,3,4,5,6,7 arr1.pop(); alert(arr1); // 1,2,3,4,5 注意:最后加的是一个数组元素
shift()/unshift()
x.unshift(value,...) // 将value值插入到数组x的开始,value可以为字符串、数字、数组等任何值 x.shift() // 将数组x的第一个元素删除 var arr1 = [1,2,3]; arr1.unshift(4,5); alert(arr1); // 4,5,1,2,3 arr1.unshift([6,7]); alert(arr1); // 6,7,4,5,1,2,3 arr1.shift(); alert(arr1); // 4,5,1,2,3
//js中数组的特性 //java中数组的特性,规定是什么类型的数组,就只能装什么类型,只有一种类型 //js中的数组特性1: js中的数组可以装任意类型,没有任何限制 //js中的数组特性2: js中的数组,长度是随着下标变化的,用到多长就有多长 var arr = ['abc',1,1.14,true,null,undefined,new String('1213'),new Function('a','b','alert(a+b)')]; alert(arr.length); // 8 arr[10] = "xxx"; alert(arr.length); // 11 alert(arr[9]); // undefined
四 Date对象
4.1 Date的创建
//方法1:不指定参数
var nowd1 = new Date();
console.log(nowd1.toLocaleString()); // 2018/10/10 下午5:22:21
//方法2:参数为日期字符串
var nowd2 = new Date("2004/3/20 11:12");
console.log(nowd2.toLocaleString()); // 2004/3/20 上午11:12:00
var nowd3 = new Date("04/03/20 11:12");
console.log(nowd3.toLocaleString()); // 2020/4/3 上午11:12:00
//方法3:参数为毫秒数,从1970年1月1日至今的毫秒数
var nowd3 = new Date(1000000000000);
console.log(nowd3.toLocaleString()); // 2001/9/9 上午9:46:40
console.log(nowd3.toUTCString()); // Sun, 09 Sep 2001 01:46:40 GMT
//方法4:参数为年月日小时分钟秒毫秒
var nowd4 = new Date(2004,2,20,11,12,0,300);
console.log(nowd4.toLocaleString()); // 2004/3/20 上午11:12:00,毫秒并不直接显示
4.2 Date的方法--获取日期和时间
getDate() // 获取日 getDay () // 获取星期 getMonth () // 获取月(0-11) getFullYear () // 获取完整年份 getYear () // 获取年 getHours () // 获取小时 getMinutes () // 获取分钟 getSeconds () // 获取秒 getMilliseconds () // 获取毫秒 getTime () // 返回累计毫秒数(从1970/1/1午夜)
function getCurrentDate(){ //1. 创建Date对象 var date = new Date(); //没有填入任何参数那么就是当前时间 //2. 获得当前年份 var year = date.getFullYear(); //3. 获得当前月份 js中月份是从0到11. var month = date.getMonth()+1; //4. 获得当前日 var day = date.getDate(); //5. 获得当前小时 var hour = date.getHours(); //6. 获得当前分钟 var min = date.getMinutes(); //7. 获得当前秒 var sec = date.getSeconds(); //8. 获得当前星期 var week = date.getDay(); // 没有getWeek // 2018年10月10日 18:40:30 星期三 return year+"年"+changeNum(month)+"月"+day+"日 "+hour+":"+changeNum(min)+":"+sec+""+parseWeek(week); } //解决月份、分钟自动补齐成两位数字的方法 function changeNum(num){ if(num < 10){ return "0"+num; }else{ return num; } } //将数字 0~6 转换成 星期日到星期六 function parseWeek(week){ var arr = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]; // 0 1 2 3 4 5 6 return arr[week]; } //函数调用 alert(getCurrentDate());
4.3 Date的方法--设置日期和时间
setDate(day_of_month) // 设置日 setMonth(month) // 设置月 setFullYear(year) // 设置年 setHours(hour) // 设置小时 setMinutes(minute) // 设置分钟 setSeconds(second) // 设置秒 setMillliseconds(ms) // 设置毫秒(0-999) setTime(allms) // 设置累计毫秒(从1970/1/1午夜)
var date = new Date(); date.setFullYear(2018); // 设置年2018 date.setMonth(1); // 设置月1 date.setDate(1); // 设置日1 date.setHours(1); // 设置小时1 date.setMinutes(1); // 设置分钟1 date.setSeconds(1); // 设置秒1 date.setMilliseconds(230); // 设置毫秒230 document.write(date.toLocaleString( )+"<br>"); // 2018/2/1 上午1:01:01 date.setTime(1000000000000); // 设置累计毫秒数 document.write(date.toLocaleString( )+"<br>"); // 2001/9/9 上午9:46:40
4.4 Date的方法--日期和时间的转换
getTimezoneOffset():8个时区×15度×4分/度=480; // 返回本地时间与GMT的时间差,以分钟为单位 toUTCString() // 返回国际标准时间字符串 toLocalString() // 返回本地格式时间字符串 Date.parse(x) // 返回1970年1月1日午夜到指定日期(字符串)的毫秒数,为静态方法 Date.UTC(x) // 根据世界时返回1970年1月1日到指定日期的毫秒数,为静态方法
4.5 日期的比较
var date = new Date(); date.setFullYear(2000,0,1); var today = new Date(); if (date > today){ document.write("今天在2000/1/1之前"); }else { document.write("今天在2000/1/1之后"); }
五 Math对象(数学相关)
abs(x) // 返回数的绝对值 exp(x) // 返回 e 的指数 floor(x) // 对数进行下舍入 log(x) // 返回数的自然对数(底为e) max(x,y) // 返回 x 和 y 中的最高值 min(x,y) // 返回 x 和 y 中的最低值 pow(x,y) // 返回 x 的 y 次幂 random() // 返回 0 ~ 1 之间的随机数 round(x) // 把数四舍五入为最接近的整数 sin(x) // 返回数的正弦 sqrt(x) // 返回数的平方根 tan(x) // 返回角的正切
document.write(Math.random()); // 随机数 0~1 不包括1 document.write(Math.round(1.5)); // 2 document.write(Math.floor(1.5)); // 1 document.write(Math.max(2,5)); // 5 document.write(Math.min(2,5)); // 2 document.write(Math.pow(2,4)); // 16 //练习:获取1-100的随机整数,包括1和100 var num = Math.random(); num = num*100; num = Math.round(num); document.write(num);
六 Function对象
6.1 函数的定义
function 函数名 (参数){
函数体;
return 返回值;
}
功能说明:
- 可以使用变量、常量或表达式作为函数调用的参数
- 函数由关键字function定义
- 函数名的定义规则与标识符一致,大小写是敏感的
- 返回值必须使用return
- Function 类可以表示开发者定义的任何函数
用 Function 类直接创建函数的语法如下:
var 函数名 = new Function("参数1","参数n","function_body");
虽然由于字符串的关系,第二种形式写起来有些困难,但有助于理解函数只不过是一种引用类型,它们的行为与用 Function 类明确创建的函数行为是相同的。
//方式一 function func1(para){ alert("hello "+para); } func1("world"); //方式二 var func2 = new Function("para","alert(\"hello \"+para);") func2("world");
注意:JS的函数加载执行与python不同,它是整体加载完才会执行,所以执行函数放在函数声明上面或下面都可以。
<script>
//f(); --->OK
function f(){
console.log("xxx")
}
f(); //--->OK
</script>
6.2 Function 对象的属性
如前所述,函数属于引用类型,所以它们也有属性和方法。
ECMAScript 定义的属性 length 声明了函数期望的参数个数。例如:
function func1(para){
alert("hello "+para);
}
func1("world");
alert(func1.length) // 1
6.3 Function 对象的方法
Function 对象也有与所有对象共享的 valueOf() 方法和 toString() 方法。这两个方法返回的都是函数的源代码,在调试时尤其有用。例如:
function func1(para){
alert("hello "+para); // hello world
}
func1("world");
alert(func1.toString()); // 函数源代码
alert(func1.valueOf()); // 函数源代码
6.4 Function 的调用
//函数的调用 function fun1(a,b) { console.log(a+b) } fun1(1,2); // 3 fun1(1,2,3,4); // 3 fun1(1); // NaN fun1(); // NaN console.log(fun1()); // NaN //只要函数名写对即可,参数怎么填都不报错 //一道小测验 function a(a,b) { console.log(a+b); } var a = 1; var b = 2; a(a,b) // 如果这样的话就会报错了,不知道是哪个a了。
6.5 函数的内置对象arguments
在函数代码中,使用特殊对象 arguments,开发者无需明确指出参数名,就能访问它们。
例如,在函数func1() 中,第一个参数是para1。用 arguments[0] 也可以访问这个值,即第一个参数的值(第一个参数位于位置 0,第二个参数位于位置 1,依此类推)。
因此,无需明确命名参数,就可以重写函数:
function func1(){
alert("hello "+ arguments[0]); // hello world
}
func1("world");
6.5.1 作用1--监测参数个数
function func1(){
alert(arguments.length); // 不可使用func1
}
func1("world"); // 1
func1("world",100); // 2
func1(); // 0
6.5.2 作用2--for循环
function myAdd(){
var result = 0;
for (var index in arguments){
// alert(index) // index为索引值
// alert(arguments) // 一个对象
result += arguments[index]
}
alert(result)
}
myAdd(1,2,3,4,5,6);
6.5.3 作用3--模拟函数重置
用 arguments 对象判断传递给函数的参数个数,即可模拟函数重置
function func1() {
if(arguments.length == 1){
alert(arguments[0]);
}
else if(arguments.length == 2){
alert(arguments[0] + arguments[1]);
}
}
func1(12); // 12
func1(12,13) // 25
6.6 函数表达式
JavaScript 函数可以通过一个表达式定义。函数表达式可以存储在变量中:
var func = function (a, b) {return a * b};
6.7 匿名函数
在函数表达式存储在变量后,变量也可作为一个函数使用:
var func = function (a, b) {return a * b};
var a = func(4, 3);
以上函数实际上是一个 匿名函数 (函数没有名称)。
函数存储在变量中,不需要函数名称,通常通过变量名来调用。
//匿名函数的应用
(function(){
alert("Joe");
})();
(function (a, b){
alert(a * b)
})(4,3);

浙公网安备 33010602011771号