2012-08-09 201 views
1

我有一个函数,它遍历一些对象,然后我想使用被迭代的对象的变量名。目前我维护一个重复的名称列表,并通过数组索引引用它们。这似乎没有必要。整个事情都在一个圈地里。由另一个变量引用变量名,或从变量确定变量名

原则上,我可以看到两种方式来做到这一点。

一个是使用名称列表,并以某种方式引用名为这样的变量,另一个是以某种方式从变量本身(保存在数组中)确定变量名称。

这是可能的,还是我应该看一个完全不同的方法?

(function(){ 

    var a = {p:true,b:true}; 
    var b = {em:true,i:true}; 
    var c = {h1:true,strong:true}; 

    var x = function(tagName){ 

    var typedefnames = ["a","b","c"] 
    var typedefs = [a,b,c]; 

    var types = {} 
    var i; 

    for(i=0; i<typedefs.length; i++) 
     if(typedefs[i][ tagName ]) 
     types[ typedefnames[i] ] = true 
     else 
     types[ typedefnames[i] ] = false 

    return types; 

    } 

    console.log(x("p")) 
    // { a:true, b:false, c:false } 

}()) 

回答

0

虽然不完美,我(因为有重复少量仍然)我认为这可能是最干净的解决方案。

(function(){ 

    // leave these as they are as they can be used from many other parts of the code 
    var a = {p:true,b:true}; 
    var b = {em:true,i:true}; 
    var c = {h1:true,strong:true}; 

    var x = function(tagName){ 
     // define a single object with key/value pairs that can both be accessed 
     var typedefs = {a:a,b:b,c:c} 
     var types = {}; 
     // iterate the type definitions, setting the value based on lookup of originals 
     for(var key in typedefs) 
      types[key] = !!typedefs[key][tagName]; 
     // good to go! 
     return types; 
    } 

    console.log(x("p")); 
    // { a:true, b:false, c:false } 

}()); 
1

如果你有在对象的自由,你可以试试这个

(function(){ 
    var a = {name: 'a', tags: {p: true, b: true}}; 
    var b = {name: 'b', tags: {em: true, i: true}}; 
    var c = {name: 'c', tags: {h1: true, strong: true}}; 

    var x = function(tagName){ 
    var typedefs = [a, b, c]; 

    var types = {}; 

    for(var i=0; i<typedefs.length; i++) { 
     if(typedefs[i].tags[tagName]) { 
     types[typedefs[i].name] = true; 
     } 
     else { 
     types[typedefs[i].name] = false; 
     } 
     //alternative way for setting true/false based on truthy value 
     //types[typedefs[i].name] = !!typedefs[i].tags[tagName]; 
    } 

    return types; 
    } 

    console.log(x("p")) 
    // { a:true, b:false, c:false } 
}()) 
2

你真的需要三个变量?我建议使用一个单一的对象,而不是和它的键会做你目前的变量名的作用:

(function(){ 
    var obj = { 
     a : {p:true,b:true}, 
     b : {em:true,i:true}, 
     c : {h1:true,strong:true} 
    }; 

    var x = function(tagName){ 
     var types = {} 
     for(var key in obj) { 
      types[key] = obj[key].hasOwnProperty(tagName) && obj[key][tagName] === true; 
     } 
     return types; 
    } 
    console.log(x("p")); 
}()); 

http://jsfiddle.net/sKbPu/1/