JS: How to fix “Expected ')' to match '(' from line 4 and instead saw '='.” JSLint error

[亡魂溺海] 提交于 2020-01-05 08:45:09

问题


I have written the following function:

function MyTest(element, no, start=0) {
    this.no = no;
    this.element = element;
    this.currentSlide = start;

    self.start();
}

JSLint complains:

Expected ')' to match '(' from line 4 and instead saw '='.

What is wrong with this? Is it the default value I've set?


回答1:


JavaScript doesn't have default values for arguments (yet; it will in the next version, and as Boldewyn points out in a comment, Firefox's engine is already there), so the =0 after start is invalid in JavaScript. Remove it to remove the error.

To set defaults values for arguments, you have several options.

  1. Test the argument for the value undefined:

    if (typeof start === "undefined") {
        start = 0;
    }
    

    Note that that does not distinguish between start being left off entirely, and being given as undefined.

  2. Use arguments.length:

    if (arguments.length < 3) {
        start = 0;
    }
    

    Note, though, that on some engines using arguments markedly slows down the function, though this isn't nearly the problem it was, and of course it doesn't matter except for very few functions that get called a lot.

  3. Use JavaScript's curiously-powerful || operator depending on what the argument in question is for. In your case, for instance, where you want the value to be 0 by default, you could do this:

    start = start || 0;
    

    That works because if the caller provides a "truthy" value, start || 0 will evaluate to the value given (e.g., 27 || 0 is 27); if the caller provides any falsey value, start || 0 will evaluate to 0. The "falsey" values are 0, "", NaN, null, undefined, and of course false. "Truthy" values are all values that aren't "falsey".



来源:https://stackoverflow.com/questions/20490718/js-how-to-fix-expected-to-match-from-line-4-and-instead-saw-jsli

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