JSLint: Unexpected assignment expression

好久不见. 提交于 2020-07-03 11:53:07

问题


I get this warning:

Unexpected assignment expression.
return task.completed = true; // Line 63, Pos 39

When using this code:

completeAll: function () {
    this.tasks = this.tasks.filter(function (task) {
        return task.completed = true;
    });
}

Why? And how else could I write this expression to avoid JSLint throwing warnings?

P.S.

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.


回答1:


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).

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;
    });
}

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;

or

return !!task.completed;

or

return task.completed; // If you know it's boolean already


来源:https://stackoverflow.com/questions/32474106/jslint-unexpected-assignment-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!