[MTR04] W2 D15 練習六


Posted by Christy on 2020-07-21

練習六:回傳第一個大寫字母以及它的 index
請寫一個 function position,接收一個字串並回傳這個字串裡面的第一個大寫字母跟它的 index,若沒有則回傳 -1。

position("abcd") 正確回傳值:-1

position("AbcD") 正確回傳值:A 0

position("abCD") 正確回傳值:C 2

錯誤解法:

function position(str){
str = "Abcd"
var index = str.indexOf()
    if(index >= "A" && index <= "Z"){
    return indexOf()
    }else{
    return -1
    }
    return indexOf()
}
position(indexOf("Abcd"))

正確解法:

function position(str){
    for(var i = 0; i < str.length; i++){
     if(str[i] >= 'A' && str[i] <= 'Z'){
      return str[i] + ' ' + i
     }
    }
    return -1
   }
   var a = position('abCd')
   console.log(a)









Related Posts

The introduction and difference between class component and function component in React

The introduction and difference between class component and function component in React

2020 COSCUP 感想

2020 COSCUP 感想

# 〈 Diffusion Model 論文研究與實作心得 Part.2 〉 U-Net 模型架構介紹與實作

# 〈 Diffusion Model 論文研究與實作心得 Part.2 〉 U-Net 模型架構介紹與實作


Comments