【问题标题】:Difference between in and includes in NodeJS [duplicate]NodeJS中的in和include之间的区别[重复]
【发布时间】:2021-12-30 21:49:21
【问题描述】:

我很惊讶地发现:

> 'a' in ['a', 'b']
false
> ['a','b'].includes('a')
true

NodeJS 中的每个命令执行什么操作?

【问题讨论】:

标签: javascript node.js arrays


【解决方案1】:

这不是特定于节点的,而是特定于 ECMA (JS)。

in运营商

检查集合中键的存在(类似于hasOwnProperty但也检查原型链中继承的键)

includesArray的方法(在ES6中引入)

检查集合中是否存在值

【讨论】:

    【解决方案2】:

    Array.includes() 检查数组中是否存在某个值,而 in 运算符检查对象中是否存在键(或您所描述的数组中的索引)。

    console.log('a' in ['a', 'b']); // false, no such key
    console.log(0 in ['a', 'b']); // true, 0 is a key that exists
    console.log(1 in ['a', 'b']); // true, 1 is a key that exists
    console.log(2 in ['a', 'b']); // false, 2 is a key that doesn't exists

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      • 2016-07-06
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多