我正在處理一個sanity.io專案。我獲取了一些資料,將其存盤在一個陣列中,然后用 express 和 ejs 將其推送到我的前端。
存盤在陣列中的每個post都將顯示為一個卡片。每張卡片都將有一個不同的 css 類,以顯示為小卡片、中卡片、大卡片或超大卡片。
因此,我的目標是回圈瀏覽陣列,并為每個物件附加一個屬性,以便在前端訪問,從而確定卡片的尺寸。
它本質上是這樣的,但這顯然無法擴展,因為我將通過 sanity.io 向網站上傳新的帖子
。 // desired result
posts[0].size = 's'.
posts[1].size = 'm'.
posts[2].size = 'l'.
posts[3].size = 'xl'.
posts[4].size = 's'.
posts[5].size = 'm'.
posts[6].size = 'l'.
posts[7].size = 'xl'.
所以我在想,我必須在陣列中進行回圈,將屬性附加到前4個物件上,然后為后面的4個物件重新啟動這個序列,然后是后面的4個物件,等等。
let items = [];
//獲取并推送給陣列。
client.fetch(query).then((posts) => {
posts.forEach((post) =>/span> {
items.push(post)。
});
//在前4個物件上設定屬性,在第5個、第9個等物件上重新啟動序列。
for(let i = 0; i < posts.length; i =4){
posts[i].size = 's'。
posts[i].size ='m'
posts[i].size = 'l'.
posts[i].size = 'xl'.
}
});
最后一個代碼塊是超級錯誤的,但它只是我現在所處的點。我真的很感謝在這方面的任何幫助或指導
uj5u.com熱心網友回復:
創建一個尺寸陣列。映射posts,并為每個帖子使用物件傳播來創建一個新的物件,并帶有size。從陣列中提取size值。為了得到帖子的相關尺寸,使用當前帖子的index余數(%)從sizes陣列length中獲取。
注意:你使用的是異步獲取,使用承諾或異步等待來創建items,而不是直接推送它。
const sizes = ['s'/span>, 'm', 'l', 'xl'] 。
const items = await client.fetch(query)。 then(posts =>)
posts.map((post, index) =>({.
...帖子。
size: sizes[index % sizes.length]
}))
);
示例:
。const fetch = () => Promise。 resolve([{ title: 'a' }, { title: 'b' }, { title: 'c' }, { title: 'd' }, { title: 'e' }, { title: 'f' }])。)
const sizes = ['s'/span>, 'm'/span>, 'l'/span>, 'xl'/span>]。
const example = async ( ) => {
const items = await fetch()。 then(posts =>)
posts.map((post, index) =>({.
...帖子。
size: sizes[index % sizes.length]
}))
);
console.log( items)。
}
example();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
這應該是作業。
//在前4個物件上設定屬性,在第5、第9等物件上重新啟動序列。
const postProp = ['s','m','l','xl'] 。
for(let a = 0; a < posts.length; a ){
for(let b ofpostProp){
posts[a].size = postProp[b];
a = 1;
}
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/309978.html
標籤:
