new Set()
set 对象 用来存储任何类型的唯一值
- new Set() ,用来去重数组。
let arr = [1, 1, 2, 2, 3,3];
let arr2 = new Set(arr);
let arr3 = Array.from(arr2);
console.log(arr3); // [1, 2, 3]
- Set.prototype.add(value) 在Set对象尾部添加一个元素。返回该Set对象。
let arr = [1, 1, 2, 2, 3, 3];
let arr2 = new Set(arr);
let a = arr2.add(8);
console.log(arr) // [1, 1, 2, 2, 3, 3];
console.log(a) // {1,2,3,8}
- Set.prototype.clear()移除
Set对象内的所有元素。
let arr = [1, 1, 2, 2, 3, 3];
let arr2 = new Set(arr);
let a = arr2.clear();
console.log(arr) // [1, 1, 2, 2, 3, 3];
console.log(a) // undefined
- Set.prototype.delete(value)移除Set的中与这个值相等的元素
let arr = [1, 1, 2, 2, 3, 3];
let arr2 = new Set(arr);
let a = arr2.delete(3);
console.log(arr) // [1, 1, 2, 2, 3, 3];
console.log(a) // true
let arr = [1, 1, 2, 2, 3, 3];
let arr2 = new Set(arr);
let a = arr2.delete(5);
console.log(arr) // [1, 1, 2, 2, 3, 3];
console.log(a) // false
- Set.prototype.forEach(callbackFn[, thisArg])
//// 按照插入顺序,为Set对象中的每一个值调用一次callBackFn。如果提供了thisArg参数,回调中的this会是这个参数。 function logSetElements(value1, value2, set) { console.log("s[" + value1 + "] = " + value2); // s[foo] = foo // test.html:16 s[bar] = bar // test.html:16 s[undefined] = undefined } new Set(["foo", "bar", undefined]).forEach(logSetElements);
- Set.prototype.values()
//
// 返回一个新的迭代器对象,该对象包含Set对象中的按插入顺序排列的所有元素的值。
var mySet = new Set();
mySet.add("foo");
mySet.add("bar");
mySet.add("baz");
var setIter = mySet.values();
console.log(setIter) // {"foo", "bar", "baz"}
console.log(setIter.next().value); // "foo"
console.log(setIter.next().value); // "bar"
console.log(setIter.next().value); // "baz"
- Set.prototype.entries()
// Set.prototype.entries()
// 返回一个新的迭代器对象,该对象包含Set对象中的按插入顺序排列的所有元素的值的[value, value]数组。为了使这个方法和Map对象保持相似, 每个值的键和值相等。
var mySet = new Set();
mySet.add("foobar");
mySet.add(1);
mySet.add("baz");
var setIter = mySet.entries();
console.log(setIter.next().value); // ["foobar", "foobar"]
console.log(setIter.next().value); // [1, 1]
console.log(setIter.next().value); // ["baz", "baz"]
浙公网安备 33010602011771号