JavaScript基础知识:数组或数组

时间:2014-10-14 19:56:57

标签: javascript arrays

我正在尝试学习JavaScript并且正在进行一项练习,我正在创建一个包含食物,数量和成本的购物清单。我似乎无法传递多个变量或创建一个数组数组。我尝试了其他一些选项,例如" new Object"但是,我无法获得任何开支。给我一个线索?

var groceryList = function(food, quantity, price) {
  var theItem = [food, quantity, price]
  var theList = new Array();
  theList.push(theItem)

}


myList = new groceryList("cookie", 2, 1.00)
console.log(myList)

3 个答案:

答案 0 :(得分:5)

使用此

var groceryList = function(food, quantity, price) {
  var theItem = [food, quantity, price]
  var theList = new Array();
  theList.push(theItem);

  return theList;
}

myList = new groceryList("cookie", 2, 1.00)
console.log(myList)

答案 1 :(得分:0)

如果你想使用对象,那么你需要稍微改变一下你的想法。使用new创建对象时,将调用构造函数。

function GroceryList(food, quantity, price) {
    this.food = food;
    this.quantity = quantity;
    this.price = price;
}
GroceryList.prototype.toString = function() {
  return this.food + (this.quantity).toString() + (this.price).toString();
}

// lazy array syntax
var GroceryListPool = [];


// popular the array list pool
var list1 = new GroceryList("Butter", 2, 3.999);


GroceryListPool.push(list1);

迭代GroceryListPool数组:

for(var i = 0; i < GroceryListPool.length; i++) {
    var list = GroceryListPool[i];
    // list is an object of type GroceryList
    // technically it is not a "type", but you know what I mean.
    alert(list);
}

答案 2 :(得分:0)

那甚至不是真正的构造函数。看看这个。

function groceryList(food, quantity, price){
  this.items = {};
  if(food !== undefined){
    this.items[food] = {quantity:quantity, price:price, total:quantity*price};
  }
  this.addItem = function(food, quantity, price){
    this.items[food] = {quantity:quantity, price:price, total:quantity*price};
  }
  this.getFood(food){
    return this.items[food];
  }
  this.getQuantity = function(food){
    return this.items[food].quantity;
  }
  this.getTotal = function(food){
    return this.items[food].total;
  }
  this.getItemsByPrice(low, high){
    var r = {}, t = this.items;
    for(var i in t){
      var f = t[i], p = f.price;
      if(p >= low && p <= high){
        r[i] = f;
      }
    }
    return r;
  }
}
var groc = new groceryList('potato', 4, 0.89);
groc.addItem('orange', 10, 1);
console.log(groc.getQuantity('potato'));
console.log(groc.getTotal('orange'));
console.log(groc.getFood('orange').price);
// same as
console.log(groc.getPrice('orange'));
// or
console.log(groc.items.orange.price);
groc.addItem('pear', 200, 0.75);
console.log(groc.getItemsByPrice(0.25, 0.99)); // should be Object with 'potato' and 'pear'