我有下面的一段代碼,我想做的是在第 0 個位置添加一條新記錄,然后根據標簽對陣列進行排序。但是我無法讓它作業;我得到一個空陣列。
const array = [{id: '3', name: 'name1'},
{id: '4', name: 'name2'},
{id: '5', name: 'name3'}]
const items = array
.map((sp) => ({ label: sp.name, value: sp.id }))
.splice(0, 0, { label: '', value: '' })
.sort((a, b) => a.label - b.label);
console.log(items);
uj5u.com熱心網友回復:
這是你想要的嗎?
const array = [
{ id: '3', name: 'name1' },
{ id: '4', name: 'name2' },
{ id: '5', name: 'name3' }
]
const items = array.map((sp) => ({ label: sp.name, value: sp.id }))
items.unshift({ label: '', value: ''})
items.sort((a, b) => a.value - b.value);
console.log(items);
輸出:
[
{ label: '', value: '' },
{ label: 'name1', value: '3' },
{ label: 'name2', value: '4' },
{ label: 'name3', value: '5' }
]
這里的方法unshift用于在串列的開頭添加一個新值。sort和都在原地unshift作業,因此它們不回傳修改后的陣列,而是更新現有變數。
uj5u.com熱心網友回復:
這段代碼的錯誤在于.splice() 方法回傳了一個包含被移除項的陣列,并沒有修改原始陣列。因此,在呼叫 .splice() 時不會修改原始陣列。要解決此問題,您可以將 .splice() 的回傳值分配給原始陣列:
const array = [{id: '3', name: 'name1'},
{id: '4', name: 'name2'},
{id: '5', name: 'name3'}]
const items = array
.map((sp) => ({ label: sp.name, value: sp.id }))
.splice(0, 0, { label: '', value: '' })
.sort((a, b) => a.label - b.label);
array = items;
console.log(array);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/535647.html
