【问题标题】:Remove Saturdays and Sundays from dates array with Jquery使用 Jquery 从日期数组中删除周六和周日
【发布时间】:2018-08-07 10:09:12
【问题描述】:

我正在尝试从我的 jquery 数组中删除周末,但我删除了星期六或星期日,从不同时删除。 你能检查一下我做错了什么吗?

$(dates).each(function( index ) {
    var dt = new Date(dates[index]);
    console.log( index + ": " + dates[index], dt.getDay() );
    if ( dt.getDay() == 0 || dt.getDay() == 6 ) {
        dates.splice(index, 1);
    }
});
console.log(dates);

我认为问题在于我的“if”语句条件。但是当我尝试编写两个单独的块时,我得到了相同的结果。

【问题讨论】:

  • 修改您正在迭代的集合需要额外的工作来“修复”索引。如果删除“当前”元素,“下一个”元素会发生什么? (并且不要使用 jQuery 来遍历日期数组...)
  • 我建议在日期上使用某种形式的过滤器。参考。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: jquery arrays date comparison-operators


【解决方案1】:

尝试过滤。

var weekdaysOnly = dates.filter(function(element, index){
    var dt = new Date(element);
    console.log( index + ": " + element, dt.getDay() );

    //not saturday or sunday
    return (dt.getDay() != 0 && dt.getDay() != 6);
});

console.log(weekdaysOnly);

【讨论】:

  • 谢谢,这比尝试从数组中删除要好得多
【解决方案2】:

不要从原始日期数组中删除值,而是尝试将其保存在临时数组中。这是因为如果您从原始日期数组中删除值,则会导致循环出错。

var date_tmp = [];
$(dates).each(function( index ) {
    var dt = new Date(dates[index]);
    console.log( index + ": " + dates[index], dt.getDay() );
    if ( dt.getDay() != 0 && dt.getDay() != 6 ) {
        date_tmp.push(dates[index]);
    }
});
console.log(date_tmp);

【讨论】:

  • 它也可以。我应该考虑临时变量。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
相关资源
最近更新 更多