You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中如何生成1至指定数值间排除已占用床位的数组并渲染为下拉选项?

Fixing the Vacant Beds Generation Code

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 patientsData handling: Used (patientsData || []) to guarantee we always have an array to work with, eliminating potential undefined errors.
  • 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 let to const for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 17:22:28