Files
2nd/10_Wiki/Topic_JavaScript/JavaScript_Arrays.md
T
koriweb 9609c04755 docs(10_Wiki): W3Schools 위키화 — HTML/CSS/JavaScript(core)
W3Schools 튜토리얼을 P-Reinforce v3.1 포맷으로 위키화(영어 본문, 한/영 섹션 헤더).
- Topic_HTML: 59문서 (튜토리얼+예제, 레퍼런스/메타 제외)
- Topic_CSS: 190문서 (메인 + Advanced/Flexbox/Grid/RWD 전체)
- Topic_JavaScript: 120문서 (코어 언어; Temporal/DOM상세/BOM/WebAPI/AJAX/jQuery/Graphics 등은 후속)
각 폴더 00_INDEX.md(MOC) 포함. 코드 verbatim, 미확인분은 "Not found in source" 표기.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 19:21:18 +09:00

218 lines
8.5 KiB
Markdown

---
id: javascript-arrays
title: "JavaScript Arrays"
category: "Frontend"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["array literal", "new Array", "array index", "array length", "isArray"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.89
created_at: 2026-06-23
updated_at: 2026-06-23
review_reason: ""
merge_history: []
tags: ["javascript", "js", "web", "frontend", "w3schools", "arrays", "data-structures", "objects"]
raw_sources: ["https://www.w3schools.com/js/js_arrays.asp"]
applied_in: []
github_commit: ""
---
# [[JavaScript Arrays]]
## 🎯 한 줄 통찰 (One-line insight)
An array is a special object that holds an ordered, zero-indexed collection of values — use `[]` literals to create them, and remember `typeof` reports them as `"object"`. [S1]
## 🧠 핵심 개념 (Core concepts)
- **Arrays store ordered collections** — a single variable can hold multiple values, accessed by zero-based index numbers. [S1]
- **Literal syntax is preferred** — `[]` is the recommended way to create an array (over `new Array()`). [S1]
- **Indexes start at 0** — the first element is at index `0`, the second at `1`, and so on. [S1]
- **Arrays are objects** — `typeof` returns `"object"`; elements can themselves be objects, functions, or other arrays. [S1]
- **No named indexes** — JavaScript does not support arrays with named indexes; using named indexes turns the array into a plain object and breaks array methods. [S1]
- **Detect with `Array.isArray()` / `instanceof`** — because `typeof` returns `"object"`, use these to recognize an array. [S1]
## 🧩 추출된 패턴 (Extracted patterns)
- **Create with a literal** — `const cars = ["Saab", "Volvo", "BMW"];`. [S1]
- **Access / change by index** — `cars[0]` reads, `cars[0] = "Opel"` writes. [S1]
- **Append with `push` or `length`** — `fruits.push("Lemon")` or `fruits[fruits.length] = "Lemon"`. [S1]
- **Iterate with `for` or `forEach`** — loop by index, or pass a callback to `forEach`. [S1]
## 📖 세부 내용 (Details)
**Creating an array (literal)**
Using an array literal is the easiest way to create a JavaScript array: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
```
Spaces and line breaks are not important; a declaration can span multiple lines: [S1]
```javascript
const cars = [
"Saab",
"Volvo",
"BMW"
];
```
You can also create an array and then provide the elements: [S1]
```javascript
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
```
**Using the `new Array()` keyword**
The following example also creates an array and assigns values to it, but the array literal method is recommended: [S1]
```javascript
const cars = new Array("Saab", "Volvo", "BMW");
```
**Accessing array elements**
You access an array element by referring to its index number. Array indexes start with 0: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
```
**Changing an array element**
This statement changes the value of the first element in `cars`: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
```
**Accessing the full array**
With JavaScript, the full array can be accessed by referring to the array name: [S1]
```javascript
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
```
**Arrays are Objects**
Arrays are a special type of object. The `typeof` operator returns `"object"` for arrays. But JavaScript arrays are best described as arrays. Arrays use *numbers* to access their "elements". This array uses numbers to access its elements: [S1]
```javascript
const person = ["John", "Doe", 46];
```
Objects use *names* to access their "members". This object uses names to access its members: [S1]
```javascript
const person = {firstName:"John", lastName:"Doe", age:46};
```
**Array elements can be objects**
JavaScript variables can be objects, and arrays are special kinds of objects. Because of this, you can have variables of different types in the same array, and array elements can themselves be objects or functions: [S1]
```javascript
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
```
**The `length` property**
The `length` property of an array returns the number of array elements: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
```
**Looping array elements (for loop)**
One way to loop through an array is using a `for` loop: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;
let text = "<ul>";
for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
```
**Looping array elements (forEach)**
You can also use the `Array.forEach()` function: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let text = "<ul>";
fruits.forEach(myFunction);
text += "</ul>";
function myFunction(value) {
text += "<li>" + value + "</li>";
}
```
**Adding array elements**
The easiest way to add a new element to an array is using the `push()` method: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon");
```
A new element can also be added to an array using the `length` property: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon";
```
**Associative arrays**
Many programming languages support arrays with named indexes (associative arrays). JavaScript does *not* support arrays with named indexes. In JavaScript, arrays always use numbered indexes. If you use named indexes, JavaScript will redefine the array as an object, and array methods and properties will produce incorrect results. [S1]
**The difference between arrays and objects**
In JavaScript, arrays use *numbered* indexes, while objects use *named* indexes. Use an object when you want the element names to be strings (text); use an array when you want the element names to be numbers. [S1]
**How to recognize an array**
A common question is: how do I know if a variable is an array? The problem is that the `typeof` operator returns `"object"`. The first solution is `Array.isArray()`: [S1]
```javascript
Array.isArray(fruits);
```
The second solution is the `instanceof` operator, which returns true if an object is created by a given constructor: [S1]
```javascript
const fruits = ["Banana", "Orange", "Apple"];
(fruits instanceof Array);
```
## 🛠️ 적용 사례 (Applied in summary)
The page's snippets are the applied cases: building a `cars`/`fruits` array, reading/writing by index, rendering a `<ul>` list via `for` and `forEach`, appending with `push`/`length`, and distinguishing arrays from objects via `Array.isArray`/`instanceof`. No external project/commit applications found in the source.
## 💻 코드 패턴 (Code patterns)
Create, read, write (language: JavaScript):
```javascript
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0]; // read
cars[0] = "Opel"; // write
```
Append:
```javascript
fruits.push("Lemon");
fruits[fruits.length] = "Lemon";
```
Detect an array:
```javascript
Array.isArray(fruits);
(fruits instanceof Array);
```
## ⚖️ 비교 및 선택 기준 (Comparison & decision criteria)
- **Array literal `[]` vs. `new Array()`** — the literal is recommended for readability and to avoid `new Array()` pitfalls. [S1]
- **Array vs. object** — use an array when element names are numbers (ordered/indexed data); use an object when names are strings. [S1]
- **`Array.isArray()` vs. `instanceof Array`** — both detect arrays where `typeof` cannot (it returns `"object"`). [S1]
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
No contradictions found in the source.
## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual (실제 적용 사례 발견 시 applied/validated로 승격 가능)
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.89
- **중복 검사 결과:** 신규 생성 (New discovery)
## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[JavaScript Tutorial]]
- **관련 개념:** [[JavaScript Array Methods]], [[JavaScript Objects]], [[JavaScript Loop For]], [[JavaScript var let const]]
- **참조 맥락:** The foundation for any indexed/ordered data handling in JavaScript.
## 📚 출처 (Sources)
- [S1] W3Schools — JavaScript Arrays — https://www.w3schools.com/js/js_arrays.asp
## 📝 변경 이력 (Change history)
- 2026-06-23: Initial draft synthesized from the W3Schools "JavaScript Arrays" page (Astra wiki-curation, P-Reinforce v3.1 format).