[英]I don't quite get a javascript syntax about passing arguments
我的代码:
const users = [ { id: 1, name: 'user1' }, { id: 2, name: 'user2' } ]
p = new Promise( resolve => resolve(users) )
p.then( (user) => console.log(user) )
返回以下日志:
[{id:1,name:'user1'},{id:2,name:'user2'}]
如果我将其更改如下
users.then( ([user]) => console.log(user) )
我收到以下日志:
{id:1,名称:'user1'}
我不太明白为什么第二个元素只记录数组中的第一个元素。
这是一项破坏性的任务
[a, b, c] = [1, 2, 3] console.log(a) console.log(b) console.log(c)
但是如果只解构一个,就可以得到数组的第一个值
[a] = [1, 2, 3] console.log(a)
对于您的示例,可以在许多地方进行解构,例如函数参数
销毁是ES6或 ECMA2015的功能。
您可以解构Array
和Objects
。
Object
分解为波纹管,使您可以使用简单的语法从object
获取要获取的keys
。
const obj = { a: 'a', b: 'b', c: 'c', }; // Without object destructuring const a_ = obj.a; const b_ = obj.b; // With object destructuring const { a, b, } = obj; console.log(a);
Array
解构是完全相同的,但是使用数据index
而不是指定要获取的keys
。
const arr = [ 'a', 'b', 'c', ]; // Without array destructuring const a_ = arr[0]; const c_ = arr[2]; // With array destructuring const [ a, , c, ] = arr; console.log(c);
您可以在任何地方使用Array
和Object
分解; 包括在功能参数中。 在这种情况下特别好,因为您可以像下面这样轻松地为keys
指定default
值
function func({ a, b, c = 'default', }) { console.log(a, '/', b, '/', c); } func({ a: 'j\\'aime la france', b: 'vive les baguettes', });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.