简体   繁体   中英

How can I create a javascript data type (accessed with key and index)

I want to create a datatype or object in javascript that I can access by both index and key, and also I want a length property that shows how many items are in datatype. Kinda like.. MyDataType[0].name="John" MyDataType[0].salary="over 1k"

So if I wrote: MyDataType['John'].salary //I should get "over 1k"

And if I wrote: MyDataType[0].salary //I should get also "over 1k"

And I would like to have: MyDataType.length //should return 1

Is this possible? I tried with Proxy and it worked perfect for the index/key part but it didnt have a length property. I tried with array and it had index and length but no access with key

Thanks guys and please help me

For anyone who is struggling like I was, I finally found the answer to this, big thanks to @ Quickredfox here: https://stackoverflow.com/a/36511465/8816810

Well that's the code:

"use strict";
 var MyCollection = new Proxy(
[{
name: 'monkey',
 score: 50
}, {
    name: 'giraffe',
 score: 100
}, {
name: 'pelican',
score: 150
}, {
    name: 'ZZoo',
  score: 69
}], {
 get: function(obj, prop) {
  if (prop in obj) {
    // default behavior
    return obj[prop];
  }
  if (typeof prop == 'string') {

      if (prop == 'length') {
      return obj.sort(function(a, b) {
        return obj.length;
      });
    }    

   for (var i = 0; i < obj.length; i++) {
      var player = obj[i];
      if (player.name == prop) {
        return player;
      }
    }

    return;
  }

}
});

document.write(MyCollection.length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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