indexOf()和lastIndexOf()的练习

来源:互联网 发布:北京algorithm算法 编辑:程序博客网 时间:2024/06/07 07:55

indexOf() 方法将从头到尾地检索字符串,可返回某个指定的字符串值在字符串中首次出现的位置。(从左到右)(如果要检索的字符串值没有出现,则该方法返回 -1)

lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索。(如果要检索的字符串值没有出现,则该方法返回 -1)

例子:

//长度为20的数组,随机添加1~30的数,找出没有出现过2次的数 

 var arr = []
 var a = 0;
 for(var i = 0;i<30;i++){
   arr[i]=parseInt(Math.random()*30+1)        
 }
 for(var i = 0;i<arr.length;i++){
     charIndex(arr,i)  
 }
 //封装成函数
 function charIndex(str,index){
    if(str.indexOf(str[index])==str.lastIndexOf(str[index])){          //找出惟一数
       console.log(str[index])
       return true
 }
 return false
 }
      console.log(arr) 
0 0
原创粉丝点击