Javascript

js get Set the first item All In One

本文主要是介绍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://bobbyhadz.com/blog/javascript-get-first-element-of-set


Flag Counter

©xgqfrms 2012-2020

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

原创文章,版权所有©️xgqfrms, 禁止转载

这篇关于js get Set the first item All In One的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!