2012-08-09 202 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/