2 回答

TA貢獻(xiàn)1820條經(jīng)驗 獲得超10個贊
嘗試在 for 循環(huán)中使用 let i 之前添加它。請參閱下面的示例。
for (let i in newArray) {
if (i.version.startsWith('iPad')) {
newlist.push(newlist.splice(i, 1)[0]);
}
}

TA貢獻(xiàn)1951條經(jīng)驗 獲得超3個贊
原代碼的幾個問題。
失蹤
const
/let
上i
in
循環(huán)應(yīng)該是of
。或者可能不是。以下幾行似乎假定i
既是索引又是條目。newlist
沒有定義。它似乎試圖在迭代數(shù)組的同時對其進(jìn)行變異。
我想你正在尋找更像這樣的東西。
const newArray = sortBy(getData(), 'version').reverse()
const nonIPads = []
const iPads = []
for (const entry of newArray) {
if (entry.version.startsWith('iPad')) {
iPads.push(entry)
} else {
nonIPads.push(entry)
}
}
const all = [...nonIPads, ...iPads]
console.log(all)
function sortBy(array, property) {
return [...array].sort((a, b) => {
const valueA = a[property]
const valueB = b[property]
if (valueA === valueB) {
return 0
}
return valueA < valueB ? -1 : 1
})
}
function getData() {
return [
{version: 'f'},
{version: 'a'},
{version: 'd'},
{version: 'iPad 3'},
{version: 'iPad 1'},
{version: 'iPad 4'},
{version: 'e'},
{version: 'c'},
{version: 'g'},
{version: 'b'},
{version: 'iPad 2'}
]
}
添加回答
舉報