Javascript 函数和默认参数,在 IE 和 Chrome 中无法工作

我创建了这样一个函数:

function saveItem(andClose = false) {


}

它在 Firefox 中运行良好

在 IE 中,它在控制台上给出这个错误: Expected ')'

在 Chrome 中,它会在控制台中显示以下错误: Uncaught SyntaxError: Unexpected token =

两种浏览器都将错误源标记为函数创建行。

69704 次浏览

That's not a valid ECMAScript syntax, but it is a valid syntax for Mozilla's superset of features they add to their implementation of the language.

Default parameter assignment syntax is likely coming in ECMAScript 6.

You can't do this, but you can instead do something like:

function saveItem(andClose) {
if(andClose === undefined) {
andClose = false;
}
}

This is often shortened to something like:

function setName(name) {
name = name || 'Bob';
}

Update

The above is true for ECMAScript <= 5. ES6 has proposed Default parameters. So the above could instead read:

function setName(name = 'Bob') {}

Javascript does not allow a "default" specifier.

A quick way of doing what you would want is changing:

function saveItem(andClose = false) {


}

to the following:

function saveItem(andClose) {
// this line will check if the argument is undefined, null, or false
// if so set it to false, otherwise set it to it's original value
var andClose = andClose || false;


// now you can safely use andClose
if (andClose) {
// do something
}
}

The code you provided won't run in Chrome < version 49: https://kangax.github.io/compat-table/es6/#test-default_function_parameters

You used valid ECMAScript 2015 syntax:

In my opinion, the best way to use ES2015 features is to bundle assets with Browserify or WebPack, with a step for using Babel to trans-compile ES2015 to ES5. That way you don't have to worry about that ES2015 browser compatibility chart. It's a pain to get started the first time, but worth it.

In your case, you have an other alternative to be sure that your variable is a boolean:

function saveItem(andClose) {
andClose = true == andClose;
// ...
}

Default value is undefined, and true == undefined => false, so your default value will be false :)