在大量数组中搜索数字的优雅方式 (jQuery)

Elegant way to search a number in a large amount of arrays (jQuery)

我想构建一个时尚尺码查找器来帮助客户找到正确的尺码。

示例: 胸围78-81cm对应XS码

现在我当然可以构建无限数量的数组,if 和 else 语句,但这必须以某种方式更优雅吗?

$('.sub').click(function(){
var brust = $('#brust').val();
var brustxs = ['78','79','80','81'];
var brusts = ['82','83','84','85'];
var brustm = ['86','87','88','89'];
var brustl = ['90','91','92','93','94','95','96','97'];
var brustxl = ['98','99','100','101','102'];
    
    if( $.inArray(brust, brustxs) !== -1 ) {
    alert('found in'+' XS');
    }else if ( $.inArray(brust, brusts) !== -1 ) {
    alert('found in'+' S');
    }else {
    alert('nothing');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input label="brustumfang" value="80" type="text" id="brust">
<input type="submit" class="sub">

您可以拥有一个带有定义的对象并循环遍历它,而无需更改与其匹配的代码。

例如:

var sizes = {
    xs: [78,79,81],
    s: [82,83,84,85]

}

for( var size in sizes ){
    vas sizeArray = sizes[size];
    if( $.inArray(brust, sizeArray ) > -1 ) {
        alert('found in'+ size  );
        break; //important bit 
    }
}

或者为了获得更好的性能,您可以像这样存储尺寸:

var sizes = [
    { size: "XS", range:[78,79,80] },
    { size: "S", range:[81,82,83] }
]

或者另一个想法只是存储每个尺寸的断点从到并检查尺寸是否适合该范围,如:

var sizes = [

    { size: "XS", from: 78, to:80},
    { size: "S", from: 81, to:85},

];

$.each(sizes, function(index,sizeInfo){ 
    //using jQuery each same as foreach for array

    if( brust>=sizeInfo.from && brust<=sizeInfo.to ){
         alert('found in'+ sizeInfo.size );
         return false; //in jQuery is same as break; 
    }
});

您可以做的不是将每个值都保存在一个数组中,而是保存一个大小数组来跟踪最小值、最大值和标签。然后你可以简单地遍历尺寸并找到匹配的尺寸(其中最小尺寸 <= brustSize 和最大尺寸 >= brustSize),如下所示:

let brustSizes = [{min: 78, max: 81, label: 'xs'}, {min: 82, max: 85, label: 's'}, {min: 86, max: 89, label: 'm'}, {min: 90, max: 97, label: 'l'}, {min: 98, max: 102, label: 'xl'}];

function getSize (brustSize) {
  let size = brustSizes.find(size => size.min <= brustSize && size.max >= brustSize);
  return size && size.label
}

console.log(getSize(81));
console.log(getSize(0));
console.log(getSize(84));
console.log(getSize(87));
console.log(getSize(96));
console.log(getSize(98));