摘要:本篇文章探讨了JavaScript基础教程之JavaScript中的集合,希望阅读本篇文章以后大家有所收获,帮助大家对相关内容的理解更加深入。
本篇文章探讨了JavaScript基础教程之JavaScript中的集合,希望阅读本篇文章以后大家有所收获,帮助大家对相关内容的理解更加深入。
<
集合是由一组无序且唯一(即不能重复)的项组成
function Set() {
var items={};
this.has=function(value){
//return value in items;
return this.hasOwnProperty(value);
}
this.add=function (value) {
if(!this.has(value)){
items[value]=value;
return true;
}
return false;
}
this.remove=function(value){
if(this.has(value)){
delete items[value];
return true;
}
return false;
}
this.clear=function(){
items={};
}
this.size=function(){
return Object.keys(items).length;
}
this.sizeLegacy=function(){
var count=0;
for (var prop in items) {
if (items.hasOwnProperty(prop)) {
++count;
}
}
}
this.values=function () {
return Object.keys(items);
}
this.valuesLagacy=function () {
var keys=[];
for (var key in items) {
if (items.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
}
//并集
this.union=function(otherSet) {
var unionSet=new Set();
var values=this.values();
for (var i = 0; i < values.length; i++) {
unionSet.add(values[i]);
}
values=otherSet.values();
for (var i = 0 i < values.length; i++) {
unionSet.add(values[i]);
}
return unionSet;
}
// 交集
this.intersection=function (otherSet) {
var intersectionSet=new Set();
var values=this.values();
for (var i = 0; i < values.length; i++) {
if (otherSet.has(values[i])) {
intersectionSet.add(values[i])
}
}
return intersectionSet;
}
// 差集
this.difference=function(otherSet){
var differenceSet=new Set();
var values=this.values();
for (var i = 0; i < values.length; i++) {
if (!otherSet.has(values[i])) {
differenceSet.add(values[i]);
}
}
return differenceSet;
}
// 子集
this.isSubsetOf=function(otherSet){
if(this.size()>otherSet.size()){
return false;
}else{
var values=this.values();
for (var i = 0; i < values.length; i++) {
if(!otherSet.has(values[i])){
return false;
}
}
return true;
}
}}
本文由职坐标整理发布,学习更多的相关知识,请关注职坐标IT知识库!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号