Square brackets surrounding parameter in function definition

寵の児 提交于 2019-12-19 01:15:05

问题


I came across the following code in the Ember CLI website:

export default Ember.Helper.helper(function([value]) {
  return value.toUpperCase();
});

What confuses me is the square brackets surrounding the value parameter. I can understand it in a function call, but why in function definition?


回答1:


This is all very surprising to me, but it appears to be valid javascript, according to the ECMAScript 2017 language specification, the formal parameter in a function declaration can any "binding element", including an array binding.

https://tc39.github.io/ecma262/#prod-BindingElement

The actual behavior of this feature seems to mean that the argument to the function should be an array, and value will take on the value of the first element in the array.




回答2:


This is a destructuring assignment. The behavior described by @recursive is correct, but it may help to know that it is not limited to the first element. If it had been written with three elements:

function xyz([a, b, c]){...}

Then a, b, and c will all be declared variables available within the function scope, and in this case, would be equal to the first three elements of the array. Further - if the array passed as an argument doesn't have at least three elements, then the remaining elements specified in the parameter (a, b, and c) will exist as being declared, but will have the value of undefined:

// Example
function destructureThis([a, b, c]){
  console.log(a, b, c);
}

var shortArray = [1, 25];
destructureThis(shortArray);

// Prints to console:
// 1 25 undefined

Likewise, if the argument array is larger, additional elements are just ignored, as already noted.

var longerArray = [1, 5, 9, 50, 60];
destructureThis(longerArray);

// Prints to console:
// 1 5 9

Also... this is a recent enough addition to the ECMAScript spec that it should be tested in all your target environments (looking at you IE) if not using Babel or equivalent to transpile it for backwards compatibility.




回答3:


This also works in reverse such that a non-array can be "converted" into an array, as follows:

var a, b;

a = {first:"Orion", middle:"Miki", last:"Kenyon"}
b = objToUpperCase([a]); // a is a single object, but is passed as an array

console.log(a);
console.log(b[0]);

function objToUpperCase(inputs) {
  var outputs = [];
  for (var i = 0; i <= inputs.length - 1; i++) {
    var input = inputs[i];
    output = {
        first: input.first.toUpperCase(),
        middle: input.middle.toUpperCase(),
        last: input.last.toUpperCase()
        };
    outputs.push(output);
  }
  return outputs;
}

Output:

Object {first: "Orion", last: "Kenyon", middle: "Miki"}
Object {first: "ORION", last: "KENYON", middle: "MIKI"}


来源:https://stackoverflow.com/questions/37691490/square-brackets-surrounding-parameter-in-function-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!