Chapter 6 - Objects
6.2.1 JS objects as associative arrays
by Denise Nepraunig
JavaScript
// JavaScript The Definitive Guide 6th Edition
// 6.2.1 Objects as associateve arrays
// JavaScript objects are associative arrays
var customer = {
address0: "SAP AG",
address1: "Hasso-Plattner-Ring 16",
address2: "69190 Walldorf",
address3: "GERMANY"
};
var addr = "";
for(var i = 0; i < 4; i++)
addr += customer["address" + i] + "\n";
console.log(addr);
// with dot-notation we would have to hard-code values
var myPortfolio = [];
function addstock(portfolio, stockname, shares) {
portfolio[stockname] = shares;
}
addstock(myPortfolio, 'IBM', 50);
addstock(myPortfolio, 'SAP', 75);
addstock(myPortfolio, 'IFX', 100);
addstock(myPortfolio, 'ABC', 1);
var myQuote = {
'IBM': 1.2,
'SAP': 2.4,
'IFX': 0.75
};
function getquote(stock) {
return myQuote[stock] || 0.0;
/*
if(myQuote[stock] !== undefined) {
return myQuote[stock];
} else {
return 0.0;
}
*/
}
function getvalue(portfolio) {
var total = 0.0;
for(stock in portfolio) {
var shares = portfolio[stock]; // get the number of shares
var price = getquote(stock);
total += shares * price;
}
return total;
}
var total = getvalue(myPortfolio);
console.log(total);