我有一个对象数组。我想将选定的对象移动到数组中的最后一个位置。我如何在 javascript 或 jquery 中执行此操作?
这是我的一些代码:
var sortedProductRow = this.product_row;
for (var s in sortedProductRow) {
if (sortedProductRow[s]["parent_product_type"] != "")
// Move this object to last position in the array
}
我用 for 循环遍历它,我希望对输出进行排序,以便所有不具有“parent_product_type”值的对象首先出现,然后是具有值的对象。
最佳答案
要将一个元素(您知道其索引)移动到数组的末尾,请执行以下操作:
array.push(array.splice(index, 1)[0]);
如果你没有索引,只有元素,那么这样做:
array.push(array.splice(array.indexOf(element), 1)[0]);
例子:
var arr = [1, 2, 6, 3, 4, 5];
arr.push(arr.splice(arr.indexOf(6), 1)[0]);
console.log(arr); // [1, 2, 3, 4, 5, 6]
NOTE:
this only works with Arrays (created with the
[ ... ]
syntax orArray()
) not with Objects (created with the{ ... }
syntax orObject()
)
关于javascript - 将数组中的项目移动到最后一个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24909371/