當(dāng)我們?cè)诒闅v的時(shí)候危彩,想要給一個(gè)對(duì)象根據(jù)遍歷的不同的 key 添加屬性時(shí)攒磨,可以這樣做:
meshes = ["m0", "m1", "m2"];
const geometry = {};
for(let i = 0; i < meshes.length; i += 1) {
// 這樣就可以給 geometry 添加三個(gè)鍵分別為 m0, m1汤徽, m2 的鍵值對(duì)娩缰。
// 這里不能使用 .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();