behappy

      JS对象遍历通常使用for/in循环来实现,for/in循环能在循环体中遍历对象中的所有可枚举的属性,并把属性名称赋值给循环变量。如果想进一步区分自由属性和方法,要进行进一步的限制,如

    

for(p in o) {
    if (o.hasOwnPeoperty(p)) continue;     // 跳过继承的属性
}

for(p in o) {
    if (typeof o[p] ==="function") continue;   // 跳过方法
} 

下面是一些用for/in来操纵对象属性的工具

/*
 * 将p中的可枚举属性复制到o中
 * 如果o和p中有同名的属性,则覆盖o中同名属性
 */
function extend(o, p) {
    for(prop in p) {                        
        o[prop] = p[prop];                   
    }
    return o
}

/*
 * 将p中的属性复制到o中,并返回o
 * 如果o和p中有同名属性,则o中属性不变
 */
function merge(o, p) {
    for(prop in p) {                           
        if (o.hasOwnProperty[prop]) continue;  
        o[prop] = p[prop];                     
    }
    return o;
}
/*
 * 如果o中的属性在p中没有同名属性,则删除o中的这个属性
 * 返回o
 */
function restrict(o, p) {
    for(prop in o) {                       
        if (!(prop in p)) delete o[prop];  
    }
    return o;

  

/*
 * 如果o中有p的同名属性,则删除之
 * 返回o
 */

function subtract(o, p) {
    for(prop in p) {                        
        delete o[prop];                      
                                            
    }
    return o;
}

  

1 /*
2  * 合并o和p对象,如果有同名,使用p中的属性
3  * 返回o
4  */
5 
6 function union(o,p) { return extend(extend({},o), p); }
View Code
 1 /*
 2  * 返回一个数组,数组中包含o中自有的属性列表
 3  */
 4 
 5 function keys(o) {
 6     if (typeof o !== "object") throw TypeError(); 
 7     var result = [];                
 8     for(var prop in o) {             
 9         if (o.hasOwnProperty(prop)) 
10             result.push(prop);       .
11     }
12     return result;                  
13 }

 

分类:

技术点:

相关文章: