[英]how to find a specific item in the object is not a function in javascript
I have the below code to Manage a collection of Books. 我有以下代码来管理图书集。
var Book = function(title,pages,priority){
this.title = title;
this.pages = pages;
this.priority = priority;
this.GetMaxmimumDays=function(){
var effortCalculator = new EffortCalculator(this.pages);
return effortCalculator.CalculateDays();
}
};
var BooksCollection = (function(){
var books=[];
return {
Add:function(book){
books.push(book);
},
Remove:function(title){
for(var i=0;i<books.length;i++){
if(books[i]["title"]==title){
books[i]["title"]=null;
}
}
},
Print:function(){
for(var i=0;i<books.length;i++){
var itemText="";
for(item in books[i]){
itemText=itemText+""+item+":"+books[i][item];
}
alert("item"+itemText); /** itemText prints the string includes the function definition. **/
}
},
Count:books.length,
SortByPriority:function(){
}
};
})();
in the above code BooksCollection.Print() prints everyItem and everyProperty in the collection. 在上面的代码中,BooksCollection.Print()打印集合中的everyItem和everyProperty。 however the book instance have got function member.
但是书籍实例有功能成员。 The same is getting printed in alert.
同样是在警报中打印。
I wrapped around the Print() as below to hide out the function being printed in the output. 我将Print()包裹在下面,以隐藏输出中正在打印的功能。
Print:function(){
for(var i=0;i<books.length;i++){
var itemText="";
for(item in books[i]){
if(!(item instanceof Function)){
itemText=itemText+""+item+":"+books[i][item];
}
}
alert("item"+itemText);
}
}
but things are still negative. 但事情仍然是消极的。 I tried (typeof(item)==="Function") but the typeof(item) still reads "String".
我试过(typeof(item)===“Function”)但是typeof(item)仍然是“String”。
I wonder the suspicious act of typeof and instanceOf keywords. 我想知道typeof和instanceOf关键字的可疑行为。
you can find a fiddle over here. 你可以在这里找到一个小提琴。 http://jsfiddle.net/saravanakumarrc/rDEnt/40/
http://jsfiddle.net/saravanakumarrc/rDEnt/40/
Please help me out to find the solution. 请帮我找出解决方案。
In your case, typeof item
will always be a string
- its the key to the property of the Book
being enumerated. 在您的情况下,
typeof item
将始终是一个string
- 它是枚举Book
的属性的关键。
What you want to test is the value of that item, so you want typeof books[i][item]
: 您想要测试的是该项目的价值 ,因此您需要类型的
typeof books[i][item]
:
for(item in books[i]){
if(typeof books[i][item] != 'function'){
itemText=itemText+""+item+":"+books[i][item]+ '\r\n';
}
}
Live example: http://jsfiddle.net/kDHfU/ 实例: http : //jsfiddle.net/kDHfU/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.