javascript - 以日期为键的映射无法正确检索项目

标签 javascript reactjs

我正在尝试构建一个以下类型的 map : 键:日期 -> 值:对象列表

为此目的,我有以下代码:

componentDidMount(){
    let allPredictions = listAllPredictions();
    this.predictions = new Map();

    for (let i = 0; i<allPredictions.length; i++) {
        let prediction = allPredictions[i];

        if (!this.predictions.has(prediction.tsPredictionFor)){
            this.predictions.set(prediction.tsPredictionFor, []);
        }

        let predictionsForDate = this.predictions.get(prediction.tsPredictionFor);
        predictionsForDate.push(prediction);
    }
    let d = new Date(2019, 1, 10, 0, 0, 0, 0);

    console.log('Prediction for date ' + d + ': ' + this.predictions.get(d));
    console.log('All predictions: ')
    console.log(this.predictions)

    //this.setState({activePredictions: listActivePredictions()})
}

似乎不起作用的是 map 无法正确比较 2 个日期。我注意到 .has 函数始终返回 false,即使存在具有相同日期的条目。

这些是日志: logs

如您所见,以下索引具有相同的日期:0 和 3、1 和 4、2 和 5,但由于某种原因, map 无法检测到这一点,因此对于每个条目,它都会创建一个新列表(如您可以看到:数组(1))。

这背后的原因是什么?

最佳答案

Date 对象不会覆盖 === 运算符,这意味着要比较的是它们是否具有相同的引用。

作为一个简单的示例,请使用以下代码:

console.log(new Date() === new Date())

无论如何,这总是会返回 false,因为创建的两个对象都有不同的引用。

但是,您可以使用通过将它们格式化生成的字符串作为键:

console.log((new Date()).getTime() === (new Date()).getTime())

关于javascript - 以日期为键的映射无法正确检索项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54291434/

相关文章:

javascript - 有条件地删除html节点

javascript - 将 React 组件构造函数作为属性传递给另一个组件时管理状态

javascript - 如何解构箭头符号中的参数

javascript - 设置状态(...): Can only update a mounted or mounting component even if component is mounted

javascript - ng-Table 点击表格标题时出现表格内容

javascript - 如何使用单击的 X 和 Y 坐标移动图像

javascript - 根据键值对对象数组进行排序或排序

javascript - 为什么不显示引导工具提示的样式?

css - 样式未加载 webpack

reactjs - CloudFront错误: This XML file does not appear to have any style information associated with it