2016-11-21 75 views
0

我試圖達到作爲數組元素的子函數。如何在jquery中運行一個數組元素的子函數

在下面的例子中,我們可以到達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'); 

    }); 
}); 
+0

正如我所看到的,你使用jquery每個似乎都不錯,嘗試做一個控制檯日誌的變種,並看到控制檯輸出並告訴我們 –

回答

2

使用typeof

PS:您還需要修復的名字,姓氏和工作在警報

$(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(); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

+0

謝謝先生,工作。 'typeof'保存一天:) 編輯:是的,我現在意識到我必須改變它們。謝謝。 –

1

您可以使用typeof

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

仍然錯誤。已經回答了 – mplungjan

+0

嗯,這是正確的!很難被移動...;) – Jai

+0

我的意思是你的是正確的... – Jai

相關問題