Retourner ' la page d'accueil de TJSRetourner ' la page d'accueil de TJS

Script arand : Création de la fonction array_rand()

Création de la fonction array_rand() qui retourne des éléments tirés au hasard d'un tableau
Partie I : Les bases de JavaScript
Edition 1 | Chapitre 7 : Les tableaux / Page 103
Edition 2 | Chapitre 7 : Les tableaux / Page 111
Edition 3 | Chapitre 7 : Les tableaux / Page 111

Exécution du script

Emulation de la console

Code source

<html><head>    <title>Création de la fonction array_rand()</title></head><body>    <script type="text/javascript">        function shuffle(tab) {          tab.sort(function(a,b) {            return Math.random()-Math.random();          });        }        function arrayRand(tableau, nb=1) {          /* Création du tableau temporaire de travail */          var tmp=[];          tableau.forEach(function(e) {            tmp.push(e);          });          /* Mélange */          shuffle(tmp);          /* Retour du 1er élément ou d'une tranche */          if (nb==1) {            return tmp[0];                } else {            return tmp.slice(0, nb);          }        }        var mois=["Jan","Fév","Mar","Avr","Mai","Jui","Jul","Aou","Sep","Oct","Nov","Déc"];        console.log(arrayRand(mois));        console.log(arrayRand(mois,3).toString());    </script></body></html>

Troisième édition Tout JavaScript chez Dunod

Tout JavaScript le livre chez DunodEn savoir plus
Sortie le 4 janvier 2023

Version papier 29€90
Format électronique 22€99.

Commandez en ligne

Chercher une fonction, un objet, ...

Le graph des objets JavaScript



Chargement
en cours...
Le 27/04/2024 03:21:53 sur php 7 en 112.98 ms