iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 29
0
自我挑戰組

利用30分鐘~想一個前端問題系列 第 29

利用30分鐘~想一個前端問題 Day29-matches

matches

Compares two objects to determine if the first one contains equivalent property values to the second one.

Use Object.keys(source) to get all the keys of the second object, then Array.prototype.every(), Object.hasOwnProperty() and strict comparison to determine if all keys exist in the first object and have the same values.

判斷兩個物件的第一個屬性是否相同,回應布林值

1.使用 Object.keys(source) 獲得第二個物件的key
2.使用 Array.prototype.every() 和 Object.hasOwnProperty() 比對物件裡面的第一個屬性裡面是否有相同的值

const matches = (obj, source) =>
  Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);
//EXAMPLES
matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true
matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false

Array.prototype.every()

陣列裡面的所有東西都符合條件才會回傳 true,只要有一個不是就會回傳 false。

const result = students.every(x => x.age >= 18);
// 執行結果:result 為 false

Object.hasOwnProperty()

hasOwnProperty()方法用來判斷某個物件是否含有指定的自身屬性,
obj.hasOwnProperty(“屬性名”);
會返回一個布林值,指示對象自身屬性中是否具有指定的屬性(也就是,是否有指定的鍵)。

//object1是不是Object2的原型,也就是說Object2是Object1的原型,,是則返回true,否則false
object1.isPrototypeOf(Object2);

參考資料

Object.prototype.hasOwnProperty()


上一篇
利用30分鐘~想一個前端問題 Day28-chainAsync
下一篇
利用30分鐘~想一個前端問題 Day30-deepClone
系列文
利用30分鐘~想一個前端問題30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言