对象解构 API 数据以便更容易抓取?
Object destructuring API data so it's easier to grab?
let pokeApi = ()=>{
let randomize = Math.floor(Math.random() * 898);
let url = `https://pokeapi.co/api/v2/pokemon/${randomize}`
fetch(url)
.then((res) => res.json())
.then((pokeData) => {
console.log(pokeData)
})
}
我以前写过这个,我自己手动输入 pokeData 来查找信息。例子是..
pokeHeight.textContent = `Height: ${data.height} ft `;
pokeWeight.textContent = `Weight: ${data.weight} KG `;
1;
pokeTemperment.textContent = `Type: ${data.types[0].type["name"]} `;
spriteImage.src = data.sprites["front_shiny"];
pokeName.textContent = data.name.toUpperCase();
hp.textContent = `HP: ${data.stats[0]["base_stat"]}`;
但是我的程序员朋友告诉我尝试对它进行对象解构,因为他通常是这样做的。我知道对象解构在技术上是什么,但我不确定如何设置它以便将其应用于数据属性。
const {height, weight, hp} = x
但是上面const中的高度如何=获取数据?
您应该对 fetch 的 result 应用析构。你可以这样做:
let pokeApi = ()=>{
let randomize = Math.floor(Math.random() * 898);
let url = `https://pokeapi.co/api/v2/pokemon/${randomize}`
fetch(url)
.then((res) => res.json())
.then(({height, weight}) => {
console.log('Height: ', height);
console.log('Weight: ', weight)
})
}
let pokeApi = ()=>{
let randomize = Math.floor(Math.random() * 898);
let url = `https://pokeapi.co/api/v2/pokemon/${randomize}`
fetch(url)
.then((res) => res.json())
.then((pokeData) => {
console.log(pokeData)
})
}
我以前写过这个,我自己手动输入 pokeData 来查找信息。例子是..
pokeHeight.textContent = `Height: ${data.height} ft `;
pokeWeight.textContent = `Weight: ${data.weight} KG `;
1;
pokeTemperment.textContent = `Type: ${data.types[0].type["name"]} `;
spriteImage.src = data.sprites["front_shiny"];
pokeName.textContent = data.name.toUpperCase();
hp.textContent = `HP: ${data.stats[0]["base_stat"]}`;
但是我的程序员朋友告诉我尝试对它进行对象解构,因为他通常是这样做的。我知道对象解构在技术上是什么,但我不确定如何设置它以便将其应用于数据属性。
const {height, weight, hp} = x
但是上面const中的高度如何=获取数据?
您应该对 fetch 的 result 应用析构。你可以这样做:
let pokeApi = ()=>{
let randomize = Math.floor(Math.random() * 898);
let url = `https://pokeapi.co/api/v2/pokemon/${randomize}`
fetch(url)
.then((res) => res.json())
.then(({height, weight}) => {
console.log('Height: ', height);
console.log('Weight: ', weight)
})
}