我有这个计算总数的方法,其中一部分是在JS Lint中发出警告。我们正在努力让JS Lint在工作中得到更清晰的检查,所以我想看看是否有一种理性的解决方法可以解决这个问题。
calculateTotal = function() {
var hours = parseFloat($hours.val());
var rate = parserFloat($rate.val());
var total = '';
if (!isNaN(hours) && !isNaN(rate)) {
// This throws the error.
total = (rate * hours).toFixed(2);
}
$total.val(total);
}
如果我执行以下操作,我可以避免该消息:
total = rate * hours;
total = total.toFixed(2);
对我来说,跳过它有点过于冗长,但这可能是最好的选择。
我检查了this question,并考虑做Number(rate * hours).toFixed(2)
,但是那个(略微)性能较差,加上从使用{的所有警告开始是一个不好的先例{1}}如回应那里接受的答案所述。
如果我的上述尝试是让JS Lint停止抱怨的最佳方式,这可能没有实际意义,但我想听听别人的意见。
答案 0 :(得分:2)
JSLint将强制您从括号后面移动toFixed()
。我建议移动它最不烦人的地方是$total.val(total)
任务。
这在JSLint.com上按照原样显示:
/*jslint white:true, browser:true */
/*global $hours, $rate, $total */
var calculateTotal = function() {
"use strict";
var hours = parseFloat($hours.val());
var rate = parseFloat($rate.val());
var total;
if (!isNaN(hours) && !isNaN(rate)) {
// This throws the error.
total = rate * hours;
}
$total.val(total.toFixed(2)); // moved `toFixed` to here
};
我尝试使用最新版本的JSLint,它在left_check
in JSLint's code, here处开始:
function left_check(left, right) {
// Warn if the left is not one of these:
// e.b
// e[b]
// e()
// identifier
var id = left.id;
if (
!left.identifier &&
(
left.arity !== "binary" ||
(id !== "." && id !== "(" && id !== "[")
)
) {
warn("unexpected_a", right);
return false;
}
return true;
}
left
基本上是(rate & hours)
,右边是.
,toFixed
是这种情况下的下一个标记。
从注释中承担代码函数是危险的,我认为这些注释告诉我们JSLint的来源 - 它想要的方法只能在对象上调用,而不是在操作上调用,包括经常在其中发生的类型强制。它几乎必须让你进行“流畅”的调用,你链接方法,并且唯一可以有方法调用的有效东西是......
e
e.b
e[key]
e()
只是为了仔细检查,因为你的建筑曾经在“旧JSLint”(last version before JSLint for ES6)工作,我问道格拉斯克罗克福德。他非常简洁,但是he did confirm JSLint is working as intended。
抱歉,我无法在那里提供更多帮助。我认为有些地方(someExpression).someMethod()
是权宜之计,但也要了解JSLint的来源。如果您将有可能进行类型强制,请明确强制。
有趣的问题;谢谢你的询问。