HashMap使用举例

HashMap关于名字查询的简单使用

phone-book-map.js

const input = `3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry
hello
`;
const arrInput = input.split('\n');
function getLength(arrInput) {
    return arrInput[0];
}

const size = parseInt(getLength(arrInput));
const allLength =  arrInput.length;

function buildMap(arrInput,size) {
    const phoneBook = new Map();
    for (let i = 0 ; i< size;i ++) {
        const phoneBookItem = arrInput[i+1].split(' ');
        phoneBook.set(phoneBookItem[0],phoneBookItem[1]);
    }
    return phoneBook;
}
const phoneBook = buildMap(arrInput, size);

function search(arrInput,phoneBook, size, restLength) {
    for (let i = 0 ; i< restLength; i++) {
        const name = arrInput[i+size+1];
        if (phoneBook.has(name)) {
            console.log(name+'='+phoneBook.get(name));
        } else {
            console.log('Not found');
        }
    }
}
search(arrInput,phoneBook,size,(allLength - size-1));

版权声明:著作权归作者所有。

thumb_up 0 | star_outline 0 | textsms 0