英文:
math.max: find the highest numeric value from a string
问题
如何基于这样的索引获取最高的数字值?
<div class="repeater-item" data-index="0-0"></div>
<div class="repeater-item" data-index="0-1"></div>
<div class="repeater-item" data-index="0-2"></div>
<div class="repeater-item" data-index="1-0"></div>
<div class="repeater-item" data-index="1-1"></div>
<div class="repeater-item" data-index="2-0"></div>
<div class="repeater-item" data-index="2-1"></div>
在我的示例中,必须检索的最高索引是2-1,然后递增:1(2-2、2-3...)
const getIndex = function() {
var num = $(".repeater-item").map(function() {
return $(this).data('index');
}).get();
return Math.max.apply(Math, num); // 失败
}
这段代码可以成功获取索引,但无法根据我的示例计算最高索引。
英文:
How to get the highest numeric value based on indexes like this ?
<div class="repeater-item" data-index="0-0"></div>
<div class="repeater-item" data-index="0-1"></div>
<div class="repeater-item" data-index="0-2"></div>
<div class="repeater-item" data-index="1-0"></div>
<div class="repeater-item" data-index="1-1"></div>
<div class="repeater-item" data-index="2-0"></div>
<div class="repeater-item" data-index="2-1"></div>
In my example, the highest index that must be retrieved is 2-1 in order to increment, thereafter: 1 (2-2, 2,3 ....)
const getIndex = function()
{
var num = $(".repeater-item").map(function() {
return $(this).data('index');
}).get();
return Math.max.apply(Math, num); // Fail
}
This code fetches the indexes fine but fails to calculate the highest index based on my example
答案1
得分: 0
You can for example, sort an array using data-index as a criteria.
Then get the first element in the sorted array:
const getMaxIndex = () => {
const sorted = $(".repeater-item").sort(function (a, b) {
const indexANumeric = +$(a).data('index').replace("-", "");
const indexBNumeric = +$(b).data('index').replace("-", "");
return indexBNumeric - indexANumeric;
}).get();
return $(sorted[0]).data('index');
}
英文:
You can for example, sort an array using data-index as a criteria.
Then get first element in the sorted array:
const getMaxIndex = () => {
const sorted = $(".repeater-item").sort(function (a, b) {
const indexANumeric = +$(a).data('index').replace("-", "");
const indexBNumeric = +$(b).data('index').replace("-", "");
return indexBNumeric - indexANumeric;
}).get();
return $(sorted[0]).data('index');
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论