ES6笔记(set)

1、Set: 新的数据结构:
类似于数组,但是成员的值都是唯一的,没有重复,
他的键跟值是一样的

(1)、set的基本用法: 初始化
    //new Array() []
    var s = new Set()
    var s = new Set( [ 1, 2, 3, 4 ] )
    var s = new Set( [...document.querySelectorAll('div')] );

(2)、属性和方法:
    size:  返回set实例的成员总数
    add( value ): 添加某个值,返回Set结构本身
    delete( value ): 删除某个值,返回布尔值
    has( value ): 返回布尔值,表示参数是否为set的成员
    clear(): 清除所有成员,没有返回值

(3)、Array.from( set对象 )  可以把set转成数组

一个类数组对象或者可遍历对象转换成一个真正的数组

//类数组转为数组        
const arrayLike={
    '0':'小明',
    '1':23,
    '2':'boy',
    length:3
}
console.log(Array.from(arrayLike))//["小明", 23, "boy"]
console.log([].slice.call(arrayLike))//["小明", 23, "boy"]


//NodeList对象转为数组
const foo = document.querySelectorAll('p'); //类似数组的对象
console.log( Array.from(foo))//[p, p]
console.log(Array.prototype.slice.call(foo))//[p, p]


//Array.from()第二个参数
<p>aaaaaaaaaAAAAA</p>
<p>bbbbbbbbbbbb</p>

let ps = document.querySelectorAll('p');
let a=Array.from(ps).filter(p => {
  return p.textContent.length > 10;
});
console.log(a); //Array[2]0: p1: plength: 2__proto__: Array[0]

//将字符串转换为数组
let  str = 'hello world!';
console.log(Array.from(str)) // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]

(4)、数组去重复:
    第一种: [...set对象]

    第二种:Array.from( set对象 )

//查看Set属性	
console.log(Set.prototype)

----------------------------------------

//Set 是一个对象
let s=new Set();
console.log(typeof s); //object

----------------------------------------

//设置值,用下标访问不到s[0]
let s=new Set([10,20,30,30]); 
console.log(s.size); //3  成员值都是唯一的,所以长度是3

----------------------------------------

//把类数组转为数组
function divs(){
	return [...document.querySelectorAll("div")]
}
var set=new Set(divs());
for(let el of set){//for of
	el.style.backgroundColor='red';//给每个div添加颜色
}
console.log(set.size)

----------------------------------------

//添加值、删除值、判断成员、清空
var s=new Set();
s.add(10).add(20).add(30).add(30)
console.log(s);//{10, 20, 30}
s.delete(30);
console.log(s);//{10, 20}
console.log(s.has(20)); //rue 判断有没有某个成员
s.clear(); //清空整个s
console.log(s);//{}

----------------------------------------

//set对象转成数组对象
//数组去重
var arr=[10,20,30,40,30,10,20];
var s=new Set(arr);
console.log(s.size);//4
var res=Array.from(s); //转为数组
console.log(res);//[10, 20, 30, 40]

----------------------------------------

//封装数组去重(两种 Array.from 和   展开运算符..)
var arr=[10,20,30,40,30,10,20];
function unique(arr){
	//return Array.from(new Set(arr)) 
	return [...new Set(arr)];//或者把set的每一项值用展开运算符展开(把每个成员展开),展开之后再放到数组中
}
console.log(unique(arr));//[10, 20, 30, 40]

2、Set遍历相关api
keys(): 返回键名
values(): 返回值
entries(): 返回值键值对
forEach(): 回调遍历每个成员

map,
    [...set].map( x => x * 2 )
filter
    [...set].filter( x => ( x % 2 ) == 0 )

let a = new Set( [ 1, 2, 3 ] );
let b = new Set( [ 2, 5, 8 ] );
并集:
    new Set( [...a, ...b ] );
交集:
    new Set( [...a].filter( x => b.has( x ) ) );
差集:
    new Set( [...a].filter( x => !b.has( x ) ) );

遍历set 同步数据
let set = new Set( [ 10, 20, 30 ] );
set = new Set( [...set].map( val => val * 2 ) );

let set = new Set( [ 10, 20, 30 ] );

set = new Set( Array.from( set, val => val * 2 ) );

//查看键、值、键值对		
var set=new Set(["a","b","aaa"]);
for(let key of set.keys()){
	console.log(key);//a b aaa
}

var set=new Set(["a","b","aaa"]);
for(let key of set.values()){
	console.log(key);//a b aaa
}

var set=new Set(["a","b","aaa"]);
for(let key of set.entries()){ //键值对
	console.log(key);//["a", "a"] ["b", "b"] ["aaa", "aaa"]
}
set.forEach((val,key)=>{
	console.log(val,key); //a a      b b    aaa aaa
})

--------------------------------------------------------

//map  set的原型(再上一层原型为object)上面没有map,把它转为数组就可以实现了
//[...set]把set的每一项展开为数组
var set=new Set([1,2,3]);
set=[...set].map((val)=>{  
	return val*2   //报错,
})
//conaole.log(Array,from(set))
console.log(set); //[2, 4, 6]

----------------------------------------------------

//过滤:在函数体为true才把他返回出来
var set=new Set([1,2,3]);
set=[...set].filter((val)=>{  
	return val%2 == 0   //是否为偶数
})
console.log(set); //[2]

----------------------------------------------------

//并集、交集、差集
let a = new Set( [ 1, 2, 3 ] );
let b = new Set( [ 2, 5, 8 ] );

//并集
//var set=new Set([...a,...b]); //两个数组展开合并到一个数组,利用set特性把重复的去掉
//console.log(set)//返回对象 {1, 2, 3, 5, 8}
//console.log([...set])//转成数组 [1, 2, 3, 5, 8]

//交集
//set=new Set( [...a].filter( x => b.has( x ) ) ); //把a里面的每一项展开,展开后转成一个数组,a里面的每一项,在b里面是否存在,存在就return出来
//console.log(set);//{2}

//差集
set=new Set( [...a].filter( x => !b.has( x ) ) );//a里面的每一项,在b里面是没有的
console.log{1, 3};

----------------------------------------------------

//同步数据
//遍历set 
let set = new Set( [ 10, 20, 30 ] );
set = new Set( [...set].map( val => val * 2 ) );
console.log(set);// {20, 40, 60}

let set = new Set( [ 10, 20, 30 ] );
set = new Set( Array.from( set, val => val * 2 ) ); //Array.from()第二个参数相当于调用
console.log(set);//{20, 40, 60}

抽奖:

<style>
	#box {
	    width: 300px;
	    height: 100px;
	    line-height: 100px;
	    font-size: 30px;
	    text-align: center;
	    border: 1px solid #aaa;
	    box-shadow: 2px 2px 3px #ccc;
	}
</style>	
	
<div id="box"></div>
<input type="button" value="小明">
<input type="button" value="小B">
<input type="button" value="小A">
<input type="button" value="小新">
<input type="button" value="小叶">
<script>
    var aPrize = ['小米', 'iphone5', 'iphone6', 'iphone7', 'iphone8'],
        aInput = document.querySelectorAll("input"),
        oBox = document.querySelector("#box"),
        set = new Set(), rand = null;
    aInput.forEach((ele, ind, cur) => {
        ele.flag = false;
        ele.addEventListener('click', () => {
            if ( !ele.flag ) {
                rand = Math.floor(Math.random() * aPrize.length);
                if (!set.has(rand)) {
                    set.add(rand);
                } else {
                    while (set.has(rand)) {
                        rand = Math.floor(Math.random() * aPrize.length);
                        if (!set.has(rand)) {
                            set.add(rand);
                            break;
                        }
                    }
                }
                oBox.innerHTML = aPrize[rand];
                ele.flag = true;
                ele.value = '您已经抽过了';
            }
        }, false );
    });
</script>

猜你喜欢

转载自blog.csdn.net/qq_14993375/article/details/79753454