我尝试到达一个作为数组元素的子函数。
在下面的示例中,我们可以访问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 :(得分: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();
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:1)
您可以使用typeof
:
if(typeof item === 'function'){
item(); // run it
}