Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我需要根据对象的属性对Vue中的对象数组进行排序,但Vue会无限循环进行排序_Javascript_Sorting_Web_Vuejs2 - Fatal编程技术网

Javascript 我需要根据对象的属性对Vue中的对象数组进行排序,但Vue会无限循环进行排序

Javascript 我需要根据对象的属性对Vue中的对象数组进行排序,但Vue会无限循环进行排序,javascript,sorting,web,vuejs2,Javascript,Sorting,Web,Vuejs2,vue js使用属性对对象数组进行排序,并尝试使用另一个属性对排序后的数组进行排序,但vue会进入无限排序循环 chatRoomArraySorted: function() { console.log("func name chatRoomArraySorted"); function compare(a, b) { if (a.name < b.name) return -1; if (a.name > b

vue js使用属性对对象数组进行排序,并尝试使用另一个属性对排序后的数组进行排序,但vue会进入无限排序循环

chatRoomArraySorted: function() {
    console.log("func name chatRoomArraySorted");

    function compare(a, b) {
        if (a.name < b.name)
            return -1;
        if (a.name > b.name)
            return 1;
        return 0;
    }

    return this.chatRoomsArray.sort(compare);
}

sortedArray: function() {
    this.log("sortedArray");

    function compare1(a, b) {
        return new Date(b.lastMsg.createdAt) - new Date(a.lastMsg.createdAt);
    }

    return this.chatRoomsArray.sort(compare1);
},
聊天室阵列排序:函数(){ log(“func name chatRoomArraySorted”); 功能比较(a、b){ 如果(a.nameb.name) 返回1; 返回0; } 返回此.chatRoomsArray.sort(比较); } SorterDarray:函数(){ 此.log(“SorterDarray”); 功能比较1(a,b){ 返回新日期(b.lastMsg.createdAt)-新日期(a.lastMsg.createdAt); } 返回此.chatRoomsArray.sort(compare1); },
只要所依赖的任何属性的值发生更改,计算属性就会更新,这意味着将再次调用定义函数

由于您在两个计算属性中的
chatRoomsArray
属性上调用
sort()
,因此您正在对
chatRoomsArray
数组本身进行变异,从而触发两个计算属性的更新。每次运行每个计算属性的函数时都会发生这种情况,这将创建无限循环


您需要做的是在每个计算属性中返回一个已排序的
chatRoomsArray
副本,而不实际排序数组本身

您可以通过调用
concat()
来复制数组,如下所示:

return this.chatRoomsArray.concat().sort(compare);
您还可以使用以下方式制作副本:

return [...this.chatRoomsArray].sort(compare);

如何调用这些函数?它们在您的代码中似乎不是相互递归的,因此问题一定在别处。我在computed中添加了此函数,并从htmlPlease中调用它们。请创建一组产生问题的代码。
chatRoomsArray
的代码是什么?无限循环运行时,我无法访问clitarthttps://stackoverflow.com/users/1497533/ippi