javascript - array adding function in object literal notation -


here code using, not quite sure how use literal notation yet, have pass currentactivecategories function somehow. not sure if preferred way it, dont want learn bad habits.

var primarycare = {     currentactivecategories : [ "1", "2"],     currentvalue : addvalues(this.currentactivecategories) }  function addvalues(activecategories) {     temptotal;     for(int = 0; < activecategories.length; i++){         temptotal += activecategories[i];     }     return temptotal; } 

currently object literal creates object 2 properties, currentactivecategories, array, , currentvalue, set result of calling addvalues() at time object literal evaluated. trying call function this.currentactivecategories, undefined, because this not equal object @ moment.

if idea have function can return current total @ time can this:

var primarycare = {     currentactivecategories : [ "1", "2"],     currentvalue : function () {                       var temptotal = "";                       for(var = 0; < this.currentactivecategories.length; i++){                          temptotal += this.currentactivecategories[i];                       }                       return temptotal;                    } }  primarycare.currentvalue(); // returns "12", i.e., "1" + "2" 

always declare variables var or they'll become globals - note can't declare int in js. need initialise temptotal empty string before start adding strings it, or instead of "12" you'll "undefined12".

when call function method of object, primarycare.currentvalue() (as shown above) within function this set object.

it seems kind of odd me adding values strings. if want use numbers , numeric total can this:

var primarycare = {     currentactivecategories : [ 1, 2],   // note no quotes around numbers     currentvalue : function () {                       var temptotal = 0;                       for(var = 0; < this.currentactivecategories.length; i++){                          temptotal += this.currentactivecategories[i];                       }                       return temptotal;                    } } 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -