Pages

Affichage des articles dont le libellé est array. Afficher tous les articles
Affichage des articles dont le libellé est array. Afficher tous les articles

le plus grand nombre de mots dans un paragraphe


nous sommes editables
C'est moi le plus grand !
Ecrivez ici des mots

Boucle sur un tableau

Voici différentes façons d’itérer sur un tableau !

let tab = [10, 11];

console.log(tab);

console.log('------- Boucle for in');
for (let index in tab){
console.log(` ${index} => ${tab[index]}`);
}
console.log('------- Boucle for in hasOwnProperty');
for (let index in tab){
if (tab.hasOwnProperty(index))
console.log(` ${index} => ${tab[index]}`);
}
console.log('------- Boucle for of ');
for (let val of tab){
console.log(` ${val} `);
}
console.log('------- Boucle forEach ');
tab.forEach(function (element, index,tab) {
console.log(` ${index} => ${element}`);
});
console.log('------- Boucle Object.keys');
Object.keys(tab).forEach(function (element, index) {
console.log(` ${index} => ${element}`);
});

Les différences entre toutes ces méthodes apparaitra plus clairement en modifiant les attributs.

Object.prototype.objCustom = function AjoutFxObj() {};
Array.prototype.arrCustom = function AjoutFxArr() {};

let tab = [10, 11];
tab[tab.length] = 12;
tab.myProp = "une propri";





Best Practices: Iterating over Arrays

  • A simple for loop (see for):
    for (var i=0; i<arr.length; i++) {
        console.log(arr[i]);
    }
  • One of the array iteration methods (see Iteration (Nondestructive)). For example,forEach():
    arr.forEach(function (elem) {
        console.log(elem);
    });
Do not use the for-in loop (see for-in) to iterate over arrays. It iterates over indices, not over values. And it includes the keys of normal properties while doing so, including inherited ones.

http://speakingjs.com/es5/ch18.html

les fonctions de base

'#'+'0123456789abcdef'.split('').map(function(v,i,a){ return i>5 ? null : a[Math.floor(Math.random()*16)] }).join('');

Est ce un code secret ?

Pour le comprendre : Décomposons le code en étape

  1. const values = '0123456789abcdef';
  2. const tab = values.split('');
  3. let random = tab.map((v,i,a) => i>5 ? null : a[Math.floor(Math.random()*16)]);
  4. let colorRandom = '#'+random.join("");
Lig. 3 transforme les 6 premiers éléments du tableaux en des nombres <16.

En action

Il vous suffit ensuite de copiez la valeur de colorRandom et de tapez dans votre console
  1. document.body.style.background = "#848250"


Les tableaux

article