簡體   English   中英

在JavaScript數組中存儲相同的鍵和不同的值,並使用鍵值對進行匹配

[英]Storing same key and different values in JavaScript array and Matching with a key value pair

     $(document).on('change', '.units', function () {
            var obj = $(this);
            unit_id = parseInt($(this).val());
            var item_array = [];
            var unit_array = [];
            var units = $(".units");
            var items = $(".items");

            $('#used_items tr').each(function () {
                $(this).find('.items').each(function () {
                    item_array.push($(this).val());
                });
                $(this).find('.units').each(function () {
                    unit_array.push($(this).val());
                });
            });
            var item_unit_associative_array = [];
            for (var i = 0; i < units.length; i++) {
                if (item_unit_associative_array[item_array[i]] == unit_array[i]) {
                    obj.val('');
                    return alert("Given Item Unit Already Selected");
                }
                else {
                    item_unit_associative_array[item_array[i]] = unit_array[i];
                }
            }
            console.log(item_unit_associative_array););

item_arrayunit_array我想構建像這樣的新對象

var item_unit_associative_array = [1:12,1:13,1:14,2:10];

最后要檢查一個對象由key組成:值如何

var test = {1:12}

是否存在於item_unit_associative_array中

我認為你需要嵌套兩層物體 請參閱結構的注釋:

 var items = [ 1, 1, 1, 2]; var units = [12, 13, 14, 10]; // Create the object like so: // { // 1: { 12: true, 13: true, 14: true }, // 2: { 10: true } // } var itemUnitAssociativeObject = {}; units.forEach(function(unitId, i) { var itemId = items[i]; if (!itemUnitAssociativeObject[itemId]) { itemUnitAssociativeObject[itemId] = {}; } itemUnitAssociativeObject[itemId][unitId] = true; }); console.log("1:13", test(1, 13)); console.log("1:10", test(1, 10)); console.log("2:10", test(2, 10)); function test(item, unit) { return !!(itemUnitAssociativeObject[item] && itemUnitAssociativeObject[item][unit]); } 

如果你不喜歡嵌套和它使測試復雜化的方式,你也可以“stringify”item-unit id組合:

 var items = [ 1, 1, 1, 2]; var units = [12, 13, 14, 10]; // Create the object like so: // { // "1:12": true, // "1:13": true, // etc. // } var map = items.reduce(function(map, itemId, i) { var id = itemId + ":" + units[i]; map[id] = true; return map; }, {}); console.log("1:13", map["1:13"]); console.log("1:10", map["1:10"]); console.log("2:10", map["2:10"]); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM