Javascript 跳出地图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49717942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:27:38  来源:igfitidea点击:

Break out of map

javascriptloopsdictionaryif-statement

提问by Benas Lengvinas

so i have this problem where if the value in the array is higher than entered value it should do something and then stop the loop and don't touch the remaining values in the array.. Here's the code so far:

所以我有这个问题,如果数组中的值高于输入的值,它应该做一些事情然后停止循环并且不要触摸数组中的剩余值..这是到目前为止的代码:

const percentages = [];
let enteredValue = parseInt(event.target.value, 10);

range.map((rangeValue, i) => {
  if (rangeValue <= enteredValue) {
    percentages.push(100);
    enteredValue = enteredValue - rangeValue;
  } else {
    percentages.push(enteredValue * 100 / (rangeValue));

    return;
  }
});

回答by George Bailey

Using .someyou can get iteration functionally similar to .forEach, mapor forloop but with the ability to breakthrough returninstead.

使用.some您可以获得与.forEach,mapforloop功能相似的迭代,但具有break通过的能力return

range.some(function(rangeValue , i) {
  if (rangeValue <= enteredValue) {
    percentages.push(100);
    enteredValue = enteredValue - rangeValue;
    return true
  }
   percentages.push(enteredValue * 100 / (rangeValue));
});

Read more about .somein es6here

.some此处阅读更多信息es6

回答by Jonas Wilms

Just use a good old for loop:

只需使用一个很好的 for 循环:

 const percentages = [];
 let enteredValue = parseInt(event.target.value, 10);

 for(const range of ranges) {
   percentages.push(Math.min(100, (enteredValue / range) * 100));
   enteredValue -= range;
   if(enteredValue <= 0) break;
 }

回答by Willem van der Veen

The other answers are perfectly sufficient. However, I would like to add that the mapfunction isn't best used for performing iterations. What the mapfunction does is perform the as argument passed in callback on every element of the array. It then returns the new array. So map is more usefull when you are in need of a mutated copy of the Array (e.g. all the elements multiplied by 10).

其他答案完全足够。但是,我想补充一点,该map函数不适合用于执行迭代。该map函数的作用是对数组的每个元素执行回调中传递的 as 参数。然后返回新数组。因此,当您需要数组的变异副本(例如,所有元素乘以 10)时,map 更有用。

For your purposes other logic like a regular for loop will be a more elegant solution.

出于您的目的,其他逻辑(如常规 for 循环)将是更优雅的解决方案。