以下是一个示例代码,演示了如何按照输入的属性数组进行forEach循环和更改:
// 输入的属性数组
var properties = ['name', 'age', 'gender'];
// 输入的对象
var person = {
name: 'John',
age: 25,
gender: 'male'
};
// 使用forEach循环和更改属性
properties.forEach(function(property) {
// 检查属性是否存在于对象中
if (person.hasOwnProperty(property)) {
// 对属性进行更改
person[property] = 'new ' + person[property];
}
});
// 输出结果
console.log(person);
/* 输出:
{
name: 'new John',
age: 'new 25',
gender: 'new male'
}
*/
在这个示例中,我们首先定义了一个属性数组 properties
,包含要遍历和更改的属性。然后,我们定义了一个对象 person
,它包含了要更改的属性。
接下来,我们使用 forEach
方法对属性数组进行循环遍历。对于每个属性,我们通过调用 hasOwnProperty
方法检查它是否存在于对象中。如果属性存在,我们将其值更改为 'new ' + person[property]
。
最后,我们输出了更改后的对象,以验证结果。