如何调用数组JavaScript中定义的函数

时间:2016-01-28 05:39:30

标签: javascript arrays

以下是我的代码,当我尝试控制数组中定义的函数时抛出错误。让我知道我做错了什么。

var a = ['This is a string', {'name': 'Test User'}, 90, undefined, 'Another String', null, function(){return 'This is also valid'}];

for(var i=0; i<a.length; i++) {
  if(typeof a[i] === 'function')
    console.log(a[i]());
  else
    console.log(a[i]());
}

获取错误 -

TypeError: a[i] is not a function

1 个答案:

答案 0 :(得分:3)

从else

中删除方法调用
for(var i=0; i<a.length; i++) {
  if(typeof a[i] === 'function')
    console.log(a[i]());
  else
    console.log(a[i]); //remove method call from here
}