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

如何确保所有Player的configuration具有相同的playerType集合?

问题

我有一个Players类型的数组,每个Player对象包含name和configuration属性,configuration是由{playerType: number, text: string}类型元素组成的数组。用户可点击按钮弹出弹窗,编辑Player的Type和Text,还能动态向player数组添加{Type, Text}对象。

我希望在更新某个Player后,校验所有Player的configuration都包含完全相同的playerType集合(例如若Player1配置了playerType 1和2,其他所有Player的configuration也必须包含这两个类型,不能多也不能少),若不满足则禁用SAVE按钮。

我尝试了以下代码,但不确定是否正确:

const allPlayers: Players[] = 
    [ {name:"Player1",
     configuration: [{playerType: 1, text:"sometext"}, {playerType: 2, text:"some text - on type 2"}]}, /* 其他玩家数据 */];

// Create an array with only the configurations
const allPLayerTypesAndTextInfo = [];
allPlayers.forEach((x)=>allPLayerTypesAndTextInfo.push(x.configuration));

// Create a Set which will have no duplicates type ids
const validPlayerTypes= new Set<number>([]);
allPLayerTypesAndTextInfo.forEach((x)=>validPlayerTypes.add(x.playerType));

// Check if there is a player with configuration that does not include all the ids of the validPlayerTypes
const hasAllPlayerConfigurationsCorrectly = allPlayers.forEach((player) => player.configuration.forEach((config) => validPlayerTypes.has(config.playerType)));

请问如何正确实现该校验逻辑?


解决方案

你当前的代码存在几个关键问题:

  1. 生成validPlayerTypes时,allPLayerTypesAndTextInfo是数组的数组(每个元素是单个玩家的configuration数组),直接遍历它取x.playerType会得到undefined,导致Set里全是无效值。
  2. 用forEach给hasAllPlayerConfigurationsCorrectly赋值是错误的——forEach没有返回值,这个变量最终会是undefined,而且你的逻辑只检查了玩家的配置类型都在全局集合里,却没检查所有全局类型都被该玩家包含,也没限制玩家不能有多余的类型。

正确的校验逻辑是确保每个玩家的configuration对应的playerType集合完全一致(元素完全相同,无遗漏也无多余)。以下是实现代码:

// 辅助函数:把单个玩家的configuration转换成playerType的Set
const getPlayerTypeSet = (player: Players) => 
  new Set(player.configuration.map(config => config.playerType));

// 处理空数组的情况(如果没有玩家,默认校验通过)
if (allPlayers.length === 0) {
  // 可根据业务需求调整逻辑,比如直接返回true
  console.log("无玩家数据,校验通过");
}

// 取第一个玩家的类型集合作为基准
const baseTypeSet = getPlayerTypeSet(allPlayers[0]);

// 校验所有玩家的类型集合是否和基准完全一致
const hasAllPlayerConfigurationsCorrectly = allPlayers.every(player => {
  const currentTypeSet = getPlayerTypeSet(player);
  // 首先检查元素数量是否相同,排除数量不一致的情况
  if (currentTypeSet.size !== baseTypeSet.size) {
    return false;
  }
  // 检查基准集合的每一个元素都存在于当前集合中
  // 数量相同的前提下,只要所有基准元素都存在,两个集合就完全一致
  for (const type of baseTypeSet) {
    if (!currentTypeSet.has(type)) {
      return false;
    }
  }
  return true;
});

// 根据校验结果控制SAVE按钮状态
// 示例:saveButton.disabled = !hasAllPlayerConfigurationsCorrectly;

逻辑说明:

  • 用辅助函数将每个玩家的配置转换为playerType的Set,简化集合对比操作。
  • 以第一个玩家的类型集合为基准,所有其他玩家的集合必须和它完全匹配:
    1. 集合大小一致:避免出现“少一个类型”或“多一个类型”的情况。
    2. 基准集合的所有元素都存在于当前玩家的集合中:确保没有遗漏必要类型。
  • 最终hasAllPlayerConfigurationsCorrectly为布尔值,true表示所有玩家配置符合要求,false则不符合,此时可禁用SAVE按钮。

内容的提问来源于stack exchange,提问作者MMario

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:40:38