为什么结果包含多个具有相同值的副本

Why does the result contain multiple copies of the same value?

本文关键字:副本 结果 包含多 为什么      更新时间:2023-09-26

使用以下JavaScript,为什么输出包含相同值的多个副本?

reduce = function(docs) {
  var values = [];
  docs.forEach(function(doc) {
    if (values.indexOf(doc.value) != -1) return;
    values.push(doc.value.toDateString());
  });
  return values;
}
doc = {value: new Date("2012-01-01T00:00:00Z")}
reduce( [ doc, doc ] )
// => ["Sat Dec 31 2011", "Sat Dec 31 2011"]

您的验证是错误的。

它应该是if (values.indexOf(doc.value.toDateString()) != -1) return;

reduce = function(docs) {
    var values = [];
    if (values.indexOf(doc.value.toDateString()) != -1) return;
    values.push(doc.value.toDateString());
    return values;
}
doc = {value: new Date("2012-01-01T00:00:00Z")}
reduce(doc)
//["Sun Jan 01 2012"]

试试这个。如果你只想通过一个foreach函数,为什么要做这个函数?您还应该只将doc传递给reduce函数一次。