WEB专题---javaScript中Map、Set的使用&&&HTML5 Web 存储

字数 351阅读 42

Map

Map是一组键值对的结构,具有极快的查找速度。

Map的定义。

//空map设值key-value
var m = new Map();
m.set("XiaoMing",99);
m.set("XiaoHong",66);
//构造参数传key-value
var m = new Map([['XiaoMing', 99], ['XiaoHong', 66]]);

Map中的方法

var m = new Map(); // 空Map
m.set('XiaoMing', 99); // 添加新的key-value
m.has('XiaoMing'); // 是否存在key 'XiaoMing': true
m.get('XiaoMing'); // 99
m.delete('XiaoMing'); // 删除key 'XiaoMing'
m.get('XiaoMing'); // undefined

对一个key重复设值,后面的值会将前面的值覆盖。

var m = new Map();
m.set('XiaoMing', 99);
m.set('XiaoMing', 98);
m.get('XiaoMing'); // 98

Set

Set和Map类似,但set之存储key,且key不重复。

Set的创建。

var s1 = new Set(); // 空Set
s1.add(1);
s1.add(2);
s1.add(3);

var s2 = new Set([1, 2, 3]); // 含1, 2, 3

插入重复的值,set会将重复的值进行过滤

var s = new Set([1, 2, 3]);
s.add(3);
>>s; // Set{1,2,3}
s.delete(3);
>>s; // Set([1,2]);

Map及Set的遍历

Array可以采用下标进行循环遍历,Map和Set就无法使用下标。为了统一集合类型,ES6标准引入了iterable类型,Array、Map、Set都属于iterable类型。

具有iterable类型的集合可以通过新的for ... of循环来遍历。

var a = ['A', 'B', 'C'];
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
for (var x of a) { // 遍历Array
    alert(x);
}
for (var x of s) { // 遍历Set
    alert(x);
}
for (var x of m) { // 遍历Map
    alert(x[0] + '=' + x[1]);
}

更好的遍历:forEach

forEach是iterable内置的方法,它接收一个函数,每次迭代就自动回调该函数。

var a = ['A', 'B', 'C'];
a.forEach(function (element, index, array) {
    // element: 指向当前元素的值
    // index: 指向当前索引
    // array: 指向Array对象本身
    alert(element);
});

Set与Array类似,但Set没有索引,因此回调函数的前两个参数都是元素本身:

var s = new Set(['A', 'B', 'C']);
s.forEach(function (element, sameElement, set) {
    alert(element);
});

Map的回调函数参数依次为value、key和map本身:

var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
m.forEach(function (value, key, map) {
    alert(value);
});

==================================================
HTML5 Web 存储
很简单
直接上代码:

import React from 'react';
import DataManagerCommonUtil from "./data.manager.common.util";


export default class LocalStorageCommonUtil {
    static instanceThis: LocalStorageCommonUtil;

    static instance(): LocalStorageCommonUtil {
        if (!LocalStorageCommonUtil.instanceThis) {
            LocalStorageCommonUtil.instanceThis = new LocalStorageCommonUtil();
        }
        return LocalStorageCommonUtil.instanceThis;
    }

    isMeSupportStorage(): boolean {
        if (typeof(Storage) !== "undefined") {
            console.log('是的! 支持 localStorage  sessionStorage 对象!');
            return !!localStorage;
        } else {
            console.log('抱歉! 不支持 web 存储。');
            return false;
        }
    }

    /**
     * 保存数据
     * @param key
     * @param value
     */
    setItem(key, value): void {
        if (this.isMeSupportStorage() && key && value) {
            localStorage.setItem(key, value)
        }
    }

    /**
     * 读取数据
     * @param key
     * @returns {*}
     */
    getItem(key): any {
        if (this.isMeSupportStorage() && key) {
            return localStorage.getItem(key)
        } else {
            return null;
        }
    }

    /**
     * 删除单个数据
     * @param key
     */
    removeItem(key): void {
        if (this.isMeSupportStorage() && key) {
            localStorage.removeItem(key)
        }
    }

    /**
     * 删除所有数据
     */
    clear(): void {
        if (this.isMeSupportStorage()) {
            localStorage.clear()
        }
    }

    /**
     * 得到某个索引的key
     * @param index
     */
    key(index): any {
        if (this.isMeSupportStorage() && index >= 0) {
            return localStorage.key(index)
        } else {
            return null;
        }
    }


}
import React, {PropTypes} from 'react';
import LocalStorageCommonUtil from "./local.storage.common.util";


export default class DataManagerCommonUtil {


    dataWorkSpaces: Map = null;
    static instanceThis: DataManagerCommonUtil;

    static instance(): DataManagerCommonUtil {
        if (!DataManagerCommonUtil.instanceThis) {
            DataManagerCommonUtil.instanceThis = new DataManagerCommonUtil();
        }
        return DataManagerCommonUtil.instanceThis;
    }

    init(workspaceKey, workspaceValue): DataManagerCommonUtil {
        if (!this.dataWorkSpaces) {
            this.dataWorkSpaces = new Map();
        }
        this.dataWorkSpaces.set(workspaceKey, workspaceValue);
        return this;
    }


    check(workspaceKey): boolean {
        if (this.dataWorkSpaces) {
            return this.dataWorkSpaces.has(workspaceKey);
        }
        return false;
    }

    delete(workspaceKey): boolean {
        if (this.dataWorkSpaces && this.dataWorkSpaces.has(workspaceKey)) {
            return this.dataWorkSpaces.delete(workspaceKey);
        }
        return false;
    }

    generRealKey(workspaceKey, key): String {
        return workspaceKey + '.' + key;
    }

    //--------------------------------------------------------------------

    /**
     * 保存数据
     * @param workspaceKey
     * @param key
     * @param value
     */
    setItem(workspaceKey, key, value): void {
        if (this.check(workspaceKey)) {
            LocalStorageCommonUtil.instance().setItem(this.generRealKey(workspaceKey, key), value);
        }
    }

    /**
     * 读取数据
     * @param workspaceKey
     * @param key
     * @returns {*}
     */
    getItem(workspaceKey, key): any {
        if (this.check(workspaceKey)) {
            return LocalStorageCommonUtil.instance().getItem(this.generRealKey(workspaceKey, key));
        } else {
            return null;
        }
    }

    /**
     * 删除单个数据
     * @param workspaceKey
     * @param key
     */
    removeItem(workspaceKey, key): void {
        if (this.check(workspaceKey)) {
            LocalStorageCommonUtil.instance().removeItem(this.generRealKey(workspaceKey, key));
        }
    }

    /**
     * 删除所有数据
     * @param workspaceKey
     * @param key
     */
    clear(workspaceKey, key): void {
        if (this.check(workspaceKey)) {
            this.delete(workspaceKey);
            LocalStorageCommonUtil.instance().removeItem(this.generRealKey(workspaceKey, key));
        }
    }

    /**
     * 得到某个索引的key
     * @param workspaceKey
     * @param index
     */
    key(workspaceKey, index): void {
        if (this.check(workspaceKey)) {
            return LocalStorageCommonUtil.instance().key(index);
        } else {
            return null;
        }
    }

}
import React, {PropTypes} from 'react';
import DataManagerCommonUtil from "./data.manager.common.util";


export default class AppManagerCommonUtil {
    user = {
        workspaceKey: 'com.hack.wang.yi.tao.desgin.web.back.site.user',
        workspaceValue: 'data',
    };
    system = {
        workspaceKey: 'com.hack.wang.yi.tao.desgin.web.back.site.system',
        workspaceValue: 'data',
    };


    static instanceThis: AppManagerCommonUtil;

    static instance(): AppManagerCommonUtil {
        if (!AppManagerCommonUtil.instanceThis) {
            AppManagerCommonUtil.instanceThis = new AppManagerCommonUtil();
        }
        return AppManagerCommonUtil.instanceThis;
    }

    init(): AppManagerCommonUtil {
        DataManagerCommonUtil.instance()
            .init(this.user.workspaceKey, this.user.workspaceValue)
            .init(this.system.workspaceKey, this.system.workspaceValue);
    }

    constructor() {
        this.init();
    }

    save(workspaceKey: String, key: String, dataStr: String): void {
        DataManagerCommonUtil.instance().setItem(workspaceKey, key, dataStr);
    }

    remove(workspaceKey: String, key: String): void {
        DataManagerCommonUtil.instance().removeItem(workspaceKey, key);
    }

    load(workspaceKey: String, key: String): void {
        return DataManagerCommonUtil.instance().getItem(workspaceKey, key);
    }

    //-----------------------------------------

    saveUser(userData: JSON): void {
        if (userData) {
            this.save(this.user.workspaceKey, this.user.workspaceValue, JSON.stringify(userData));
        }
    }

    removeUser(): void {
        this.remove(this.user.workspaceKey, this.user.workspaceValue);
    }

    loadUser(): JSON {
        let result = this.load(this.user.workspaceKey, this.user.workspaceValue);
        if (result) {
            return JSON.parse(result);
        } else {
            return result;
        }
    }

    saveSystem(userData: JSON): void {
        if (userData) {
            this.save(this.system.workspaceKey, this.system.workspaceValue, JSON.stringify(userData));
        }
    }

    removeSystem(): void {
        this.remove(this.system.workspaceKey, this.system.workspaceValue);
    }

    loadSystem(): JSON {
        let result = this.load(this.system.workspaceKey, this.system.workspaceValue);
        if (result) {
            return JSON.parse(result);
        } else {
            return result;
        }
    }


    //---------------
    isLogin(): boolean {
        let result = this.loadUser();
        return !!(result && result.sessionId);
    }


}

COVER:
http://www.runoob.com/html/html5-webstorage.html
https://www.cnblogs.com/weilan/p/7002088.html

推荐阅读更多精彩内容