map() 方法創建一個新數組,其中填充了對調用數組中每個元素調用所提供函數的結果。
- 這是一個簡單的 map() 示例:
const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(num => num * 2); console.log(doubled); // output: [2, 4, 6, 8, 10]
關注:愛掏網
- 使用map()創建包含汽車信息和顯示的json文件
首先,創建一個名為 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="https://www.php.cn/faq/${car.image}" alt="${car.name}"> `).join(''); }) .catch(error => console.error('Error fetching the car data:', error)); </script>
關注:愛掏網
確保將 cars.json 文件放在與 html 文件相同的目錄中或相應地調整獲取 url
以上就是JavaScript 的 map() 方法的詳細內容,更多請關注愛掏網 - it200.com其它相關文章!
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。