是否有更好的方法从数组中获取最接近的较大数字,或者如果scrWidth大于最大数值然后取最大数值?
例如,如果使用500,则返回640,使用5000,则返回1920。
(仅适用于旧版javascript) 答案 0 :(得分:0) 如果在 答案 1 :(得分:0) 您可以使用underscore's 或香草JavaScript: 答案 2 :(得分:0) 使用map和min方法尝试下面的小代码,并观察结果: 谢谢,:) 答案 3 :(得分:0) 下面的函数将提供比参数中提供的数字更大的最接近的数字,如果它在数组中,否则将返回参数中提供的数字,因为其数字大于数组中的所有数字。 var scrWidth = $window.width();
var scrSizes = [320, 480, 640, 768, 1024, 1366, 1600, 1920];
var theSize = 0;
if (scrWidth >= 1920) {
theSize = 1920;
} else {
theSize = scrSizes.find(function(element){return element > scrWidth});
}
4 个答案:
function recursive(list) {
return list
? [list.value, ...recursive(list.rest)]
: [];
}
var list = { value: 1, rest: { value: 2, rest: { value: 3, rest: null } } };
console.log(recursive(list));
可以在|| 1920
产生.find
的末尾添加:undefined
var scrSizes = [320, 480, 640, 768, 1024, 1366, 1600, 1920];
var scrWidth = 12345;
var theSize = scrSizes.find(function(element) { return element > scrWidth; }) || 1920;
console.log(scrWidth, theSize);
var scrWidth = 320;
var theSize = scrSizes.find(function(element) { return element > scrWidth; }) || 1920;
console.log(scrWidth, theSize);
为320时结果应为320,则将scrWidth
替换为>
。bool equals = (ExpRequestItemsWithSection.Count == ActRequestItemsWithSection.Count) &&
ExpRequestItemsWithSection
.Zip(ActRequestItemsWithSection, (left, right) => left.SequenceEqual(right))
.All(item => item);
方法很整齐地做到这一点:filter
function getNextHighestNumber(arr, number) {
return _.filter(arr, function(val) {
return val > number
})[0];
}
getNextHighestNumber([2, 5, 12, 34, 56], 17);
var scrWidth = $window.width();
var scrSizes = [320, 480, 640, 768, 1024, 1366, 1600, 1920];
var theSize = 0;
if (scrWidth >= 1920) {
theSize = 1920;
} else {
var test = scrSizes.map(a=> Math.abs(scrWidth - a));
theSize = scrSizes.find( a => a == scrWidth - Math.min(...test));
theSize = theSize ? theSize : scrSizes.find( a => a == scrWidth + Math.min(...test));
}
function getNextHighestNumber(arr, number) {
for (var i = 0; i < arr.length; i ++) {
if (arr[i] > number) {
return arr[i];
}
}
return number
}