[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

畫frequency response和phase response(MATLAB))

畫frequency response和phase response(MATLAB))

React Native 手動換字型

React Native 手動換字型

Command Line 初學

Command Line 初學


Comments