我在 ES5 代码中有一个 var,如下所示。
var options = {
clientId : clientId
keepAlive : keepAlive,
clean : clean,
reconnectPeriod : reconnectPeriod,
will : lastWillMessage
};
我可以通过说
将其更改为 ES6let options = {clientId,keepAlive,reconnectPeriod,lastWillMessage};
但是如果我不想为所有属性传递值,我该怎么做呢?例如,我只想传递 clientId 和 keepAlive。 Rest 将具有 MQTT 模块设置的默认值。那么我怎样才能只为这个对象的某些属性设置值呢?
最佳答案
我不确定这是否能回答您的问题,但 Object.assign 可能会有所帮助:
var options = getOptionsFromMQTT();
Object.assign(options, {options, {clientID, keepAlive});
// options now uses whatever values are assigned to clientID and keepAlive
更多来自 MDN:
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
关于javascript - 从变量创建对象 ES6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37200744/