Sometimes, we want to use an integer as a key in an associative array in JavaScript.
In this article, we’ll look at how to use an integer as a key in an associative array in JavaScript.
How to use an integer as a key in an associative array in JavaScript?
To use an integer as a key in an associative array in JavaScript, we declare a variable as an object.
For instance, we write
const test = {};
test[2300] = 20;
console.log(test["2300"]);
to create the test
variable that’s set to an empty object.
Then we add the key 2300
to it and set its value to 20.
The 2300
key will be converted to a string automatically, so we access the value with test["2300"]
.
Conclusion
To use an integer as a key in an associative array in JavaScript, we declare a variable as an object.