是否可以创建可以像数组和对象一样使用的对象?创建可以像数组和对象一样使用的JavaScript数组对象
到目前为止,我已经得到的最接近的是下面这只是使得你可以使用数组键分配一个值或对象属性:
var ALO = {
db: {}
};
Object.defineProperty(ALO, 'length', {
get: function() {
var count = 0;
for (var prop in ALO.db) {
if (ALO.db.hasOwnProperty(prop)) count++;
}
return count;
},
enumerable: false
});
function add(baseObj, obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (!isNaN(prop)) {
//create a default string begining with i
baseObj.db["i" + prop] = obj[prop];
} else {
baseObj.db[prop] = obj[prop];
}
Object.defineProperty(baseObj, prop, {
get: function() {
return baseObj.db[prop];
},
set: function(newValue) {
baseObj.db[prop] = newValue;
},
enumerable: false,
configurable: true
});
Object.defineProperty(baseObj, baseObj.length - 1, {
get: function() {
return baseObj.db[prop];
},
set: function(newValue) {
baseObj.db[prop] = newValue;
},
enumerable: false,
configurable: true
});
}
}
}
add(ALO, {
"myprop": "myvalue"
});
document.write(ALO["myprop"] + "<br>");
ALO[0] = "mynewvalue";
document.write(ALO["myprop"] + "<br>");
ALO["myprop"] = "mynewervalue";
document.write(ALO["myprop"]);
我想能够自动创建分配不存在的项目时所需的内容,例如
ALO[1] = "create and assign this string";
或
ALO["somenonexistingprop"] = "another string";
http://www.nfriedly.com/techblog/2009/06/advanced-javascript-objects-arrays-and-array-like-objects/ – Barmar
http://2ality.com/2013/05/quirk- array-like-objects.html – Barmar
你想得到什么样的行为,与普通的JS对象不同,即'var a = {}'? – Ryan1729