【VUE】數組


【VUE】常用函數

轉載:https://www.cnblogs.com/yangchongxing/p/10637087.html

目錄

==================================================

1、變異方法

2、替換數組

3、修改數組

==================================================

 1、變異方法

push() 方法可向數組的末尾添加一個或多個元素,並返回新的長度。

this.items.push({msg:'n1'})
this.items.push({msg:'n1'},{msg:'n2'})

pop() 方法用於刪除並返回數組的最后一個元素。

this.items.pop()

unshift() 方法可向數組的開頭添加一個或更多元素,並返回新的長度。

this.items.unshift({msg:'n1'})
this.items.unshift({msg:'n1'},{msg:'n2'})

shift() 方法用於把數組的第一個元素從其中刪除,並返回第一個元素的值。

this.items.shift()

splice() 方法向/從數組中添加/刪除項目,然后返回被刪除的項目。

splice(length) 設置長度

splice(index, len, [item])

添加,在索引1的位置
this.items.splice(1,0,{msg:'n1'})
this.items.splice(1,0,{msg:'n1'},{msg:'n2'})
刪除,從索引1開始,刪除2個含索引
this.items.splice(1,2)
替換,從索引1開始,替換1個含索引
this.items.splice(1,1,{msg:'n'})
this.items.splice(1,2,{msg:'n'}) 替換2個

 sort() 方法用於對數組的元素進行排序。按照字符編碼默認從小到大排序

 默認字母排序

this.items.sort()

reverse() 方法用於顛倒數組中元素的順序。

this.items.reverse()

 1、替換數組

filter() 方法創建一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素。

this.items.filter(function (item) {
    return item.message.match(/Foo/)
})

concat() 方法用於連接兩個或多個數組。

this.items.concat([{message:'JJ'},{message:'BB'}])

slice() 方法可從已有的數組中返回選定的元素。

this.items.slice(開始索引, 結束索引)   結束索引不包含
this.items.slice(開始索引) 從開始到結尾
索引為負數時,數組長度加上負數索引就是使用的索引

3、修改數組

this.items[1] = { message: 'Bar m' }  修改不響應
解決方式,一下三種都可以
Vue.set(this.items, 1, { message: 'Bar11' })
vm.$set(this.items, 1, { message: 'Bar22' })
this.items.splice(1, 1, { message: 'Bar33' })
this.items.length = 2  修改不響應
解決方式
this.items.splice(2)

 

其他

split() 方法用於把一個字符串分割成字符串數組


免責聲明!

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



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