1. 程式人生 > >【JavaScript】Array 物件(二)[並列陣列、多維陣列、陣列字串相互轉換]

【JavaScript】Array 物件(二)[並列陣列、多維陣列、陣列字串相互轉換]

  使用陣列儲存資料,常常允許用一個指令碼查詢陣列中是否有某一個值(可能驗證使用者輸入到文字框中的資料是否是可接受的)。另外,在查詢匹配的項時,指令碼可以在另一個數組中查詢一些相關的資訊。完成這個任務的

  • 一種方式是使用兩個或多個並行陣列
  • 另一種方式是模擬多維陣列(並行陣列的替代方法)

並列陣列

考慮下面的三個陣列:

var regionalOffices = ["New York", "Chicago", "Houston", "Portland"];
var regionalManagers = ["Shirley Smith", "Todd Gaston", "Leslie Jones"
, "Harold Zoot"]; var reOfficeQuotes = [300000, 250000, 350000, 225000];

  這些語句假定,Shirley Smith 是紐約辦公室的區域經理,她的辦公室經費是300000。這些資料放在一個文件中,可以通過一個伺服器端程式得到,此程式從 SQL 資料庫中獲得最新的資料,並通過陣列建構函式嵌入這些資料。把這些資料顯示在一個簡單的頁面上,並通過 select 元素查詢經理姓名和辦公經費值。select 元素列表中資料項的順序不是隨機的:為了方便查詢指令碼,該順序與陣列的順序相同。

例子:一個簡單的並行陣列查詢

// html
<form id="officeData"
action="" method="post"> <p> <label for="offices">Select a regional office: </label> <select id="offices" name="offices"></select> </p> <p> <label for="manager">The manager is: </label> <input type="text"
id="manager" name="manager" size="35" /> </p> <p> <label for="quota">The office quota is: </label> <input type="text" id="quota" name="quota" size="8" /> </p> </form> // js addEvent(window, 'load', initialize); function initialize() { if(document.getElementById) { aRegionalOffices = ["New York", "Chicago", "Houston", "Portland"]; aRegionalManagers = ["Shirley Smith", "Todd Gaston", "Leslie Jones", "Harold Zoot"]; aRegOfficeQuotas = [300000, 250000, 350000, 225000]; oSelect = document.getElementById('offices'); oManager = document.getElementById('manager'); oQuota = document.getElementById('quota'); if(oSelect && oManager && oQuota) { for(var i=0; i<aRegionalOffices.length; i++) { oSelect.options[i] = new Option(aRegionalOffices[i]); } addEvent(oSelect, 'change', getData); } getData(); } } function getData(evt) { var index = oSelect.selectedIndex; oManager.value = aRegionalManagers[index]; oQuota.value = aRegionalQuotas[index]; }

多維陣列

  上面的例子原理簡單,就是依靠相同的索引值將多個數組有關聯的串聯起來使用,但一個合理的方法是建立自定義物件的陣列,因為物件屬性的命名很容易理解,所以多維陣列中的資料引用更易於讀取。

將上面並行陣列的例子重寫為多維陣列:

function officeRecord(city, manager, quota) {
    this.city = city;
    this.manager = manager;
    this.quota = quota;
}

var regionalOffices = new Array();

// 傳統的多維陣列方式
regionalOffices[0] = new officeRecord("New York", "Shirley Smith", 300000);
regionalOffices[1] = new officeRecord("Chicago", "Todd Gaston", 250000);
regionalOffices[2] = new officeRecord("Houston", "Leslie Jones", 350000);
regionalOffices[3] = new officeRecord("Portland", "Harold Zoot", 255000);

// 也可以使用非常簡潔的字面量記號
var regionalOffices = [
    ["New York", "Shirley Smith", 300000],
    ["Chicago", "Todd Gaston", 250000],
    ["Houston", "Leslie Jones", 350000],
    ["Portland", "Harold Zoot", 255000]
]

訪問陣列中陣列的單個值需要兩個陣列引用。例如,獲得 Houston 辦公室經理的姓名要使用以下語法:

var HoustonMgr = regionalOffices[2][1];

模擬 Hash 表

在 ES6 之前,JavaScript 是沒有 hashmap 的。
ES6 以 Map 和 Set 形式引入原生的 hashmap。

  利用字串索引查詢物件屬性有時非常有用。上面例子中只有5項,所以工作量不大。但如果列表有 100 項,這個處理就相當耗時。更快捷的方法是直接跳到 city 屬性是所選值的陣列項。此時可使用模擬 Hash 表。

下面是通過建構函式得到一個雜湊表,在使用時只需例項化即可,且下面的功能較為豐富,在實際問題中,我們可以選擇性的使用 。

// 建立建構函式HashTable
function HashTable() {
    // 初始化雜湊表的記錄條數size
    var size = 0;

    // 建立物件用於接受鍵值對
    var res = {};

    // 新增關鍵字,無返回值
    this.add = function (key, value) {

        //判斷雜湊表中是否存在key,若不存在,則size加1,且賦值 
        if (!this.containKey(key)) {
            size++;
        }

        // 如果之前不存在,賦值; 如果之前存在,覆蓋。
        res[key] = value;
    };

    // 刪除關鍵字, 如果雜湊表中包含key,並且delete返回true則刪除,並使得size減1
    this.remove = function (key) {
        if (this.containKey(key) && (delete res[key])) {
            size--;
        }
    };

    // 雜湊表中是否包含key,返回一個布林值
    this.containKey = function (key) {
        return (key in res);
    };

    // 雜湊表中是否包含value,返回一個布林值
    this.containValue = function (value) {

        // 遍歷物件中的屬性值,判斷是否和給定value相等
        for (var prop in res) {
            if (res[prop] === value) {
                return true;
            }
        }
        return false;
    };

    // 根據鍵獲取value,如果不存在就返回null
    this.getValue = function (key) {
        return this.containKey(key) ? res[key] : null;
    };

    // 獲取雜湊表中的所有value, 返回一個數組
    this.getAllValues = function () {
        var values = [];
        for (var prop in res) {
            values.push(res[prop]);
        }
        return values;
    };

    // 根據值獲取雜湊表中的key,如果不存在就返回null
    this.getKey = function (value) {
        for (var prop in res) {
            if (res[prop] === value) {
                return prop;
            }
        }

        // 遍歷結束沒有return,就返回null
        return null;
    };

    // 獲取雜湊表中所有的key,返回一個數組
    this.getAllKeys = function () {
        var keys = [];
        for (var prop in res) {
            keys.push(prop);
        }
        return keys;
    };

    // 獲取雜湊表中記錄的條數,返回一個數值
    this.getSize = function () {
        return size;
    };

    // 清空雜湊表,無返回值
    this.clear = function () {
        size = 0;
        res = {};
    };
}

Hash 表 應用例項

問題:給定一個整型的陣列(無序),找出其中的兩個數使得其和為某個指定的值,並返回這兩個數的下標(陣列下標從0開始),假設陣列元素的值各不相同。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>雜湊表的使用</title>
</head>
<body>
    <script>
    function queryIndex(arr, result) {
        var hashTable = new HashTable();
        var arrLength = arr.length;
        var sub = [];
        for (var i = 0; i < arrLength; i++) {

            // 掃描一遍,儲存下標和值 
            hashTable.add(i, arr[i]);
        }
        for (var j = 0; j < arrLength; j++) {
            if (hashTable.containValue(result - arr[j]) && result !== 2*arr[j]) {
                // 獲取兩個下標,跳出迴圈
                sub.push(j);
                var antherIndex = Number(hashTable.getKey(result - arr[j]));
                sub.push(antherIndex);
                break;
            }
        }
        if (sub.length !== 0) {
            return sub;
        } else {
            return -1;
        }


    }
    console.log(queryIndex([1,5,7,3,8], 15)); // 2, 4
    console.log(queryIndex([8,18,28,12,29,17], 46)); // 2, 4
    console.log(queryIndex([8,18,28,12,29,17], 2)); // -1


     // 建立建構函式HashTable
    function HashTable() {
        // 初始化雜湊表的記錄條數size
        var size = 0;

        // 建立物件用於接受鍵值對
        var res = {};

        // 新增關鍵字,無返回值
        this.add = function (key, value) {

            //判斷雜湊表中是否存在key,若不存在,則size加1,且賦值 
            if (!this.containKey(key)) {
                size++;
            }

            // 如果之前不存在,賦值; 如果之前存在,覆蓋。
            res[key] = value;
        };

        // 刪除關鍵字, 如果雜湊表中包含key,並且delete返回true則刪除,並使得size減1
        this.remove = function (key) {
            if (this.containKey(key) && (delete res[key])) {
                size--;
            }
        };

        // 雜湊表中是否包含key,返回一個布林值
        this.containKey = function (key) {
            return (key in res);
        };

        // 雜湊表中是否包含value,返回一個布林值
        this.containValue = function (value) {

            // 遍歷物件中的屬性值,判斷是否和給定value相等
            for (var prop in res) {
                if (res[prop] === value) {
                    return true;
                }
            }
            return false;
        };

        // 根據鍵獲取value,如果不存在就返回null
        this.getValue = function (key) {
            return this.containKey(key) ? res[key] : null;
        };

        // 獲取雜湊表中的所有value, 返回一個數組
        this.getAllValues = function () {
            var values = [];
            for (var prop in res) {
                values.push(res[prop]);
            }
            return values;
        };

        // 根據值獲取雜湊表中的key,如果不存在就返回null
        this.getKey = function (value) {
            for (var prop in res) {
                if (res[prop] === value) {
                    return prop;
                }
            }

            // 遍歷結束沒有return,就返回null
            return null;
        };

        // 獲取雜湊表中所有的key,返回一個數組
        this.getAllKeys = function () {
            var keys = [];
            for (var prop in res) {
                keys.push(prop);
            }
            return keys;
        };

        // 獲取雜湊表中記錄的條數,返回一個數值
        this.getSize = function () {
            return size;
        };

        // 清空雜湊表,無返回值
        this.clear = function () {
            size = 0;
            res = {};
        };
    }
    </script>
</body>
</html>

陣列、字串互相轉換

陣列 轉 字串

var arr = [1,2,3,4,'巴德','merge'];
var str = arr.toString(arr);
console.log(str);       // 1,2,3,4,巴德,merge

字串 轉 陣列

var str = '1,2,3,4,巴德,merge';
var arr = str.split(',');
console.log(arr);       // ["1","2","3","4","巴德","merge"];
console.log(arr[4]);    // 巴德