数组随机抽取对象实现对战:去重与undefined问题解决咨询
Hey there! Sounds like you're dealing with two snags when building your random Avengers battle lineup: duplicate heroes getting picked, and your ARR variable ending up full of undefined values. Let's break this down and fix both problems step by step.
First: Why is ARR all undefined?
Chances are, ARR is either being declared without a value, or you're trying to populate it from an empty/incorrect source. Let's start by making sure your base Avengers array is properly defined first—this is the source we'll pull heroes from:
// Make sure your core Avengers array is set up correctly const avengers = [ {id: 1, fullName: "Steve Rogers", avengerName: "Captain America", gender: "Male", city: "New York City", markAv: 10}, {id: 2, fullName: "Tony Stark", avengerName: "IronMan", gender: "Male", city: "New York City", markAv: 9}, // Add the rest of your heroes here... ];
Once this is solid, you can assign your lineup to ARR later without getting undefined values.
Implementing Duplicate-Free Random Selection
To avoid picking the same hero twice, we've got two reliable approaches. Both work by operating on a copy of your original array (so we don't mess up the original list for future selections):
Approach 1: Fisher-Yates Shuffle (Recommended)
This is the standard, efficient way to randomize an array. We'll shuffle a copy of the Avengers list, then grab the first N heroes we need for the lineup:
function getRandomUniqueAvengers(avengerList, teamSize) { // Create a copy of the original array to avoid modifying it const shuffledList = [...avengerList]; let currentIndex = shuffledList.length; let randomIndex; // Fisher-Yates shuffle algorithm while (currentIndex > 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; // Swap elements to randomize [shuffledList[currentIndex], shuffledList[randomIndex]] = [shuffledList[randomIndex], shuffledList[currentIndex]]; } // Return the first `teamSize` elements as our lineup return shuffledList.slice(0, teamSize); } // Example usage: Grab 3 unique Avengers for your battle lineup const ARR = getRandomUniqueAvengers(avengers, 3); console.log(ARR); // This will now have valid, unique hero objects
Approach 2: Pick & Remove (Great for Small Arrays)
If your Avengers list isn't huge, you can randomly pick a hero, remove them from the candidate pool, and repeat until you have your team:
function pickUniqueAvengers(avengerList, teamSize) { const candidatePool = [...avengerList]; const battleLineup = []; for (let i = 0; i < teamSize; i++) { // Stop if we run out of heroes (in case teamSize is bigger than the array length) if (candidatePool.length === 0) break; const randomIdx = Math.floor(Math.random() * candidatePool.length); // Pull the selected hero from the pool and add to our lineup battleLineup.push(candidatePool.splice(randomIdx, 1)[0]); } return battleLineup; } // Example: Grab 4 unique heroes const ARR = pickUniqueAvengers(avengers, 4); console.log(ARR);
Quick Tips to Avoid Issues
- Always use a copy of the original array: If you modify the original
avengersarray directly, future selections will have fewer heroes to choose from. - Check team size vs array length: If you ask for more heroes than exist in the array, both methods will just return all available heroes (no errors, just a full lineup).
- Assign
ARRcorrectly: Make sure you're assigning the result of the function toARRlike the examples above—this fixes theundefinedproblem entirely.
That should give you a perfect, duplicate-free random battle lineup every time!
内容的提问来源于stack exchange,提问作者jaumeserr

