Utilizing strings as array keys

When utilizing strings as keys in an array, the console does not display these declared values when iterating through them, even though the values can still be accessed.

>> var arr = [ 0, 1, 2, 3 ];
   undefined

>> arr["something"] = "aught";
   "aught"

>> arr
   [0, 1, 2, 3]

>> arr["something"]
   "aught"

>> for( var i = arr.length; i--; console.log( arr[ i ] ) );
   3
   2
   1
   0

I've come to understand that arrays are essentially objects with a built-in 'enumerate' interface within JavaScript's engine.

What's most intriguing is that the interpreter doesn't throw any warnings or errors, leading me to spend time searching for where the data could potentially be lost.

Answer №1

JavaScript offers two types of arrays: standard arrays and associative arrays

  • [ ] - standard array that uses 0 based integer indexes only
  • { } - associative array represented by JavaScript objects where keys can be any strings

When you declare:

var arr = [ 0, 1, 2, 3 ];

You are creating a standard array where indexes must be integers. If you use arr["something"], because something is not an integer value, you are essentially defining a property on the arr object (remember, everything is an object in JavaScript), but you are not adding an element to the standard array.

Answer №2

for( let counter = arr.length; counter--; console.log( arr[ counter ] ) );

In this code snippet, only the numeric indices are printed. However, you can still iterate over both numeric indices and string keys of the array by using the following loop:

for (let key in arr) {
    console.log(key + ": " + arr[key]);
}
/* This will output:
     0: 0
     1: 1
     2: 2
     3: 3
     something: aught
*/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The value control input does not get properly updated by ngModelChange

Having difficulty updating an input as the user types. Trying to collect a code from the user that follows this format: 354e-fab4 (2 groups of 4 alphanumeric characters separated by '-'). The user should not need to type the '-', as it ...

What is the best way to prevent images from being loaded with broken links?

Currently, I am working on a new feature that involves rendering images from servers. In the process of aligning these images, I noticed an excessive amount of white space due to loading images with broken links. https://i.stack.imgur.com/jO8BR.png Here ...

The v-menu closes before the v-list-item onclick event is detected

I have set up the following menu using vue and vuetify: <div id="app"> <v-app id="inspire"> <div class="text-center"> <v-menu> <template v-slot:activator="{ on }"> ...

Unable to populate data to HTML table using AJAX success function

When I use AJAX to filter data in the table, the data is not showing up. Instead, the data on the table disappears. Below is the script code I am using: $(document).ready(function() { $("#inputJenis").change(function() { var key = $(this).val ...

Working with Multidimensional Arrays in VueJS

Designing a virtual toaster using VueJS, where different types of bread are toasted with varying results. The toaster should be able to toast sourdough, wheat, and rye, while rejecting white and English muffins. Additionally, rye should never burn, but t ...

When using res.render to send results, redundant lines are displayed

I feel like I must be missing something really obvious, but for the life of me I cannot figure out what it is. All I want to do is list the documents in a MongoDB collection in a straightforward manner. I am working with nodejs, mongoose, and Jade (althoug ...

EventListener fails to function following form button click within iframe

I have a code snippet that allows me to close a form when clicking a button inside an iframe: <!DOCTYPE html> <html lang="en-US" prefix="og: http://ogp.me/ns#"> <head> <script> $(document).ready(function(){ ...

Creating numerous bar graphs for each specific date

I have a dataset containing dates and corresponding information for each element. Despite trying various approaches, I am unable to create a barchart. Every solution I've attempted has been unsuccessful thus far. The dataset is structured as follows ...

Guide on developing a dynamic Navbar component on Laravel Mix with Vue Js

As I delve into learning and practicing Vue.js, my goal is to create a component that includes elements like Navbar and Footer within a single view. Initially, I set up an index for the first view but faced an issue with adding the navbar as it did not sho ...

Converting a ScrollView to a FlatList: A step-by-step guide

Recently, I came across a React Native pure JavaScript wheel picker component that works great. Here is the link where I found it: https://www.npmjs.com/package/react-native-picker-scrollview However, I noticed that the ScrollView used in this component m ...

The value of this.$refs.<refField> in Vue.js with TypeScript is not defined

During the process of converting my VueJs project to TypeScript, I encountered an error related to TypeScript. This issue arises from a component with a custom v-model implementation. In the HTML, there is an input field with a 'plate' ref that ...

Issue with AngularJS: Unable to add a new property to an object

Here is the Javascript code I am working with in an AngularJS controller: $scope.schedule = {} $scope.selectEquipment = function(equip) { //alert(equip); $scope.schedule.equipment = equip; } I am successfully receiving the equip variable, but fo ...

Transforming data format from JavaScript to JSON

Currently, I am extracting information from a page that is presented in the following format: {"cars":0,"bikes":"1"} To enable the charts on my page to function properly, I need to transform it into this structure: [{"key":"cars","value":0},{"key":"bike ...

Spacing the keyboard and input field in React Native

Is there a way to add margin between the input and keyboard so that the bottom border is visible? Also, how can I change the color of the blinking cursor in the input field? This is incorrect https://i.sstatic.net/Jsbqi.jpg The keyboard is hidden https: ...

Proper method to link information using angular.extend within a completed promise

My goal is to enhance the clarity of my Angular code by transitioning from using this.vm to angular.extend to better understand private and public variables/methods when utilizing the controller as syntax. However, I am facing an issue with data binding fr ...

Using the factory pattern in a Node.js (Express) application

As I delved into the realm of design patterns, I found myself drawn to the factory pattern. However, as I perused through code written by others, I noticed that this particular pattern wasn't as prevalent, especially in newer stacks. Take for example ...

What is the best way to set up a static array of pointers within an object during initialization

Suppose I have a class named CardHandler and I want to create a static allocated array of pointers of type Card with 40 places. How should I declare this in the header file and implementation file? This is what I have attempted: class CardHandler { pr ...

javascript code to combine two JSON objects with numeric string keys and sort them in ascending order

Is there a way to combine two JSON objects with numerical string keys and arrange them in ascending order? let obj1 = { '10' : "ten" '2' : "two", "30": "thirty } let obj2 = { '4' : "four", '5' : "five", "1": "on ...

Replace the transformation matrix of a three.js object/mesh entirely

Creating a new object in three.js In order to create a three.js mesh object, follow these steps: var geometry = new THREE.BufferGeometry(); var standardMaterial = new THREE.MeshStandardMaterial( {/* inputs */ } ); var mesh = new THREE.Mesh( ...

Loop through an array in PHP and display specific elements

I'm currently working on displaying transaction details using PHP and Paypal's NVP method called TransactionSearch. I've managed to retrieve the transactions successfully, but I'm facing an issue in organizing the response to show only ...