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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)