更新时间:2023-01-30 12:42:39
您可以使用具有值及其顺序的对象。使用默认值,您可以将未指定的值移动到数组的开头或结尾。
You could use an object with the order of the values and their order. With a default value, you could move not specified values to start or end of the array.
var order = { wheel: 1, book: 2, car: 3, default: 1000 },
array = ['foo', 'car', 'book', 'wheel'];
array.sort(function (a, b) {
return (order[a] || order.default) - (order[b] || order.default);
});
console.log(array);