1

いくつかのオブジェクトを反復する関数があり、反復されるオブジェクトの変数名を使用したいと考えています。現在、名前の重複リストを維持しており、配列インデックスでそれらを参照しています。これは不必要に思えます。全体がエンクロージャーに入っています。

原則として、それを行うには2つの方法があります。

1 つは名前のリストを使用して、そのような名前の変数を何らかの方法で参照することです。もう 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 }

}())
4

3 に答える 3

2

本当に3つの変数が必要ですか? 代わりに単一のオブジェクトを使用することをお勧めします。そのキーは現在の変数名の役割を果たします。

(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/

于 2012-08-09T21:57:59.003 に答える
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 }
}())
于 2012-08-09T21:21:51.197 に答える
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 }

}());
于 2012-08-10T00:48:26.313 に答える