4Manuals

  • PDF Cloud HOME

javascript:较大一侧数组中最接近的数字 Download

    CSS / JS-如何覆盖一个孩子而不是其他孩子的父母过渡 反应:更改方向后触发重新渲染和offsetWidth的重新计算 我的Javascript从'string'转换为'integer'或'number'无效 如何删除外部索引并合并内部json 在React Native 图片无法通过javascript刷新 如何在react图表上的datakey中操作DateTime 如何在Swift中将数组的每个元素与下一个数组的每个元素相乘? 字符串数组在for循环中初始化时忽略索引0 在Cypress中保存变量

  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});
  }

是否有更好的方法从数组中获取最接近的较大数字,或者如果scrWidth大于最大数值然后取最大数值? 例如,如果使用500,则返回640,使用5000,则返回1920。 (仅适用于旧版javascript)

4 个答案:

答案 0 :(得分:0)

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替换为>。

答案 1 :(得分:0)

您可以使用underscore's bool equals = (ExpRequestItemsWithSection.Count == ActRequestItemsWithSection.Count) && ExpRequestItemsWithSection .Zip(ActRequestItemsWithSection, (left, right) => left.SequenceEqual(right)) .All(item => item); 方法很整齐地做到这一点:

filter

或香草JavaScript:

 function getNextHighestNumber(arr, number) {
      return _.filter(arr, function(val) { 
        return val > number 
      })[0];
    }

 getNextHighestNumber([2, 5, 12, 34, 56], 17);

答案 2 :(得分:0)

使用map和min方法尝试下面的小代码,并观察结果:

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));
  }

谢谢,:)

答案 3 :(得分:0)

下面的函数将提供比参数中提供的数字更大的最接近的数字,如果它在数组中,否则将返回参数中提供的数字,因为其数字大于数组中的所有数字。

 function getNextHighestNumber(arr, number) {
          for (var i = 0; i < arr.length; i ++) {
            if (arr[i] > number) {
              return arr[i];
            }
          }
         return number
  }



Similar searches
    在搜索委托buildResults()中使用setstate()吗? 是否可以复制Azure DevOps构建并在本地运行? 宏VBA-具有2个Y轴的xlColumnClustered 由于我的PHP preg_match函数不适用于以下代码 无法使用Selenium Java测试用例调用HTML FRAME链接