JS:如何修复"Expected')'以匹配第4行的'(',而是看到'='." JSLint错误 [英] JS: How to fix "Expected ')' to match '(' from line 4 and instead saw '='." JSLint error

查看:421
本文介绍了JS:如何修复"Expected')'以匹配第4行的'(',而是看到'='." JSLint错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下函数:

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

    self.start();
}

JSLint抱怨:

期望')'与第4行的'('相匹配,而是看到'='.

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

这有什么问题?是我设置的默认值吗?

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

推荐答案

JavaScript尚没有参数的默认值(还;它 Boldewyn 点注释中,Firefox的引擎已经存在),因此start之后的=0在JavaScript中无效.删除它以消除错误.

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. 测试参数undefined的参数:

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

请注意,这并不能区分完全放弃start和以undefined给出.

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

使用arguments.length:

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

但是请注意,在某些使用arguments的引擎上,该功能明显减慢了速度,尽管这几乎不是问题所在,但除了很少之外,这当然没有关系. >称为 lot 的函数.

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.

使用JavaScript的功能强大的||运算符,具体取决于所讨论的参数是什么.例如,在您的情况下,您希望默认值为0,则可以执行以下操作:

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;

之所以可行,是因为如果调用方提供了一个真实的"值,则start || 0将求出给定的值(例如,27 || 027);如果呼叫者提供任何 falsey 值,则start || 0的评估结果为0. 假"值是0""NaNnullundefined,当然还有false. "Truthy"值是所有非"falsey"值.

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

这篇关于JS:如何修复"Expected')'以匹配第4行的'(',而是看到'='." JSLint错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆