用ES6中数组的解构赋值来获取当前的时间,后附数组解构的详解

2022-07-21 12:08:51

什么是解构赋值?
ES6允许按照一定的模式从数组或者对象中提取值,然后对变量进行赋值,这被称为解构赋值。
举例说明下,以前变量只有一个一个的赋值,

var a = "番茄", b = "西红柿", c = "鸡蛋";

现在ES6可以这样写

let [a,b,c] = ["番茄","西红柿","鸡蛋"];

按照对应位置为变量赋值。这样的话,为多个变量赋值就会很方便,哈哈,第一个想到的例子就是时间戳,之前的时间戳,相信大家都写过,随便拎一个过来,如下:

function currentTime() {
	var parseDate = function (val) {				//为10以下的数字前面加个0
		val = val < 10 ? '0' + val : val;
		return val
	}
	var value = new Date();
	var year = value.getFullYear();
	var month = parseDate(value.getMonth() + 1);
	var day = parseDate(value.getDate());
	var hour = parseDate(value.getHours());
	var minutes = parseDate(value.getMinutes());
	var seconds = parseDate(value.getSeconds());
	return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds;
}
console.log(currentTime())				//2019-04-10 20:45:10

用解构赋值的话就方便多了,如下:

function currentTime() {
	let T = new Date();
	let [y, M, d, h, m, s] = [T.getFullYear(), T.getMonth() + 1, T.getDate(), T.getHours(), T.getMinutes(), T.getSeconds()];
	[y, M, d, h, m, s] = [y, M, d, h, m, s].map(n => n = n < 10 ? '0' + n : n);				//ES6箭头函数,为小于10的数字前面加0
	return y + '-' + M + '-' + d + ' ' + h + ':' + m + ':' + s;
}

console.log(currentTime())				//2019-04-10 20:57:31

娃哈哈,有没有感觉很方便???

除了可以按照对应位置赋值,还可以嵌套数组进行解构赋值,几维数组都可以,例如:

let [a, [b, [c]]] = ["番茄", ["西红柿", ["鸡蛋"]]];
console.log(a)				//番茄
console.log(b)				//西红柿
console.log(c)				//鸡蛋

哈哈,是不是很厉害,可以做各种骚操作。

当等号两边的东西不匹配的时候呢?不要怕,并不会报错。两种情况,一种是左边有,右边对应位置无,无对应的赋值为undefined,例如:

let [a,b] = ["番茄"];
console.log(a)				//番茄
console.log(b)				//undefined

另一种是右边有,左边对应位置无,这种是不完全解构,但可以赋值成功,例如:

let [a,b] = ["番茄","西红柿","鸡蛋"];
console.log(a)				//番茄
console.log(b)				//西红柿

另外,解构赋值还允许指定默认值,例如:

let [a = "番茄"] = [];
console.log(a)				//番茄

let [a,b = "西红柿"] = ["番茄"];
console.log(a)				//番茄
console.log(b)				//西红柿

let [a = "番茄"] = [undefined];
console.log(a)				//undefined

let [a = "番茄"] = [null];
console.log(a)				//null

数组的解构赋值就举这么多例子了,如果你还有其他的想法不妨自己去撸一下代码试试。
ES6中变量的解构赋值有很多,数组,对象,字符串,数字等都可以,对象的解构赋值用到的也蛮多的,有兴趣的可以去了解一下。

  • 作者:半斤番茄➕八两西红柿
  • 原文链接:https://blog.csdn.net/dreamora/article/details/89195716
    更新时间:2022-07-21 12:08:51