是否可以創建可以像數組和對象一樣使用的對象?創建可以像數組和對象一樣使用的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