修改以减少es6

时间:2017-12-17 21:01:12

标签: javascript arrays ecmascript-6 reduce

我想用文本内容flexbox收集所有li并减少秒的总时间并将其返回。我做到了,但是如何将代码重写为单个reduce函数。结果应该是以秒为单位的数据时间总和

HTML

<li data-time="3:07">Flexbox Video</li>
<li data-time="5:59">Redux Video</li>
...

JS

const listItems = [...document.querySelectorAll('li')];

const flexBoxItem = listItems
    .filter(item => item.textContent.includes('Flexbox'))
    .map(item => item.dataset.time)
    .map(item => {
        let parts = item.split(':').map(i => parseFloat(i))
        return (parts[0] * 60) + parts[1]
    })
    .reduce((prev, next) => prev + next, 0)

3 个答案:

答案 0 :(得分:6)

我会过滤,然后减少,因为它更具功能性和可读性:

&#13;
&#13;
const listItems = [...document.querySelectorAll('li')];

const flexBoxTime = listItems
  .filter(item => item.textContent.includes('Flexbox'))
  .reduce((prev, item) => {
    const [min, sec] = item.dataset.time.split(':');
    return prev + (+min * 60) + +sec
  }, 0);
  
console.log(flexBoxTime);
&#13;
<li data-time="3:07">Flexbox Video</li>
<li data-time="5:59">Redux Video</li>
&#13;
&#13;
&#13;

但是,如果你想要将它们组合起来,因为性能是一个问题:

&#13;
&#13;
const listItems = [...document.querySelectorAll('li')];

const flexBoxTime = listItems
  .reduce((prev, item) => {
    if(!item.textContent.includes('Flexbox')) {
      return prev;
    }
    
    const [min, sec] = item.dataset.time.split(':');
    return prev + (+min * 60) + +sec
  }, 0);
  
console.log(flexBoxTime);
&#13;
<li data-time="3:07">Flexbox Video</li>
<li data-time="5:59">Redux Video</li>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

另一种方法是使用旧样式循环(是的,我不回答问题):

 let result = 0;
 for(const item of listItems){
   if(!item.textContent.includes('Flexbox'))
      continue;
   const [mins, secs] = item.dataset.time.split(":");
   result += mins * 60 + +secs;
 }

答案 2 :(得分:0)

缩小和优化的替代方案:

&#13;
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>

<script>
  $(document).ready(function() {
    $(function() {
      $("#from_date").datepicker();
      $("#to_date").datepicker();
    });
  });
</script>

<input id="from_date">
<input id="to_date">
&#13;
const time = [].reduce.call(document.getElementsByTagName('li'), (r, v) => v.textContent
    .includes('Flexbox') ? (v = v.dataset.time.split(':'), v[0] * 60 + +v[1] + r) : r, 0)

console.log(time)
&#13;
&#13;
&#13;