Est-il possible de créer un objet pouvant être utilisé comme un tableau et un objet?Création d'un objet de type tableau JavaScript pouvant être utilisé comme un tableau et un objet
Le plus proche que je l'ai obtenu à ce jour est ci-dessous qui vient vous permet d'attribuer une valeur à l'aide soit une clé de tableau ou objet propriété:
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"]);
Je voudrais pouvoir créer automatiquement ce qui est nécessaire lors de l'attribution d'un élément non existant, par exemple
ALO[1] = "create and assign this string";
ou
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
Quel comportement essayez-vous d'obtenir qui est différent d'un objet JS normal, c'est-à-dire 'var a = {}'? – Ryan1729