繁体   English   中英

通过断点而不是多个 else if 语句查找索引

[英]Find index by breakpoints instead of multiple else if statements

我正在尝试根据人的身高生成尺寸。 目前我的程序可以工作,但我想找到一种更短的方法来获取大小,而不是使用所有这些else if语句。 我想循环通过“断点”来找到相应的索引。

这是我的原始代码+我的想法。

 const sizes = ['xxs', 'xxs or xs', 'xs', 'xs or s'] // Goes on for all sizes... function generateSize(height) { let size; if (height < 142) { size = sizes[0]; } else if (height >= 142 && height < 148) { size = sizes[1]; } else if (height >= 148 && height < 154) { size = sizes[2]; } else if (height >= 154 && height < 160) { size = sizes[3]; // Goes on for all sizes... } else { size = 'larger...'; } return size; } // Example of what I had in mind. const heightBreakpoints = [142, 148, 154, 160]; function getByBreakpoints(breakpoints, height){ // Part where I am stuck. let index; // Loop through breakpoints... return index; } const sizeIndex = (getByBreakpoints(heightBreakpoints, 158)); const s = sizes[sizeIndex];

我认为你可以通过调整你的起始数据结构来大大简化这一点。 如果我们有一个将大小及其断点联系在一起的对象数组怎么办:

const sizeMap = [
    { maxHeight: 142, size: 'xxs' },
    { maxHeight: 148, size: 'xxs or xs' },
    { maxHeight: 154, size: 'xs' },
    { maxHeight: 160, size: 'xs or s' },
]

const getSize = height => sizeMap.find(item => height < item.maxHeight).size

console.log(getSize(143))

数组 function find返回满足您条件的第一个值。 这种方法工作的先决条件是让您的数组对象的高度按升序排列。

 const sizes = ['xxs', 'xxs or xs', 'xs', 'xs or s', "even another one here"] // Goes on for all sizes... function generateSize(height){ let size; let left = 142; let right = 142; // Initialize the variables for comparison // Left and right comparison based on position of "&" // This is just user-defined for(var i = 0; i < sizes.length; i++){ if(height < right){ size = sizes[i]; return size; } else { // add counter from here // This takes us to the next item in the array i += 1; // add right comparison with intervals of 6 right += 6; if(height >= left && height < right){ size = sizes[i]; return size; } else { // add left comparison with intervals of 6 left += 6; // revert the counter to its initial value i -= 1; } } } } console.log("First: " + generateSize(141)) console.log("Second: " + generateSize(147)) console.log("Third: " + generateSize(153)) console.log("Fourth: " + generateSize(159)) console.log("Last: " + generateSize(161)); // Note this 161, which will return the new last value in the array

这假设您的大小间隔为 6,(它们是)并返回与数组对应的相应值

if(height<160){
height-=142;
if(height<0){size=sizes[0]}
else{
size=sizes[(hieght)%6]
}
}
else{
size='larger...'
}

检查这是否适用于所有情况我困了

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM