xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js get Set the first item All In One

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

  1. 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);
}
  1. [...set]
const set = new Set();
set.add(2);

// set 转 array ✅
const first = [...set][0];
console.log(`first =`, first);

  1. 解构赋值 destructuring assignment
const set = new Set();
set.add(2);

// 解构赋值 ✅
const [first] = set;
console.log(`first =`, first);

  1. 迭代器 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://stackoverflow.com/questions/32539354/how-to-get-the-first-element-of-set-in-es6-ecmascript-2015/73281564#73281564

https://bobbyhadz.com/blog/javascript-get-first-element-of-set



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-08-09 12:05  xgqfrms  阅读(246)  评论(1编辑  收藏  举报