Définir une valeur de paramètre par défaut pour une fonction JavaScript

Mots clés : javascriptfunctionparametersargumentsdefault-parametersjavascript

meilleur 5 Réponses Définir une valeur de paramètre par défaut pour une fonction JavaScript

vote vote

99

function read_file(file, delete_after = false) {   // Code } 
// the `= {}` below lets you call the function without any parameters function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)     // Use the variables `start`, `end` and `step` here     ··· } 
function foo(a, b) {   a = typeof a !== 'undefined' ? a : 42;   b = typeof b !== 'undefined' ? b : 'default_b';   ... } 
vote vote

82

function read_file(file, delete_after) {     delete_after = delete_after || "my default here";     //rest of code } 
function read_file(values) {     values = merge({          delete_after : "my default here"     }, values || {});      // rest of code }  // simple implementation based on $.extend() from jQuery function merge() {     var obj, name, copy,         target = arguments[0] || {},         i = 1,         length = arguments.length;      for (; i < length; i++) {         if ((obj = arguments[i]) != null) {             for (name in obj) {                 copy = obj[name];                  if (target === copy) {                     continue;                 }                 else if (copy !== undefined) {                     target[name] = copy;                 }             }         }     }      return target; }; 
// will use the default delete_after value read_file({ file: "my file" });   // will override default delete_after value read_file({ file: "my file", delete_after: "my value" });  
vote vote

78

function pick(arg, def) {    return (typeof arg == 'undefined' ? def : arg); }  function myFunc(x) {   x = pick(x, 'my default'); }  
vote vote

68

function read_file(file, delete_after = false) {   // Code } 
vote vote

55

function foo(x,y) {  x = x || 11;  y = y || 31;  console.log( x + y ); } foo(); // 42 foo( 5, 6 ); // 11 foo( 5 ); // 36 foo( null, 6 ); // 17 
foo(0, 42) foo( 0, 42 ); // 53 <-- Oops, not 42 
function foo(x,y) {  x = (x !== undefined) ? x : 11;  y = (y !== undefined) ? y : 31;  console.log( x + y ); } foo( 0, 42 ); // 42 foo( undefined, 6 ); // 17 
function foo(x = 11, y = 31) {  console.log( x + y ); }  foo(); // 42 foo( 5, 6 ); // 11 foo( 0, 42 ); // 42 foo( 5 ); // 36 foo( 5, undefined ); // 36 <-- `undefined` is missing foo( 5, null ); // 5 <-- null coerces to `0` foo( undefined, 6 ); // 17 <-- `undefined` is missing foo( null, 6 ); // 6 <-- null coerces to `0` 
function bar(val) {  console.log( "bar called!" );  return y + val; } function foo(x = y + 3, z = bar( x )) {  console.log( x, z ); } var y = 5; foo(); // "bar called"  // 8 13 foo( 10 ); // "bar called"  // 10 15 y = 6; foo( undefined, 10 ); // 9 10 
function foo( x =  (function(v){ return v + 11; })( 31 ) ) {  console.log( x ); } foo(); // 42 

Questions similaires