对象传播的顺序和其他属性起什么作用?
Which role does the order of object spread and other properties play?
考虑一个对象 data
。
data = {
draggingTaskId: '',
entities: {},
selectedTaskIds: [],
}
我在两个不同的顺序中使用解构赋值,但两次的行为都不同。对象解构赋值中的顺序重要吗?
console.log('----------------------------------');
console.log({
...data,
draggingTaskId: "task-0",
});
console.log({
draggingTaskId: "task-0",
...data,
});
console.log('----------------------------------');
输出:
--------------------------------
draggingTaskId: "task-0"
entities: {}
selectedTaskIds: []
draggingTaskId: ""
entities: {}
selectedTaskIds: []
-----------------------------------
在第二个实例中,draggingTaskId
显示为空字符串。
顺序确实是相关的 - 如果它们具有相同的键,则较晚出现的项目会覆盖较早出现的项目。
console.log({
...data,
draggingTaskId: 'task-0', // this overrides the value of data.draggingTaskId = '', resulting in 'task-0'
})
console.log({
draggingTaskId: 'task-0', // In this case this key is overridden by the value of data.draggingTaskId = '', resulting in ''
...data,
})
您可能会发现这很有帮助 - https://dmitripavlutin.com/object-rest-spread-properties-javascript/#21-object-spread-rule-latter-property-wins
考虑一个对象 data
。
data = {
draggingTaskId: '',
entities: {},
selectedTaskIds: [],
}
我在两个不同的顺序中使用解构赋值,但两次的行为都不同。对象解构赋值中的顺序重要吗?
console.log('----------------------------------');
console.log({
...data,
draggingTaskId: "task-0",
});
console.log({
draggingTaskId: "task-0",
...data,
});
console.log('----------------------------------');
输出:
--------------------------------
draggingTaskId: "task-0"
entities: {}
selectedTaskIds: []
draggingTaskId: ""
entities: {}
selectedTaskIds: []
-----------------------------------
在第二个实例中,draggingTaskId
显示为空字符串。
顺序确实是相关的 - 如果它们具有相同的键,则较晚出现的项目会覆盖较早出现的项目。
console.log({
...data,
draggingTaskId: 'task-0', // this overrides the value of data.draggingTaskId = '', resulting in 'task-0'
})
console.log({
draggingTaskId: 'task-0', // In this case this key is overridden by the value of data.draggingTaskId = '', resulting in ''
...data,
})
您可能会发现这很有帮助 - https://dmitripavlutin.com/object-rest-spread-properties-javascript/#21-object-spread-rule-latter-property-wins