第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定

自定義indexOf()方法

標簽:
JavaScript

JS中的indexOf()

indexOf(searchElement,fromIndex)。接受两个参数,第一个是要查询的项,第二个表示查找起点的索引。如找到,则返回找到的第一个位置,否则返回-1。当fromIndex小于0或者无值,则从0开始查找,若fromIndex>arr.length-1,则返回-1。 全等===比较

var numbers = [1,2,3,4,5,4,3,2,1,4];
alert(numbers.indexOf(4)); //3alert(numbers.indexOf(4,4)); //5alert(numbers.indexOf(4,9)); //9alert(numbers.indexOf(4,10)); //-1alert(numbers.indexOf(4,-10)); //3

一个有意思的事儿

var person = { name: "Nicholas" };var people = [{ name: "Nicholas" }];var morePeople = [person];
alert(people.indexOf(person)); //-1alert(morePeople.indexOf(person)); //0alert(people[0]==(person)); //falsealert(morePeople[0]==person); //truealert(morePeople[0]==people[0]); //false

原因:person和people[0]不是同一个对象,而morePeople[0]和person是同一个对象,所以才有了上述代码的结果。

自定义具有相同功能的indexof

Array.prototype.indexof=function(searchElement,fromIndex){    var len=this.length;    //检测有效性
    if(len<=0) reutrn -1;    //判断fromIndex,来决定下一步处理
    if(typeof fromIndex=='undefined'){fromIndex=0;console.log(fromIndex)}    if(typeof fromIndex=='number'){
        fromIndex=fromIndex>=0?fromIndex:0;
    }else{        return 'err';
    }    //遍历寻找
    for(let i=fromIndex;i<len;i++){        if(this[i]===searchElement)return i;//返回找到的第一个索引
    }    return -1;
}

注意:不建议些项目用Array.prototype更改原始对象,更改了会破坏原始环境,引起不必要的bug

//寄生模式function IndexOf(ar){    var arr=new Array(),arr=arr.concat(ar)
    arr.indexof=function(search,index){        var len=this.length        if(len<=0)return -1
        if(typeof index=='undefined') index=0;        if(typeof index=='number'){
            index=index>=0?index:0
        }else{            return 'err'
        }        for(let i=index;i<len;i++){            if(this[i]===search)return i;
        }        return -1
    }    return arr
}var x=new IndexOf([1,2,3,4])console.log(x.indexof(2))

下面内容和标题无关:字符串中没有splice()方法的原因:splice()可以更改母体,而字符串不可更改,所有不能用。使用Array.prototype.splice.call(string)也没用,但是Array.prototype.slice.call(string)可以,因为slice不改变母体。



作者:fenerchen
链接:https://www.jianshu.com/p/97a0da229ff4


點擊查看更多內(nèi)容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優(yōu)惠券免費領(lǐng)

立即參與 放棄機會
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號

舉報

0/150
提交
取消