我有這樣一個陣列,它的長度可以是任何數字,但不能小于4。我如何在這個陣列中回圈得到一個長度不大于4的新陣列?我試著使用過濾方法,但它回傳了一個空陣列。
這是我的嘗試:
。//array could be any length but not less than 4.
const projects = [
'landing page'。
'組合頁'。
'e-commerce app',
'Dapps'。
'注冊頁面'。
//...甚至更多。
];
const newProjects = projects.filter((project, index, array) => /span> {
return project[index <=4]
})
console.log(newProjects);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
糾正了你的方法;
const projects = ['landing page'/span>, '投資組合頁', '電子商務應用', 'Dapps', '注冊頁',. ....] //陣列可以是任何長度,但不能少于4。
const newProjects = projects.filter((project, index, array) => /span> {
return index < 4;
})
console.log(newProjects)。
請記住,陣列的索引為零。
建議的解決方案:
const newProjects = projects.slice(0,3) 。
uj5u.com熱心網友回復:
你可以簡單地使用slice()來實作:
const projects = ['landing page'/span>, '投資組合頁', '電子商務應用', 'Dapps', '注冊頁面']。
console.log(projects.slice(0,4));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
Slice回傳一個現有陣列的一部分,而不對其進行修改。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/322436.html
標籤:
