Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

javascript - Square brackets surrounding parameter in function definition

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...