如何在jquery中运行作为数组元素的子函数

时间:2016-11-21 07:35:21

标签: javascript jquery window

我尝试到达一个作为数组元素的子函数。

在下面的示例中,我们可以访问name属性window['name']

但是如果属性是一个函数,就不能像这样调用它。我尝试做的是在.each函数中,如果item是一个函数运行函数。我怎么能这样做?。

$(document).ready(function() {

  var human = {
    name: 'Emin',
    surname: 'Çiftçi',
    job: 'Software Developer',
    func: function() {
      alert(name + ' ' + surname + ', ' + job);
    }
  };

  $.each(human, function(index, item) {
    //if(item is a function) {
    // run the function
    //}
    $('<div>').text(index + ': ' + item).appendTo('#deneme');

  });
});

2 个答案:

答案 0 :(得分:2)

使用typeof

PS:您还需要在警报中修复姓名,姓氏和工作

&#13;
&#13;
$(document).ready(function() {

  var human = {
    name: 'Emin',
    surname: 'Çiftçi',
    job: 'Software Developer',
    func: function() {
      alert(human.name + ' ' + human.surname + ', ' + human.job);
    }
  };

  $.each(human, function(name, item) {
    console.log(typeof item);
    if (typeof item == "function") item();
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用typeof

 if(typeof item === 'function'){
      item(); // run it
 }