map() 方法創(chuàng)建一個新數(shù)組,其中填充了對調(diào)用數(shù)組中每個元素調(diào)用所提供函數(shù)的結(jié)果。
- 這是一個簡單的 map() 示例:
const numbers = [1, 2, 3, 4, 5]; const doubled = numbers.map(num => num * 2); console.log(doubled); // output: [2, 4, 6, 8, 10]
關(guān)注:愛掏網(wǎng)
- 使用map()創(chuàng)建包含汽車信息和顯示的json文件
首先,創(chuàng)建一個名為 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" } ]
關(guān)注:愛掏網(wǎng)
創(chuàng)建一個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>
關(guān)注:愛掏網(wǎng)
確保將 cars.json 文件放在與 html 文件相同的目錄中或相應(yīng)地調(diào)整獲取 url
以上就是JavaScript 的 map() 方法的詳細內(nèi)容,更多請關(guān)注愛掏網(wǎng) - it200.com其它相關(guān)文章!
聲明:所有內(nèi)容來自互聯(lián)網(wǎng)搜索結(jié)果,不保證100%準(zhǔn)確性,僅供參考。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進行處理。