javascript - Array.find() 获得正确的值但返回错误的值

标签 javascript arrays

因此,我认为编写一些 Array 方法来帮助对对象进行排序和分组会很有趣。这是我的代码。请原谅 log,这让我很生气。您可以在 JSBin 上运行此代码,here .

/**
 * uniquePush method - conditionally add an object to an array
 *
 * Only adds an object if it is not already present on this array.
 * Doesn't do a deep comparison.
 * 
 * @param {Object} newElement - the element to check for before pushing
 * @returns {Array} the array, modified if nescessary
 */
Array.prototype.uniquePush = function (newElement) {
  console.dir(this);
  var findCount = 0;

  function findNewElement(element) {
    console.log("findCount: " + (++findCount));
    console.log("Element: " + element);
    console.log("newElement: " + newElement);
    var found = (element === newElement);
    console.log("findNewElement -> " + found);
    return found;
  }

  var foundNewElement = this.find(findNewElement);
  console.log("this.find(findNewElement): " + foundNewElement)
  if (foundNewElement) {
    // Found it. Don't add it.
    console.log("Declined to add \'" + newElement + "\' to array");
  } else {
    // Didn't find it, go ahead and add it
    console.log("Adding \'" + newElement + "\' to array");
  }

  console.log("---------------------------------");
  return (foundNewElement ? this : this.push(newElement));
}

/**
 * groupBy method - groups an array of objects by property value
 *
 * Returned Array will look like:
 * [
 *  [{prop: "propValue", ...}, {prop: "propValue", ...}],
 *  [{prop: "anotherValue", ...}, {prop: "anotherValue", ...}],
 *  ...
 *  [{prop: "nValue", ...}, {prop: "nValue", ...}]
 * ]
 *
 * @param {String} prop - the property to group by
 * @returns {Array} an Array containing the grouped arrays
 */
Array.prototype.groupBy = function (prop) {
  // Gather all the possible property values
  var propValues = [];
  var entries = this.entries();

  var entryValue;
  while (entryValue = entries.next().value) {
    propValues.uniquePush(entryValue[1][prop]);
  }

  var result = [];
  for (var i = 0; i < propValues.length; i += 1) {
    var innerResult = [];
    this.forEach(function(element) {
      if (element[prop] === this.propValue) {
        this.result.push(element);
      }
    }, {
      propValue: propValues[i], 
      result: innerResult
    });
    result.push(innerResult);
  }
  return result;
};

var PRODUCTS = [
  {category: 'Sporting Goods', price: '$29.99', stocked: true, name: 'Football'},
  {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
  {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
  {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
  {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
  {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];

var groupedByCategory = PRODUCTS.groupBy("category");
console.dir(groupedByCategory);
var groupedByStocked = PRODUCTS.groupBy("stocked");
console.dir(groupedByStocked);

这段代码大部分工作正常,但我发现它在 bool 值数组上有问题。具体来说,uniquePush() 方法使用 Array.find() 方法来确定给定的 newElement 是否存在于 中这个数组。

但是,它似乎返回了错误的值。例如,当我在 "stocked" 上运行它时,我得到了这个:

<edited for brevity>

[true, false]
"findCount: 1"
"Element: true"
"newElement: true"
"findNewElement -> true"
"foundNewElement: true"
"---------------------------------"
"Declined to add true to array"
[true, false]
"findCount: 1"
"Element: true"
"newElement: false"
"findNewElement -> false"
"findCount: 2"
"Element: false"
"newElement: false"
"findNewElement -> true"
"foundNewElement: false"
"---------------------------------"
"Adding false to array"
[true, false, false]

如您所见,最后,findNewElement 被评估为 trueArray.find() 返回 false。有人可以向我解释为什么会这样吗?

最佳答案

Array.find如果未找到任何内容,则返回 undefined。

var foundNewElement = this.find(findNewElement);
  if (foundNewElement) ...

如果发现“假”,则此检查失败。使用 if (typeof(foundElement)!='undefined')

关于javascript - Array.find() 获得正确的值但返回错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36319369/

相关文章:

javascript - 使用 React Native Animated 淡入淡出元素

javascript - 创建 React 组件的 2 种不同方式

javascript - 如何使用 Post 发送数据库将动态添加的表行表单值传递给 Javascript

arrays - 如何在 JSON Schema 中制作二维数组?

javascript - 在我进行第二次提交后,每当我尝试获取登录页面或注册页面时,都会收到 404 错误

Java登录系统不起作用;读取第一个用户但无法解析第二个或下一个用户

javascript迭代并映射多维数组

arrays - 在读取文件 bash 时将分割单词存储到数组中

php - Laravel json 仅转换为数组数字 PHP

javascript - node.js - 如何将附加参数传递给 async.map