JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

WPS宏(JSA)教程——Map和Set

wys521 2024-12-06 18:18:28 精选教程 22 ℃ 0 评论

Map对象

Map对象其实就是一种简单的键/值对的集合,可以通过for...of...在按照数据插入时的顺序遍历所有的[key: value]对元素。Map对象具有极快的查找速度。

定义Map

因为Map是个对象,因此要定义一个Map对象,有两种方法:初始化一个空对象;用二维数组初始化Map对象。

如下示例:

let friutColor0 = new Map();//创建一个空的Map对象

//创建Map对象时初始化,需要一个二维数组来进行
let friutColor1 = new Map([['Orange','orange'],['Apple','red'],['Banana','yellow']])

Map的相关操作

1、添加元素,用Map的set方法。

let friutPrice = new Map();
friutPrice.set('Apple',7.00);
friutPrice.set('Orange',4.50);

2、读取元素,用Map的get方法(,继续上方的代码进行)。

console.log(friutPrice.get('Apple'));//返回7
console.log(friutPrice.get('Orange'));//返回4.5
console.log(friutPrice.get('Banana'));//返回undefined,因为没有Banana

3、判断元素是否存在,用Map的has方法(,继续上方的代码进行)。

console.log(friutPrice.has('Banana'));//返回false
console.log(friutPrice.has('Orange'));//返回true

4、删除元素,用Map的delete方法(,继续上方的代码进行)。

console.log(friutPrice.delete('Orange'));//返回true,删除一个存在的键值对,将会返回true
console.log(friutPrice.has('Orange'));//返回false,此时该键值对不存在,返回false
console.log(friutPrice.delete('Orange'));//返回false,删除一个不存在的键值对,将会返回false

5、对同一个键值对多次赋值,新值会替换旧值。因为键在Map中是唯一的。

friutPrice.set('Banana',2.5);
friutPrice.set('Orange',4.5);
console.log(friutPrice.get('Banana'));//返回2.5
console.log(friutPrice.get('Orange'));//返回4.5
friutPrice.set('Banana',3.5);
friutPrice.set('Orange',4);
console.log(friutPrice.get('Banana'));//返回3.5
console.log(friutPrice.get('Orange'));//返回4

6、遍历Map

for (let [key, value] of friutPrice) {
  console.log(`${key} price: ¥${value}元`);
}
/*
 "Apple price: ¥7元"
 "Orange price: ¥4元"
 "Banana price: ¥3.5元"
*/

7、获取Map的大小:Map的size属性

console.log(friutPrice.size);//返回3

8、清空Map,用clear()方法

friutPrice.clear();
console.log(friutPrice.size);//返回0

Set对象

Set对象是一组唯一值的集合,可以用for...of...按照添加顺序来遍历。Set 中的值只能出现一次;它在集合 Set 中是唯一的。要理解set,那么可以将set看作是一个特殊的map,只不过只保留了key,而抛弃了value。因此,Set的所有值都是唯一的。

定义Set

因为Set是一个特殊的Map对象,因此要定义一个Set对象,有两种方法:初始化一个空Set对象;用一个一维数组初始化Set对象,Set会自动忽略重复的元素。

let friut1 = new Set(); // 空Set
let friut2 = new Set(['Apple', 'Banana', 'Orange']); // 含'Apple', 'Banana', 'Orange'
let numbers = new set([1,2,3,4,'4']);//numbers{1,2,3,4,'4'}
let array1 = ['A','B','C'];
let friut3 = new Set(array1); //{'A','B','C'}

Set常规操作

1、添加元素,用set的add方法。

let friut1 = new Set(); 
friut1.add('Pear');
friut1.add('Pine apple');

2、判断是否存在元素,用set的has方法。

console.log(friut1.has('Pear'));//返回true
console.log(friut1.has('Apple'));//返回false,因为friut1中不存在Apple

3、删除元素,delete方法

console.log(friut1.delete('Pear'));//返回true
console.log(friut1.delete('Pear'));//删除不存的元素,返回false

4、遍历Set,用for...of...

for(item of friut1)
{
  console.log(item);
}

/*
 "Pear"
 "Pine apple"
*/

5、获取Set的大小,用属性size

console.log(friut1.size);//2

6、清空Set的大小,用clear方法

friut1.clear();
console.log(friut1.size);//0

***Map和Set这两个对象,是ES6新增加的两个对象。***



关注我,持续共同学习,一起踏上wps宏(JSA)的登山之路。

#头条创作挑战赛#

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表