tag不存在或已被下架!
測試範例:
const cat = {
name : "Toby",
color:"虎斑",
age:2
}
將object轉換為帶有key與value的數組:
Object.prototype.ownEntries = function(obj) {
const result = [];
for(let key in obj) {
obj.hasOwnProperty(key) && result.push([key,obj[key]])
}
return result;
}
console.log(Object.ownEntries(cat));
// [["name", "Toby"],["color", "虎斑"],["age", 2]]
與entries相反,把帶有key與value的數組轉換為object:
Object.prototype.ownEntries = function(arr) {
const result = {};
for(let i = 0; i < arr.length; i++) {
result[arr[i][0]] = arr[i][1]
}
}
console.log(Object.fromEntries([["name", "Toby"],["color", "虎斑"],["age", 2]]))
//
{
name : "Toby",
color:"虎斑",
age:2
}
Object.prototype.ownKeys = function(obj) {
const result = [];
for(let key in obj) {
obj.hasOwnProperty(key) && result.push(key)
}
return result;
}
console.log(Object.ownKeys(cat)); // ["name", "color", "age"]
Object.prototype.ownValues = function(obj) {
const result = [];
for(let key in obj) {
obj.hasOwnProperty(key) && result.push(obj[key])
}
return result;
}
console.log(Object.ownValues(cat)); // ["Toby", "虎斑", 2]