Assign default value when destructing arrays

0

I would like to know how to put a default value for the constant b , I have to do an exercise 'deconstructing' arrays, but b is already assigned as constant and I do not know how to make it worth 2 without touching this line of code. I tried let [,b] = [a,b,c] but obviously it does not go and I do not know how it is.

You must pass this testing with Jasmine:

describe('destructuring can also have default values. ', () => {
  it('for a missing value', () => {
    const [a,b,c] = [1,,3];
    expect(b).toEqual(2);
  });
});

// load jasmine htmlReporter
(function() {
  var env = jasmine.getEnv();
  env.addReporter(new jasmine.HtmlReporter());
  env.execute();
}());
<link rel="stylesheet" href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" />
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
    
asked by Francisco Manrique de lara 18.06.2018 в 14:57
source

1 answer

0

Can not be touched without touching the line where the assignment is touched: The only way to define default values to the variables or parameters is when they are declared.

//Si no se pasa un valor, b valdrá 2
function porDefecto([a,b = 2,c]) {
  console.log(a,b,c);
}

let miArray = [1,,3];

porDefecto(miArray);


//Si no se pasa un valor, b valdrá 5
const [a = 0,b = 5, c= 2]=miArray;
console.log(a,b,c);

Outside the statement, it is already considered a normal assignment:

let miArray = [1,,3];


//No pueden ser constantes o b no podría ser reasignada a 2
let [a, b, c]=miArray;
b = b || 2;
console.log(a,b,c);
    
answered by 18.06.2018 в 16:34