js實現嵌套數組重排序
本文實例為大傢分享瞭js實現嵌套數組重排序的具體代碼,供大傢參考,具體內容如下
總共遇到兩個問題:
1、JS中for循環輸出同一變量值的問題
js事件處理器在線程空閑事件不會運行,導致最後運行的時候輸出的都是i最後的值。
解決方法:在循環中聲明 this.content1 = {}
2、排序算法在序號到10以後出錯
解決方法:沒註意string和int,原數據為string
原數據:
目標:將table、text、image合並到一個content裡面,並按blockNO排序
代碼:
<script> export default { data() { return { data: [], content1: {} } }, created() { this.test() }, methods: { async test() { const { data: res } = await this.$http.get('test1') for (let i = 0; i < res.length; i++) { this.data1 = {} this.data1.name = res[i].name this.data1.blockNO = res[i].blockNO this.data1.class = res[i].class this.data1.id = res[i].id this.data1.children = [] this.data1.content = [] if (res[i].text) { for (let j = 0; j < res[i].text.length; j++) { this.content1 = {} this.content1.blockNO = res[i].text[j].blockNO this.content1.type = 'text' this.content1.detail = res[i].text[j].text this.data1.content.push(this.content1) } } if (res[i].table) { for (let j = 0; j < res[i].table.length; j++) { this.content1 = {} this.content1.blockNO = res[i].table[j].blockNO this.content1.type = 'table' this.content1.detail = res[i].table[j].table this.data1.content.push(this.content1) } } if (res[i].image) { for (let j = 0; j < res[i].image.length; j++) { this.content1 = {} this.content1.blockNO = res[i].image[j].blockNO this.content1.type = 'image' this.content1.detail = res[i].image[j].image this.data1.content.push(this.content1) } } for (let j = 1; j < this.data1.content.length; j++) { for (let i = 0; i < this.data1.content.length - j; i++) { if ( parseInt(this.data1.content[i].blockNO) > parseInt(this.data1.content[i + 1].blockNO) ) { let tempnum = this.data1.content[i + 1] this.data1.content[i + 1] = this.data1.content[i] this.data1.content[i] = tempnum } } } this.data.push(this.data1) } console.log(this.data) } } } </script>
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。