JavaScript에서 세트를 만드는 방법은 무엇입니까?
Eloquent JavaScript 4 장에서는 객체를 생성하고 값을 속성 이름으로 저장하고 임의의 값 (예 : true)을 속성 값으로 할당하여 값 집합을 만듭니다. 값이 이미 세트에 포함되어 있는지 확인하기 위해 in연산자가 사용됩니다.
var set = {};
if (!'Tom' in set) {
set.Tom = true;
}
이것은 관용적 JavaScript입니까? 어레이를 더 잘 사용하지 않겠습니까?
var set = [];
if (!'Tom' in set) {
set.push = 'Tom';
}
세트 는 이제 ES2015 (일명 ES6, 즉 ECMAScript 6)에서 사용할 수 있습니다. ES6는 2015 년 6 월부터 JavaScript의 현재 표준이었습니다.
ECMAScript 6에는 임의의 값에 대해 작동하는 데이터 구조 세트가 있으며, 빠르며 NaN을 올바르게 처리합니다. - 악셀 Rauschmayer , 탐색 ES6
Axel Rauschmayer의 저서 Exploring ES6 에서 처음 두 가지 예 :
단일 요소 관리 :
> let set = new Set();
> set.add('red')
> set.has('red')
true
> set.delete('red')
true
> set.has('red')
false
세트의 크기 결정 및 지우기 :
> let set = new Set();
> set.add('red')
> set.add('green')
> set.size
2
> set.clear();
> set.size
0
JavaScript의 세트에 대해 자세히 알아 보려면 Exploring ES6를 확인하십시오 . 이 책은 온라인에서 무료로 읽을 수 있지만 저자 Axel Rauschmayer 박사 를 지원하고 싶다면 약 $ 30에 책을 구입할 수 있습니다.
이제 세트와 ES6을 사용하려면 Babel , ES6에서 ES5 로의 트랜스 파일러 및 해당 폴리 필을 사용할 수 있습니다 .
편집 : 2017 년 6 월 6 일 현재 대부분의 주요 브라우저는 최신 버전 (IE 11 제외)에서 전체 세트를 지원합니다. 즉, 이전 브라우저를 지원하지 않는 경우 바벨이 필요하지 않을 수 있습니다. 현재 브라우저를 포함하여 다른 브라우저에서 호환성을 확인하려면 Kangax의 ES6 호환성 표를 확인하십시오 .
편집하다:
초기화에 대한 설명입니다. 집합은 생성자에서 모든 동기 반복 가능 항목을 사용할 수 있습니다. 즉, 배열뿐만 아니라 문자열 및 반복자를 사용할 수 있습니다. 예를 들어 세트의 다음 배열 및 문자열 초기화를 사용하십시오.
const set1 = new Set(['a','a','b','b','c','c']);
console.log(...set1);
console.log(set1.size);
const set2 = new Set("aabbcc");
console.log(...set2);
console.log(set2.size);
배열과 문자열의 두 출력이 동일합니다. 참고 ...set1는 IS 확산 구문 . iterable의 각 요소가 세트에 하나씩 추가되는 것처럼 보이므로 배열과 문자열 모두 동일한 요소를 가지며 요소가 동일한 순서이기 때문에 세트가 동일하게 생성됩니다. 집합에 대해주의해야 할 또 다른 사항은 반복 할 때 요소가 집합에 삽입 된 순서를 따른다는 것입니다. 다음은 세트를 반복하는 예입니다.
const set1 = new Set(['a','a','b','b','c','c']);
for(const element of set1) {
console.log(element);
}
이터 러블을 사용하여 집합을 초기화 할 수 있으므로 생성기 함수 에서 이터레이터를 사용할 수도 있습니다 . 다음은 동일한 출력을 생성하는 반복기 초기화의 두 가지 예입니다.
// a simple generator example
function* getLetters1 () {
yield 'a';
yield 'a';
yield 'b';
yield 'b';
yield 'c';
yield 'c';
}
// a somewhat more commonplace generator example
// with the same output as getLetters1.
function* getLetters2 (letters, repeatTimes) {
for(const letter of letters) {
for(let i = 0; i < repeatTimes; ++i) {
yield letter;
}
}
}
console.log("------ getLetters1 ------");
console.log(...getLetters1());
const set3 = new Set(getLetters1());
console.log(...set3);
console.log(set3.size);
console.log("------ getLetters2 ------");
console.log(...getLetters2('abc', 2));
const set4 = new Set(getLetters2('abc', 2));
console.log(...set4);
console.log(set4.size);
이 예제의 생성기 함수는 반복되지 않도록 작성 될 수 있지만 생성기 함수가 더 복잡하고 다음이 성능에 너무 부정적인 영향을주지 않는 한 Set 메서드를 사용하여 다음과 같은 생성기에서 값만 가져올 수 있습니다. 반복하지 마십시오.
If you want to know more about sets without reading Dr. Rauschmayer's chapter of his book you can check out the MDN docs on Set. MDN also has more examples of iterating over a set such as using forEach and using the .keys, .values, and .entries methods. MDN also has examples such as set union, set intersection, set difference, symmetric set difference, and set superset checking. Hopefully most of those operations will become available in JavaScript without needing to build your own functions supporting them. In fact, there is this TC39 proposal for new Set methods which should hopefully add the following methods to Set in JavaScript at some future point in time if the proposal reaches stage 4:
- Set.prototype.intersection(iterable) - method creates new Set instance by set intersection operation.
- Set.prototype.union(iterable) - method creates new Set instance by set union operation.
- Set.prototype.difference(iterable) - method creates new Set without elements present in iterable.
- Set.prototype.symmetricDifference(iterable) - returns Set of elements found only in either this or in iterable.
- Set.prototype.isSubsetOf(iterable)
- Set.prototype.isDisjointFrom(iterable)
- Set.prototype.isSupersetOf(iterable)
I use dict objects as sets. This works with strings and numbers, but I suppose would cause problems if you wanted to have a set of objects using custom equality and comparison operators:
Creating a set:
var example_set =
{
'a':true,
'b':true,
'c':true
}
Testing for inclusion in a set
if( example_set['a'] ){
alert('"a" is in set');
}
Adding an element to a set
example_set['d'] = true;
Removing an element from a set
delete example_set['a'];
Sets do not allow duplicate entries and don't typically guarantee predefined ordering. Arrays do both of these, thus violating what it means to be a set (unless you do additional checks).
The first way is idiomatic JavaScript.
Any time you want to store a key/value pair, you must use a JavaScript object. As for arrays, there are several problems:
The index is a numerical value.
No easy way to check to see if a value is in an array without looping through.
A set doesn't allow duplicates. An array does.
If you want to create a set from an array, simply do:
let arr = [1, 1, 2, 1, 3];
let mySet = new Set(arr); // Set { 1, 2, 3 }
This is a sugar syntax that I quite fancied when programming in Python, so glad that ES6 finally made it possible to do the same thing.
NOTE: then I realize what I said didn't directly answer your question. The reason you have this "hack" in ES5 is because lookup time in an object by keys is significantly faster (O(1)) than in an array (O(n)). In performance critical applications, you can sacrifice this bit of readability or intuition for better performance.
But hey, welcome to 2017, where you can use proper Set in all major modern browsers now!
Sets in ES6/ES2015:
ES6/ES2015 now has built in sets. A set is data structure which allows storage of unique values of any type, whether this are primitive values or object references. A set can be declared using the ES6 built in set constructor in the following manner:
const set = new Set([1, 2, 3, 4, 5]);
When creating a set using the Set constructor our newly created set object inherits from the Set.prototype. This has all sorts of auxiliary methods and properties. This allows you to easily do the following things:
Example:
const set = new Set([1, 2, 3, 4, 5]);
// checkout the size of the set
console.log('size is: ' + set.size);
// has method returns a boolean, true if the item is in the set
console.log(set.has(1));
// add a number
set.add(6);
// delete a number
set.delete(1);
// iterate over each element using a callback
set.forEach((el) => {
console.log(el);
});
// remove all the entries from the set
set.clear();
Browser compatibility:
All major browser now fully support sets except IE where some features are missing. For exact reference please refer to the mdn docs.
There are two problems with using bare javascript objects to emulate sets: first, an object can have an inherited property which would screw the "in" operator and second, you can only store scalar values in this way, making a set of objects is not possible. Therefore, a realistic implementation of Sets should provide methods add and contains instead of plain in and property assignments.
You can try Buckets, is a javascript data structure library and has everything you need to manipulate sets.
참고URL : https://stackoverflow.com/questions/8363564/ways-to-create-a-set-in-javascript
'IT박스' 카테고리의 다른 글
| Jinja2에서 목록을 어떻게 정렬합니까? (0) | 2020.10.21 |
|---|---|
| 블록이 전달 될 때 Array # sort는 어떻게 작동합니까? (0) | 2020.10.21 |
| Promise / Defer 라이브러리는 어떻게 구현됩니까? (0) | 2020.10.21 |
| 클릭시 접을 수있는 Bootstrap 4 navbar를 숨기는 방법 (0) | 2020.10.21 |
| $ this vs $ (this) in jQuery (0) | 2020.10.20 |