美文网首页web颜值要爆表Web前端之路Web 前端开发
JavaScript引用类型——基本包装类型

JavaScript引用类型——基本包装类型

作者: 胖胖冰 | 来源:发表于2017-05-24 15:24 被阅读16次

    基本包装类型

    为了便于操作基本类型值,ECMAScript还提供了3个特殊的引用类型:BooleanNumberString。这些类型与其它引用类型相似,但同时也具有与各自的基本类型相应的特殊行为。
    实际上, 每当读取一个基本类型值得时候,后台就会创建一个对应的基本包装类型的对象,从而能够调用一些方法来操作这些数据。

    var s1 = "some text";
    var s2 = s1.substring(2);
    

    s1保护一个字符串,字符串是基本类型值,基本类型值不是对象,从逻辑上讲不应该有方法,当访问s1时,访问过程处于一种读取模式,也就是要从内存中读取这个字符串的值。在独缺模式中访问字符串时,后台都会自动完成下列处理。

    (1) 创建String类型的一个实例;
    (2) 在实例上调用指定的方法;
    (3) 销毁这个实例。

    var s1 =new String(some text);
    var s2 = s1.substring(2);
    s1 = null;
    

    上面三个步骤也适用于Bollean和Number类型对应的布尔值和数字值。
    引用类型与基本包装类型的主要区别就是对象的生存期。使用new操作符创建的引用类型的实例,在执行流离开当前作用域之前都一直保存在内存中。而自动创建的基本包装类型的对象,则只存在于一行代码执行的瞬间,然后立即被销毁。这意味着我们不能再运行时为基本类型值添加属性和方法。

    var s1 = "some text";
    s1.color = "red";
    alert(s1.color); //undefined
    

    当然可以显示的调用Boolean、Number和String来创建基本包装类型的对象。不过,应该在绝对必要的情况下在这样做,因为这种做法很容易让人分不清自己是在处理基本类型还是引用类型的值。
    对基本包装类型的实例调用typeof会返回"object",所有基本包装类型的对象在转换为布尔类型时值都是true。
    Object构造函数会根据传入值得类型返回相应基本包装类型的实例。

    var obj = new Object("some text");
    alert(obj instanceof String); //true
    

    把字符串传给Object构造函数,就会创建String的实例,而传入数字就会得到Number的实例,传入布尔值就会得到Boolean的实例。
    需要注意的是,使用new调用基本包装类型的构造函数,与直接调用同名的转型函数是不一样的。

    var value = "25";
    var number = Number(value); //转型函数
    alert(typeof number); //"number"
    
    var obj = new Number(value); //构造函数
    alert(typeof obj); //"object"
    

    变量number中保存的是基本类型的值25,变量obj中保存的是Number的实例。每个基本包装类型提供了操作相应值得便捷方法。

    • Bollean类型
      Boolean类型是与布尔值对应的引用类型。
    var booleanObject = new  Boolean(true);
    

    Boolean的实例重写了valueOf()方法,返回基本类型值true或false;重写了toString()方法,返回字符串"true"或"false"。
    Boolean对象经常会造成人们的误解,在ECMAScript中的用处不大。

    var falseObject = new Boolean(false);
    var result = falseObject && true;
    alert(result); //true
    
    var falseValue = false;
    result = falseValue && true;
    alert(result); //false
    

    布尔表达式中所有对象都会被转换为true。

    alert(typeof falseObject); //object
    alert(typeof falseValue); //boolean
    alert(falseObject instanceof Boolean); //true
    alert(falseValue instanceof Boolean); //false
    
    • Number类型

    Number是与数字值对应的引用类型。创建Number对象,如:

    var numberObject = new Number(10);
    

    与Boolean类型一样,Number类型也重写了valueOf()、toLocalString()和toString()方法。重写后的valueOf()方法返回对象表示的基本类型的数值,另外两种方法则返回字符串形式的数值,可以为toString()方法传递一个表示基数的参数,告诉它返回几进制数值的字符串形式,如:

    var num = 10;
    alert(num.toString()); //"10"
    alert(num.toString(2)); //1010
    alert(num.toString(8)); //12
    alert(num.toString(10)); //10
    alert(num.toString(16)); //a
    

    除了继承的方法之外,Number类型还提供了一些用于将数值格式转化为字符串的方法。
    toFixed()方法会按照指定的小数返回数值的字符串表示,如:

    var num = 10;
    alert(num.toFixed(2)); //"10.00"
    
    var num = 10.005;
    alert(num.toFixed(2)); //"10.01" 能够自动舍入
    

    toFixed()方法适合处理货币值。

    toExponential()用于格式化的方法,该方法返回以指数表示法(也称e表示法)表示数值的字符串形式。

    var num = 10;
    alert(num.toExponential(1)); //"1.0e+1"
    

    toPrecision()方法可能会返回固定大写(fixed)格式,也可能返回指数(exponential)格式,具体规则看哪种格式最合适。这个方法接收一个参数,即表示数值的所有数字的位数(不包括指数部分)。

    var num = 99;
    alert(num.toPrecision(1)); //"1e+2"
    alert(num.toPrecision(2)); //"99"
    alert(num.toPrecision(3)); //"99.0"
    
    var numberObject = new Number(10);
    var numberValue = 10;
    alert(typeof numberObject); //"object"
    alert(typeof numberValue); //"number"
    alert(numberObject instanceof Number); //true
    alert(numberValue instanceof Number); //false
    
    • String类型
      String类型是字符串的对象包装类型。
    var stringObject = new String("hello world");
    

    String对象的方法也可以在所有基本字符串值中访问到。继承的valueOf()方法,toLocaleString()和toString()方法,都返回对象所表示的基本字符串值。
    String类型的每个实例都有一个length属性

    var stringObject = new String("hello world");
    alert(stringObject.length); //"11"
    

    String类型提供了很多方法,由于辅助完成对ECMAScript中字符串的解析和操作。

    • 1. 字符方法

    两个由于访问字符串中特定字符的方法:charAt()charCodeAt()。这两个方法都接收一个参数,即基于0的字符位置。其中,charAt()方法以单字符字符串的形式返回给定位置的那个字符:

    var stringValue = "hello world";
    alert(stringValue.charAt(1)); //"e"
    

    如果想得到字符编码,就是用charCodeAt():

    var stringValue = "hello world";
    alert(stringValue.charCodeAt(1)); //输出"101"
    

    另一个访问个别字符的方法,使用方括号加数字索引来访问字符串中特定字符:

    var stringValue = "hello world";
    alert(stringValu[1]); //"e"
    
    • 2. 字符串操作方法
      下面介绍与操作字符串有关的几个方法。
      concat()方法,由于将一个或多个字符串拼接起来,返货拼接得到的新字符串。
    var stringValue = "hello ";
    var result = stringValue.concat("world");
    alert(result); //"hello world"
    alert(stringValue); //"hello"
    
    var stringValue = "hello ";
    var result = stringValue.concat("world", "!");
    alert(result); //"hello world!"
    alert(stringValue); //"hello"
    

    在实践中更多的是用加号操作符(+)拼接字符串。

    ECMAScript还提供了三个基于子字符串创建新字符串的方法:slice()substr()substring()。这三个方法都会返回被操作字符串的一个子字符串,而且也都接受一个或两个参数。第一个参数指定子字符串的开始位置,第二个参数(在指定情况下)表示字符串到哪里结束。具体来说,slice()和substring()的第二个参数指定的是子字符串最后一个字符后面的位置。而substr()的第二个参数指定的则是返回的字符个数。如果没有给这些方法传递第二个参数,则将字符串的末尾作为结束的位置。
    与concat()方法一样,slice()、substr()和substring()也不会修改字符串本身的值——它们只是返回一个基本类型的字符串值,对原始字符串没有任何影响。

    var stringValue = "hello world";
    alert(stringValue.slice(3)); //"lo world"
    alert(stringValue.substring(3)); //"lo world"
    alert(stringValue.substr(3)); //"lo world"
    alert(stringValue.slice(3,7)); //"lo w"
    alert(stringValue.substring(3,7)); //"lo w"
    alert(stringValue.substr(3,7)); //"lo worl"
    

    在传递给这些方法的参数是负值的情况下,slice()方法会给传入的负值与字符串的长度相加,substr()方法将负的第一个参数加上字符串的长度,而将负的第二个参数转换为0,substring()方法会把所有负值参数都转换为-。

    var stringValue = "hello world";
    alert(stringValue.slice(-3)); //"rld"
    alert(stringValue.substring(-3)); //"hello world"
    alert(stringValue.substr(-3)); //"rld"
    alert(stringValue.slice(3,-4)); //"lo w"
    alert(stringValue.substring(3,-4)); //"hel"
    alert(stringValue.substr(3,-4)); //""(空字符串)
    

    substring()方法会将较小的数作为开始位置,将较大的数作为结束位置。

    • 3. 字符串位置方法
      有两个可以从字符串中查找子字符串的方法:indexOf()方法和lastIndexOf()方法。这两个方法都是从一个字符串中搜索给定的子字符串,然后返回子字符串的位置(如果没有找到,则放回-1)。
      indexOf()从字符串开头向后搜索子字符串,lastIndexOf()从字符串末尾向前搜索子字符串。
    var stringValue = "hello world";
    alert(stringValue.indexOf("o"); //4
    alert(stringValue.lastIndexOf("o")); //7
    

    这两个方法都可以接收可选的第二个参数,表示从字符串中的哪个位置开始搜索。

    var stringValue = "hello world";
    alert(stringValue.indexOf("o", 6); //7
    alert(stringValue.lastIndexOf("o", 6)); //4
    

    可以通过循环调用indexOf()或lastIndexOf()来找到所有匹配的子字符串。

    var stringValue = "Lorem ipsum dolor sit amet, consectetur 
    adipisicing elit. ";
    var positions = new Array();
    var pos = stringValue.indexOf("e");
       
    while(pos>-1){
     positions.push(pos);
     pos = stringValue.indexOf("e", pos+1);
    }
    alert(positions); //"3,24,32,35,52"
    

    在循环外,首先找到"e"在字符串中的初始位置,然后进入循环。

    • 4. trim()方法
      ECMAScript5 为所有字符串定义了trim()方法。这个方法会创建一个字符串的副本,删除前置及后缀的所有空格,然后返回结果。
    var stringValue = "    hello world    ";
    var trimmedStringValue = stringValue.trim();
    alert(stringValue); //"    hello world    "
    alert(trimmedStringValue); //"hello workd"
    

    由于trim()返回的是字符串的副本,所以原始字符串中的前置及后缀空格会保持不便。
    trimLeft()和trimRight()方法,分别用于删除字符串开头和末尾的空格。

    • 5. 字符串大小转换方法

    ECMAScript中涉及字符串大小写转换的方法有四个:toLowerCase()toLocaleLowerCase()toUpperCase()toLocaleUpperCase()

    var stringValue = "hello world";
    alert(stringValue.toLocaleUpperCase()); //"HELLO WORLD"
    alert(stringValue.toUpperCase()); //"HELLO WORLD"
    alert(stringValue.toLocaleLowerCase()); //"hello world"
    alert(stringValue.toLowerCase()); //"hello world"
    
    • 6. 字符串模式匹配方法

    String类型定义了几个用于在字符串中匹配模式的方法。
    match()方法,在字符串调用这个方法,本质上与调用RegExp的exec方法相同。match()方法只接受一个参数,要么是一个正则表达式,要么是一个RegExp对象。

    //与pattern.exec(text)相同
    var matches = text.match(pattern);
    alert(matches.index); //0
    alert(matches[0]); //"cat"
    alert(pattern.lastIndex); //0
    

    match()方法返回了一个数组,数组的第一项是与整个模式匹配的字符串,之后的每一项(如果有)保存着与正则表达式中的捕获组匹配的字符串。

    search()方法,这个方法只接受一个参数,要么是一个正则表达式,要么是一个RegExp对象。search()方法返回字符串中第一个匹配项的索引;如果没有找到匹配项,则返回01。search()方法始终是从字符串开头向后查找模式。

    var text = "cat, bat, sat, fat";
    var pos = text.search(/at/);
    alert(pos); //1
    

    replace()方法,这个方法接受两个参数:第一个参数可以是一个RegExp对象或这一个字符串(这个字符串不会被转换成正则表达式),第二个参数可以是一个字符串或者一个函数。如果第一个参数是字符串,那么只会替换第一个子字符串。要想替换所有子字符串,唯一的办法就是提供一个正则表达式,而且要指定全局(g)标志。

    var text = "cat, bat, sat, fat";
    var result = text.replace("at", "ond");
    alert(result); //"cond, bat, sat, fat"
    
    result = text.replace(/at/g, "ond");
    alert(result); //"cond, bond, sond, fond"
    

    ECMAScript提供一些特殊的字符序列。

    • $$: $
    • $&:匹配真个模式的子字符串。与RegExp.lastMatch值相同
    • $':匹配子字符串之前的子字符串。与RegExp.leftContext的值相同
    • $`:匹配子字符串之后的子字符串。与RegExp.rightContext的值相同
    • $n:匹配第n个捕获组字符串。n等于0~9。
    • $nn:匹配第n 个捕获组字符串。n等于0你~99。
    var text = "cat, bat, sat, fat";
    result = text.replace("/(.at)/g","word($1)");
    alert(result); //word(cat), word(bat), word(sta), word(fat)
    

    replace()方法的第二个参数可以是一个函数。在只有一个匹配项(即与模式匹配的字符串)的情况下,会向这个函数传递3个参数,模式的匹配项,模式匹配项在字符串中的位置和原始字符串。在正则表达是中定义了多个捕获组的情况下,传递给函数的参数依次是模式的匹配项、第一个捕获组的匹配项
    第二个不过组的匹配项......,但组后两个参数仍然分别是模式匹配项在字符串中的位置和原始字符串。这个函数返回一个字符串,表示应该被替换的匹配项。

            function htmlEscape(text) {
                return text.replace(/[<>]&/g, function(match, pos, originalText) {
                    switch (match) {
                        case "<":
                            return "&lt;";
                        case ">":
                            return "&gt;";
                        case "&":
                            return "&amp;";
                        case "\"":
                        return "&quot;";
                    }
                });
            }
     alert(htmlEscape("<p class=\"greeting\">Hello world!</p>")); 
    //&lt;p class=&quot;"greeting&quot;"&gt;Hello world!&lt;/p&gt;
    
     **split()**方法,这个方法可以基于指定的分隔符将一个字符串分割成多个子字符串,并将结果放在一个数组中。分隔符可以使字符串,也可以是RegExp对象(这个方法不会将字符串看成正则表达式)。split()方法可以接受第二个参数,用于指定数组的大小以便确保返回的数组不会超过既定大小。
    
    var colorText = "red,blue,green,yellow";
    var colors1 = colorText.split(","); //["red", "blue", "green", "yellow"]
    var colors2 = colorText.split(",",2); //["red", "blue"]
    var colors3 = colorText.split(/[^\,]+/); //["", ",", ",", ",", ""]
    
    • 7. localeCompare()方法

    localeCompare()这个方法比较两个字符串,并返回下列值中的一个:

    • 如果字符串在字母表中排在字符串参数之前,返回一个负数(大多数是-1,具体视情况而定);
    • 如果字符串等于字符串参数,返回0;
    • 如果字符串在字母表中排在字符串参数之后,返回一个正数(大多数是1,具体视情况而定);
    var stringValue = "yellow";
    alert(stringValue.localeCompare("brick")); //1
    alert(stringValue.localeCompare("yellow")); //0
    alert(stringValue.localeCompare("zoo")); //-1
    
    function determineOrder(value) {
        var result stringValue.localeCompare(value);
        if(value<0){
            alert("The string 'yellow' comes before the string '"+value+"'.");
        }else if(value>0){
            alert("The string 'yellow' comes after the string '"+value+"'.");       
        }else{
                    alert("The string 'yellow' comes equal the string '"+value+"'.");
    
        }
    }
    determineOrder("brick");
    determineOrder("yellow");
    determineOrder("zoo");
    
    • 8. fromCharCode()方法
      String构造函数本身还有一个静态方法:fromCharCode()。这个方法的任务是接收一或多个字符编码,然后将它们转换成一个字符串。这个方法与实例方法charCodeAt()执行相反的操作。
     alert(String.fromCharCode(104, 101, 108, 108, 111));//"hello"
    

    相关文章

      网友评论

        本文标题:JavaScript引用类型——基本包装类型

        本文链接:https://www.haomeiwen.com/subject/yqdgxxtx.html