js get Set the first item All In One
2022/8/9 23:22:49
本文主要是介绍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
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, 禁止转载
这篇关于js get Set the first item All In One的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-01Vue.js 是什么-icode9专业技术文章分享
- 2024-11-01Vue3入门教程:从零开始搭建第一个Vue3项目
- 2024-11-01详解vueRouter4基础教程
- 2024-11-01Vuex4课程:初学者的完整入门指南
- 2024-10-31Vue3课程:新手入门到初级掌握
- 2024-10-31Vue3课程:新手入门到初级应用详解
- 2024-10-31VueRouter4课程:新手入门与实战指南
- 2024-10-31Vuex4学习:从入门到初级实战教程
- 2024-10-31Vue3教程:新手入门与基础实战
- 2024-10-31Vue教程:新手快速入门指南