Reputation: 11
I am new to javascript and have been reading eloquent javascript to start off. I am trying to make a function that stores entries of items, price, and whether it's on sale. I can't seem to replicate some of the things the author of Eloquent Javascript does. I want to add the additional arguments to their appropriate properties, but I can't seem to add to the object properties. I don't know what I am doing wrong. I tried to follow the author's code, but it's not happening for me.
var itemList = [];
function addEntry(item){
var entry = {item: item, price: [], sale: []};
for(var i = 0; i < arguments.list; i++){
if(typeof arguments[i] == boolean)
entry.sale.push(arguments[i]);
else
entry.price.push(arguments[i]);
};
console.log(entry);
}
addEntry('couch', '$500', true)
I also tried altering the code below to create a new property every loop iteration, but I can't do that either. I am fully aware that I am most likely leaving some crucial code out or making an easy mistake, but I am blind to it. Please help me out. Even if the code seems to work for you let me know.
var itemList = [];
function addEntry(item){
var entry = {item: item};
for(var i = 0; i < arguments.list; i++){
if(typeof arguments[i] == boolean)
entry.sale = arguments[i];
else
entry.price arguments[i];
};
console.log(entry);
}
addEntry('couch', '$500', true)
Upvotes: 0
Views: 69
Reputation: 1
You have to loop thru the list of arguments as below. Also if you make item an array, you could accomodate multiple items, just like multiple price list. So you could call
addEntry('couch', '$100', true);
addEntry('couch', '$100', true, 'chair', '$50', false);
function addEntry(){
var entry = {item: [], price: [], sale: []};
for(var i = 0; i < arguments.length; i++){
if(typeof arguments[i] == 'boolean')
entry.sale.push(arguments[i]);
else if (!isNaN(arguments[i].replace('$','')))
{
entry.price.push(arguments[i]);
}
else
entry.item.push(arguments[i]);
}
console.log(entry);
}
Upvotes: 0
Reputation: 6052
There are some typo errors in your code. See the comment below in the updated code:
var itemList = [];
function addEntry(item){
var entry = {item: item};
for(var i = 0; i < arguments.length; i++){ // Use argument.length to specify upper bound of the loop
if(typeof arguments[i] == 'boolean') // typeof returns a string, so use 'boolean'
entry.sale = arguments[i];
else
entry.price = arguments[i];
};
console.log(entry);
itemList.push(entry); // Have you forgotten to add it to the list?
}
addEntry('couch', '$500', true)
Upvotes: 2