开发者

Javascript array with custom properties

I have started using a techique for indexing arrays by adding a key property to the array. This is useful if you wish to preserve the order of an array but also do quick lookups on it (especially when getting data sets from JSON). The advantage of the the individual key properties is that they are a reference back to the original item in the array saving on memory.

Can anyone think of any memory/implications for this techniq开发者_如何学编程ue? Already I am running into minor issues such as:

  • Qunit cannot test for a property on array as it expects an array type,
  • jQuery extend won't copy the key property when copying an arrray.

These aside this seems the nicest way to index an array while mainting its order.

var keyArray = function(arrayToKey,property){
        if (typeof arrayToKey !== 'undefined') {
            arrayToKey.key = {};
            var l = arrayToKey.length,
                i = 0;
            if (typeof property !== 'undefined') {
                for (i = 0; i < l; i++) {
                    if (arrayToKey[i] !== null) {
                        arrayToKey.key[arrayToKey[i][property]] = arrayToKey[i];
                    }
                }
            } else {
                for (i = 0; i < l; i++) {
                    if (arrayToKey[i] !== null) {
                        arrayToKey.key[arrayToKey[i]] = true;
                    }
                }
            }
        } else {
            return null;
        }
    };

This takes an array and either: keys it on the content of each array item, or if a property name is passed in it keys it on the property of each object in the array e.g.

Example 1:
keyArray(['hello','nice','world']);
-> 
['hello',' ','world'].key{
    hello: true,
    nice, true,
    world, true
};
Example 2:
keyArray([
    {
        name: 'hello',
        value: 'hello value'
    },
    {
        name: 'nice',
        value: '  value'
    },
    {
        name: 'world',
        value: 'world value'
    }
]);
->
[
    {
        name: 'hello',
        value: 'hello value'
    },
    {
        name: 'nice',
        value: '  value'
    },
    {
        name: 'world',
        value: 'world value'
    }
].key{
    hello: {
        name: 'hello',
        value: 'hello value'
    },
    nice: {
        name: 'nice',
        value: 'nice value'
    },
    world: {
        name: 'world',
        value: 'world value'
    }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜