JSLint:意外的赋值表达式 [英] JSLint: Unexpected assignment expression
问题描述
我收到此警告:
Unexpected assignment expression.
return task.completed = true; // Line 63, Pos 39
使用此代码时:
completeAll: function () {
this.tasks = this.tasks.filter(function (task) {
return task.completed = true;
});
}
为什么?而且我还能怎么写这个表达式来避免JSLint抛出警告?
Why? And how else could I write this expression to avoid JSLint throwing warnings?
P.S.
该代码块来自此处的Vue TodoMVC示例: http://todomvc.dev/examples/vue/,因此我认为必须已经进行了代码审查.
The codeblock is taken from the Vue TodoMVC Example here: http://todomvc.dev/examples/vue/, therefore I assume that code review must have already been happened.
推荐答案
之所以这样做,是因为警告您在不只是上下文中使用=
而不是==
或===
分配,但还要对分配的结果做些事情.那是完全有效的JavaScript,但是经常是无意的.一个更好的例子是:
It's doing that because it's warning you that you're using =
rather than ==
or ===
in a context where you're not just assigning, but also doing something with the assigned result. That's perfectly valid JavaScript, but it's frequently unintentional. A better example is:
if (foo = bar) {
// ...
}
...您可能指的是==
或===
(检查它们是否相等).
...where you probably meant ==
or ===
(checking that they were equal).
如何修复它取决于您要执行的操作.从方法的名称来看,我认为您正在尝试设置task.completed
,在这种情况下,坦率地说filter
是使用错误的函数.他们应该使用forEach
:
How you fix it depends on what you're trying to do. From the name of the method, I assume you're (well, they're) trying to set task.completed
, in which case frankly filter
is the wrong function to use; they should be using forEach
:
completeAll: function () {
this.tasks.forEach(function (task) {
task.completed = true;
});
}
但是如果您(他们)真的想使用filter
:
but if you (they) really wanted to use filter
:
completeAll: function () {
this.tasks = this.tasks.filter(function (task) {
task.completed = true;
return true; // Or return task.completed
});
}
如果您要进行比较(我对此表示怀疑),而不是进行分配,那么:
If you're trying to do a comparison (which I doubt), not an assignment, then:
return task.completed == true;
或
return !!task.completed;
或
return task.completed; // If you know it's boolean already
这篇关于JSLint:意外的赋值表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!