1

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 ]
2
  • It's not very clear to be what you're trying to do. Commented Dec 16, 2022 at 4:23
  • @Spectric Hello, sorry just typo with shortcutting example names . I'm trying to create array with key names, and update zero value by index, use value by key name Commented Dec 16, 2022 at 4:27

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

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.