无法在 JS 中重新排序对象数组

Cannot reorder an array of objects in JS

我有一个对象数组,以块的形式呈现给用户。他们可以拖放以更改块出现的顺序,然后我想更改对象在数组中的位置。

$scope.myArray = [{a:1,b:2,c:3}, {a:11,b:22,c:33}, {a:111,b:222,c:333}];

function orderChanged(event) {
  console.log($scope.myArray);
    //logs [{a:1,b:2,c:3}, {a:11,b:22,c:33}, {a:111,b:222,c:333}]

  console.log("source:", event.source.index, "dest:", event.dest.index);
    //logs source: 1 dest: 2

  $scope.myArray.move(event.source.index, event.dest.index);

  console.log($scope.myArray);
    //logs [{a:1,b:2,c:3}, {a:11,b:22,c:33}, {a:111,b:222,c:333}]
};

//this is going to rearrange the array
Array.prototype.move = function (from, to) {
  this.splice(to, 0, this.splice(from, 1)[0]);
};

orderChange 事件将源索引和目标索引作为整数表示它们呈现给用户的顺序,这也映射到它们在发生任何移动之前在数组中的位置。

我无法让数组重新排列,每次我在 orderChange 函数中记录数组时都记录 return 相同的顺序。

数组重新排序的所有其他示例都是针对不包含对象的数组,我想知道这是否是我的代码乱七八糟的原因?

我正在测试您的代码并且工作正常。你在哪里修改数组原型?只需尝试用实际执行重新排序和测试的代码替换对 move() 的调用...

无论如何,您正在使用 AngularJS。你为什么要搞乱 DOM?为您的每个对象添加一个名为 Order 的 属性,然后让 Angular 进行同步...这意味着什么。

总之,看看这个模块,也许它会让你的生活更轻松:

http://ngmodules.org/modules/ng-sortable

我认为,您的代码工作正常,但日志不正常。

console.log 可能不代表运行时的值,但代表查看时的值,尤其是对于多维对象和数组。

尝试不同的日志以查看 console.log($scope[0].a, $scope[1].a, $scope[2].a)

您可能想签入不同的浏览器,因为这似乎是一个 Chrome 问题,请参阅此处:
Is Chrome's JavaScript console lazy about evaluating arrays?
Wrong value in console.log