16

オプションのパラメーターを受け入れるJavaScript関数があります。これは で正常に動作しますFirefoxが、次のGoogle Chromeように表示されます:-

Uncaught SyntaxError: Unexpected token =

私のコード、

function errorNotification(text = "Something went wrong!") {
  $.pnotify({
      title: 'Error',
      text: text,
      type: 'error'
  });
}

同様の質問をたくさん見ましたが、自分の問題を理解できません。

4

4 に答える 4

32

現在、Firefox でのみサポートされているデフォルトのパラメーター機能を使用しています。

function errorNotification(text) {
    text = text || "Something went wrong!";
    $.pnotify({
        title: 'Error',
        text: text,
        type: 'error'
    });
}
于 2013-10-31T05:48:55.950 に答える
6

Javascript では、そのようなデフォルトの引数を渡すことはできません。デフォルトを内部的に関数に割り当てる必要があります。

function errorNotification(text) {
  text || (text = "Something went wrong!");
  $.pnotify({
      title: 'Error',
      text: text,
      type: 'error'
  });
}
于 2013-10-31T05:49:46.983 に答える
1

注:デフォルトにしたいブール値がある場合、他の回答は機能しませんtrue。これanything||trueは、常に が返されるためtrueです。代わりに、次のようにする必要があります。

function foo(bar){
  if(bar === undefined)
    bar = true;
  //rest of your function
}
于 2015-05-08T17:34:49.630 に答える
0

function [a-zA-Z0-9_]*?\s{0,}\([^=$)]*?(=)[^)$]*?\)デフォルトのパラメーターを持つ js 関数を見つけて修正すると役立つ場合があります。

于 2015-03-12T08:09:56.170 に答える