0

In the below code I am trying to create an object named "portfolio" inside which I want to create other objects that contain the properties "stockvalue" and "price"?

var portfolio_create = function(stock,stockvalue,price)
{
    for(i in stock)
    {
        this[stock[i]] = stock[i];
        this[stock[i]]["stockvalue"] =stockvalue[i];
        this[stock[i]]["price"]=price[i]    
    }
}

var portfolio = new portfolio_create(["ibm","tcs"],[23,34],[34,45]);

var stock_market = portfolio;


alert(portfolio["ibm"]["stockvalue"]);  // undefined

Why does the alert return "undefined" and not 23?

Thnaks in advance.

3 Answers 3

1
var portfolio_create = function (stock, stockvalue, price) {

    for (var i = 0, len = stock.length; i < len; i++) {
        this[stock[i]] = {};

        this[stock[i]]["stockvalue"] = stockvalue[i];
        this[stock[i]]["price"]      = price[i];    
    }
}
var portfolio = new portfolio_create(["ibm", "tcs"], [23,34], [34,45]);
  1. Don't use for..in for arrays.
  2. this[stock[i]] = stock[i]; replace to this[stock[i]] = {};.

Example

Sign up to request clarification or add additional context in comments.

Comments

1

I think there is a little confusion here, between objects and variables.

You can create a real JavaScript class portfolio, which contain a collection of another class stock, which contain 2 variables value and price.

In your portfolio class, you can add a AddStock methode, and a GetStock.

Look at JavaScript Classes, I think you will find your hapiness.

Steeve

Comments

1

And try to use libs like underscore or lodash to get rid of these for loops (each). It is much nicer and more functional.

A little bit shorter:

this[stock[i]] = { stockvalue: stockvalue[i], price: price[i] };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.