What are the collection types of JavaScript?

青灯夜游
Release: 2022-04-11 12:03:58
Original
2583 people have browsed it

There are three types of collection types: 1. Map type. The Map collection stores key-value pairs. The keys cannot be repeated, but the values ​​can be repeated. 2. Set type. The objects stored in the Set are unordered and cannot be Repeated, the objects in the collection are not sorted in a specific way; 3. List type, the objects stored in the List are ordered and repeatable, and the query speed is high.

What are the collection types of JavaScript?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

There are three collection types in JavaScript: set, list and map.

1. Map (key-value pairs, unique keys, non-unique values):

Map is a set of key-value pair structures, which is extremely fast search speed. Created by passing in an array of arrays. Add new elements by calling .set(key,value).

var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);
m.get('Michael'); // 95
m.set('Adam', 67); // 添加新的key-value
Copy after login

For example, suppose you want to find the corresponding grades based on the names of classmates. If you use Array to implement it, you need two Arrays:

var names = ['Michael', 'Bob', 'Tracy'];
var scores = [95, 75, 85];
Copy after login

Given a name, you want to find the corresponding grades. You need to first find the corresponding position in names, and then retrieve the corresponding results from scores. The longer the Array, the longer it takes.

If implemented using Map, only a "name"-"score" comparison table is needed, and the results can be searched directly based on the name. No matter how big the table is, the search speed will not slow down.

Write a Map in JavaScript as follows:

var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);
m.get('Michael'); // 95
Copy after login

Initializing the Map requires a two-dimensional array, or directly initialize an empty Map.

Map has the following methods:

var m = new Map(); // 空Map
m.set('Adam', 67); // 添加新的key-value
m.set('Bob', 59);
m.has('Adam'); // 是否存在key 'Adam': true
m.get('Adam'); // 67
m.delete('Adam'); // 删除key 'Adam'
m.get('Adam'); // undefined
Copy after login

Since one key can only correspond to one value, if you put value into a key multiple times, the subsequent value will flush out the previous value:

var m = new Map();
m.set('Adam', 67);
m.set('Adam', 88);
m.get('Adam'); // 88
Copy after login

1) Properties and methods

Definition: A collection of key/value pairs.

Syntax: mapObj = new Map()

Note: The keys and values ​​in the collection can be of any type. If you add a value to the collection using an existing key, the new value replaces the old value.

Map Object PropertiesDescription
ConstructorSpecify the function that creates the mapping
Prototype — PrototypeReturns a reference to the prototype for the mapping
ConstructorReturn the number of elements in the map
##Map object methodDescriptionclearRemove all elements from the map deleteRemove from the map The specified elementforEachPerforms the specified operation on each element in the mapgetReturn the specified element in the maphasIf the map contains the specified element, return truetoStringReturn the string representation of the mapsetAdd a new element to the mapvalueOfReturns the primitive value of the specified object
// 如何将成员添加到 Map,然后检索它们
var m = new Map();
m.set(1, "black");
m.set(2, "red");
m.set("colors", 2);
m.set({x:1}, 3);

m.forEach(function (item, key, mapObj) {
    document.write(item.toString() + "<br />");
});

document.write("<br />");
document.write(m.get(2));

// Output:
// black
// red
// 2
// 3
//
// red
Copy after login

2、Set(无序、不能重复):

Set和Map类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在Set中,没有重复的key。

Set里存放的对象是无序,不能重复的,集合中的对象不按特定的方式排序,只是简单地把对象加入集合中。

1)创建Set

Set 本身是一个构造函数,调用构造函数用来生成 Set 数据结构。

关键词 标识符 = new Set();
Copy after login

var s1 = new Set(); // 空Set
var s2 = new Set([1, 2, 3]); // 含1, 2, 3
Copy after login

Set 函数可以接受一个数组(或类似数组的对象)作为参数,用来进行数据初始化。

let i = new Set([1, 2, 3, 4, 4]);  //会得到  set{1, 2, 3, 4,}
Copy after login

注:如果初始化时给的值有重复的,会自动去除。集合并没有字面量声明方式。

2)Set的属性

常用的属性就一个:size   返回 Set 实例的成员总数。

let s = new Set([1, 2, 3]);
console.log( s.size ); // 3
Copy after login

3)Set的方法

Set 实例的方法分为两大类:操作方法(用于数据操作)和遍历方法(用于遍历数据)。

操作方法:

  • add(value)    添加数据,并返回新的 Set 结构

  • delete(value)   删除数据,返回一个布尔值,表示是否删除成功

  • has(value)    查看是否存在某个数据,返回一个布尔值

  • clear()      清除所有数据,没有返回值

let set = new Set([1, 2, 3, 4, 4]);
// 添加数据 5
let addSet = set.add(5);
console.log(addSet); // Set(5) {1, 2, 3, 4, 5}
// 删除数据 4s
let delSet = set.delete(4);
console.log(delSet); // true
// 查看是否存在数据 4
let hasSet = set.has(4);
console.log(hasSet); // false
// 清除所有数据
set.clear();
console.log(set); // Set(0) {}
Copy after login

遍历方法:

Set 提供了三个遍历器生成函数和一个遍历方法。

  • keys()     返回一个键名的遍历器

  • values()    返回一个键值的遍历器

  • entries()    返回一个键值对的遍历器

  • forEach()   使用回调函数遍历每个成员

let color = new Set(["red", "green", "blue"]);
for(let item of color.keys()){
 console.log(item);
}
// red
// green
// blue
for(let item of color.values()){
 console.log(item);
}
// red
// green
// blue
for(let item of color.entries()){
 console.log(item);
}
// ["red", "red"]
// ["green", "green"]
// ["blue", "blue"]
color.forEach((item) => {
 console.log(item)
})
// red
// green
// blue
Copy after login

3、List(有序、可重复) :

列表是一组有序的数据,每个列表中的数据项称为元素。

List里存放的对象是有序的,同时也是可以重复的,List关注的是索引,拥有一系列和索引相关的方法,查询速度快。因为往list集合里插入或删除数据时,会伴随着后面数据的移动,所有插入删除数据速度慢。

列表拥有描述元素位置的属性,列表有前有后(front和end)。

使用next()方法可以从当前元素移动到下一个元素,使用next() 可以从当前元素移动到下一个元素,使用prev()方法可以移动到当前元素的前一个元素,还可以使用moveTo(n)方法直接移动到指定位置

1)List的方法:

  • 定义的属性有:

    • listSize : 列表的元素个数

    • pos: 列表的当前位置

  • 定义的方法有:

    • getElement(): 返回当前位置的元素

    • insert(): 在现有元素后插入新元素

    • append(): 在列表的尾部添加新元素

    • remove(): 从列表中删除元素

    • length(): 返回列表中元素的个数

    • clear(): 清空列表

    • contains(): 判断元素是否存在列表中

  • 移动元素:

    • front(): 将列表的当前位置移动到第一个元素

    • end(): 将列表的当前位置移动到最后一个元素

    • prev(): 将当前位置后移一位

    • next(): 将当前位置前移一位

    • currPos(): 返回列表的当前位置

    • moveTo(): 将当前位置移动到指定位置

2)List的实现

  • 使用数组实现一个列表,并初始化属性值

function List() {
    this.listSize = 0; //记录列表元素的个数
    this.pos = 0; //记录列表的位置
    this.dataStore = []; //存储列表元素
}
Copy after login
  • append(element) 添加元素

给列表尾部添加新元素的方法与栈的压栈方法一样;

将记录元素个数的listSize加1,从而获取到存储元素的位置;再将元素添加到这个位置;

function append(element) {
    //让列表的长度加1,再将元素填充到新增的位置
    this.dataStore[this.listSize++] = element;
}
Copy after login
  • find(element) 查找元素

首先遍历列表,如果要查找的元素存在列表中,则返回该元素的位置,未找到则返回-1

function find(element) {
    //遍历列表
    for (let i = 0; i < this.dataStore.length; ++i) {
        //判断列表中是否有该元素,存在则返回索引i
        if (this.dataStore[i] == element) {
            return i;
        };
    };
    //不存在返回-1
    return -1;
};
Copy after login
  • remove(element) 删除元素

先调用find方法,查找元素的位置,如果存在返回true,不存在则会返回false;

如果存在,使用js数组操作方法splice删除当前元素,splice方法接收两个参数,即要删除的元素的索引和要删除的个数;

删除元素后,要将列表的长度减1;

function remove(element) {
    //调用定义的find方法查找元素
    let fountAt = this.find(element);
    //元素存在
    if (fountAt > -1) {
        //删除索引对应的值
        this.dataStore.splice(fountAt, 1);
        //列表少了一个元素,减1
        --this.listSize;
        //操作成功返回true
        return true;
    };
    //找不到元素返回false
    return false;
};
Copy after login
  • length() 查询列表中有多少元素

该方法返回列表中的元素,直接返回listSize的值

function length() {
    return this.listSize;
}
Copy after login
  • insert(element, after) 向列表中插入元素

该方法是将目标元素插入到指定元素的后面,它接收两个参数,即目标元素element和指定元素after;

实现:先使用定义的find方法找到after的位置,然后使用splice方法在该位置的后一位插入目标元素;

splice方法传入三个参数,目标值的位置,要删除的数量,要插入的值(第二个参数为0表示删除0个,不删除元素);

操作成功返回true, 未找到指定元素则返回false

function insert(element, after) {
    let insertPos = this.find(after);
    if (insertPos > -1) {
        this.dataStore.splice(insertPos + 1, 0, element);
        ++this.listSize;
        return true;
    };
    return false;
}
Copy after login
  • clear() 清空列表

删除列表,初始化数据

function clear() {
    delete this.dataStore;
    this.dataStore = [];
    this.listSize = 0;
    this.pos = 0;
};
Copy after login
  • contains(element) 判断元素是否存在列表中

与find方法类似,也可直接使用find方法查找,找到返回true,不存在返回false

function contains(element) {
	for (let i = 0; i < this.dataStore.length; ++i) {
        if (this.dataStore[i] == element) {
            return true;
        };
    };
    return false;
};
Copy after login
  • 迭代器:移动列表中的元素

创建手动迭代列表的一些方法,可以不用关心数据的内部存储方法,以实现对列表的遍历。

//移动到最前面
function front() {
    this.pos = 0;
};
//移动到最后面
function end() {
    this.pos = this.listSize - 1;
};
//往后移一位
function prev() {
    if (this.pos > 0) {
        --this.pos;
    };
};
//往前移一位
function next() {
    if (this.pos < this.listSize-1) {
        ++this.pos;
    };
};
//返回列表当前的位置
function currPos() {
    return this.pos;
};
//移动到指定的位置
function moveTo(position) {
    this.pos = position;
};
//返回当前元素的位置
function getElement() {
    return this.dataStore[this.pos];
};
Copy after login

【相关推荐:javascript视频教程web前端

The above is the detailed content of What are the collection types of JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!