JavaScript字符串對象的創建和屬性

JavaScript字符串對象的創建和屬性

字符串對象同樣是JavaScript的內置對象,用來儲存和處理文本。

1.字符串的創建

    // 創建字符串
    // 1.字面量的方式     "" '' ``
    var str="hello";
    var str1='world';
    var str2=`hello China`;//模板字符串
    // 2.使用 new 關鍵字創建  構造函數
    var str3=new String("hello Nanjing");

    console.log(typeof str);// String
    console.log(str1);
    console.log(str2);
    console.log(typeof str3);// Object

兩種聲明方式的區別 :字面量方式聲明,數據類型爲string;使用new關鍵字創建,數據類型爲object。

2.字符串的屬性

    // 字符串對象的屬性
    var str="hello China";
    // length	字符串的長度
    console.log(str.length);//11   空格字符也算長度
    // constructor	對創建該對象的函數的引用   返回對象引用的原型
    console.log(str.constructor);//ƒ String() { [native code] }
    // prototype	向對象添加屬性和方法

    Array.prototype.func=function(){
        for(var i=0;i<this.length;i++){
            console.log(this[i])
        }
    }
    var arr=[1,2,3,4,5,6,7];
    arr.func();

    String.prototype.func=function(){
        console.log(this.length);
    }
    str.func();

視頻講解鏈接:
https://www.bilibili.com/video/BV1HZ4y1W792/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章