ES6対応環境(node.js、必要なES6機能を備えた特定のブラウザー、または環境に合わせてES6コードをトランスパイルするなど)でプログラミングしている場合は、ES6にSet組み込まれているオブジェクトを使用できます。非常に優れた機能を備えており、ご使用の環境でそのまま使用できます。
ES5環境での多くの単純なことに対して、オブジェクトの使用は非常にうまく機能します。objがオブジェクトでありA、セットで操作したい値を持つ変数である場合は、次の操作を実行できます。
初期化コード:
// create empty object
var obj = {};
// or create an object with some items already in it
var obj = {"1":true, "2":true, "3":true, "9":true};
質問1:ですAリストに:
if (A in obj) {
// put code here
}
質問2:ある場合は、リストから「A」を削除します。
delete obj[A];
質問3:リストにまだない場合は、「A」をリストに追加します
obj[A] = true;
完全を期すためAに、リストにあるかどうかのテストは、これで少し安全です。
if (Object.prototype.hasOwnProperty.call(obj, A))
// put code here
}
constructorプロパティのような基本オブジェクトの組み込みメソッドやプロパティ間で潜在的な競合があるため。
ES6のサイドバー:ECMAScript 6の現在の作業バージョンまたはES 2015と呼ばれるものには、組み込みのSetオブジェクトがあります。現在、一部のブラウザーで実装されています。ブラウザの可用性は時間の経過とともに変化するためSet、このES6互換性テーブルの行を見て、ブラウザの可用性の現在のステータスを確認できます。
組み込みのSetオブジェクトの利点の1つは、オブジェクトのようにすべてのキーを文字列に強制変換しないため、5と "5"を別々のキーとして使用できることです。また、文字列を変換せずに、セットで直接オブジェクトを使用することもできます。ここだ、物品の機能とのいくつかについて説明しMDNのマニュアルセットオブジェクトには。
ES6セットオブジェクトのポリフィルを作成したので、今すぐそれを使い始めることができます。ブラウザがサポートしている場合は、組み込みのセットオブジェクトを自動的に遅延させます。これには、IE7まで機能するES6互換コードを作成するという利点があります。しかし、いくつかの欠点があります。ES6セットインターフェースはES6イテレータを利用しているため、ユーザーは次のようなことができfor (item of mySet)、自動的にセットを反復処理します。ただし、このタイプの言語機能は、ポリフィルを介して実装することはできません。新しいES6言語機能を使用せずにES6セットを繰り返し処理することもできますが、率直に言って、新しい言語機能がないと、以下に示す他のセットインターフェイスほど便利ではありません。
両方を見て、どちらが最適かを判断できます。ES6セットのポリフィルはhttps://github.com/jfriend00/ES6-Setにあります。
ちなみに、私自身のテストで、Firefox v29 Setの実装が仕様の現在のドラフトでは完全に最新ではないことに気づきました。たとえば.add()、仕様の説明や私のポリフィルサポートのようにメソッド呼び出しをチェーンすることはできません。まだ確定されていないため、これはおそらく仕様の進行中の問題です。
事前に作成されたセットオブジェクト:任意のブラウザで使用できるセットを操作するためのメソッドが既に作成されているオブジェクトが必要な場合は、さまざまなタイプのセットを実装する一連のさまざまな事前に作成されたオブジェクトを使用できます。セットオブジェクトの基本を実装する小さなコードであるminiSetがあります。また、機能が豊富なセットオブジェクトと、ディクショナリ(各キーの値を保存/取得しましょう)やオブジェクトセット(オブジェクトのセット(JSオブジェクトまたはDOMオブジェクトを提供するオブジェクト)それぞれに一意のキーを生成する関数またはObjectSetがキーを生成します)。
これがminiSetのコードのコピーです(最新のコードはgithubにあります)。
"use strict";
//-------------------------------------------
// Simple implementation of a Set in javascript
//
// Supports any element type that can uniquely be identified
// with its string conversion (e.g. toString() operator).
// This includes strings, numbers, dates, etc...
// It does not include objects or arrays though
// one could implement a toString() operator
// on an object that would uniquely identify
// the object.
//
// Uses a javascript object to hold the Set
//
// This is a subset of the Set object designed to be smaller and faster, but
// not as extensible. This implementation should not be mixed with the Set object
// as in don't pass a miniSet to a Set constructor or vice versa. Both can exist and be
// used separately in the same project, though if you want the features of the other
// sets, then you should probably just include them and not include miniSet as it's
// really designed for someone who just wants the smallest amount of code to get
// a Set interface.
//
// s.add(key) // adds a key to the Set (if it doesn't already exist)
// s.add(key1, key2, key3) // adds multiple keys
// s.add([key1, key2, key3]) // adds multiple keys
// s.add(otherSet) // adds another Set to this Set
// s.add(arrayLikeObject) // adds anything that a subclass returns true on _isPseudoArray()
// s.remove(key) // removes a key from the Set
// s.remove(["a", "b"]); // removes all keys in the passed in array
// s.remove("a", "b", ["first", "second"]); // removes all keys specified
// s.has(key) // returns true/false if key exists in the Set
// s.isEmpty() // returns true/false for whether Set is empty
// s.keys() // returns an array of keys in the Set
// s.clear() // clears all data from the Set
// s.each(fn) // iterate over all items in the Set (return this for method chaining)
//
// All methods return the object for use in chaining except when the point
// of the method is to return a specific value (such as .keys() or .isEmpty())
//-------------------------------------------
// polyfill for Array.isArray
if(!Array.isArray) {
Array.isArray = function (vArg) {
return Object.prototype.toString.call(vArg) === "[object Array]";
};
}
function MiniSet(initialData) {
// Usage:
// new MiniSet()
// new MiniSet(1,2,3,4,5)
// new MiniSet(["1", "2", "3", "4", "5"])
// new MiniSet(otherSet)
// new MiniSet(otherSet1, otherSet2, ...)
this.data = {};
this.add.apply(this, arguments);
}
MiniSet.prototype = {
// usage:
// add(key)
// add([key1, key2, key3])
// add(otherSet)
// add(key1, [key2, key3, key4], otherSet)
// add supports the EXACT same arguments as the constructor
add: function() {
var key;
for (var i = 0; i < arguments.length; i++) {
key = arguments[i];
if (Array.isArray(key)) {
for (var j = 0; j < key.length; j++) {
this.data[key[j]] = key[j];
}
} else if (key instanceof MiniSet) {
var self = this;
key.each(function(val, key) {
self.data[key] = val;
});
} else {
// just a key, so add it
this.data[key] = key;
}
}
return this;
},
// private: to remove a single item
// does not have all the argument flexibility that remove does
_removeItem: function(key) {
delete this.data[key];
},
// usage:
// remove(key)
// remove(key1, key2, key3)
// remove([key1, key2, key3])
remove: function(key) {
// can be one or more args
// each arg can be a string key or an array of string keys
var item;
for (var j = 0; j < arguments.length; j++) {
item = arguments[j];
if (Array.isArray(item)) {
// must be an array of keys
for (var i = 0; i < item.length; i++) {
this._removeItem(item[i]);
}
} else {
this._removeItem(item);
}
}
return this;
},
// returns true/false on whether the key exists
has: function(key) {
return Object.prototype.hasOwnProperty.call(this.data, key);
},
// tells you if the Set is empty or not
isEmpty: function() {
for (var key in this.data) {
if (this.has(key)) {
return false;
}
}
return true;
},
// returns an array of all keys in the Set
// returns the original key (not the string converted form)
keys: function() {
var results = [];
this.each(function(data) {
results.push(data);
});
return results;
},
// clears the Set
clear: function() {
this.data = {};
return this;
},
// iterate over all elements in the Set until callback returns false
// myCallback(key) is the callback form
// If the callback returns false, then the iteration is stopped
// returns the Set to allow method chaining
each: function(fn) {
this.eachReturn(fn);
return this;
},
// iterate all elements until callback returns false
// myCallback(key) is the callback form
// returns false if iteration was stopped
// returns true if iteration completed
eachReturn: function(fn) {
for (var key in this.data) {
if (this.has(key)) {
if (fn.call(this, this.data[key], key) === false) {
return false;
}
}
}
return true;
}
};
MiniSet.prototype.constructor = MiniSet;