【问题标题】:Is indexOf() type sensitive in javascript?javascript 中的 indexOf() 类型是否敏感?
【发布时间】:2022-01-20 02:32:11
【问题描述】:

我有这个函数迭代数组中的每个对象以获取它们的 id,然后使用给定的 id 过滤结果:

const id = another.id; //variable used to filter through the items
const pos = this.items.map(function(e){return e.id}).indexOf(id); //filter items with another.id
this.items.splice(pos, 1) //remove item with the same id as another.id

another.id 有时是 string 有时是 number,当类型为 stringpos 将变为 -1 时它会起作用,这表明 indexOf() 没有找到一场比赛。 e.id 也是 string 的一个类型。

所以我的问题就像标题所说的那样,indexOf() 类型敏感吗?

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    是的,根据mdn,它是类型敏感的:

    indexOf() 使用严格相等(与 === 或三等号运算符使用的方法相同)将 searchElement 与 Array 的元素进行比较。

    【讨论】:

    • 有没有不区分类型的indexOf() 的替代品?那将使用== 作为比较器而不是===
    • @永品this.items.findIndex(e => e.id == id)
    猜你喜欢
    • 1970-01-01
    • 2016-11-12
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    相关资源
    最近更新 更多