考虑以下示例代码,其中需要遍历一个具有可空属性的对象,并根据用户输入设置这些属性:
const user = {
name: 'John',
age: 30,
email: null, //可空属性
address: {
street: '123 Main St',
city: 'New York',
state: 'NY',
zip: null //可空属性
}
}
function setNullableProperties(obj) {
for (const prop in obj) {
if (obj[prop] === null) {
const newValue = prompt(`Enter new value for ${prop}`);
obj[prop] = newValue;
} else if (typeof obj[prop] === 'object') {
setNullableProperties(obj[prop]);
}
}
}
setNullableProperties(user);
console.log(user);
该示例代码定义了一个名为user的对象,它有两个可空属性:email和address.zip。接下来我们创建了一个名为setNullableProperties的函数,它采用对象作为参数,并使用for-in循环来遍历对象的属性。如果属性的值是null,则使用prompt函数提示用户输入值,并将新值分配给该属性。如果属性的值是另一个对象,则递归调用setNullableProperties函数来继续遍历该对象的属性。
最后,我们将user对象传递给setNullableProperties函数,并在控制台中打印该对象,以查看输入的新值是否在相应的属性中更改。
这是一种简单而有效的方法来遍历具有可空属性的对象,并从用户输入中设置这些属性的值。