自定义对象的属性名称/属性数据与副本
·
Yin灏
对象属性的名称或数据所构成的数组
通过内置函数Object.keys()
或Object.getOwnPropertyNames()
,均可获取内含自定义对象实例的各属性名称的数组实例。
通过内置函数Object.value()
可返回内含自定义对象实例的各属性数据的数组实例。
let profile_array = ['Peter', 'male', 27, 'IT', 3.5];
let key_list01 = Object.keys(profile_array);
console.log(key_list01); // ["0", "1", "2", "3", "4"]
let key_list02 = Object.getOwnPropertyNames(profile_array);
console.log(key_list02); // ["0", "1", "2", "3", "4", "length"]
let value_list = Object.values(profile_array);
console.log(value_list); // ["Peter", "male", 27, "IT", 3.5]
let profile_object = { name: 'Peter', gender: 'male', age: 27, department: 'IT', years_of_service: 3.5 };
key_list01 = Object.keys(profile_object);
console.log(key_list01); // ["name", "gender", "age", "department", "years_of_service"]
key_list02 = Object.getOwnPropertyNames(profile_object);
console.log(key_list02); // ["name", "gender", "age", "department", "years_of_service"]
value_list = Object.values(profile_object);
console.log(value_list); // ["Peter", "male", 27, "IT", 3.5]
let all_antries = Object.entries(profile_object);
console.log(all_antries); // [["name", "Peter"], ["gender", "male"], ["age", 27], ["department", "IT"], ["years_of_service", 3.5]]
精细创建特定对象实例的副本
精细创建特定自定义对象实例的副本,可以通过内置函数 Object.create()
来实现。
let person = {
name: 'Json',
age: 37,
married: true,
occupation: 'finance manager',
department: 'Frinance Team'
}
let new_one = Object.create(person, {
department: {
value: 'Frinance Team',
writable: false
}
})
console.log(new_one);
new_one.name = 'Alex';
console.log(new_one);
console.log(new_one.name); // Alex
console.log(new_one.department); // Frinance Team
console.log(new_one.age); // 37
console.log(new_one.__proto__.age); // 37
new_one.department = 'IT'; // 不可写
console.log(new_one.department); // Frinance Team
// Object.create() 的第一个参数会被放在原型链上
let my_love = Object.create({
name: 'Cindy',
occupation: 'angel'
}, {
age: {
value: 18,
writable: false, // 不可写入
enumerable: false, // 不可被迭代
configurable: false // 不可被删除、修改、设置
}
})
console.log(my_love);
console.log(my_love.age); // 18
my_love.age = 27; // 不可写
console.log(my_love.age); // 18
for(let property in my_love) {
console.log(property); // name occupation
}