我有一个函数,它迭代一些对象,然后我想使用正在迭代的对象的变量名。目前,我维护了一个重复的名称列表,并通过数组索引来引用它们。这似乎是不必要的。整个东西都在一个围栏里。
原则上,我可以看到两种方法。
一种是使用名称列表,并以某种方式引用这样命名的变量,另一种是通过变量本身(保存在一个数组中)来确定变量名称。
这是可能的吗,或者我应该考虑一种完全不同的方法?
(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 }
}())发布于 2012-08-10 08:48:26
虽然对我来说并不完美(因为仍然有少量的重复),但我认为这可能是最干净的解决方案。
(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-10 05:57:59
你真的需要三个变量吗?我建议使用单个对象,它的键将充当当前变量名的角色:
(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-10 05:21:51
如果你可以自由的使用这些对象,你可以尝试这样做
(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 }
}())https://stackoverflow.com/questions/11891911
复制相似问题