如何解决Math.max无法获取data-index中最高x-y格式索引值的问题?
解决x-y格式索引的最大值获取问题
你当前代码调用Math.max.apply(Math, num)失败的核心原因有两个:
$(this).data('index')获取的是字符串类型,这类带横杠的字符串无法直接转换为有效数字,导致Math.max处理时所有元素都变成NaN,最终返回NaN。- 即使能转换,字符串的ASCII码比较逻辑也不符合我们对x-y格式索引的大小判断规则(我们需要先比较x部分数值,x相等再比较y部分)。
以下是几种可行的解决方案:
方法一:使用reduce逐个比较(推荐)
遍历所有索引,每次保留当前最大的索引值,核心是将每个索引拆分为x和y两个数字,按规则比较:
const getIndex = function() { const indexes = $(".repeater-item").map(function() { return $(this).data('index'); }).get(); return indexes.reduce((maxIdx, currIdx) => { const [maxX, maxY] = maxIdx.split('-').map(Number); const [currX, currY] = currIdx.split('-').map(Number); // 比较规则:x大则当前索引更大;x相等时y大的更大 if (currX > maxX || (currX === maxX && currY > maxY)) { return currIdx; } return maxIdx; }, indexes[0]); }
方法二:排序后取最后一个元素
通过自定义排序规则对索引数组排序,排序完成后最后一个元素就是最大值:
const getIndex = function() { const indexes = $(".repeater-item").map(function() { return $(this).data('index'); }).get(); indexes.sort((a, b) => { const [aX, aY] = a.split('-').map(Number); const [bX, bY] = b.split('-').map(Number); if (aX !== bX) { return aX - bX; } return aY - bY; }); return indexes[indexes.length - 1]; }
方法三:转换为可比较数值(限固定位数场景)
如果你的x和y都是固定位数的数字(比如均为1位),可以把索引转成组合数字来比较,最后再转回x-y格式:
const getIndex = function() { const numArr = $(".repeater-item").map(function() { const [x, y] = $(this).data('index').split('-'); return Number(x) * 10 + Number(y); }).get(); const maxNum = Math.max.apply(Math, numArr); const x = Math.floor(maxNum / 10); const y = maxNum % 10; return `${x}-${y}`; }
注意:此方法仅适用于y位数固定的场景,若y可能是多位数(如"2-10"),需要调整乘数(比如用100、1000),通用性不如前两种方法。
内容的提问来源于stack exchange,提问作者Raphael M
相关产品推荐
相关产品推荐

