javascript - 如何在技术上避免不正确的比较功能?
问题描述
[2,4,1,7,5].sort((a, b)=>a>b) // wrong
[2,4,1,7,5].sort((a, b)=>a-b) // correct
如果我几年没有使用此功能,我很有可能以错误的方式使用它。
有什么技术手段可以避免吗?
解决方案
如果你认为你很可能会像你的第一个示例那样编写代码并且你真的想避免它,我可以想到两种方法:
为 ESLint 或类似的插件编写一个插件,查看
sort
回调是否返回比较操作的结果。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);
}
推荐阅读
- c# - 资源不包含菜单的定义
- node.js - 如何使用 babel 确保“require()”语句位于转译文件的顶部?
- c++ - 使用 Boost.asio 并行 Ping(ICMP) 多个目的地
- kubernetes - 如何在 Kong 的同一服务中使用多个身份验证插件
- python - 对整个测试集进行预测
- python - 如何使用 Python 将函数应用于多个列?
- discord.js - 如何计算有多少人在使用我的机器人?
- excel - Excel VBA - 删除特定的条件格式规则
- leaflet - 在 Leaflet 中的 WMS Tiles 之间切换
- ckeditor5 - CKEditor5 样式下拉菜单