You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何更简洁地从固定长度对象数组中为变量赋值?

更简洁优雅的赋值方式

你可以用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:09:22