JavaScript(JS)之Javascript对象 JavaScript(JS)之Javascript对象

简介:

在JavaScript中除了null和undefined以外其他的数据类型都被定义成了对象,也可以用创建对象的方法定义变量,String、Math、Array、Date、RegExp都是JavaScript中重要的内置对象,在JavaScript程序大多数功能都是基于对象实现的

复制代码
<script language="javascript">
var aa=Number.MAX_VALUE; 
//利用数字对象获取可表示最大数
var bb=new String("hello JavaScript"); 
//创建字符串对象
var cc=new Date();
//创建日期对象
var dd=new Array("星期一","星期二","星期三","星期四"); 
//数组对象
</script>
复制代码

 

一、string对象(字符串)

1.字符串对象创建

字符串创建(两种方式)
       ① 变量 = “字符串”
       ② 字串串对象名称 = new String (字符串)

复制代码
//        ========================
//        字符串对象的创建有两种方式
//        方式一
          var s = 'sffghgfd';
//        方式二
          var s1 = new String('  hel lo ');
          console.log(s,s1);
          console.log(typeof(s)); //object类型
          console.log(typeof (s1)); //string类型
复制代码

2.字符串对象的属性和函数

复制代码
-------属性
x.length ----获取字符串的长度
------方法 x.toLowerCase() ----转为小写 x.toUpperCase() ----转为大写 x.trim() ----去除字符串两边空格 ----字符串查询方法 x.charAt(index) ----str1.charAt(index);----获取指定位置字符,其中index为要获取的字符索引 x.indexOf(index)----查询字符串位置 x.lastIndexOf(findstr) x.match(regexp) ----match返回匹配字符串的数组,如果没有匹配则返回null x.search(regexp) ----search返回匹配字符串的首字符位置索引 示例: var str1="welcome to the world of JS!"; var str2=str1.match("world"); var str3=str1.search("world"); alert(str2[0]); // 结果为"world" alert(str3); // 结果为15 ----子字符串处理方法 x.substr(start, length) ----start表示开始位置,length表示截取长度 x.substring(start, end) ----end是结束位置 x.slice(start, end) ----切片操作字符串 示例: var str1="abcdefgh"; var str2=str1.slice(2,4); var str3=str1.slice(4); var str4=str1.slice(2,-1); var str5=str1.slice(-3,-1); alert(str2); //结果为"cd" alert(str3); //结果为"efgh" alert(str4); //结果为"cdefg" alert(str5); //结果为"fg" x.replace(findstr,tostr) ---- 字符串替换 x.split(); ----分割字符串 var str1="一,二,三,四,五,六,日"; var strArray=str1.split(","); alert(strArray[1]);//结果为"二" x.concat(addstr) ---- 拼接字符串
复制代码

方法的使用

 1     <script>
 2 //        ========================
 3 //        字符串对象的创建有两种方式
 4 //        方式一
 5           var s = 'sffghgfd';
 6 //        方式二
 7           var s1 = new String('  hel lo ');
 8           console.log(s,s1);
 9           console.log(typeof(s)); //object类型
10           console.log(typeof (s1)); //string类型
11 
12 //        ======================
13 //        字符串对象的属性和方法
14 //           1.字符串就这么一个属性
15         console.log(s.length);  //获取字符串的长度
16 
17 //           2.字符串的方法
18         console.log(s.toUpperCase()) ; //变大写
19         console.log(s.toLocaleLowerCase()) ;//变小写
20         console.log(s1.trim());  //去除字符串两边的空格(和python中的strip方法一样,不会去除中间的空格)
21 ////           3.字符串的查询方法
22         console.log(s.charAt(3));  //获取指定索引位置的字符
23         console.log(s.indexOf('f')); //如果有重复的,获取第一个字符的索引,如果没有你要找的字符在字符串中没有就返回-1
24         console.log(s.lastIndexOf('f')); //如果有重复的,获取最后一个字符的索引
25         var str='welcome to the world of JS!';
26         var str1 = str.match('world');  //match返回匹配字符串的数组,如果没有匹配则返回null
27         var str2 = str.search('world');//search返回匹配字符串从首字符位置开始的索引,如果没有返回-1
28         console.log(str1);//打印
29         alert(str1);//弹出
30         console.log(str2);
31         alert(str2);
32 
33 
34 //        =====================
35 //        子字符串处理方法
36         var aaa='welcome to the world of JS!';
37         console.log(aaa.substr(2,4)); //表示从第二个位置开始截取四个
38         console.log(aaa.substring(2,4)); //索引从第二个开始到第四个,注意顾头不顾尾
39         //切片操作(和python中的一样,都是顾头不顾尾的)
40         console.log(aaa.slice(3,6));//从第三个到第六个
41         console.log(aaa.slice(4)); //从第四个开始取后面的
42         console.log(aaa.slice(2,-1)); //从第二个到最后一个
43         console.log(aaa.slice(-3,-1));
44 
45 
46 //        字符串替换、、
47         console.log(aaa.replace('w','c')); //字符串替换,只能换一个
48         //而在python中全部都能替换
49         console.log(aaa.split(' ')); //吧字符串按照空格分割
50         alert(aaa.split(' ')); //吧字符串按照空格分割
51         var strArray = aaa.split(' ');
52         alert(strArray[2])
53     </script>
使用方法

二、Array对象(数组)

1.创建数组的三种方式

复制代码
创建方式1:
var arrname = [元素0,元素1,….];          // var arr=[1,2,3];

创建方式2:
var arrname = new Array(元素0,元素1,….); // var test=new Array(100,"a",true);

创建方式3:
var arrname = new Array(长度); 
            //  初始化数组对象:
                var cnweek=new Array(7);
                    cnweek[0]="星期日";
                    cnweek[1]="星期一";
                    ...
                    cnweek[6]="星期六";
复制代码

2.数组的属性和方法

 1 //        ====================
 2 //        数组对象的属性和方法
 3           var arr = [11,55,'hello',true,656];
 4 //      1.join方法
 5         var arr1 = arr.join('-'); //将数组元素拼接成字符串,内嵌到数组了,
 6         alert(arr1);                //而python中内嵌到字符串了
 7 //        2.concat方法(链接)
 8         var v = arr.concat(4,5);
 9         alert(v.toString())  //返回11,55,'hello',true,656,4,5
10 //        3.数组排序reserve  sort
11 //        reserve:倒置数组元素
12         var li = [1122,33,44,20,'aaa',2];
13         console.log(li,typeof (li));  //Array [ 1122, 33, 44, 55 ] object
14         console.log(li.toString(), typeof(li.toString())); //1122,33,44,55 string
15         alert(li.reverse());  //2,'aaa',55,44,33,1122
16 //         sort :排序数组元素
17         console.log(li.sort().toString()); //1122,2,20,33,44,aaa  是按照ascii码值排序的
18 //        如果就想按照数字比较呢?(就在定义一个函数)
19 //        方式一
20         function intsort(a,b) {
21             if (a>b){
22                 return 1;
23             }
24             else if (a<b){
25                 return -1;
26             }
27             else{
28                 return 0;
29             }
30         }
31         li.sort(intsort);
32         console.log(li.toString());//2,20,33,44,1122,aaa
33 
34 //        方式二
35         function Intsort(a,b) {
36             return a-b;
37         }
38         li.sort(intsort);
39         console.log(li.toString());
40         // 4.数组切片操作
41         //x.slice(start,end);
42         var arr1=['a','b','c','d','e','f','g','h'];
43         var arr2=arr1.slice(2,4);
44         var arr3=arr1.slice(4);
45         var arr4=arr1.slice(2,-1);
46         alert(arr2.toString());//结果为"c,d"
47         alert(arr3.toString());//结果为"e,f,g,h"
48         alert(arr4.toString());//结果为"c,d,e,f,g"
49 //        5.删除子数组
50         var a = [1,2,3,4,5,6,7,8];
51         a.splice(1,2);
52         console.log(a) ;//Array [ 1, 4, 5, 6, 7, 8 ]
53 //        6.数组的push和pop
54 //        push:是将值添加到数组的结尾
55         var b=[1,2,3];
56         b.push('a0','4');
57         console.log(b) ; //Array [ 1, 2, 3, "a0", "4" ]
58 
59 //        pop;是讲数组的最后一个元素删除
60         b.pop();
61         console.log(b) ;//Array [ 1, 2, 3, "a0" ]
62         //7.数组的shift和unshift
63         unshift: 将值插入到数组的开始
64         shift: 将数组的第一个元素删除
65         b.unshift(888,555,666);
66         console.log(b); //Array [ 888, 555, 666, 1, 2, 3, "a0" ]
67 
68         b.shift();
69         console.log(b); //Array [ 555, 666, 1, 2, 3, "a0" ]
70 //        8.总结js的数组特性
71 //        java中的数组特性:规定是什么类型的数组,就只能装什么类型.只有一种类型.
72 //        js中的数组特性
73 //            js中的数组特性1:js中的数组可以装任意类型,没有任何限制.
74 //            js中的数组特性2: js中的数组,长度是随着下标变化的.用到多长就有多长.
75     </script>
数组的一些方法和属性

三、date对象(日期)

1.创建date对象

复制代码
     创建date对象
//        方式一:
        var now = new Date();
        console.log(now.toLocaleString()); //2017/9/25 下午6:37:16
        console.log(now.toLocaleDateString()); //2017/9/25
//        方式二
        var now2 = new Date('2004/2/3 11:12');
        console.log(now2.toLocaleString());  //2004/2/3 上午11:12:00
        var now3 = new Date('08/02/20 11:12'); //2020/8/2 上午11:12:00
        console.log(now3.toLocaleString());

        //方法3:参数为毫秒数
        var nowd3=new Date(5000);
        alert(nowd3.toLocaleString( ));
        alert(nowd3.toUTCString()); //Thu, 01 Jan 1970 00:00:05 GMT
复制代码

2.Date对象的方法—获取日期和时间

复制代码
获取日期和时间
getDate()                 获取日
getDay ()                 获取星期
getMonth ()               获取月(0-11)
getFullYear ()            获取完整年份
getYear ()                获取年
getHours ()               获取小时
getMinutes ()             获取分钟
getSeconds ()             获取秒
getMilliseconds ()        获取毫秒
getTime ()                返回累计毫秒数(从1970/1/1午夜)
复制代码

实例练习

1.打印这样的格式2017-09-25 17:36:星期一

 1   function  foo() {
 2             var date = new Date();
 3             var year = date.getFullYear();
 4             var month = date.getMonth();
 5             var day= date.getDate();
 6             var hour = date.getHours();
 7             var min= date.getMinutes();
 8             var week = date.getDay();
 9             console.log(week);
10             var arr=['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
11             console.log(arr[week]);
12 //            console.log(arr[3]);
13             console.log(year+'-'+chengemonth(month+1)+'-'+day+' '+hour+':'+min+':'+arr[week])
14         }
15         function  chengemonth(num) {
16             if (num<10){
17                 return  '0'+num
18             }
19             else{
20                 return num
21             }
22         }
23         foo()
24         console.log(foo())  //没有返回值返回undefined
25 
26         //三元运算符
27          console.log(2>1?2:1)
View Code

2.设置日期和时间

 1 //设置日期和时间
 2 //setDate(day_of_month)       设置日
 3 //setMonth (month)                 设置月
 4 //setFullYear (year)               设置年
 5 //setHours (hour)         设置小时
 6 //setMinutes (minute)     设置分钟
 7 //setSeconds (second)     设置秒
 8 //setMillliseconds (ms)       设置毫秒(0-999)
 9 //setTime (allms)     设置累计毫秒(从1970/1/1午夜)
10     
11 var x=new Date();
12 x.setFullYear (1997);    //设置年1997
13 x.setMonth(7);        //设置月7
14 x.setDate(1);        //设置日1
15 x.setHours(5);        //设置小时5
16 x.setMinutes(12);    //设置分钟12
17 x.setSeconds(54);    //设置秒54
18 x.setMilliseconds(230);        //设置毫秒230
19 document.write(x.toLocaleString( )+"<br>");
20 //返回1997年8月1日5点12分54秒
21 
22 x.setTime(870409430000); //设置累计毫秒数
23 document.write(x.toLocaleString( )+"<br>");
24 //返回1997年8月1日12点23分50秒
设置日期和时间

3.日期和时间的转换:

 1 日期和时间的转换:
 2 
 3 getTimezoneOffset():8个时区×15度×4分/度=480;
 4 返回本地时间与GMT的时间差,以分钟为单位
 5 toUTCString()
 6 返回国际标准时间字符串
 7 toLocalString()
 8 返回本地格式时间字符串
 9 Date.parse(x)
10 返回累计毫秒数(从1970/1/1午夜到本地时间)
11 Date.UTC(x)
12 返回累计毫秒数(从1970/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)    返回角的正切。
复制代码

使用

方法的使用

五、Function对象(重点)

1.函数的定义

function 函数名 (参数){
<br>    函数体;

    return 返回值;

}

功能说明:

可以使用变量、常量或表达式作为函数调用的参数
函数由关键字function定义
函数名的定义规则与标识符一致,大小写是敏感的
返回值必须使用return
Function 类可以表示开发者定义的任何函数。

用 Function 类直接创建函数的语法如下:

var 函数名 = new Function("参数1","参数n","function_body");

虽然由于字符串的关系,第二种形式写起来有些困难,但有助于理解函数只不过是一种引用类型,它们的行为与用 Function 类明确创建的函数行为是相同的。

示例:

var  func2 = new Function('name',"alert(\"hello\"+name);");
    func2('haiyan');

 注意:js的函数加载执行与python不同,它是整体加载完才会执行,所以执行函数放在函数声明上面或下面都可以:

    f(); --->OK
       function f(){
        console.log("hello")
       }
      f();//----->OK
//

2.Function 对象的属性

如前所述,函数属于引用类型,所以它们也有属性和方法。
比如,ECMAScript 定义的属性 length 声明了函数期望的参数个数。

alert(func1.length)

 3.Function 的调用

 1 //    ========================函数的调用
 2     function fun1(a,b) {
 3            console.log(a+b)
 4     }
 5     fun1(1,2);// 3
 6     fun1(1,2,3,4); //3
 7     fun1(1); //NaN
 8     fun1(); //NaN
 9     console.log(fun1())
10 
11 //    ===================加个知识点
12     var d="yuan";
13     d=+d;
14     alert(d);//NaN:属于Number类型的一个特殊值,当遇到将字符串转成数字无效时,就会得到一个NaN数据
15     alert(typeof(d));//Number
16     NaN特点:
17     var n=NaN;
18     alert(n>3);
19     alert(n<3);
20     alert(n==3);
21     alert(n==NaN);
22     alert(n!=NaN);//NaN参与的所有的运算都是false,除了!=
23 
24     =============一道面试题、、
25     function a(a,b) {
26         console.log(a+b);
27     }
28     var a=1;
29     var b=2;
30     a(a,b)   //如果这样的话就会报错了,不知道是哪个a了。
View Code

4.函数的内置对象arguments

 1 //    函数的内置对象arguments,相当于python中的动态参数
 2     function add(a,b){
 3         console.log(a+b);//3
 4         console.log(arguments.length);//2
 5         console.log(arguments);//[1,2]
 6     }
 7     add(1,2)
 8 //     ------------------arguments的用处1 ------------------
 9     function ncadd() {
10         var sum = 0;
11         for (var i =0;i<arguments.length;i++){
12 //            console.log(i);//打印的是索引
13 //            console.log(arguments);//Arguments { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 等 2 项… }
14             console.log(arguments[i]);//1,2,3,4,5
15             sum +=arguments[i]
16         }
17         return sum
18     }
19     ret = ncadd(1,2,3,4,5,6);
20     console.log(ret);
21 
22 
23 //     ------------------arguments的用处2 ------------------
24 
25     function f(a,b,c){
26         if (arguments.length!=3){
27             throw new Error("function f called with "+arguments.length+" arguments,but it just need 3 arguments")
28         }
29         else {
30             alert("success!")
31         }
32     }
33 
34     f(1,2,3,4,5)
View Code

 5.匿名函数

 1 /    =======================
 2     // 匿名函数
 3     var func = function(arg){
 4         return "tony";
 5     };
 6 
 7 // 匿名函数的应用
 8     (function(){
 9         alert("tony");
10     } )()
11 
12     (function(arg){
13         console.log(arg);
14     })('123')
View Code

六、BOM对象(重点)

window对象

所有浏览器都支持 window 对象。
概念上讲.一个html文档对应一个window对象.
功能上讲: 控制浏览器窗口的.
使用上讲: window对象不需要创建对象,直接使用即可.

1.对象方法

复制代码
alert()            显示带有一段消息和一个确认按钮的警告框。
confirm()          显示带有一段消息以及确认按钮和取消按钮的对话框。
prompt()           显示可提示用户输入的对话框。

open()             打开一个新的浏览器窗口或查找一个已命名的窗口。
close()            关闭浏览器窗口。

setInterval()      按照指定的周期(以毫秒计)来调用函数或计算表达式。
clearInterval()    取消由 setInterval() 设置的 timeout。
setTimeout()       在指定的毫秒数后调用函数或计算表达式。
clearTimeout()     取消由 setTimeout() 方法设置的 timeout。
scrollTo()         把内容滚动到指定的坐标。
复制代码

2.方法使用

复制代码
<script>
    window.open();
    window.alert(123);
    window.confirm(546);
    window.prompt(147258);
    window.close();

//    =============定时器
    function foo() {
        console.log(123)
    }
    var ID = setInterval(foo,1000); //每个一秒执行一下foo函数,如果你不取消
                         //,就会一直执行下去
    clearInterval(ID)  //还没来得及打印就已经停掉了
    
//    =====================
        function foo() {
            console.log(123)
        }
        var ID=setTimeout(foo,1000);
        clearTimeout(ID)
复制代码
 1 //    定时器实例
 2 // var date = new Date();  //Date 2017-09-25T12:20:25.536Z
 3 // console.log(date);
 4 // var date1 = date.toLocaleString();
 5 //  console.log(date1); //2017/9/25 下午8:20:59
 6 
 7     function foo() {
 8         var date = new Date();
 9         var date = date.toLocaleString();//吧日期字符串转换成字符串形式
10         var ele = document.getElementById('timer')  //从整个html中找到id=timer的标签,也就是哪个input框
11 
12         ele.value = date;
13         console.log(ele)  //ele是一个标签对象
14 //    value值是什么input框就显示什么
15     }
16     var ID;
17     function begin() {
18         if (ID==undefined){
19             foo();
20             ID = setInterval(foo,1000)
21         }
22     }
23 
24     function end() {
25         clearInterval(ID);
26         console.log(ID);
27         ID = undefined
28     }
定时器实例

七、DOM对象(重点)

简介:

在JavaScript中除了null和undefined以外其他的数据类型都被定义成了对象,也可以用创建对象的方法定义变量,String、Math、Array、Date、RegExp都是JavaScript中重要的内置对象,在JavaScript程序大多数功能都是基于对象实现的

复制代码
<script language="javascript">
var aa=Number.MAX_VALUE; 
//利用数字对象获取可表示最大数
var bb=new String("hello JavaScript"); 
//创建字符串对象
var cc=new Date();
//创建日期对象
var dd=new Array("星期一","星期二","星期三","星期四"); 
//数组对象
</script>
复制代码

 

一、string对象(字符串)

1.字符串对象创建

字符串创建(两种方式)
       ① 变量 = “字符串”
       ② 字串串对象名称 = new String (字符串)

复制代码
//        ========================
//        字符串对象的创建有两种方式
//        方式一
          var s = 'sffghgfd';
//        方式二
          var s1 = new String('  hel lo ');
          console.log(s,s1);
          console.log(typeof(s)); //object类型
          console.log(typeof (s1)); //string类型
复制代码

2.字符串对象的属性和函数

复制代码
-------属性
x.length ----获取字符串的长度
------方法 x.toLowerCase() ----转为小写 x.toUpperCase() ----转为大写 x.trim() ----去除字符串两边空格 ----字符串查询方法 x.charAt(index) ----str1.charAt(index);----获取指定位置字符,其中index为要获取的字符索引 x.indexOf(index)----查询字符串位置 x.lastIndexOf(findstr) x.match(regexp) ----match返回匹配字符串的数组,如果没有匹配则返回null x.search(regexp) ----search返回匹配字符串的首字符位置索引 示例: var str1="welcome to the world of JS!"; var str2=str1.match("world"); var str3=str1.search("world"); alert(str2[0]); // 结果为"world" alert(str3); // 结果为15 ----子字符串处理方法 x.substr(start, length) ----start表示开始位置,length表示截取长度 x.substring(start, end) ----end是结束位置 x.slice(start, end) ----切片操作字符串 示例: var str1="abcdefgh"; var str2=str1.slice(2,4); var str3=str1.slice(4); var str4=str1.slice(2,-1); var str5=str1.slice(-3,-1); alert(str2); //结果为"cd" alert(str3); //结果为"efgh" alert(str4); //结果为"cdefg" alert(str5); //结果为"fg" x.replace(findstr,tostr) ---- 字符串替换 x.split(); ----分割字符串 var str1="一,二,三,四,五,六,日"; var strArray=str1.split(","); alert(strArray[1]);//结果为"二" x.concat(addstr) ---- 拼接字符串
复制代码

方法的使用

 1     <script>
 2 //        ========================
 3 //        字符串对象的创建有两种方式
 4 //        方式一
 5           var s = 'sffghgfd';
 6 //        方式二
 7           var s1 = new String('  hel lo ');
 8           console.log(s,s1);
 9           console.log(typeof(s)); //object类型
10           console.log(typeof (s1)); //string类型
11 
12 //        ======================
13 //        字符串对象的属性和方法
14 //           1.字符串就这么一个属性
15         console.log(s.length);  //获取字符串的长度
16 
17 //           2.字符串的方法
18         console.log(s.toUpperCase()) ; //变大写
19         console.log(s.toLocaleLowerCase()) ;//变小写
20         console.log(s1.trim());  //去除字符串两边的空格(和python中的strip方法一样,不会去除中间的空格)
21 ////           3.字符串的查询方法
22         console.log(s.charAt(3));  //获取指定索引位置的字符
23         console.log(s.indexOf('f')); //如果有重复的,获取第一个字符的索引,如果没有你要找的字符在字符串中没有就返回-1
24         console.log(s.lastIndexOf('f')); //如果有重复的,获取最后一个字符的索引
25         var str='welcome to the world of JS!';
26         var str1 = str.match('world');  //match返回匹配字符串的数组,如果没有匹配则返回null
27         var str2 = str.search('world');//search返回匹配字符串从首字符位置开始的索引,如果没有返回-1
28         console.log(str1);//打印
29         alert(str1);//弹出
30         console.log(str2);
31         alert(str2);
32 
33 
34 //        =====================
35 //        子字符串处理方法
36         var aaa='welcome to the world of JS!';
37         console.log(aaa.substr(2,4)); //表示从第二个位置开始截取四个
38         console.log(aaa.substring(2,4)); //索引从第二个开始到第四个,注意顾头不顾尾
39         //切片操作(和python中的一样,都是顾头不顾尾的)
40         console.log(aaa.slice(3,6));//从第三个到第六个
41         console.log(aaa.slice(4)); //从第四个开始取后面的
42         console.log(aaa.slice(2,-1)); //从第二个到最后一个
43         console.log(aaa.slice(-3,-1));
44 
45 
46 //        字符串替换、、
47         console.log(aaa.replace('w','c')); //字符串替换,只能换一个
48         //而在python中全部都能替换
49         console.log(aaa.split(' ')); //吧字符串按照空格分割
50         alert(aaa.split(' ')); //吧字符串按照空格分割
51         var strArray = aaa.split(' ');
52         alert(strArray[2])
53     </script>
使用方法

二、Array对象(数组)

1.创建数组的三种方式

复制代码
创建方式1:
var arrname = [元素0,元素1,….];          // var arr=[1,2,3];

创建方式2:
var arrname = new Array(元素0,元素1,….); // var test=new Array(100,"a",true);

创建方式3:
var arrname = new Array(长度); 
            //  初始化数组对象:
                var cnweek=new Array(7);
                    cnweek[0]="星期日";
                    cnweek[1]="星期一";
                    ...
                    cnweek[6]="星期六";
复制代码

2.数组的属性和方法

 1 //        ====================
 2 //        数组对象的属性和方法
 3           var arr = [11,55,'hello',true,656];
 4 //      1.join方法
 5         var arr1 = arr.join('-'); //将数组元素拼接成字符串,内嵌到数组了,
 6         alert(arr1);                //而python中内嵌到字符串了
 7 //        2.concat方法(链接)
 8         var v = arr.concat(4,5);
 9         alert(v.toString())  //返回11,55,'hello',true,656,4,5
10 //        3.数组排序reserve  sort
11 //        reserve:倒置数组元素
12         var li = [1122,33,44,20,'aaa',2];
13         console.log(li,typeof (li));  //Array [ 1122, 33, 44, 55 ] object
14         console.log(li.toString(), typeof(li.toString())); //1122,33,44,55 string
15         alert(li.reverse());  //2,'aaa',55,44,33,1122
16 //         sort :排序数组元素
17         console.log(li.sort().toString()); //1122,2,20,33,44,aaa  是按照ascii码值排序的
18 //        如果就想按照数字比较呢?(就在定义一个函数)
19 //        方式一
20         function intsort(a,b) {
21             if (a>b){
22                 return 1;
23             }
24             else if (a<b){
25                 return -1;
26             }
27             else{
28                 return 0;
29             }
30         }
31         li.sort(intsort);
32         console.log(li.toString());//2,20,33,44,1122,aaa
33 
34 //        方式二
35         function Intsort(a,b) {
36             return a-b;
37         }
38         li.sort(intsort);
39         console.log(li.toString());
40         // 4.数组切片操作
41         //x.slice(start,end);
42         var arr1=['a','b','c','d','e','f','g','h'];
43         var arr2=arr1.slice(2,4);
44         var arr3=arr1.slice(4);
45         var arr4=arr1.slice(2,-1);
46         alert(arr2.toString());//结果为"c,d"
47         alert(arr3.toString());//结果为"e,f,g,h"
48         alert(arr4.toString());//结果为"c,d,e,f,g"
49 //        5.删除子数组
50         var a = [1,2,3,4,5,6,7,8];
51         a.splice(1,2);
52         console.log(a) ;//Array [ 1, 4, 5, 6, 7, 8 ]
53 //        6.数组的push和pop
54 //        push:是将值添加到数组的结尾
55         var b=[1,2,3];
56         b.push('a0','4');
57         console.log(b) ; //Array [ 1, 2, 3, "a0", "4" ]
58 
59 //        pop;是讲数组的最后一个元素删除
60         b.pop();
61         console.log(b) ;//Array [ 1, 2, 3, "a0" ]
62         //7.数组的shift和unshift
63         unshift: 将值插入到数组的开始
64         shift: 将数组的第一个元素删除
65         b.unshift(888,555,666);
66         console.log(b); //Array [ 888, 555, 666, 1, 2, 3, "a0" ]
67 
68         b.shift();
69         console.log(b); //Array [ 555, 666, 1, 2, 3, "a0" ]
70 //        8.总结js的数组特性
71 //        java中的数组特性:规定是什么类型的数组,就只能装什么类型.只有一种类型.
72 //        js中的数组特性
73 //            js中的数组特性1:js中的数组可以装任意类型,没有任何限制.
74 //            js中的数组特性2: js中的数组,长度是随着下标变化的.用到多长就有多长.
75     </script>
数组的一些方法和属性

三、date对象(日期)

1.创建date对象

复制代码
     创建date对象
//        方式一:
        var now = new Date();
        console.log(now.toLocaleString()); //2017/9/25 下午6:37:16
        console.log(now.toLocaleDateString()); //2017/9/25
//        方式二
        var now2 = new Date('2004/2/3 11:12');
        console.log(now2.toLocaleString());  //2004/2/3 上午11:12:00
        var now3 = new Date('08/02/20 11:12'); //2020/8/2 上午11:12:00
        console.log(now3.toLocaleString());

        //方法3:参数为毫秒数
        var nowd3=new Date(5000);
        alert(nowd3.toLocaleString( ));
        alert(nowd3.toUTCString()); //Thu, 01 Jan 1970 00:00:05 GMT
复制代码

2.Date对象的方法—获取日期和时间

复制代码
获取日期和时间
getDate()                 获取日
getDay ()                 获取星期
getMonth ()               获取月(0-11)
getFullYear ()            获取完整年份
getYear ()                获取年
getHours ()               获取小时
getMinutes ()             获取分钟
getSeconds ()             获取秒
getMilliseconds ()        获取毫秒
getTime ()                返回累计毫秒数(从1970/1/1午夜)
复制代码

实例练习

1.打印这样的格式2017-09-25 17:36:星期一

 1   function  foo() {
 2             var date = new Date();
 3             var year = date.getFullYear();
 4             var month = date.getMonth();
 5             var day= date.getDate();
 6             var hour = date.getHours();
 7             var min= date.getMinutes();
 8             var week = date.getDay();
 9             console.log(week);
10             var arr=['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
11             console.log(arr[week]);
12 //            console.log(arr[3]);
13             console.log(year+'-'+chengemonth(month+1)+'-'+day+' '+hour+':'+min+':'+arr[week])
14         }
15         function  chengemonth(num) {
16             if (num<10){
17                 return  '0'+num
18             }
19             else{
20                 return num
21             }
22         }
23         foo()
24         console.log(foo())  //没有返回值返回undefined
25 
26         //三元运算符
27          console.log(2>1?2:1)
View Code

2.设置日期和时间

 1 //设置日期和时间
 2 //setDate(day_of_month)       设置日
 3 //setMonth (month)                 设置月
 4 //setFullYear (year)               设置年
 5 //setHours (hour)         设置小时
 6 //setMinutes (minute)     设置分钟
 7 //setSeconds (second)     设置秒
 8 //setMillliseconds (ms)       设置毫秒(0-999)
 9 //setTime (allms)     设置累计毫秒(从1970/1/1午夜)
10     
11 var x=new Date();
12 x.setFullYear (1997);    //设置年1997
13 x.setMonth(7);        //设置月7
14 x.setDate(1);        //设置日1
15 x.setHours(5);        //设置小时5
16 x.setMinutes(12);    //设置分钟12
17 x.setSeconds(54);    //设置秒54
18 x.setMilliseconds(230);        //设置毫秒230
19 document.write(x.toLocaleString( )+"<br>");
20 //返回1997年8月1日5点12分54秒
21 
22 x.setTime(870409430000); //设置累计毫秒数
23 document.write(x.toLocaleString( )+"<br>");
24 //返回1997年8月1日12点23分50秒
设置日期和时间

3.日期和时间的转换:

 1 日期和时间的转换:
 2 
 3 getTimezoneOffset():8个时区×15度×4分/度=480;
 4 返回本地时间与GMT的时间差,以分钟为单位
 5 toUTCString()
 6 返回国际标准时间字符串
 7 toLocalString()
 8 返回本地格式时间字符串
 9 Date.parse(x)
10 返回累计毫秒数(从1970/1/1午夜到本地时间)
11 Date.UTC(x)
12 返回累计毫秒数(从1970/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)    返回角的正切。
复制代码

使用

方法的使用

五、Function对象(重点)

1.函数的定义

function 函数名 (参数){
<br>    函数体;

    return 返回值;

}

功能说明:

可以使用变量、常量或表达式作为函数调用的参数
函数由关键字function定义
函数名的定义规则与标识符一致,大小写是敏感的
返回值必须使用return
Function 类可以表示开发者定义的任何函数。

用 Function 类直接创建函数的语法如下:

var 函数名 = new Function("参数1","参数n","function_body");

虽然由于字符串的关系,第二种形式写起来有些困难,但有助于理解函数只不过是一种引用类型,它们的行为与用 Function 类明确创建的函数行为是相同的。

示例:

var  func2 = new Function('name',"alert(\"hello\"+name);");
    func2('haiyan');

 注意:js的函数加载执行与python不同,它是整体加载完才会执行,所以执行函数放在函数声明上面或下面都可以:

    f(); --->OK
       function f(){
        console.log("hello")
       }
      f();//----->OK
//

2.Function 对象的属性

如前所述,函数属于引用类型,所以它们也有属性和方法。
比如,ECMAScript 定义的属性 length 声明了函数期望的参数个数。

alert(func1.length)

 3.Function 的调用

 1 //    ========================函数的调用
 2     function fun1(a,b) {
 3            console.log(a+b)
 4     }
 5     fun1(1,2);// 3
 6     fun1(1,2,3,4); //3
 7     fun1(1); //NaN
 8     fun1(); //NaN
 9     console.log(fun1())
10 
11 //    ===================加个知识点
12     var d="yuan";
13     d=+d;
14     alert(d);//NaN:属于Number类型的一个特殊值,当遇到将字符串转成数字无效时,就会得到一个NaN数据
15     alert(typeof(d));//Number
16     NaN特点:
17     var n=NaN;
18     alert(n>3);
19     alert(n<3);
20     alert(n==3);
21     alert(n==NaN);
22     alert(n!=NaN);//NaN参与的所有的运算都是false,除了!=
23 
24     =============一道面试题、、
25     function a(a,b) {
26         console.log(a+b);
27     }
28     var a=1;
29     var b=2;
30     a(a,b)   //如果这样的话就会报错了,不知道是哪个a了。
View Code

4.函数的内置对象arguments

 1 //    函数的内置对象arguments,相当于python中的动态参数
 2     function add(a,b){
 3         console.log(a+b);//3
 4         console.log(arguments.length);//2
 5         console.log(arguments);//[1,2]
 6     }
 7     add(1,2)
 8 //     ------------------arguments的用处1 ------------------
 9     function ncadd() {
10         var sum = 0;
11         for (var i =0;i<arguments.length;i++){
12 //            console.log(i);//打印的是索引
13 //            console.log(arguments);//Arguments { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 等 2 项… }
14             console.log(arguments[i]);//1,2,3,4,5
15             sum +=arguments[i]
16         }
17         return sum
18     }
19     ret = ncadd(1,2,3,4,5,6);
20     console.log(ret);
21 
22 
23 //     ------------------arguments的用处2 ------------------
24 
25     function f(a,b,c){
26         if (arguments.length!=3){
27             throw new Error("function f called with "+arguments.length+" arguments,but it just need 3 arguments")
28         }
29         else {
30             alert("success!")
31         }
32     }
33 
34     f(1,2,3,4,5)
View Code

 5.匿名函数

 1 /    =======================
 2     // 匿名函数
 3     var func = function(arg){
 4         return "tony";
 5     };
 6 
 7 // 匿名函数的应用
 8     (function(){
 9         alert("tony");
10     } )()
11 
12     (function(arg){
13         console.log(arg);
14     })('123')
View Code

六、BOM对象(重点)

window对象

所有浏览器都支持 window 对象。
概念上讲.一个html文档对应一个window对象.
功能上讲: 控制浏览器窗口的.
使用上讲: window对象不需要创建对象,直接使用即可.

1.对象方法

复制代码
alert()            显示带有一段消息和一个确认按钮的警告框。
confirm()          显示带有一段消息以及确认按钮和取消按钮的对话框。
prompt()           显示可提示用户输入的对话框。

open()             打开一个新的浏览器窗口或查找一个已命名的窗口。
close()            关闭浏览器窗口。

setInterval()      按照指定的周期(以毫秒计)来调用函数或计算表达式。
clearInterval()    取消由 setInterval() 设置的 timeout。
setTimeout()       在指定的毫秒数后调用函数或计算表达式。
clearTimeout()     取消由 setTimeout() 方法设置的 timeout。
scrollTo()         把内容滚动到指定的坐标。
复制代码

2.方法使用

复制代码
<script>
    window.open();
    window.alert(123);
    window.confirm(546);
    window.prompt(147258);
    window.close();

//    =============定时器
    function foo() {
        console.log(123)
    }
    var ID = setInterval(foo,1000); //每个一秒执行一下foo函数,如果你不取消
                         //,就会一直执行下去
    clearInterval(ID)  //还没来得及打印就已经停掉了
    
//    =====================
        function foo() {
            console.log(123)
        }
        var ID=setTimeout(foo,1000);
        clearTimeout(ID)
复制代码
 1 //    定时器实例
 2 // var date = new Date();  //Date 2017-09-25T12:20:25.536Z
 3 // console.log(date);
 4 // var date1 = date.toLocaleString();
 5 //  console.log(date1); //2017/9/25 下午8:20:59
 6 
 7     function foo() {
 8         var date = new Date();
 9         var date = date.toLocaleString();//吧日期字符串转换成字符串形式
10         var ele = document.getElementById('timer')  //从整个html中找到id=timer的标签,也就是哪个input框
11 
12         ele.value = date;
13         console.log(ele)  //ele是一个标签对象
14 //    value值是什么input框就显示什么
15     }
16     var ID;
17     function begin() {
18         if (ID==undefined){
19             foo();
20             ID = setInterval(foo,1000)
21         }
22     }
23 
24     function end() {
25         clearInterval(ID);
26         console.log(ID);
27         ID = undefined
28     }
定时器实例

七、DOM对象(重点)

猜你喜欢

转载自www.cnblogs.com/maaosheng/p/11619135.html