ReactJS中如何生成1至指定数值间排除已占用床位的数组并渲染为下拉选项?
Let's break down what's wrong with your current implementation and fix it to get the expected result:
Core Issue in Your Code
The main problem lies in the filter condition:
let filtered = numArr.filter((x) => x !== occupiedBeds)
Here, you're comparing a single bed number x directly to the entire occupiedBeds array. A number can never equal an array, so this condition always returns true—meaning no occupied beds get filtered out at all. That's why your function isn't excluding values like 2 and 8 as expected.
Additional Edge Case to Handle
You should also guard against cases where patientsData is undefined or null. Your current patientsData && ... logic will leave occupiedBeds as undefined if patientsData doesn't exist, which will throw errors when you try to use includes() on it later.
Corrected Code
Here's the fixed version with key improvements explained:
const vacantBeds = (number) => { // Ensure we always have an array to map over, even if patientsData is missing const occupiedBeds = (patientsData || []).map((patient) => Number(patient.room.slice(-1)[0].bed) ); // Generate array from 1 to the given number (this part was already correct!) const numArr = [...Array(number).keys()].map((x) => x + 1); // Filter out any numbers present in the occupiedBeds array const filtered = numArr.filter((x) => !occupiedBeds.includes(x)); // Render the vacant beds as option elements return filtered.map((bed) => ( <option key={bed} value={bed}> {bed} </option> )); };
Key Changes Made
- Safe
patientsDatahandling: Used(patientsData || [])to guarantee we always have an array to work with, eliminating potentialundefinederrors. - Fixed filter logic: Replaced the invalid array-to-number comparison with
!occupiedBeds.includes(x)—this correctly checks if the current bed number is in the occupied list. - Improved variable declarations: Switched from
lettoconstfor variables that don't get reassigned, following modern JavaScript best practices for immutability.
Testing with Your Example
If number = 10 and occupiedBeds = [2,8], this code will generate the exact expected array:[1,3,4,5,6,7,9,10]
And render each value as a properly formatted <option> element.
内容的提问来源于stack exchange,提问作者Ahmed Ibrahim

