首页 > 解决方案 > 如何在技术上避免不正确的比较功能?

问题描述

[2,4,1,7,5].sort((a, b)=>a>b)  // wrong
[2,4,1,7,5].sort((a, b)=>a-b)  // correct

如果我几年没有使用此功能,我很有可能以错误的方式使用它。

有什么技术手段可以避免吗?

标签: javascriptarrays

解决方案


如果你认为你很可能会像你的第一个示例那样编写代码并且你真的想避免它,我可以想到两种方法:

  1. 为 ESLint 或类似的插件编写一个插件,查看sort回调是否返回比较操作的结果。

  2. sort如果回调不返回数字,则编写一个仅开发时的包装器会引发错误。但我可能不会将它包含在生产版本中,只是在开发过程中。

#2 看起来像这样:

const sort = Array.prototype.sort;
Array.prototype.sort = function(callback) {
    return sort.call(this, (a, b) => {
        const rv = callback(a, b);
        if (typeof rv !== "number") {
            throw new Error("Array.prototype.sort callback must return a number");
        }
        return rv;
    });
};

现场示例:

const sort = Array.prototype.sort;
Array.prototype.sort = function(callback) {
    return sort.call(this, (a, b) => {
        const rv = callback(a, b);
        if (typeof rv !== "number") {
            throw new Error("Array.prototype.sort callback must return a number");
        }
        return rv;
    });
};

try {
  console.log([2,4,1,7,5].sort((a, b)=>a>b));
} catch (e1) {
  console.error(e1.message);
}

try {
  console.log([2,4,1,7,5].sort((a, b)=>a-b));
} catch (e2) {
  console.error(e2.message);
}


推荐阅读