如何更简洁地从固定长度对象数组中为变量赋值?
更简洁优雅的赋值方式
你可以用ES6的解构赋值来实现,这是目前最简洁优雅的写法,有两种常用方式:
方式一:先映射属性再解构
先通过map把数组里每个对象的attributeValue提取出来,再解构赋值给A和B:const [A, B] = data.map(item => item.attributeValue);方式二:解构时直接提取属性
直接在解构数组的同时,提取对应索引对象的attributeValue属性,这种方式不需要遍历整个数组,性能更优:const [{ attributeValue: A }, { attributeValue: B }] = data;
如果你的A和B已经提前用let声明过,可以去掉const直接赋值:
[{ attributeValue: A }, { attributeValue: B }] = data;
用你的示例数据测试,两种方式都能得到预期结果:
A = 'Test A' B = 'Test B'
内容的提问来源于stack exchange,提问作者Tim Launders
相关产品推荐
相关产品推荐

