Vue反轉字符串及join(),reverse()與 split()函數用法解析


HTML

<div id="app">
  <p>{{ massage }}</p>
  <button @click="reverseMassage">反轉字符串</button> </div>

script

var vm = new Vue({
    el : ''#app',
  data : {
    massage:'hello vue'
  },
  methods : {
    reverseMassage:function(){
      this.massage= this.massage.split('').reverse().join('')
    }
  }
})

反轉前:

 反轉后:

 


解析:

split(' ')是分裂的意思,也就是把一個數據拆分

split(' ')會把數據拆分為一個數組,括號里的' '是把數據拆分為每個字符串的意思,如果不用就不會拆分成每個字符串

在控制台嘗試輸出:

console.log(this.message.split(''));  //結果["e", "u", "v", " ", "o", "l", "l", "e", "h"]

reverse( )是翻轉的意思,把數據反過來
message.reverse() == Not split //無效,因為只能對數組起作用
所以要跟在split(' ')后使用

console.log(this.message.split('').reverse());  //結果["h", "e", "l", "l", "o", " ", "v", "u", "e"]

join(' ')是重組的意思,把數組合成一個字符串
message.split('').join(' ')
slpit后會拆散會數組,join后就會變回原來的字符串了
所以我們要把數據反過來重組就可以用message.split(' ').reverse( ).join(' ')

 

 

 

參考文章:

Akiode  https://blog.csdn.net/weixin_42553164/article/details/81218051 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM