简体   繁体   English

使用嵌套函数遍历对象文字

[英]Looping through object literal with nested functions

I'm trying to loop through an object literal and select just one of the keys and return it's value, which will be a function. 我试图遍历对象文字并仅选择其中一个键并返回它的值,这将是一个函数。 My problem is, that I can't get the loop to return just one value - it always returns all of the values (functions). 我的问题是,我无法使循环仅返回一个值-它总是返回所有值(函数)。 I noticed that if I nest the function inside of the object literal (see foo), then it works better, but still not looping through. 我注意到,如果我将函数嵌套在对象文字中(请参见foo),则它会更好地工作,但仍无法遍历。

Here is the JS fiddle . 这是JS小提琴

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();

You are not checking for the key, you are checking a string against a function. 您不是在检查键,而是在根据函数检查字符串。

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

another way is to use Object.keys() 另一种方法是使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM