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

你真的需要三个变量吗?我建议改用单个对象,它的键将扮演您当前变量名的角色:

(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 回答