[JavaScript]Array Definition and Data Access Basics (Literal Notation and Indices)

目次

Overview

Managing multiple related data points efficiently is a fundamental requirement in software development, and JavaScript fulfills this primarily through the Array object. This article explores the essential techniques for defining arrays using the bracket literal [], constructing complex data structures such as nested arrays and arrays of objects, and retrieving specific elements using numerical indices.


Specifications (Input/Output)

  • Input: Data values to be grouped (numbers, strings, objects, or even other arrays).
  • Output: A structured array object or a specific element retrieved via its index.

Array Syntax and Definitions

SyntaxMeaningReturn Type
[val1, val2, ...]Array literal. Defines elements separated by commas.Array (Object)
array[n]Index access. Retrieves the $n$-th element of the array.Dependent on element type

Note: The index in JavaScript is zero-based. The first element is accessed at index $0$.


Basic Usage

1. Defining Various Arrays

JavaScript arrays are dynamic and can hold multiple data types, although it is best practice to keep them homogenous for consistency.

// 1. Empty array for dynamic population
const nodeLogs = [];

// 2. Numeric data for metric points
const cpuUsage = [45, 52, 49, 61];

// 3. String values for configuration keys
const configSettings = ['production', 'debug', 'verbose'];

2. Complex Data Structures

In professional scenarios, you will often encounter nested arrays or arrays containing objects for more complex data management.

// 4. Nested (Multi-dimensional) Arrays
// Example: Grid coordinates [x, y]
const gridPoints = [
    [0, 10],
    [5, 15],
    [10, 20]
];

// 5. Array of Objects
// Standard format for system entities or API responses
const infrastructureNodes = [
    { id: 1, type: 'web', status: 'active' },
    { id: 2, type: 'db', status: 'idle' }
];

3. Accessing Elements by Index

Retrieval is performed using the numerical position, starting from $0$.

const clusters = ['Primary', 'Secondary', 'Backup'];

console.log(clusters[0]); // "Primary"
console.log(clusters[1]); // "Secondary"
console.log(clusters[2]); // "Backup"

Full Code (Infrastructure Management Scenario)

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Infrastructure Monitor</title>
    <style>
        .node-card {
            border: 1px solid #444;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 6px;
            background-color: #1a1a1a;
            color: #efefef;
            font-family: 'Segoe UI', sans-serif;
            max-width: 450px;
        }
        .node-hostname {
            font-weight: bold;
            color: #00ffcc;
            font-size: 1.1em;
        }
        .node-details {
            margin-top: 8px;
            font-size: 0.9em;
            color: #bbb;
        }
        .status-up { color: #4caf50; }
        .status-down { color: #f44336; }
    </style>
</head>
<body>

<div id="monitor-display">
    </div>

<script src="app.js"></script>
</body>
</html>

JAVASCRIPT

/**
 * System Infrastructure Monitoring Logic
 */

// Define an array of system nodes (objects)
const systemInventory = [
    { uuid: 'node-a1', host: 'load-balancer-01', state: 'UP', address: '10.0.0.1' },
    { uuid: 'node-b2', host: 'app-engine-01', state: 'UP', address: '10.0.0.5' },
    { uuid: 'node-c3', host: 'storage-cluster-01', state: 'DOWN', address: '10.0.0.20' }
];

const displayContainer = document.getElementById('monitor-display');

/**
 * Renders node details to the dashboard based on array index
 * @param {Array} inventory - The list of hardware nodes
 * @param {number} targetIndex - The index of the node to inspect
 */
const updateDashboard = (inventory, targetIndex) => {
    // Access the specific node in the array
    const selectedNode = inventory[targetIndex];

    // Safety check for indices out of range
    if (!selectedNode) {
        displayContainer.innerHTML = '<p>Error: Specified node index not found in inventory.</p>';
        return;
    }

    // Determine status class based on the state property
    const statusClass = selectedNode.state === 'UP' ? 'status-up' : 'status-down';
    
    // Construct HTML template literal
    const nodeTemplate = `
        <div class="node-card">
            <div class="node-hostname">Hostname: ${selectedNode.host}</div>
            <div class="node-details">
                Current State: <span class="${statusClass}">${selectedNode.state}</span>
            </div>
            <div class="node-details">IP Reference: ${selectedNode.address}</div>
        </div>
    `;

    displayContainer.innerHTML = nodeTemplate;
};

// Inspecting the Database Cluster (Index 2)
updateDashboard(systemInventory, 2);

Customization Points

  • Modifying Initial Data: You can adjust the systemInventory array elements to manage different entities, such as user records, product catalogs, or application state objects.
  • Dynamic Index Selection: While this example uses a static index for demonstration, you can link the targetIndex argument to user input or event listeners to allow for real-time data switching.

Important Notes

  • Zero-Based Indexing: It is a common mistake to attempt to retrieve the first item using array[1]. In JavaScript, the first element always resides at index $0$.
  • Out-of-Range Retrieval: Accessing an index that does not exist, such as inventory[99] in a three-item list, will return undefined rather than throwing an error. Developers must include logic to handle these cases to avoid UI bugs.
  • Nested Access Syntax: For multi-dimensional structures like const matrix = [[5, 10], [15, 20]], you access values by chaining brackets, such as matrix[0][1] to retrieve the value $10$.

Advanced Applications

When the size of an array is unknown or dynamic, retrieving the final element is best achieved using the length property. Since the length is always one digit higher than the final index, you must subtract $1$. For instance, in const queue = ['job1', 'job2'], the final item is accessed via queue[queue.length - 1].


Summary

Array definition using literal brackets and data retrieval via numerical indices form the bedrock of JavaScript data management. By enclosing elements in comma-separated structures, developers can organize everything from simple string lists to complex arrays of objects. It is essential to remember that counting begins at zero and that accessing indices outside the established range results in undefined rather than a system crash. Mastering these structural patterns allows for the efficient organization of vast datasets, making them accessible and manageable within any modern application.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次