用来枚举属性的对象工具函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>對象的枚舉屬性</title>
</head>
<body>
<script>
// 用來枚舉屬性的對象工具函數
/*把p中的可枚舉屬性復制到o中,并返回o,
如果p和o中含有同名屬性,則覆蓋o中的屬性,
這個函數并不處理getter和setter以及復制屬性。*/
function extend(o,p){
for(prop in p){//遍歷p中的所有屬性
o[prop] = p[prop];//將屬性添加到o中
}
return o;
}
var o = {
name:'anan',
age:'22',
sex:'girl',
}
var p = {
name:'xiaoke',
age:'0',
love:'sing',
father:'yy'
}
/*var extenddata = extend(o,p);
console.log(extenddata);*/
// Object {name: "xiaoke", age: "0", sex: "girl", love: "sing", father: "yy"}
/*把p中的可枚舉屬性復制到o中,并返回o,
如果p和o中含有同名屬性,o中的屬性不受影響,
這個函數并不處理getter和setter以及復制屬性。*/
function merge(o,p){
for(prop in p){
if(o.hasOwnProperty(prop)) continue;//o.hasOwnProperty[prop]過濾掉已經在o中存在的屬性
o[prop] = p[prop];
}
return o;
}
/*var mergedata = merge(o,p);
console.log(mergedata);*/
// Object {name: "anan", age: "0", sex: "girl", love: "sing", father: "yy"}
// 如果o中的屬性在p中沒有同名屬性,則從o中刪除這個屬性。返回o
function restrict(o,p){
for(prop in o){
if(!(prop in p)) delete o[prop];//如果p中不存在,則刪除
}
return o;
}
/*var restrictdata = restrict(o,p);
console.log(restrictdata);*/
// Object {name: "anan", age: "22"}
// 如果o中的屬性在p中存在同名屬性,則從o中刪除這個屬性,返回o
function subtract(o,p){
for(prop in p){
delete o[prop];
}
return o;
}
/*var subtractdata = subtract(o,p);
console.log(subtractdata);*/
// Object {sex: "girl"}
// 返回一個新對象,這個對象同時擁有o的屬性和p的屬性
// 如果o和p中有重名屬性,使用p中的屬性值
function union(o,p){
return extend(extend({},p),o)
}
// console.log(union(o,p));
// 返回一個新對象,這個對象擁有同時在o和p的屬性,很像求o和p的交集,但p中屬性的值被忽略
function intersection(o,p){
return restrict(extend({},o),p);
}
// console.log(intersection(o,p));
// 返回一個數組,這個數組包含的是o中可枚舉的自有屬性的名字
function keys(o){
if(typeof o !== 'object') throw TypeError();//參數必須是對象
var result = [];//將要返回的數組
for (var prop in o){//遍歷所有可枚舉的屬性
if(o.hasOwnProperty(prop))//判斷是否是自有屬性
{
result.push(prop)//將屬性名添加到數組中
}
}
return result;//返回這個數組
}
console.log(keys(o))
</script>
</body>
</html>
轉載于:https://www.cnblogs.com/studyh5/p/9232868.html
總結
以上是生活随笔為你收集整理的用来枚举属性的对象工具函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android studio——替换全局
- 下一篇: Java基础知识回顾之七 ----- 总