JavaScript 给一个对象添加属性的方法

当我们在遍历的时候,想要给一个对象根据遍历的不同的 key 添加属性时,可以这样做:

  meshes = ["m0", "m1", "m2"];
  const geometry = {};
  for(let i = 0; i < meshes.length; i += 1) {
        // 这样就可以给 geometry 添加三个键分别为 m0, m1, m2 的键值对。
        // 这里不能使用 .key 的方法。
        geometry[key] = { normal: [], position: [] }; 
  }

geometry[key] 和 geometry.key 两种方法的不同之处:

const test = () => {
  const meshes1 = {};
  const meshes2 = {};
  const key = 'box';
  meshes1[key] = { normal: 0, position: 0 }; 
  console.log(meshes1); // { box: { normal: 0, position: 0 } }
  meshes2.key = { normal: 0, position: 0 }; 
  console.log(meshes2); // { key: { normal: 0, position: 0 } }
};

test();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。