我試圖將提示的結果與陣列中各種物件的屬性相匹配。(即,如果輸入的城市與列出的物件之一的名稱匹配,則回傳一致的溫度)
let cities = [
{
name: "San Luis Obispo",
temp: 16,
uv: 1,
humidity: 5,
elevation: 28,
wind: 2,
},
{
name: "Morro Bay",
temp: 11,
uv: 2,
humidity: 8,
elevation: 1,
wind: 8,
}]
let city = prompt("Enter a city");
if (city === cities.name){
alert(`It is currently ${temp}°C in ${city}`);
}
uj5u.com熱心網友回復:
let cities = [
{
name: "San Luis Obispo",
temp: 16,
uv: 1,
humidity: 5,
elevation: 28,
wind: 2,
},
{
name: "Morro Bay",
temp: 11,
uv: 2,
humidity: 8,
elevation: 1,
wind: 8,
}]
let cityName = prompt("Enter a city");
const city = cities.find(cityX => {
return cityName === cityX.name
})
if (city){
alert(`It is currently ${city.temp}°C in ${cityName}`);
}
uj5u.com熱心網友回復:
在物件陣列 ( ) 上運行 for 回圈cities,檢查陣列中的每個城市:
let cities = [{
name: "San Luis Obispo",
temp: 16,
uv: 1,
humidity: 5,
elevation: 28,
wind: 2,
},
{
name: "Morro Bay",
temp: 11,
uv: 2,
humidity: 8,
elevation: 1,
wind: 8,
}
]
let city = prompt("Enter a city");
for (let i = 0; i < cities.length; i ) {
if (city == cities[i].name) {
alert(`It is currently ${cities[i].temp}°C in ${city}`);
}
}
uj5u.com熱心網友回復:
以下代碼應該可以作業。評論中的解釋。
const cityName = prompt("Enter a city").trim() // save city given in prompt in variable "cityName" (remove trailing whitespace via trim)
for(const city of cities) { // execute following code for all cities; the current city will be saved in variable "city"
if(city.name === cityName) { // check if name of currently checked city matches cityName
// if the city name matched, the variable "city" contains the correct city
alert(`It is currently ${city.temp}°C in ${cityName}`) // give correct alert relative to matched city
break // skip the rest of the cities
}
}
uj5u.com熱心網友回復:
嘗試這個
let city = prompt("Enter a city");
Cities.forEach(current=>{
if (city.trim() === current.name){
alert(`It is currently ${current.temp}°C in ${city}`);
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/440293.html
上一篇:Haskell-型別和if陳述句
