1. 程式人生 > >web前端【第六篇】JavaScript對象

web前端【第六篇】JavaScript對象

ima cal 知識 重復 功能說明 push 前端 date() abcd

在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) ---- 拼接字符串

方法的使用

<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中的數組,長度是隨著下標變化的.用到多長就有多長.
    </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:星期一

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)

  

2.設置日期和時間

//設置日期和時間
//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秒

  

3.日期和時間的轉換:

日期和時間的轉換:

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  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 的調用

//    ========================函數的調用
    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())

//    ===================加個知識點
    var d="yuan";
    d=+d;
    alert(d);//NaN:屬於Number類型的一個特殊值,當遇到將字符串轉成數字無效時,就會得到一個NaN數據
    alert(typeof(d));//Number
    NaN特點:
    var n=NaN;
    alert(n>3);
    alert(n<3);
    alert(n==3);
    alert(n==NaN);
    alert(n!=NaN);//NaN參與的所有的運算都是false,除了!=

    =============一道面試題、、
    function a(a,b) {
        console.log(a+b);
    }
    var a=1;
    var b=2;
    a(a,b)   //如果這樣的話就會報錯了,不知道是哪個a了。

  

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 "tony";
    };

// 匿名函數的應用
    (function(){
        alert("tony");
    } )()

    (function(arg){
        console.log(arg);
    })(‘123‘)

  

六、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)

//    定時器實例
// 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
    }

  

web前端【第六篇】JavaScript對象