【问题标题】:Why does `arr.find()` return `undefined`?为什么`arr.find()`返回`undefined`?
【发布时间】:2018-12-18 07:40:25
【问题描述】:

在下面的代码中his._notifications是一个对象数组,每个对象都包含如下所示的属性。

我要做的是检查传递给函数func() 的每个对象not是否被推入数组?

所以我使用.find(),如果对象被传递给函数或者它已经存在于数组中,我希望它返回true,否则返回false

但下面的日志语句打印undefined!为什么isExists 未定义?以及在数组中检查项目是否重复的推荐方法是什么?

代码

func(noti)
const isExists = this._notifications.find((obj) =>
  obj.title === noti.safeTitle
  && obj.text === noti.safeText
  && obj.bannerTitle === noti.safeBannerTitle
  && obj.bannerText === noti.safeBannerText
  && obj.icon === noti.icon
  && obj.onClickCallback === noti.onClickCallback
  && obj.eNotificationType === noti.notificationType
  && obj.deleteable === noti.deletable
  && obj.withBanner === noti.withBanner
);
logger.info('[isNotificationExists] For the current notification: ', JSON.stringify(notification), ' isExists: ', isExists);

【问题讨论】:

标签: javascript arrays node.js


【解决方案1】:

来自MDN

find() 方法返回数组中第一个元素的值 满足提供的测试功能。否则 undefined 是 返回。

includes()方法判断一个数组是否包含某个 元素,根据需要返回 true 或 false。它使用 sameValueZero 算法判断给定元素是否为 找到了。

To check if an item is duplicated in array

function hasDuplicates(array) {
  return (new Set(array)).size !== array.length;
}

【讨论】:

  • 是否有推荐的方法来检查数组中的条目是否重复
  • 如果您想检查数组中的重复项,该问题可能已经在网站上提出。如果那个/那些问题的答案不能满足你的需求,那么考虑问一个新的;但要准备好解释为什么现有答案不符合您的要求。
【解决方案2】:

find() 在这里不是一个合适的数据结构,因为它的返回类型是找到的元素而不是标志(无论是否找到)。您可以为此使用 underscorejs _.contains 函数。

http://underscorejs.org/#contains

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    相关资源
    最近更新 更多