1. Object.hasOwnProperty()的使用
hasOwnProperty()方法會回傳一個布林值,指示物件自身屬性 (忽略原型鏈) 中是否具有指定的屬性- 語法:
obj.hasOwnProperty(prop) - 引數
prop: 要檢測的屬性的String字串形式表示的名稱,或者Symbol - 回傳值: 用來判斷某個物件是否含有指定的屬性的布林值
Boolean
**注意**:即使屬性的值是 null 或 undefined,只要屬性存在,hasOwnProperty 依舊會回傳 true,
let o = new Object();
o.propOne = null;
o.hasOwnProperty('propOne'); // 回傳 true
o.propTwo = undefined;
o.hasOwnProperty('propTwo'); // 回傳 true
示例
使用 hasOwnProperty 方法判斷屬性是否存在
// 判斷 o 物件中是否存在 prop 屬性
o = new Object();
o.hasOwnProperty('prop'); // 回傳 false
o.prop = 'exists';
o.hasOwnProperty('prop'); // 回傳 true
delete o.prop;
o.hasOwnProperty('prop'); // 回傳 false
hasOwnProperty 方法對待自身屬性和繼承屬性的區別:
o = new Object();
o.prop = 'exists';
o.hasOwnProperty('prop'); // 回傳 true
o.hasOwnProperty('toString'); // 回傳 false
o.hasOwnProperty('hasOwnProperty'); // 回傳 false
/*
給一個陣列numberArr
撰寫代碼: 計算numberArr中相同數字的次數, 并把相容陣列去掉 (使得剩下的數字都唯一)
然后按照次數的大小列印出剩下的所有數字以及數字的相同次數 (一次列印一個數字和其次數)
例如:
12345679 10 (數字 數字相同次數)
*/
let numberArr = [
1,1,1,
2,2,2,2,2,2,2,2,2,2,
10,10,10,10,10,10,
1,1,1,1,1,1,1,1,
5,5,5,5,5,5,5,
0,0,0,0,0,0,0,0,
6,6,6,6,6,6,6,6,6,
0,0,
8,8,8,8,8,8,8,8,8,8,
4,4,4,4,4,4,4,4,
3,3,3,3,3,3
];
let newObj = {}
// forEach 遍歷陣列中每一位數值
numberArr.forEach(item=>{
// 使用 hasOwnProperty 判斷 newObj 物件中是否有 item 這個屬性
if(newObj.hasOwnProperty(item)){
// 如果有, 讓 item 屬性的 value 自增一
newObj[item]++
// console.log(newObj[item])
}else{
// 如果沒有, 讓 item屬性的 value = https://www.cnblogs.com/long-mao-bu-re/archive/2021/09/07/1, 下次回圈時就會走 true 部分, 將item對應的屬性自增一
newObj[item] = 1
}
})
console.log(newObj)
2.Object.keys()的使用
Object.keys()方法會回傳一個由一個給定物件的自身可列舉屬性組成的陣列,陣列中屬性名的排列順序和正常回圈遍歷該物件時回傳的順序一致- 語法:
Object.keys(obj) - 引數
obj: 要列舉的物件 - 回傳值: 一個表示給定物件的所有可列舉屬性的字串陣列,
// 簡單的陣列
var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// 類似陣列的物件
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// 類似陣列的物件, 但key是隨機的
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']
// getFoo 為非列舉的屬性
var myObj = Object.create({}, {
getFoo: {
value: function () { return this.foo; }
}
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']
/*
給出兩個物件 a,b
撰寫代碼: 比較兩個物件中的主鍵, 若b中的主鍵與a中的主鍵相同, 則把a中的相同主鍵洗掉
*/
let a = {
"0x91232312":"a",
"0x98232312":"b",
"0x912323212":"c",
"0x915232312":"d",
"0x912262312":"e"
}
let b= {
"0x1":"xxxx",
"0x912323212":"xxsaasdfxx",
"0x2":"xxxx",
"0x3":"xxxx",
"0x912262312":"xzcv"
}
Object.keys(b).forEach(item=>{
if(a.hasOwnProperty(item)){
delete a[item]
}
})
console.log(a)
```
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/298277.html
標籤:其他
上一篇:H5、C3基礎知識筆記
下一篇:前端SEO技巧
