- Home /
Adding array values together
So, i'm being a fish out of water again...yey.
I built a simple array :
var itemList = new Item[40];
class Item {
var itemName : String;
var sellPrice : int;
var weight : float;
var quantityInInventory : int;
}
And then set about populating the list. Now for the dillemma. How do i add all the weights of each item together then display the total?
I am using javascript.
Answer by Mikilo · Jan 29, 2013 at 12:40 AM
Hi,
The code in C# looks like that:
float total = 0;
for (int i = 0; i < items.Length; i++)
{
total += items[i].weight;
}
return total;
In JS:
class Item
{
var weight : float;
}
var items : Item[];
function GetTotal()
{
var total = 0.0f;
for (var i = 0; i < items.Length; i++)
{
total += items[i].weight;
}
return total;
}
As i comented above i'm using javascript and i'm not that confident with code. Using my rudementary knowledge, i tried to convert your code to javascript but it kept throwing up the following error:
Assets/Scripts/Test/ItemDictionary.js(20,12): BCE0044: expecting ;, found 'i'.
Answer by $$anonymous$$ · Jan 27, 2013 at 01:17 AM
You don't have a list or array in this code snippet but I guess you have a list of these items like so:
var items : List.<Item>();
Then you add items with for example:
items.Add(someItem);
You calculate the total weight with:
float TotalWeightOfItems() {
float totalWeight = 0;
foreach (item in items) {
totalWeight += item.weight;
}
return totalWeight;
}
Sorry, im using
var itemList = new Item[40];
Where do i put your code snippet, it returns with wanting to put a semi colon after float.
I'm using javascipt.
Answer by toddisarockstar · Feb 02, 2019 at 04:12 AM
var itemList = new Item[40];
class Item {
var itemName : String;
var sellPrice : int;
var weight : float;
var quantityInInventory : int;
}
// set some values
itemList[2].sellPrice=23;
itemList[5].sellPrice=18;
itemList[8].sellPrice=3;
var total : int=0;
for(var it : Item in itemList){
total+=it.sellPrice;}
print(total);