数组(索引/关联)

演示索引数组与关联数组(键值对)的创建与取值。

C C23

C23
#include <stdio.h>
typedef struct { const char *key; int val; } Pair;
int main(void) {
    int nums[] = {10, 20, 30}; // 索引数组
    Pair scores[] = { {"math", 95}, {"english", 88} }; // 关联数组:用结构体模拟
    printf("%d\n", nums[0]);
    printf("%d\n", scores[0].val);
    return 0;
}
输出
10
95

C++ C++26

C++26
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
    std::vector<int> nums = {10, 20, 30}; // 索引数组
    std::map<std::string, int> scores = { {"math", 95}, {"english", 88} }; // 关联数组
    std::cout << nums[0] << "\n";
    std::cout << scores["math"] << "\n";
    return 0;
}
输出
10
95

C# v11.0.100

v11.0.100
var nums = new[] { 10, 20, 30 }; // 索引数组
var scores = new Dictionary<string, int> { ["math"] = 95, ["english"] = 88 }; // 关联数组
Console.WriteLine(nums[0]);
Console.WriteLine(scores["math"]);
输出
10
95

Go v1.27.4

v1.27.4
package main

import "fmt"

func main() {
    nums := []int{10, 20, 30}
    scores := map[string]int{"math": 95, "english": 88}
    fmt.Println(nums[0])
    fmt.Println(scores["math"])
}
输出
10
95

Java v27.0.1

v27.0.1
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        int[] nums = {10, 20, 30};
        Map<String, Integer> scores = Map.of("math", 95, "english", 88);
        System.out.println(nums[0]);
        System.out.println(scores.get("math"));
    }
}
输出
10
95

JavaScript v26.13.1

v26.13.1
const nums = [10, 20, 30];
const scores = { math: 95, english: 88 };
console.log(nums[0]);
console.log(scores.math);
输出
10
95

PHP v8.6.0

v8.6.0
$nums = [10, 20, 30];
$scores = ["math" => 95, "english" => 88];
echo $nums[0], "\n";
echo $scores["math"];
输出
10
95

Python v3.15.2

v3.15.2
nums = [10, 20, 30]
scores = {"math": 95, "english": 88}
print(nums[0])
print(scores["math"])
输出
10
95

Rust v1.99.1

v1.99.1
use std::collections::HashMap;

fn main() {
    let nums = [10, 20, 30];
    let scores: HashMap<&str, i32> = HashMap::from([("math", 95), ("english", 88)]);
    println!("{}", nums[0]);
    println!("{}", scores["math"]);
}
输出
10
95

TypeScript v26.13.1

v26.13.1
const nums: number[] = [10, 20, 30];
const scores: Record<string, number> = { math: 95, english: 88 };
console.log(nums[0]);
console.log(scores.math);
输出
10
95

语言差异说明

C:以数组与结构体模拟索引/关联数组。

Go:索引数组称切片;关联数组称 map,遍历无序。

Java:关联数组称 Map;Map.of 返回不可变 Map。

JavaScript:索引数组称数组;关联数组称对象。

PHP:索引数组与关联数组用同一个 array 表示。

Python:索引数组称 list;关联数组称 dict,3.7+ 保持插入顺序。

Rust:索引数组称数组;关联数组称 HashMap,遍历无序。