在javascript中设置对象的默认值 [英] Set the default value for the object in javascript
问题描述
我有一个名为 addAlert
的函数,该函数接受两个参数。
此函数的第一个参数是一个字符串,此函数的第二个参数是一个对象。该对象具有三个属性 status
, position
和 align
我未设置此参数的任何属性时都想设置默认值。
addAlert(stringValue,valueObject){
//设置valueObject的默认值
}
您可以使用 Object.assign
创建具有默认值的对象:
const defaults = {a:1,b:2,c:3} const obj1 = { a:11} const obj2 = {a:11,c:33} const obj3 = {a:11,b:22,c:33} const newObj1 = Object.assign({},默认值,obj1); const newObj2 = Ø bject.assign({},默认值,obj2); const newObj3 = Object.assign({},默认值,obj3); console.log(newObj1); console.log(newObj2); console.log(newObj3);
或者,您也可以使用扩展语法:
const defaults = {a:1,b:2,c:3} const obj1 = {a:11} const obj2 = {a:11,c:33} const obj3 = {a:11,b:22,c:33} const newObj1 = {...默认值,... obj1}; const newObj2 = {...默认值,。 ..obj2}; const newObj3 = {...默认值,... obj3}; console.log(newObj1); console.log(newObj2); console.log(newObj3);
您可以使用以下任一设置默认值:
addAlert(stringValue,valueObject){
const defaults = {status: INFO,position: TOP:align: LEFT};
常量设置= Object.assign({},默认值为valueObj);
/ *使用代码中的设置* /
}
或
addAlert(stringValue,valueObject){
const defaults = {status: INFO,position: TOP:align : 剩下 };
常量设置= {...默认值,... valueObj};
/ *使用代码中的设置* /
}
I have a function called addAlert
and this function accepts two parameters.
The first parameter of this function is a string and the second parameter of this function is an object. The object has three properties status
, position
, and align
.
I want to set a default value when I did not set any of the properties of this parameter.
addAlert(stringValue,valueObject) {
//Set the default values for the valueObject
}
You can use Object.assign
to create an object with default values:
const defaults = {
a: 1,
b: 2,
c: 3
}
const obj1 = { a: 11 }
const obj2 = { a: 11, c: 33}
const obj3 = { a: 11, b: 22, c: 33 }
const newObj1 = Object.assign({}, defaults, obj1);
const newObj2 = Object.assign({}, defaults, obj2);
const newObj3 = Object.assign({}, defaults, obj3);
console.log(newObj1);
console.log(newObj2);
console.log(newObj3);
Alternatively, you can do the same using spread syntax:
const defaults = {
a: 1,
b: 2,
c: 3
}
const obj1 = { a: 11 }
const obj2 = { a: 11, c: 33}
const obj3 = { a: 11, b: 22, c: 33 }
const newObj1 = { ...defaults, ...obj1};
const newObj2 = { ...defaults, ...obj2};
const newObj3 = { ...defaults, ...obj3};
console.log(newObj1);
console.log(newObj2);
console.log(newObj3);
You can use either of these to set the default values:
addAlert(stringValue,valueObject) {
const defaults = { status: "INFO", position: "TOP": align: "LEFT" };
const settings = Object.assign({}, defaults, valueObj);
/* use settings in the code */
}
or
addAlert(stringValue,valueObject) {
const defaults = { status: "INFO", position: "TOP": align: "LEFT" };
const settings = { ...defaults, ...valueObj };
/* use settings in the code */
}
这篇关于在javascript中设置对象的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!