3 回答

TA貢獻1826條經(jīng)驗 獲得超6個贊
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,(它們是)并返回與數(shù)組對應的相應值

TA貢獻1848條經(jīng)驗 獲得超10個贊
我認為你可以通過調整你的起始數(shù)據(jù)結構來大大簡化這一點。如果我們有一個將大小及其斷點聯(lián)系在一起的對象數(shù)組怎么辦:
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))
數(shù)組函數(shù)find返回滿足您條件的第一個值。這種方法工作的先決條件是讓您的數(shù)組對象的高度按升序排列。

TA貢獻1862條經(jīng)驗 獲得超7個贊
if(height<160){
height-=142;
if(height<0){size=sizes[0]}
else{
size=sizes[(hieght)%6]
}
}
else{
size='larger...'
}
檢查這是否適用于所有情況我困了
添加回答
舉報