【问题标题】:javascript string comparison issue in array.filter()array.filter() 中的 javascript 字符串比较问题
【发布时间】:2020-09-26 22:27:12
【问题描述】:

我有一个包含以下对象的数组。

myArray = [
    { item: { id: 111557 } },
    { item2: { id: 500600 } }]

我有一个变量

targetItemID = '111557'

注意其中一个是字符串,数组中的一个是数字。我正在尝试获取具有正确项目 ID 的对象。

这是我尝试过的,

    myArray = [
        { item: { id: 111557 } },
        { item2: { id: 500600 } }]


    
    targetItemID = '111557'
    
var newArray = myArray.filter(x => {

    console.log(x.item.id.toString())
    console.log(targetItemID.toString())

    x.item.id.toString() === itemID.toString()

    })

    console.log(newArray);

我希望将所有匹配的对象添加到“newArray”中。我试着在比较之前检查值,它们都是字符串,它们看起来完全一样,但我的 newArray 仍然是空的。

【问题讨论】:

    标签: javascript arrays filtering string-comparison


    【解决方案1】:
    • 您的第二个对象没有 item 属性并且应该。
    • 您的filter 函数中需要return
    • 您必须将x.item.idtargetItemID 进行比较,而不是itemID。由于您使用的是console.log(),因此您会看到itemID id not defined 的错误;)。

    myArray = [
            { item: { id: 111557 } },
            { item: { id: 500600 } }
    ];
    
    
    targetItemID = '111557'
        
    var newArray = myArray.filter(x => {
    
        //console.log(x.item.id.toString())
        //console.log(targetItemID.toString())
    
        return x.item.id.toString() === targetItemID.toString();
    });
    
    console.log(newArray);

    【讨论】:

    • 是的,他需要返回条件
    • 哦,是的,这是一个错字。 return 关键字是我的问题,已经解决了,谢谢
    • @neiloth 请对所有答案进行投票,并考虑将其标记为“最佳”答案。
    【解决方案2】:

    这里有几个问题。首先,并非所有对象都有item 属性,因此您需要检查它是否存在。其次,您将它们与不存在的 itemID 而不是 targetItemID 进行比较,最后,@bryan60 提到,如果您在匿名 lambda 中打开一个块,您需要一个明确的 return 语句,尽管,老实说,在这种情况下你真的不需要这个块:

    var newArray =
        myArray.filter(x => x.item && x.item.id && x.item.id.toString() === targetItemID)
    

    【讨论】:

      【解决方案3】:

      您需要返回过滤器才能工作:

      return x.item.id.toString() === itemID.toString();
      

      【讨论】:

      • 哦,谢谢,很好 :) 我会在 9 分钟内标记为正确答案。
      • 不仅如此。看我的回答。
      • @ScottMarcus 我不知道我怎么没有先看到你的答案 :) 谢谢,我会标记你的。
      • @ScottMarcus true 没有仔细阅读/认为它们是拼写错误
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 2017-09-18
      相关资源
      最近更新 更多