js get Set the first item All In One
const set = new Set();
// Set(0) {size: 0}
set.add(2);
// Set(1) {2}
// ❌
set[0];
// undefined
solutions
for...of
要想获取 Set 第一个元素,定义一个函数遍历 Set 到第一个元素就立即返回即可;
const set = new Set();
set.add(2);
function getFirstItemOfSet(set) {
// for...of 遍历✅
for(let item of set) {
console.log('item =', item);
if(item) {
return item;
}
}
return undefined;
}
const first = getFirstItemOfSet(set);
for(let [i, item] of set.entries()) {
console.log('i, item =', i, item);
}
[...set]
const set = new Set();
set.add(2);
// set 转 array ✅
const first = [...set][0];
console.log(`first =`, first);
- 解构赋值 destructuring assignment
const set = new Set();
set.add(2);
// 解构赋值 ✅
const [first] = set;
console.log(`first =`, first);
- 迭代器 Iterator
const set = new Set();
set.add(2);
// 迭代器 next ✅
set.keys().next().value;
set.values().next().value;
set.entries().next().value[0];
set.entries().next().value[1];
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/@@iterator
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/next
demo
TypeScript
function singleNumber(nums: number[]): number {
const set = new Set<number>();
for(let i = 0; i < nums.length; i ++) {
if(set.has(nums[i])) {
set.delete(nums[i]);
} else {
set.add(nums[i]);
}
}
// Property 'toJSON' does not exist on type 'Set<number>'.(2339)
// return (set.toJSON())[0];
for(let item of set) {
return item;
}
};
leetcode ???
toJSON()
❓
Set.prototype.toJSON = function() {
return Object(n.__spread)(this)
},
Map.prototype.toJSON = function() {
return Object(n.__spread)(this)
}
https://static.leetcode.cn/cn-mono-assets/production/main/noj-common.7286330c.js:formatted
const set = new Set();
set.add(2);
set.toJSON();
// [2]
const arr = set.toJSON();
// [2]
arr[0];
// 2
https://leetcode.cn/problems/single-number/submissions/
refs
https://bobbyhadz.com/blog/javascript-get-first-element-of-set
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/279671.html