使用嵌套函数循环遍历对象字面量

Looping through object literal with nested functions

我正在尝试遍历一个对象字面量,select 只是一个键,return 它是一个函数的值。我的问题是,我无法将循环设为 return 只有一个值 - 它总是 return 所有值(函数)。我注意到如果我将函数嵌套在对象字面量中(参见 foo),那么它会工作得更好,但仍然不会循环。

Here is the JS fiddle

var functions = {
   blah: blah(),
   foo: function() { console.log("foo"); }
};


for(var key in functions){
   if(functions[key] == 'foo') {
   console.log("hello"); //if functions contains the key 'foo' say hi
  }
}
function blah () {alert("blah")};

functions.foo();

您不是在检查密钥,而是在根据函数检查字符串。

for(var key in functions){
    if (key==="foo") {
        console.log("hello");
    }
}

另一种方法是使用 Object.keys()

var keys = Object.keys(functions);
if (keys.indexOf("foo")>-1) {
    console.log("hello");
}
in your condition if(functions[key] == 'foo')

the functions[key] returns a function. the key itself is already a literal that can be compare to 'foo'

var functions = {
   blah: blah(),
   foo: function() { console.log("foo"); }
};


for(var key in functions){
   if(key == 'foo') {
   console.log("hello"); //if functions contains the key 'foo' say hi
  }
}
function blah () {alert("blah")};

functions.foo();