如何在JS中使用局部变量创建对象?

时间:2015-03-23 08:09:33

标签: javascript arrays function object scope

我希望有人可以帮我理解一两件事。我试图通过页面上的表单提交的信息创建一个对象数组。我的createItem()中的变量是本地的,用于填充新项目的对象构造函数。反过来,这个新项目被推送到一个数组,但是一旦该功能结束,该项目就不会停留在数组中。

以下是代码:

var itemList = [];
var newItem;

// item constructor function
function item(name, quantity, length, width, height, cubicFeet, totalCubicFeet) {
  this.name = name;
  this.quantity = quantity;
  this.length = length;
  this.width = width;
  this.height = height;
  this.cubicFeet = cubicFeet;
  this.totalCubicFeet = totalCubicFeet;
}

//Getters
function getItemName() {
  var name = document.getElementById("item-name").value;
  return name;
}

function getWidth() {
  var width = parseInt(document.getElementById("width").value);
  return width;
}

function getHeight() {
  var height = parseInt(document.getElementById("height").value);
  return height;
}

function getLength() {
  var length = parseInt(document.getElementById("length").value);
  return length;
}

function getQuantity() {
  var quantity = parseInt(document.getElementById("quantity").value);
  return quantity;
}


//calculates cubic footage of item from inches
function getCubicFeet(length, width, height) {
  var cubicFeet = Math.ceil((length / 12) * (width /12) * (height / 12));
  return cubicFeet;
}

//prints list of items to console
function printList() {

  for (var i = 0; i <= itemList.length; i++) {
      console.log(itemList[i]);
  }

}

//retrieves the information from the form and creates an object OnClick
function createItem() {

  var name = getItemName();
  var quantity = getQuantity();
  var length = getLength();
  var width = getWidth();
  var height = getHeight();
  var cubicFeet = getCubicFeet(length, width, height);
  var totalCubicFeet = cubicFeet * quantity;

  newItem =  new item(name, quantity, length, width, height, cubicFeet, totalCubicFeet);

  itemList.push(newItem);

  printList();

}

我是否需要为每个项目值创建全局变量以使它们粘在一起,然后将其推送到数组?或者有没有办法使用本地变量来实现这一点,就像我在这里一样?

0 个答案:

没有答案