使用 JavaScript 检查集合中是否包含某个值
使用 has() 方法检查 Set 是否包含值,例如 set.has(1)。 如果该值包含在 Set 中,则 has() 方法返回 true,否则返回 false。
const set1 = new Set(['one', 'two', 'three']);
console.log(set1.has('one')); // ?️ true
console.log(set1.has('four')); // ?️ false
Set.has() 方法采用的唯一参数是我们要测试是否存在于 Set 中的值。
has 方法返回一个布尔结果:
- 如果值包含在 Set 中则为真
- 如果值不在集合中则为 false
这里还有一些例子。
const set1 = new Set();
const obj = {country: 'Chile'};
set1.add(obj);
console.log(set1.has(obj)); // ?️ true
const arr = ['one', 'two'];
set1.add(arr);
console.log(set1.has(arr)); // ?️ true
// ?️ false because they reference
// different locations in memory
console.log(set1.has(['one', 'two']));
set1.delete(arr);
console.log(set1.has(arr)); // ?️ false
has() 方法甚至适用于对象和数组,只要它们具有相同的引用即可。
has() 方法不检查对象或数组的值是否相等,而是检查它们是否引用内存中的相同位置。
const obj = {};
console.log(obj === obj); // ?️ true
console.log({} === {}); // ?️ false
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。