JavaScript(JS)之Javascript对象BOM,History,Location,Function...(二)

https://www.cnblogs.com/haiyan123/p/7594046.html

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

//利用数字对象获取可表示最大数
var a = Number.MAX_VALUE;
console.log(a);
//创建字符串对象
var bb = new String("Hello JS");
console.log(bb);
//创建日期对象
var cc = new Date();
console.log(cc);
//数组对象
var dd = new Array(1,2,3,4);
console.log(dd);
1.7976931348623157e+308
String {"Hello JS"}
0: "H"1: "e"2: "l"3: "l"4: "o"5: " "6: "J"7: "S"
length: 8
__proto__:
 String[[PrimitiveValue]]: "Hello JS"
 Sun Mar 17 2019 07:11:00 GMT+0800 (中国标准时间)
 (4) [1, 2, 3, 4]
0: 1
1: 2
2: 3
3: 4
length: 4
__proto__: Array(0)

JavaScript(JS)之Javascript对象BOM,History,Location,Function...(二)

一、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)         ----    拼接字符串
<script>
//        ========================
//        字符串对象的创建有两种方式
//        方式一
          var s = 'sffghgfd';
//        方式二
          var s1 = new String('  hel lo ');
          console.log(s,s1);
          console.log(typeof(s)); //object类型
          console.log(typeof (s1)); //string类型

//        ======================
//        字符串对象的属性和方法
//           1.字符串就这么一个属性
        console.log(s.length);  //获取字符串的长度

//           2.字符串的方法
        console.log(s.toUpperCase()) ; //变大写
        console.log(s.toLocaleLowerCase()) ;//变小写
        console.log(s1.trim());  //去除字符串两边的空格(和python中的strip方法一样,不会去除中间的空格)
////           3.字符串的查询方法
        console.log(s.charAt(3));  //获取指定索引位置的字符
        console.log(s.indexOf('f')); //如果有重复的,获取第一个字符的索引,如果没有你要找的字符在字符串中没有就返回-1
        console.log(s.lastIndexOf('f')); //如果有重复的,获取最后一个字符的索引
        var str='welcome to the world of JS!';
        var str1 = str.match('world');  //match返回匹配字符串的数组,如果没有匹配则返回null
        var str2 = str.search('world');//search返回匹配字符串从首字符位置开始的索引,如果没有返回-1
        console.log(str1);//打印
        alert(str1);//弹出
        console.log(str2);
        alert(str2);


//        =====================
//        子字符串处理方法
        var aaa='welcome to the world of JS!';
        console.log(aaa.substr(2,4)); //表示从第二个位置开始截取四个
        console.log(aaa.substring(2,4)); //索引从第二个开始到第四个,注意顾头不顾尾
        //切片操作(和python中的一样,都是顾头不顾尾的)
        console.log(aaa.slice(3,6));//从第三个到第六个
        console.log(aaa.slice(4)); //从第四个开始取后面的
        console.log(aaa.slice(2,-1)); //从第二个到最后一个
        console.log(aaa.slice(-3,-1));


//        字符串替换、、
        console.log(aaa.replace('w','c')); //字符串替换,只能换一个
        //而在python中全部都能替换
        console.log(aaa.split(' ')); //吧字符串按照空格分割
        alert(aaa.split(' ')); //吧字符串按照空格分割
        var strArray = aaa.split(' ');
        alert(strArray[2])
    </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.数组的属性和方法

    //        ====================
//        数组对象的属性和方法
          var arr = [11,55,'hello',true,656];
//      1.join方法
        var arr1 = arr.join('-'); //将数组元素拼接成字符串,内嵌到数组了,
        alert(arr1);                //而python中内嵌到字符串了
//        2.concat方法(链接)
        var v = arr.concat(4,5);
        alert(v.toString())  //返回11,55,'hello',true,656,4,5
//        3.数组排序reserve  sort
//        reserve:倒置数组元素
        var li = [1122,33,44,20,'aaa',2];
        console.log(li,typeof (li));  //Array [ 1122, 33, 44, 55 ] object
        console.log(li.toString(), typeof(li.toString())); //1122,33,44,55 string
        alert(li.reverse());  //2,'aaa',55,44,33,1122
//         sort :排序数组元素
        console.log(li.sort().toString()); //1122,2,20,33,44,aaa  是按照ascii码值排序的
//        如果就想按照数字比较呢?(就在定义一个函数)
//        方式一
        function intsort(a,b) {
            if (a>b){
                return 1;
            }
            else if (a<b){
                return -1;
            }
            else{
                return 0;
            }
        }
        li.sort(intsort);
        console.log(li.toString());//2,20,33,44,1122,aaa

//        方式二
        function Intsort(a,b) {
            return a-b;
        }
        li.sort(intsort);
        console.log(li.toString());
        // 4.数组切片操作
        //x.slice(start,end);
        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);
        alert(arr2.toString());//结果为"c,d"
        alert(arr3.toString());//结果为"e,f,g,h"
        alert(arr4.toString());//结果为"c,d,e,f,g"
//        5.删除子数组
        var a = [1,2,3,4,5,6,7,8];
        a.splice(1,2);
        console.log(a) ;//Array [ 1, 4, 5, 6, 7, 8 ]
//        6.数组的push和pop
//        push:是将值添加到数组的结尾
        var b=[1,2,3];
        b.push('a0','4');
        console.log(b) ; //Array [ 1, 2, 3, "a0", "4" ]

//        pop;是讲数组的最后一个元素删除
        b.pop();
        console.log(b) ;//Array [ 1, 2, 3, "a0" ]
        //7.数组的shift和unshift
        //unshift: 将值插入到数组的开始
        //shift: 将数组的第一个元素删除
        b.unshift(888,555,666);
        console.log(b); //Array [ 888, 555, 666, 1, 2, 3, "a0" ]

        b.shift();
        console.log(b); //Array [ 555, 666, 1, 2, 3, "a0" ]
//        8.总结js的数组特性
//        java中的数组特性:规定是什么类型的数组,就只能装什么类型.只有一种类型.
//        js中的数组特性
//            js中的数组特性1:js中的数组可以装任意类型,没有任何限制.
//            js中的数组特性2: js中的数组,长度是随着下标变化的.用到多长就有多长.

三、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
获取日期和时间
getDate()                 获取日
getDay ()                 获取星期
getMonth ()               获取月(0-11)
getFullYear ()            获取完整年份
getYear ()                获取年
getHours ()               获取小时
getMinutes ()             获取分钟
getSeconds ()             获取秒
getMilliseconds ()        获取毫秒
getTime ()                返回累计毫秒数(从1970/1/1午夜)
function  foo() {
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth();
            var day= date.getDate();
            var hour = date.getHours();
            var min= date.getMinutes();
            var week = date.getDay();
            console.log(week);
            var arr=['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
            console.log(arr[week]);
//            console.log(arr[3]);
            console.log(year+'-'+chengemonth(month+1)+'-'+day+' '+hour+':'+min+':'+arr[week])
        }
        function  chengemonth(num) {
            if (num<10){
                return  '0'+num
            }
            else{
                return num
            }
        }
        foo()
        console.log(foo())  //没有返回值返回undefined

        //三元运算符
         console.log(2>1?2:1)
View Code
//
//setDate(day_of_month)       设置日
//setMonth (month)                 设置月
//setFullYear (year)               设置年
//setHours (hour)         设置小时
//setMinutes (minute)     设置分钟
//setSeconds (second)     设置秒
//setMillliseconds (ms)       设置毫秒(0-999)
//setTime (allms)     设置累计毫秒(从1970/1/1午夜)
    
var x=new Date();
x.setFullYear (1997);    //设置年1997
x.setMonth(7);        //设置月7
x.setDate(1);        //设置日1
x.setHours(5);        //设置小时5
x.setMinutes(12);    //设置分钟12
x.setSeconds(54);    //设置秒54
x.setMilliseconds(230);        //设置毫秒230
document.write(x.toLocaleString( )+"<br>");
//返回1997年8月1日5点12分54秒

x.setTime(870409430000); //设置累计毫秒数
document.write(x.toLocaleString( )+"<br>");
//返回1997年8月1日12点23分50秒

设置日期和时间
设置日期和时间
getTimezoneOffset():8个时区×15度×4分/度=480;
返回本地时间与GMT的时间差,以分钟为单位
toUTCString()
返回国际标准时间字符串
toLocalString()
返回本地格式时间字符串
Date.parse(x)
返回累计毫秒数(从1970/1/1午夜到本地时间)
Date.UTC(x)
返回累计毫秒数(从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 func = new Function("name","alert("hello " + name)");
    func("zhangsan");

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

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

2.Function 对象的属性

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

    var func = new Function("name","alert("hello " + name)");
    func("zhangsan");
    alert(func.length);// 1

 3.Function 的调用

    function func1(a,b){
        console.log( a + b);
        console.log(arguments);
    }

    func1(1, 2);
    func1(1,2,3,4);
    func1(1);
    func1();

JavaScript(JS)之Javascript对象BOM,History,Location,Function...(二)

4.函数的内置对象arguments

//    函数的内置对象arguments,相当于python中的动态参数
    function add(a,b){
        console.log(a+b);//3
        console.log(arguments.length);//2
        console.log(arguments);//[1,2]
    }
    add(1,2)
//     ------------------arguments的用处1 ------------------
    function ncadd() {
        var sum = 0;
        for (var i =0;i<arguments.length;i++){
//            console.log(i);//打印的是索引
//            console.log(arguments);//Arguments { 0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 等 2 项… }
            console.log(arguments[i]);//1,2,3,4,5
            sum +=arguments[i]
        }
        return sum
    }
    ret = ncadd(1,2,3,4,5,6);
    console.log(ret);


//     ------------------arguments的用处2 ------------------

    function f(a,b,c){
        if (arguments.length!=3){
            throw new Error("function f called with "+arguments.length+" arguments,but it just need 3 arguments")
        }
        else {
            alert("success!")
        }
    }

    f(1,2,3,4,5)

 5.匿名函数

    var func = function(arg){
        return "hello";
    }
    alert(func());

    // 匿名函数的自调用
    (function(){
        alert("world");
    })();

    (function(arg){
        console.log(arg);
    })("你好世界");

六、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);
    var ret = window.confirm(546); // 有返回值 true / false
    var ret = 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)
//    定时器实例
// var date = new Date();  //Date 2017-09-25T12:20:25.536Z
// console.log(date);
// var date1 = date.toLocaleString();
//  console.log(date1); //2017/9/25 下午8:20:59

    function foo() {
        var date = new Date();
        var date = date.toLocaleString();//吧日期字符串转换成字符串形式
        var ele = document.getElementById('timer')  //从整个html中找到id=timer的标签,也就是哪个input框

        ele.value = date;
        console.log(ele)  //ele是一个标签对象
//    value值是什么input框就显示什么
    }
    var ID;
    function begin() {
        if (ID==undefined){
            foo();
            ID = setInterval(foo,1000)
        }
    }

    function end() {
        clearInterval(ID);
        console.log(ID);
        ID = undefined
    }
定时器
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #timer{
            width: 200px;
            height: 30px;
        }
    </style>

</head>
<body>

    <input type="text" id="timer" onclick=begin()>
    <button name="stop" onclick=stop()>停止</button>

    <script>
        var ele = document.getElementById("timer");
        function show_time(){
            var current_time = new Date().toLocaleString();
            ele.value = current_time;
        }
        var clock;
        function begin(){
            if (clock == undefined){
                show_time();
                clock = setInterval(show_time,1000);
            }
        }
        function stop(){
            clearInterval(clock);
            clock = undefined;
        }
    </script>

</body>
</html>

七,History对象

History对象属性:

  History对象包含用户(在浏览器窗口中)访问过的URL。

  History对象是window对象的一部分,可以通过window.history属性对其进行访问

length 返回浏览器历史列表中的URL数量
back()  加载history列表中的前一个URL
forward() 加载列表中的下一个URL
go() 加载history列表中的某个具体页面
history.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<a href="history2.html">click</a>
<!--<button onclick="history.forward()">前进>>></button>-->
<button onclick="history.go(1)">前进>>></button>

</body>
</html>
history.html2

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--<button onclick="history.back()"><<<返回</button>-->
<button onclick="history.go(-1)"><<<返回</button>

</body>
</html>

八,Location对象

Location对象包含有关当前URL的信息

Location对象是window对象的一部分,可以通过window.Location属性对其进访问

location.assign(URL)
location.reload()
location.replace(newURL) // 注意与assign的区别
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <button onclick="f()">click</button>

<script>
    function f() {
        //location.reload(); // 刷新
        location.replace("http://www.baidu.com"); // 替换,不可以退回到原来页面
    }
    // location.assign("http://www.baidu.com"); // 可以退回到原来页面
</script>

</body>
</html>

相关推荐