const arr = [1, 3, 4, 2, 7];
const arrObj = [
{
key: 2
},
{
key: 1
},
{
key: 4
},
{
key: 3
},
{
key: 7
},
{
key: 2
}
];
const res = arrObj.sort(this.sortFunc('key', arr));
console.log(res, 'res');
sortFunc(propName, referArr) {
return function (prev, next) {
return (
referArr.indexOf(prev[propName]) - referArr.indexOf(next[propName])
);
};
},

这段代码展示了如何使用JavaScript对一个对象数组按照对象内的属性值(key)进行排序,参考另一个数组的顺序。sortFunc函数作为比较器,利用referArr的indexOf方法确定元素位置差异进行排序。
2998

被折叠的 条评论
为什么被折叠?



