我收到以下代码的“不是函数”错误
function menu_item(name,price,description,type){
this.name=name;
this.price="$"+price;
this.description=description;
this.type=type;
this.create_item=create_item;
function create_item(){
var item_slot=document.createElement('div');
item_slot.className='item';
item_slot.id=this.name;
document.getElementById(this.type).appendChild(item_slot);
var the_name=document.createTextNode(this.name);
item_slot.appendChild(the_name);
}
}
var hamburger=new menu_item("Hamburger",4.55,"A 6oz patty burger served on your choice of wheat, white, or rye bun.","burger");
var cheeseburger=new menu_item("Cheeseburger",4.95,"A 6oz patty burger served with American,Mozzarella, or Provolone cheese on your choice of wheat, white, or rye bun.","burger");
var bacon_hamburger=new menu_item("Bacon Hamburger",5.65,"A 6oz patty burger and honey glazed bacon served on your choice of wheat, white, or rye bun.","burger");
var bacon_cheeseburger=new menu_item("Hamburger",5.90,"A 6oz patty burger,topped with honey glazed bacon served with American,Mozzarella, or Provolone cheese on your choice of wheat, white, or rye bun.","burger");
//wings
var chicken_wings=new menu_item("Chicken Wings(6)",4.55,"A basket of 6 crispy chicken wings in your choice of bbq,hot,mild, or tangy sauce.","wings");
//fries
var fries=new menu_item("Freedom Fries",1.50,"A 1/2 pound of crispy golden fries.","fries");
var gravy_fries=new menu_item("Gravy Fries",2.50,"A 1/2 pound of freedom fries slathered in gravy and melted cheese.","fries");
//desert
var cheesecake=new menu_item("Cheese Cake",2.00,"Top off you meal with a slice of our signature cheese cake","desert");
var oreocake=new menu_item("Oreo Cake",2.00,"A delectable oreo cheese cake complements any meal well","desert");
var chocolatechip_cookies=new menu_item("Chocolate Chip Cookies",1.50,"A bag of five chocolate chip cookies are always a favorite with the kids.","desert");
//drinks
var drinks=new menu_item("Drinks", 1.00, "16 oz drink of your choice of apple,grape,lemon, or orange soda","drinks");
//various objects created that are then put into array below vv
var food_array=[hamburger,cheeseburger,bacon_cheeseburger,bacon_hamburger,chicken_wings,fries,gravy_fries,cheesecake,oreocake,chocolatechip_cookies,drinks];
function populate_menu(){
for(var x in food_array){
x.create_item();
}
}
然后在html中执行onulate执行populate_menu函数,但是我收到错误...有人可以解释为什么会发生这种情况吗?
答案 0 :(得分:1)
一个问题是for(var x in obj)
iterates all Enumerable properties in obj
(未定义的顺序)。因此,for-in 不适合将数组迭代为一系列项目。
我怀疑代码遇到了这个问题并找到了一个没有“create_item”方法的“非menu_item”对象;相反,使用如下循环迭代一个数组:
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
// ..
}
或者,使用Array.prototype.forEach in ES5:
arr.forEach(function (item) {
// ..
});