Comme les autres l'ont dit, il est length
, pas lenght
.
Mais personne ne semble avoir abordé la deuxième partie de votre question, donc:
Vous n'avez pas besoin push
pour faire défiler les valeurs.Tout ce que vous avez besoin est un indice:
var fondetcaption = [
["fond/fond1.jpg","« aaa"],
["fond/fond2.jpg","« bbb"],
["fond/fond3.jpg","« ccc"],
["fond/fond4.jpg","« ddd"]
];
var fondetcaptionIndex = 0;
// Call this when you click your button or whatever
function getNextBackground() {
if (fondetcaptionIndex >= fondetcaption.length) {
fondetcaptionIndex = 0;
}
return fondetcaption[fondetcaptionIndex++];
}
Ou, si vous le souhaitez, vous pouvez simplement mettre l'index directement sur l'objet de tableau, puisque les objets de tableau JavaScript peuvent avoir arbitraires propriétés non-élément et qui aide à garder les symboles ensemble :
var fondetcaption = [
["fond/fond1.jpg","« aaa"],
["fond/fond2.jpg","« bbb"],
["fond/fond3.jpg","« ccc"],
["fond/fond4.jpg","« ddd"]
];
fondetcaption.index = 0;
// Call this when you click your button or whatever
function getNextBackground() {
if (fondetcaption.index >= fondetcaption.length) {
fondetcaption.index = 0;
}
return fondetcaption[fondetcaption.index++];
}
en fait, vous pouvez même faire la partie fonction du tableau:
var fondetcaption = [
["fond/fond1.jpg","« aaa"],
["fond/fond2.jpg","« bbb"],
["fond/fond3.jpg","« ccc"],
["fond/fond4.jpg","« ddd"]
];
fondetcaption.index = 0;
fondetcaption.getNext = function() {
if (this.index >= this.length) {
this.index = 0;
}
return this[this.index++];
};
// Use
background = fondetcaption.getNext();
Si faire le tableau lui-même le conteneur de ces propriétés supplémentaires vous dérange (i t dérange certaines personnes), envelopper le tout dans un objet:
var fondetcaption = (function() {
var index = 0,
values = [
["fond/fond1.jpg","« aaa"],
["fond/fond2.jpg","« bbb"],
["fond/fond3.jpg","« ccc"],
["fond/fond4.jpg","« ddd"]
];
function fondetcaption_getNext() {
if (index >= values.length) {
index = 0;
}
return values[index++];
}
return {
values: values,
getNext: fondetcaption_getNext
};
})();
// Sample use:
background = fondetcaption.getNext();
// Original array still accessible if desired as fondetcaption.values
longueur ou longueur? faute de frappe? – suhprano
Où utilisez-vous le tableau? parce que cela fonctionne pour moi http://i.imgur.com/QIiGy.png. Votre tableau est défini dans une portée locale, ce qui pourrait être votre problème. – mhitza