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

2024-04-28

我有一系列对象。我想将选定的对象移动到数组中的最后一个位置。我如何在 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]);

Example:

    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:

这仅适用于数组(使用[ ... ]语法或Array())不与对象(使用创建{ ... }语法或Object())

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将数组中的项目移动到最后一个位置 的相关文章

随机推荐