通过原型链继承的方式实现:IE8不支持的indexOf和trim方法

IndexOf(“要查找的字符”)方法:返回找到字符串首次出现的位子,如果找不到返回 -1

trim()方法:去除字符串前后的空白符

这两种方法在低版本的IE8中都没有实现,那么如何通过原型链的方式实现呢?

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>原型继承</title>
</head>
<body>

</body>
<script>
    //要求:通过原型链的方式实现:IE8不支持的indexOf和trim方法

    /*******indexOf方法的实现************/
    if (!Array.prototype.hasOwnProperty("indexOf")){    //四种方法检测对象中是否存在指定属性
    //if (!("indexOf" in Array.prototype)){
    //if (!Array.prototype.indexOf){
    //if (Array.prototype.indexOf === undefined){
        Array.prototype.indexOf = function(keyword){
            for (var i=0;i<this.length;i++){
                if(keyword == this[i]){
                    return i;
                }
            }
            return -1;
        }
    }
    var arr = ["Mary","Kangkang","Macal"];
    var arr1 = [1,2,45,99];
    document.write(arr.indexOf("Mary")+"<br/>");        //0
    document.write(arr.indexOf("Lili")+"<br/>");        //-1
    document.write(arr1.indexOf(999)+"<br/>");        //-1
    document.write(arr1.indexOf(99)+"<br/>");        //3


    /*************trim方法的实现*************/
    if (!String.prototype.hasOwnProperty("trim")){
        String.prototype.trim = function(){
            return this.replace(/^\s+|\s+$/g,"");
        }
    }
    var str1 = "    Hello World   ";
    var str2 = "    You can you up   ";
    document.write(str1.replace(/ /g,"_")+"<br/>");     //____Hello_World___
    document.write(str1.trim()+"<br/>");                //Hello World
    document.write(str2.replace(/ /g,"_")+"<br/>");     //____You_can_you_up___
    document.write(str2.trim()+"<br/>");                //You can you up

</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_39579242/article/details/81631473