通过原型链继承的方式实现: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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值