[英]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. 我想在JavaScript中创建一个可以同时通过索引和键访问的数据类型或对象,并且我还需要一个length属性来显示该数据类型中有多少项。 Kinda like..
MyDataType[0].name="John" MyDataType[0].salary="over 1k"
有点像
MyDataType[0].name="John" MyDataType[0].salary="over 1k"
So if I wrote: MyDataType['John'].salary //I should get "over 1k"
因此,如果我写了:
MyDataType['John'].salary //I should get "over 1k"
And if I wrote: MyDataType[0].salary //I should get also "over 1k"
如果我写了:
MyDataType[0].salary //I should get also "over 1k"
And I would like to have: MyDataType.length //should return 1
我想拥有:
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.
我尝试使用Proxy,它对于索引/键部分非常有效,但是它没有length属性。 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 对于像我一样挣扎的任何人,我终于找到了答案,在此感谢@ Quickredfox : 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.