3 回答

TA貢獻1848條經(jīng)驗 獲得超6個贊
我認為對數(shù)組進行洗牌會更有用。并且您還應該更改常量的定義。
你可以嘗試這樣的事情:
const shuffle = arr => [...arr].sort(() => Math.random() - 0.5);
const list = [
{id: 0, img: "img", key: 0, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 1, img: "img", key: 0, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 2, img: "img", key: 2, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 3, img: "img", key: 2, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 4, img: "img", key: 3, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 5, img: "img", key: 3, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 6, img: "img", key: 4, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 7, img: "img", key: 4, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 8, img: "img", key: 5, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 9, img: "img", key: 5, class: "wrap", classFlip: "wrap card-flip", match: false}
];
const newList = shuffle(list);
console.log(newList);

TA貢獻1824條經(jīng)驗 獲得超8個贊
這是一個具有不可變數(shù)據(jù)范例的純函數(shù):
const shuffleArray = (arr) => {
// leave arr as it is (immutable data in react)
const copy = [...arr];
// our output array
const output = [];
// while there are items
while (copy.length > 0) {
// removes 1 random element from copy and adds it to output;
output.push(copy.splice(Math.floor(Math.random() * copy.length), 1));
}
// return our random array
return output;
};

TA貢獻2016條經(jīng)驗 獲得超9個贊
您應該構建一個函數(shù)來隨機洗牌項目。嘗試下面。
const list = [
{id: 0, img: "img", key: 0, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 1, img: "img", key: 0, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 2, img: "img", key: 2, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 3, img: "img", key: 2, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 4, img: "img", key: 3, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 5, img: "img", key: 3, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 6, img: "img", key: 4, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 7, img: "img", key: 4, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 8, img: "img", key: 5, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 9, img: "img", key: 5, class: "wrap", classFlip: "wrap card-flip", match: false}
];
const shuffle = array => {
let currentIndex = array.length,
temporaryValue,
randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
};
console.log(shuffle(list))
添加回答
舉報