简体   繁体   English

关联数组如果从regexp返回,则正在对索引进行排序

[英]Associative array was sorting indexs if it return from regexp

I need to save order in array. 我需要将订单保存在数组中。 A normal array was destroying it, so i found associative array, but with indexes from regexp was sorting records too. 普通数组正在销毁它,所以我找到了关联数组,但是正则表达式中的索引也对记录进行了排序。 My function is 我的功能是

var myArray = {};
var searchIndex = '';
$("#searchList").find('li').each(function( index ) {
    id = $( this ).attr('id');
    if(id.match(/search(:?\d+|\w+)/)){
        searchIndex = id.match(/search(\d+|\w+)/)[1]; 
        myArray[searchIndex] = "empty";
    }
});

This code works well, order are saved. 此代码运行良好,订单已保存。

myArray[id] = "empty"; 

http://screenshooter.net/100008827/fhbsvjm But when i want to remove string "search" from id, by regexp, array just sorting indexes... http://screenshooter.net/100008827/fhbsvjm但是当我想从ID中删除字符串“搜索”时,通过正则表达式,数组仅对索引进行排序...

searchIndex = id.match(/search(\d+|\w+)/)[1]; 
myArray[searchIndex] = "empty";

http://screenshooter.net/100008827/gmxusyu But order should be last->7->9->8 http://screenshooter.net/100008827/gmxusyu但顺序应为last-> 7-> 9-> 8

JavaScript does not have associative arrays. JavaScript没有关联数组。 The plain objects in JavaScript are similar to associative arrays in some ways, but the order of their properties is not guaranteed. JavaScript中的普通对象在某些方面类似于关联数组,但是不能保证其属性顺序。

If you want an associative array that preserves the order of items in the order they were added, it is possible to create one from scratch. 如果您想要一个关联数组,可以按添加顺序保留项目的顺序,则可以从头开始创建一个。 Here is a fairly simple implementation that provides that functionality: 这是一个提供该功能的相当简单的实现:

 function AssociativeArray() { var items = []; var refs = {}; this.set = function(key, value) { if (key in refs) { refs[key].value = value; } else { var entry = { key: key, value: value }; items.push(entry); refs[key] = entry; } }; this.get = function(key) { var entry = refs[key]; return entry && entry.value; }; this.allItems = function() { return items.slice(); }; } var assoc = new AssociativeArray(); assoc.set(7, "hello"); assoc.set(3, "goodbye"); assoc.set("cheer", "yay"); var items = assoc.allItems(); for (var i = 0; i < items.length; i += 1) { console.log(items[i].key + " - " + items[i].value); } console.log("The item with key 7 is: " + assoc.get(7)); 

The way you would adapt this to your current code is: 使它适应当前代码的方式是:

var myArray = new AssociativeArray();
$("#searchList").find('li').each(function( index ) {
    var id = $( this ).attr('id'),
        searchIndex;
    if(id.match(/search(:?\d+|\w+)/)){
        searchIndex = id.match(/search(\d+|\w+)/)[1]; 
        myArray.set(searchIndex, "empty");
    }
});

The first code snippet above shows how to iterate through the array in the order that items were added. 上面的第一个代码段显示了如何按照添加项目的顺序遍历数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM