Home > OS >  Create and update array value index with key names in JavaScript
Create and update array value index with key names in JavaScript

Time:12-16

I'm creating array arr with 0 values and variable number nmb = 2 // 4, 6.. of index's:

for (n = 0; n < nmb; n  ) {
    arr.push(0);  
}

my array:

[0, 0]

then update with increment value by index arr[1] = arr[1] 1;:

[0, 1]

and displaying scores by index console.log("Name:", arr[0], "Case:", arr[1]);.

I'm trying to figure out, how to create array, add different key names with default zero values by variable number of names. Then update, getting value by index or key name:

[Name: 0, Case: 1]

Use array according described scenario:

 var arr = new Array();
 var keyNames = ["Name", "Case"];
  for (n = 0; n < keyNames.length; n  ) {
    arr[keyNames[n]] = 0;
  }

but result looks like this:

[ NaN, NaN, NaN, Name: 0, Case: 0 ]

CodePudding user response:

Store the values in an object, by key name, then look up the value by key name, and increment the value by key name, derived from looking up the key name in an array by index.

const keyNames = ['Name', 'Case'];
const store = {};

for (const kn of keyNames) {
  store[kn] = 0;
}

const incrementStore = (index) => {
  store[keyNames]  = 1;
};

const printStore = () => {
  keyNames.map(kn => `${kn}: ${store[kn]}`).join(', ');
};


incrementStore(1);

printStore();
// Name: 0, Case: 1
  • Related