// ES5
var parts = '2010-11-11'.split('-'),
year = parts[0],
month = parts[1],
day = parts[2];
// ES6
var [year, month, day] = '2010-10-11'.split('-');
console.log(year); // 2010
console.log(month); // 10
console.log(day); // 11
// Only take the month and day
var [, month, day] = '2010-10-11'.split('-');
console.log(month); // 10
console.log(day); // 11
// Only take the year and day
var [year, , day] = '2010-10-11'.split('-');
console.log(year); // 2010
console.log(day); // 11
// Set default values
// Assume that date is going to be optional and if it is not found, we would like to use `1` then
var [year, month, date=1] = '2010-10'.split('-');
console.log(year); // 2010
console.log(month); // 10
console.log(date); // 1
var [year, month, date=1] = '2010-10-11'.split('-');
console.log(year); // 2010
console.log(month); // 10
console.log(date); // 11
// With object
var person = { name: 'John Doe', age: 23, gender: 'male' };
var {name, age, gender} = person;
console.log(name); // John Doe
console.log(age); // 23
console.log(gender); // male
// Aliasing
var person = { name: 'John Doe', age: 23, gender: 'male' };
var {name:tag, age, gender:sex} = person;
console.log(tag); // John Doe
console.log(age); // 23
console.log(sex); // male
// Set default values on object
var person = { name: 'John Doe', age: 23};
var {name, age, gender = 'male'} = person;
console.log(name); // John Doe
console.log(age); // 23
console.log(gender); // male
// Alias and default value at the same time
var person = { name: 'John Doe', age: 23};
var {name, age, gender:sex = 'male'} = person;
console.log(name); // John Doe
console.log(age); // 23
console.log(sex); // male
// Example
// Returning object/multiple values from a function call
function getLocation() {
return {
latitude: 23.4125,
longitude: 45.128
};
}
var {latitude:lat, longitude:long} = getLocation();
console.log(lat); //23.4125
console.log(long); //45.128
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.