map() 方法创建一个新数组,其中填充了对调用数组中每个元素调用所提供函数的结果。
const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(num => num * 2); console.log(doubled); // output: [2, 4, 6, 8, 10]
首先,创建一个名为 cars.json 的 json 文件:
[ { "name": "toyota camry", "model": "2023", "image": "https://example.com/toyota_camry.jpg" }, { "name": "honda accord", "model": "2022", "image": "https://example.com/honda_accord.jpg" }, { "name": "tesla model 3", "model": "2024", "image": "https://example.com/tesla_model_3.jpg" } ]
创建一个html文件index.html并使用javascript来获取并显示汽车信息:
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Car Display</title><style> .car { border: 1px solid #ddd; padding: 10px; margin: 10px; text-align: center; } .car img { width: 100px; height: auto; } </style><h1>Car Information</h1> <div id="car-container"></div> <script> // Here we have Fetch the car data fetch('cars.json') .then(response => response.json()) .then(data => { const carContainer = document.getElementById('car-container'); carContainer.innerHTML = data.map(car => ` <div class="car"> <h2>${car.name} <p>Model: ${car.model} <img src="${car.image}" alt="${car.name}"> `).join(''); }) .catch(error => console.error('Error fetching the car data:', error)); </script>
确保将 cars.json 文件放在与 html 文件相同的目录中或相应地调整获取 url