gpt4 book ai didi

javascript - 将数组中的项目移动到最后一个位置

转载 作者:可可西里 更新时间:2023-11-01 01:35:52 25 4
gpt4 key购买 nike

我有一个对象数组。我想将选定的对象移动到数组中的最后一个位置。我如何在 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 or Array()) not with Objects (created with the { ... } syntax or Object())

关于javascript - 将数组中的项目移动到最后一个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24909371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com