
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来获取并显示汽车信息:
<!DOCTYPE html>
<html lang="en">
<head>
<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>
</head>
<body>
<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}</h2>
<p>Model: ${car.model}</p>
<img src="${car.image}" alt="${car.name}">
</div>
`).join('');
})
.catch(error => console.error('Error fetching the car data:', error));
</script>
</body>
</html>
确保将 cars.json 文件放在与 html 文件相同的目录中或相应地调整获取 url
以上就是JavaScript 的 map() 方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号