玩家权重匹配系统key达两位数时val.foreach is not a function报错如何解决
问题根因分析
- 函数返回值结构错误:
newCombine最后执行return { ...groups, ...nonMatched }时,nonMatched是存储未匹配单个玩家的数组,用展开运算符放到对象里时,会自动把数组下标转为字符串key,对应value是单个玩家对象(不是长度为2的数组)。当未匹配玩家数≥10时,下标key变成两位数,后续错误的遍历逻辑命中这些key,拿到单个对象调用forEach就触发报错。 - 输出和遍历逻辑混乱:没有区分匹配成功的分组和未匹配玩家,导致不需要的未匹配数据也进入了处理流程。
修复代码
修改newCombine函数
将匹配分组和未匹配玩家分开返回,避免结构混淆:
function newCombine(data, difference) { let nonMatched = [...data] const groups = {} for (let i = 0; i < nonMatched.length - 1; i++) { const first = nonMatched[i] inner: for (let j = nonMatched.length - 1; j > i; j--) { const second = nonMatched[j] const delta = Math.abs(first.weight - second.weight) if (delta <= difference && first.entryName !== second.entryName) { const groupKey = `${first.weight}_${second.weight}` groups[groupKey] = [first, second] nonMatched = nonMatched.filter( obj => obj.entryID != first.entryID && obj.entryID != second.entryID ) i = -1 break inner } } } return { groups, nonMatched } }
修改success回调逻辑
仅处理匹配成功的分组,跳过未匹配玩家,同时满足仅输出长度为2的匹配数据的要求:
$(document).ready(function() { let resulta = []; var entry_list =$('#entry_list1').DataTable({ "ajax": { "url": "<?php echo site_url('report/controlget')?>", "type": "get", success: function(data) { const source = data; const { groups, nonMatched } = newCombine(source, 15); // 仅输出匹配成功的长度为2的分组 console.log(groups); let html = ""; // 直接遍历匹配分组,不需要处理未匹配数据 Object.values(groups).forEach(group => { if(group.length !== 2) return group.forEach(function(value, index) { var entryIDs = index == 0 ? "entryIDM[]" : "entryIDW[]" var players = index == 0 ? "playerM[]" : "playerW[]" var weights = index == 0 ? "weightM[]" : "weightW[]" var legBands = index == 0 ? "legBandM[]" : "legBandW[]" var wingBands = index == 0 ? "wingBandM[]" : "wingBandW[]" html += `<input type="text" name="${entryIDs}" value="${value.entryID}"> <input type="text" name="${players}" value="${value.entryName}"> <input type="text" name="${weights}" value="${value.weight}"> <input type="text" name="${legBands}" value="${value.legBand}"> <input type="text" name="${wingBands}" value="${value.wingBand}"> <input type="text" name="eventID" value="${value.eventID}"> ` }) }) document.getElementById("resulta").innerHTML = html } } }); });
内容的提问来源于stack exchange,提问作者Ulquiorra Schiffer
相关产品推荐
相关产品推荐

