From 5154dc2695afa17021127627c8c4056fad367bbc Mon Sep 17 00:00:00 2001 From: "Queen Vinyl Da.i'gyu-Kazotetsu" Date: Fri, 28 Jul 2023 01:42:32 -0700 Subject: [PATCH] fr: Format /web/javascript using Prettier (part 3) (#14641) --- .../global_objects/dataview/index.md | 29 ++++-- .../global_objects/dataview/setint8/index.md | 2 +- .../global_objects/dataview/setuint8/index.md | 2 +- .../global_objects/date/date/index.md | 30 +++--- .../global_objects/date/getdate/index.md | 2 +- .../global_objects/date/getday/index.md | 8 +- .../global_objects/date/getfullyear/index.md | 2 +- .../global_objects/date/gethours/index.md | 2 +- .../date/getmilliseconds/index.md | 2 +- .../global_objects/date/getminutes/index.md | 2 +- .../global_objects/date/getmonth/index.md | 8 +- .../global_objects/date/getseconds/index.md | 2 +- .../global_objects/date/gettime/index.md | 9 +- .../date/gettimezoneoffset/index.md | 2 +- .../global_objects/date/getutcdate/index.md | 2 +- .../global_objects/date/getutcday/index.md | 6 +- .../date/getutcfullyear/index.md | 2 +- .../global_objects/date/getutchours/index.md | 2 +- .../date/getutcmilliseconds/index.md | 2 +- .../date/getutcminutes/index.md | 2 +- .../global_objects/date/getutcmonth/index.md | 2 +- .../date/getutcseconds/index.md | 2 +- .../global_objects/date/getyear/index.md | 2 +- .../reference/global_objects/date/index.md | 46 ++++----- .../global_objects/date/now/index.md | 1 - .../global_objects/date/parse/index.md | 36 +++---- .../global_objects/date/setdate/index.md | 14 +-- .../global_objects/date/sethours/index.md | 2 +- .../date/setmilliseconds/index.md | 2 +- .../global_objects/date/setminutes/index.md | 2 +- .../global_objects/date/setmonth/index.md | 2 +- .../global_objects/date/setseconds/index.md | 4 +- .../global_objects/date/settime/index.md | 2 +- .../global_objects/date/setutcdate/index.md | 2 +- .../date/setutcmilliseconds/index.md | 2 +- .../global_objects/date/setyear/index.md | 2 +- .../global_objects/date/todatestring/index.md | 4 +- .../global_objects/date/toisostring/index.md | 40 ++++---- .../global_objects/date/tojson/index.md | 4 +- .../date/tolocaledatestring/index.md | 13 ++- .../date/tolocalestring/index.md | 18 ++-- .../date/tolocaletimestring/index.md | 10 +- .../global_objects/date/tostring/index.md | 2 +- .../global_objects/date/totimestring/index.md | 4 +- .../global_objects/date/toutcstring/index.md | 2 +- .../global_objects/date/valueof/index.md | 4 +- .../global_objects/decodeuri/index.md | 10 +- .../decodeuricomponent/index.md | 2 +- .../global_objects/encodeuri/index.md | 16 ++-- .../encodeuricomponent/index.md | 70 +++++++------- .../error/columnnumber/index.md | 2 +- .../global_objects/error/error/index.md | 12 ++- .../reference/global_objects/error/index.md | 37 ++++---- .../global_objects/error/linenumber/index.md | 6 +- .../global_objects/error/stack/index.md | 46 ++++----- .../global_objects/error/tostring/index.md | 15 ++- .../reference/global_objects/escape/index.md | 10 +- .../reference/global_objects/eval/index.md | 93 ++++++++++--------- .../evalerror/evalerror/index.md | 22 ++--- .../global_objects/evalerror/index.md | 14 +-- .../finalizationregistry/index.md | 2 +- .../finalizationregistry/index.md | 10 +- .../finalizationregistry/register/index.md | 2 +- .../finalizationregistry/unregister/index.md | 20 ++-- .../float32array/float32array/index.md | 6 +- .../global_objects/float32array/index.md | 6 +- .../float64array/float64array/index.md | 6 +- .../global_objects/float64array/index.md | 6 +- .../global_objects/function/apply/index.md | 33 +++---- .../function/arguments/index.md | 6 +- .../global_objects/function/bind/index.md | 27 +++--- .../global_objects/function/call/index.md | 28 +++--- .../global_objects/function/caller/index.md | 22 +++-- .../function/displayname/index.md | 28 +++--- .../global_objects/function/function/index.md | 16 +++- .../global_objects/function/index.md | 22 ++--- .../global_objects/function/length/index.md | 10 +- .../global_objects/function/name/index.md | 48 +++++----- .../global_objects/generator/index.md | 15 ++- .../global_objects/generator/next/index.md | 12 +-- .../global_objects/generator/return/index.md | 6 +- .../global_objects/generator/throw/index.md | 8 +- .../global_objects/generatorfunction/index.md | 6 +- .../global_objects/globalthis/index.md | 18 ++-- .../global_objects/infinity/index.md | 10 +- .../global_objects/int16array/index.md | 6 +- .../int16array/int16array/index.md | 6 +- .../global_objects/int32array/index.md | 6 +- .../int32array/int32array/index.md | 8 +- .../global_objects/int8array/index.md | 6 +- .../int8array/int8array/index.md | 6 +- .../global_objects/internalerror/index.md | 2 +- .../internalerror/internalerror/index.md | 10 +- .../intl/collator/collator/index.md | 17 ++-- .../intl/collator/compare/index.md | 9 +- .../global_objects/intl/collator/index.md | 14 +-- .../intl/collator/resolvedoptions/index.md | 14 +-- .../intl/collator/supportedlocalesof/index.md | 2 +- .../datetimeformat/datetimeformat/index.md | 65 +++++++++---- .../intl/datetimeformat/format/index.md | 23 +++-- 100 files changed, 698 insertions(+), 566 deletions(-) diff --git a/files/fr/web/javascript/reference/global_objects/dataview/index.md b/files/fr/web/javascript/reference/global_objects/dataview/index.md index 008951950044ae..cae7f978181b2b 100644 --- a/files/fr/web/javascript/reference/global_objects/dataview/index.md +++ b/files/fr/web/javascript/reference/global_objects/dataview/index.md @@ -15,7 +15,7 @@ La vue **`DataView`** fournit une interface de bas niveau pour lire et écrire d Les formats numériques sur plusieurs octets sont représentés différemment en mémoire selon l'architecture de la machine (voir [la page du glossaire sur le boutisme](/fr/docs/Glossary/Endianness) pour plus d'explications). Les accesseurs `DataView` permettent de contrôler explicitement la façon dont se fait l'accès aux données, quel que soit le boutisme de l'ordinateur. ```js -var littleEndian = (function() { +var littleEndian = (function () { var buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 256, true /* littleEndian */); // Int16Array utilise le boutisme de la plateforme @@ -35,9 +35,14 @@ function getUint64(dataview, byteOffset, littleEndian) { const droite = dataview.getUint32(byteOffset + 4, littleEndian); // on combine les deux valeurs 32 bits - const combinaison = littleEndian ? gauche + 2**32*droite : 2**32*gauche + droite; - if(!Number.isSafeInteger(combinaison)){ - console.warn(combinaison, " dépasse MAX_SAFE_INTEGER : perte de précision !"); + const combinaison = littleEndian + ? gauche + 2 ** 32 * droite + : 2 ** 32 * gauche + droite; + if (!Number.isSafeInteger(combinaison)) { + console.warn( + combinaison, + " dépasse MAX_SAFE_INTEGER : perte de précision !", + ); } return combinaison; } @@ -46,14 +51,22 @@ function getUint64(dataview, byteOffset, littleEndian) { On peut également créer un objet [`BigInt`](/fr/docs/Web/JavaScript/Reference/Global_Objects/BigInt) si on veut avoir accès à 64 bits. Sur le plan des performances, les grands entiers ([`BigInt`](/fr/docs/Web/JavaScript/Reference/Global_Objects/BigInt) ont une taille variable, aussi leur manipulation sera nécessairement plus lente que celle des nombres stockés sur 32 bits. Ceci étant écrit, les valeurs natives [`BigInt`](/fr/docs/Web/JavaScript/Reference/Global_Objects/BigInt) seront plus performantes que les implémentations tierces (bibliothèques, etc.). ```js -const BigInt = window.BigInt, bigThirtyTwo = BigInt(32), bigZero = BigInt(0); +const BigInt = window.BigInt, + bigThirtyTwo = BigInt(32), + bigZero = BigInt(0); function getUint64BigInt(dataview, byteOffset, littleEndian) { // on décompose la valeur 64 sur bits en deux nombres 32 bits (4 octets) - const gauche = BigInt(dataview.getUint32(byteOffset|0, !!littleEndian)>>>0); - const droite = BigInt(dataview.getUint32((byteOffset|0) + 4|0, !!littleEndian)>>>0); + const gauche = BigInt( + dataview.getUint32(byteOffset | 0, !!littleEndian) >>> 0, + ); + const droite = BigInt( + dataview.getUint32(((byteOffset | 0) + 4) | 0, !!littleEndian) >>> 0, + ); // on recombine les deux valeurs sur 32 bits et on la renvoie - return littleEndian ? (droite< **Note :** La seule façon correcte d'instancier un nouvel objet `Date` est d'utiliser l'opérateur [`new`](/fr/docs/Web/JavaScript/Reference/Operators/new). Si vous invoquez ce constructeur directement (`now = Date()` par exemple), la valeur renvoyée sera une chaîne de caractères plutôt qu'un objet `Date`. @@ -87,11 +87,11 @@ Les exemples qui suivent illustrent différentes façons de créer des dates Jav > **Note :** L'analyse de chaîne de caractères représentant des dates avec le constructeur `Date` (ou `Date.parse` qui est équivalent à cet égard) est fortement déconseillée en raison des différences et incohérences entre les navigateurs. ```js -let today = new Date() -let birthday = new Date('December 17, 1995 13:24:00') -let birthday = new Date('1995-12-17T13:24:00') -let birthday = new Date(1995, 11, 17) // les mois sont numérotés à partir de 0 -let birthday = new Date(1995, 11, 17, 13, 24, 0) +let today = new Date(); +let birthday = new Date("December 17, 1995 13:24:00"); +let birthday = new Date("1995-12-17T13:24:00"); +let birthday = new Date(1995, 11, 17); // les mois sont numérotés à partir de 0 +let birthday = new Date(1995, 11, 17, 13, 24, 0); ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/date/getdate/index.md b/files/fr/web/javascript/reference/global_objects/date/getdate/index.md index d45f97b81e5254..832c5fbfdaa9b4 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getdate/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getdate/index.md @@ -13,7 +13,7 @@ La méthode **`getDate()`** retourne le jour du mois pour la date spécifiée d' ## Syntaxe ```js -dateObj.getDate() +dateObj.getDate(); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/date/getday/index.md b/files/fr/web/javascript/reference/global_objects/date/getday/index.md index a00a140c20ddef..3259130f3e8a73 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getday/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getday/index.md @@ -13,7 +13,7 @@ La méthode **`getDay()`** renvoie le jour de la semaine pour la date spécifié ## Syntaxe ```js -dateObj.getDay() +dateObj.getDay(); ``` ### Valeur de retour @@ -36,10 +36,10 @@ console.log(jourSemaine); //1 > **Note :** Si besoin, on pourra obtenir le nom complet du jour (`"lundi"` par exemple) en utilisant la méthode {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} avec un paramètre `options`. Ce faisant, il est plus simple d'internationaliser un site ou une application : > > ```js -> var options = { weekday: 'long'}; -> console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95)); +> var options = { weekday: "long" }; +> console.log(new Intl.DateTimeFormat("en-US", options).format(Xmas95)); > // Monday -> console.log(new Intl.DateTimeFormat('de-DE', options).format(Xmas95)); +> console.log(new Intl.DateTimeFormat("de-DE", options).format(Xmas95)); > // Montag > ``` diff --git a/files/fr/web/javascript/reference/global_objects/date/getfullyear/index.md b/files/fr/web/javascript/reference/global_objects/date/getfullyear/index.md index bdfab5e3ff0517..38722f916e2be4 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getfullyear/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getfullyear/index.md @@ -15,7 +15,7 @@ Cette méthode doit être utilisée à la place de {{jsxref("Date.prototype.getY ## Syntaxe ```js -dateObj.getFullYear() +dateObj.getFullYear(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/gethours/index.md b/files/fr/web/javascript/reference/global_objects/date/gethours/index.md index efe04904f34134..0033b5c6d0f136 100644 --- a/files/fr/web/javascript/reference/global_objects/date/gethours/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/gethours/index.md @@ -13,7 +13,7 @@ La méthode **`getHours()`** renvoie l'heure pour la date renseignée, d'après ## Syntaxe ```js -dateObj.getHours() +dateObj.getHours(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/getmilliseconds/index.md b/files/fr/web/javascript/reference/global_objects/date/getmilliseconds/index.md index 0af6723548e847..201fd30a298515 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getmilliseconds/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getmilliseconds/index.md @@ -13,7 +13,7 @@ La méthode **`getMilliseconds()`** renvoie les millièmes de secondes de la dat ## Syntaxe ```js -dateObj.getMilliseconds() +dateObj.getMilliseconds(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/getminutes/index.md b/files/fr/web/javascript/reference/global_objects/date/getminutes/index.md index 58a188af775cab..5f3f80fcec6817 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getminutes/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getminutes/index.md @@ -13,7 +13,7 @@ La méthode **`getMinutes()`** renvoie les minutes pour la date renseignée d'ap ## Syntaxe ```js -dateObj.getMinutes() +dateObj.getMinutes(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/getmonth/index.md b/files/fr/web/javascript/reference/global_objects/date/getmonth/index.md index 03cdcd5f6aa10e..54861d144f8656 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getmonth/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getmonth/index.md @@ -13,7 +13,7 @@ La méthode **`getMonth()`** retourne le mois de la date renseignée d'après l' ## Syntaxe ```js -dateObj.getMonth() +dateObj.getMonth(); ``` ### Valeur de retour @@ -36,10 +36,10 @@ console.log(mois); //11 > **Note :** Si besoin, on pourra récupérer le nom complet du mois (`"Janvier"` par exemple) en utilisant [`Intl.DateTimeFormat()`](/fr/docs/Web/JavaScript/Reference/Objets_globaux/DateTimeFormat) avec un paramètre `options`. En utilisant cette méthode, il est plus simple d'internationaliser le site ou l'application : > > ```js -> var options = { month: 'long'}; -> console.log(new Intl.DateTimeFormat('en-US', options).format(noel95)); +> var options = { month: "long" }; +> console.log(new Intl.DateTimeFormat("en-US", options).format(noel95)); > // December -> console.log(new Intl.DateTimeFormat('de-DE', options).format(noel95)); +> console.log(new Intl.DateTimeFormat("de-DE", options).format(noel95)); > // Dezember > ``` diff --git a/files/fr/web/javascript/reference/global_objects/date/getseconds/index.md b/files/fr/web/javascript/reference/global_objects/date/getseconds/index.md index a1e599bff30296..128c7b78fecf00 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getseconds/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getseconds/index.md @@ -13,7 +13,7 @@ La méthode **`getSeconds()`** renvoie les secondes pour la date renseignée d'a ## Syntaxe ```js -dateObj.getSeconds() +dateObj.getSeconds(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/gettime/index.md b/files/fr/web/javascript/reference/global_objects/date/gettime/index.md index bd797dc54ff52f..a0d441471b3799 100644 --- a/files/fr/web/javascript/reference/global_objects/date/gettime/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/gettime/index.md @@ -15,7 +15,7 @@ Vous pouvez utiliser cette méthode pour vous affecter une date et un temps à u ## Syntaxe ```js -dateObj.getTime() +dateObj.getTime(); ``` ### Valeur de retour @@ -29,7 +29,7 @@ La valeur renvoyée par la méthode `getTime()` est le nombre de millièmes de s L'exemple qui suit assigne la valeur de `anniversaire` à `copie` : ```js -var anniversaire = new Date(1994 , 11, 10); // 10 décembre 1994 +var anniversaire = new Date(1994, 11, 10); // 10 décembre 1994 var copie = new Date(); copie.setTime(anniversaire.getTime()); ``` @@ -47,7 +47,9 @@ for (var i = 0; i < 1000; i++) { } fin = new Date(); -console.log('Durée de cette opération : ' + (fin.getTime() - début.getTime()) + ' msec'); +console.log( + "Durée de cette opération : " + (fin.getTime() - début.getTime()) + " msec", +); ``` ## Précision temporelle réduite @@ -62,7 +64,6 @@ new Date().getTime(); // 1519211811670 // ... - // précision temporelle avec `privacy.resistFingerprinting` activé new Date().getTime(); // 1519129853500 diff --git a/files/fr/web/javascript/reference/global_objects/date/gettimezoneoffset/index.md b/files/fr/web/javascript/reference/global_objects/date/gettimezoneoffset/index.md index c04c0d3adcae84..00626ac2d5805e 100644 --- a/files/fr/web/javascript/reference/global_objects/date/gettimezoneoffset/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/gettimezoneoffset/index.md @@ -13,7 +13,7 @@ La méthode **`getTimezoneOffset()`** retourne la différence en minutes entre l ## Syntaxe ```js -dateObj.getTimezoneOffset() +dateObj.getTimezoneOffset(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/getutcdate/index.md b/files/fr/web/javascript/reference/global_objects/date/getutcdate/index.md index 514e41174c566a..8decd00dafd0d6 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getutcdate/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getutcdate/index.md @@ -13,7 +13,7 @@ La méthode **`getUTCDate()`** renvoie le jour du mois pour la date renseignée ## Syntaxe ```js -dateObj.getUTCDate() +dateObj.getUTCDate(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/getutcday/index.md b/files/fr/web/javascript/reference/global_objects/date/getutcday/index.md index 281deb69b65d95..57cbee00ea0c78 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getutcday/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getutcday/index.md @@ -13,7 +13,7 @@ La méthode **`getUTCDay()`** renvoie le jour de la semaine pour la date renseig ## Syntaxe ```js -dateObj.getUTCDay() +dateObj.getUTCDay(); ``` ### Valeur de retour @@ -27,8 +27,8 @@ La valeur renvoyée par `getUTCDay()` est un entier correspondant au jour de la L'exemple suivant assigne le jour de la semaine de la date actuelle à la variable `jourSemaine`. ```js -var aujourdhui = new Date() -var jourSemaine = aujourdhui.getUTCDay() +var aujourdhui = new Date(); +var jourSemaine = aujourdhui.getUTCDay(); ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/date/getutcfullyear/index.md b/files/fr/web/javascript/reference/global_objects/date/getutcfullyear/index.md index abd790e9b30790..8749bd812d7876 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getutcfullyear/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getutcfullyear/index.md @@ -13,7 +13,7 @@ La méthode **`getUTCFullYear()`** renvoie l'année de la date renseignée, d'ap ## Syntaxe ```js -dateObj.getUTCFullYear() +dateObj.getUTCFullYear(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/getutchours/index.md b/files/fr/web/javascript/reference/global_objects/date/getutchours/index.md index 76bedb4408df37..3d229776c72c35 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getutchours/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getutchours/index.md @@ -13,7 +13,7 @@ La méthode **`getUTCHours()`** renvoie les heures de la date renseignée, d'apr ## Syntaxe ```js -dateObj.getUTCHours() +dateObj.getUTCHours(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/getutcmilliseconds/index.md b/files/fr/web/javascript/reference/global_objects/date/getutcmilliseconds/index.md index 82aec8625f0286..1e8818c439d27b 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getutcmilliseconds/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getutcmilliseconds/index.md @@ -13,7 +13,7 @@ La méthode **`getUTCMilliseconds()`** renvoie les millièmes de secondes pour l ## Syntaxe ```js -dateObj.getUTCMilliseconds() +dateObj.getUTCMilliseconds(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/getutcminutes/index.md b/files/fr/web/javascript/reference/global_objects/date/getutcminutes/index.md index b161d459ae6d52..53b428fb5dc184 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getutcminutes/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getutcminutes/index.md @@ -13,7 +13,7 @@ La méthode **`getUTCMinutes()`** renvoie les minutes de la date renseignée, d' ## Syntaxe ```js -dateObj.getUTCMinutes() +dateObj.getUTCMinutes(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/getutcmonth/index.md b/files/fr/web/javascript/reference/global_objects/date/getutcmonth/index.md index c4af809d1971a8..fae98ff7cbbd2d 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getutcmonth/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getutcmonth/index.md @@ -13,7 +13,7 @@ La méthode **`getUTCMonth()`** renvoie le mois de la date renseignée, d'après ## Syntaxe ```js -dateObj.getUTCMonth() +dateObj.getUTCMonth(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/getutcseconds/index.md b/files/fr/web/javascript/reference/global_objects/date/getutcseconds/index.md index 26ad75f0e7b266..5faab4939d2006 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getutcseconds/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getutcseconds/index.md @@ -13,7 +13,7 @@ La méthode **`getUTCSeconds()`** renvoie les secondes de la date renseignée, d ## Syntaxe ```js -dateObj.getUTCSeconds() +dateObj.getUTCSeconds(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/getyear/index.md b/files/fr/web/javascript/reference/global_objects/date/getyear/index.md index f439fc2280dfae..9aaa514b60126d 100644 --- a/files/fr/web/javascript/reference/global_objects/date/getyear/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/getyear/index.md @@ -11,7 +11,7 @@ La méthode **`getYear()`** renvoie l'année de la date renseignée, d'après l' ## Syntaxe ```js -dateObj.getYear() +dateObj.getYear(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/index.md b/files/fr/web/javascript/reference/global_objects/date/index.md index 9efa333d9b4560..23470a53ab8057 100644 --- a/files/fr/web/javascript/reference/global_objects/date/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/index.md @@ -148,14 +148,14 @@ Ainsi, on dispose de méthodes permettant d'obtenir ou de définir les différen Les exemples qui suivent illustrent différentes méthodes permettant de créer des dates JavaScript : -> **Note :** L'analyse de chaîne de caractères représentant des dates avec le constructeur `Date` (ou `Date.parse` qui est équivalent) est fortement déconseillée en raison des différences de comportement existant entre les navigateurs. +> **Note :** L'analyse de chaîne de caractères représentant des dates avec le constructeur `Date` (ou `Date.parse` qui est équivalent) est fortement déconseillée en raison des différences de comportement existant entre les navigateurs. ```js -let aujourdhui = new Date() -let anniversaire = new Date('September 22, 2018 15:00:00') -let anniversaire = new Date('2018-09-22T15:00:00') -let anniversaire = new Date(2018, 8, 22) // the month is 0-indexed -let anniversaire = new Date(2018, 8, 22, 15, 0, 0) +let aujourdhui = new Date(); +let anniversaire = new Date("September 22, 2018 15:00:00"); +let anniversaire = new Date("2018-09-22T15:00:00"); +let anniversaire = new Date(2018, 8, 22); // the month is 0-indexed +let anniversaire = new Date(2018, 8, 22, 15, 0, 0); ``` ### Les années sur deux chiffres correspondent à la période 1900 – 1999 @@ -163,12 +163,12 @@ let anniversaire = new Date(2018, 8, 22, 15, 0, 0) Afin de créer et de manipuler des dates sur les années `0` à `99` de notre ère, on doit utiliser les méthodes {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}}. ```js -let date = new Date(98, 1) // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) +let date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) // Méthode dépréciée, 98 correspond également ici à 1998 -date.setYear(98) // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) +date.setYear(98); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) -date.setFullYear(98) // Sat Feb 01 0098 00:00:00 GMT+0000 (BST) +date.setFullYear(98); // Sat Feb 01 0098 00:00:00 GMT+0000 (BST) ``` ### Calculer le temps écoulé @@ -179,36 +179,36 @@ En raison de durées différentes pour les jours (heure d'été / heure d'hiver) ```js // Utiliser des objets Date -let debut = Date.now() +let debut = Date.now(); // Ici, l'évènement dont on veut mesurer la durée : -faireQuelqueChosePendantLongtemps() -let fin = Date.now() -let duree = fin - debut // La durée écoulée, en millisecondes +faireQuelqueChosePendantLongtemps(); +let fin = Date.now(); +let duree = fin - debut; // La durée écoulée, en millisecondes ``` ```js // En utilisant les méthodes natives -let debut = new Date() +let debut = new Date(); // Ici, l'évènement dont on veut mesurer la durée : -faireQuelqueChosePendantLongtemps() -let fin = new Date() -let duree = fin.getTime() - debut.getTime() // La durée écoulée, en millisecondes +faireQuelqueChosePendantLongtemps(); +let fin = new Date(); +let duree = fin.getTime() - debut.getTime(); // La durée écoulée, en millisecondes ``` ```js // Pour tester le temps d'exécution d'une fonction function afficheDureeEcoulee(fTest) { let debut = Date.now(), - valRetour = fTest(), - fin = Date.now() + valRetour = fTest(), + fin = Date.now(); - console.log(`Durée écoulée : ${ String(fin - debut) } millisecondes`) - return valRetour + console.log(`Durée écoulée : ${String(fin - debut)} millisecondes`); + return valRetour; } -let valeurDeRetour = afficheDureeEcoulee(maFonctionATester) +let valeurDeRetour = afficheDureeEcoulee(maFonctionATester); ``` > **Note :** Pour les navigateurs qui prennent en charge l'{{domxref("Window.performance", "API Web Performance", "", 1)}}, la méthode {{domxref("Performance.now()")}} peut fournir un outil de mesure des durées écoulées plus fiable et précis que {{jsxref("Date.now()")}}. @@ -216,7 +216,7 @@ let valeurDeRetour = afficheDureeEcoulee(maFonctionATester) ### Obtenir le nombre de secondes écoulées depuis l'epoch ECMAScript ```js -let secondes = Math.floor(Date.now() / 1000) +let secondes = Math.floor(Date.now() / 1000); ``` Dans ce cas, on renvoie un entier et c'est pour ça qu'on utilise {{jsxref("Math.floor()")}}. Par ailleurs, on n'utilise pas {{jsxref("Math.round()")}} afin d'avoir le nombre de secondes effectivement écoulées. diff --git a/files/fr/web/javascript/reference/global_objects/date/now/index.md b/files/fr/web/javascript/reference/global_objects/date/now/index.md index 4f8fa741a1d9f0..e4f949f6c6fb31 100644 --- a/files/fr/web/javascript/reference/global_objects/date/now/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/now/index.md @@ -50,7 +50,6 @@ new Date().getTime(); // 1519211811670 // ... - // précision temporelle avec `privacy.resistFingerprinting` activé new Date().getTime(); // 1519129853500 diff --git a/files/fr/web/javascript/reference/global_objects/date/parse/index.md b/files/fr/web/javascript/reference/global_objects/date/parse/index.md index 113485d643cfdb..0bf60281f04d8c 100644 --- a/files/fr/web/javascript/reference/global_objects/date/parse/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/parse/index.md @@ -17,13 +17,13 @@ La méthode **`Date.parse()`** analyse la représentation textuelle d'une date, Appel direct : ```js -Date.parse(dateString) +Date.parse(dateString); ``` Appel implicite : ```js -new Date(dateString) +new Date(dateString); ``` ### Paramètres @@ -61,29 +61,29 @@ Cependant, les valeurs invalides qui ne sont pas reconnues dans un format ISO pr ```js // Chaîne non ISO avec des valeurs invalides -new Date('23/25/2014'); +new Date("23/25/2014"); ``` sera traitée comme la date locale du 25 novembre 2015 avec Firefox 30 et comme invalide avec Safari 7. Cependant, si la chaîne est reconnue dans un format ISO mais contient des valeurs invalides, la méthode renverra {{jsxref("NaN")}} pour tous les navigateurs conformes à ES5 (ou aux versions ultérieures) : ```js // Chaîne ISO avec des valeurs invalides new -Date('2014-25-23').toISOString(); +Date("2014-25-23").toISOString(); // renvoie "RangeError: invalid date" pour les navigateurs ES5 ``` L'implémentation spécifique de SpiderMonkey peut être trouvée dans le fichier [`jsdate.cpp`](https://dxr.mozilla.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889). La chaîne `"10 06 2014"` est un exemple de chaîne non ISO, utiliser parse() sur cette chaîne entraînera le moteur JavaScript à utiliser son implémentation de recours. Voir ce [bug](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6) pour une explication rapide de la façon dont est faite l'analyse de la chaîne. ```js -new Date('10 06 2014'); +new Date("10 06 2014"); ``` sera traitée comme la date locale du 6 octobre 2014 et non comme le 10 juin 2014. D'autres exemples : ```js -new Date('toto-truc 2014').toString(); +new Date("toto-truc 2014").toString(); // renvoie : "Invalid Date" -Date.parse('toto-truc 2014'); +Date.parse("toto-truc 2014"); // renvoie : NaN ``` @@ -94,15 +94,15 @@ Date.parse('toto-truc 2014'); Les appels suivants renvoient tous `1546300800000`. Dans le premier appel, on indique uniquement la date (et donc le fuseau UTC implicite). Les chaînes qui suivent utilisent une indication de fuseau horaire selon la norme ISO (`Z` et `+00:00`) ```js -Date.parse("2019-01-01") -Date.parse("2019-01-01T00:00:00.000Z") -Date.parse("2019-01-01T00:00:00.000+00:00") +Date.parse("2019-01-01"); +Date.parse("2019-01-01T00:00:00.000Z"); +Date.parse("2019-01-01T00:00:00.000+00:00"); ``` L'appel suivant, qui ne précise pas le fuseau horaire, fournira le nombre de millisecondes écoulées entre le premier janvier 1970 minuit UTC et le premier janvier 2019 à minuit selon l'heure locale du système utilisé. ```js -Date.parse("2019-01-01T00:00:00") +Date.parse("2019-01-01T00:00:00"); ``` ### Chaînes de caractères non-standard @@ -112,43 +112,43 @@ Date.parse("2019-01-01T00:00:00") Si `IPOdate` est un objet {{jsxref("Date")}}, on peut définir sa valeur au 9 août 1995 (heure locale), de la façon suivante : ```js -IPOdate.setTime(Date.parse('Aug 9, 1995')); +IPOdate.setTime(Date.parse("Aug 9, 1995")); ``` Voici un autre exemple avec une chaîne qui ne suit pas le format standard. ```js -Date.parse('Aug 9, 1995'); +Date.parse("Aug 9, 1995"); ``` Cette méthode renverra `807937200000` pour le fuseau horaire GMT-0300 et d'autres valeurs pour d'autres fuseaux car la chaîne n'indique pas le fuseau horaire et ne respecte pas le format ISO (le fuseau considéré par défaut est donc le fuseau local). ```js -Date.parse('Wed, 09 Aug 1995 00:00:00 GMT'); +Date.parse("Wed, 09 Aug 1995 00:00:00 GMT"); ``` Renvoie `807926400000` quel que soit le fuseau local car on indique GMT. ```js -Date.parse('Wed, 09 Aug 1995 00:00:00'); +Date.parse("Wed, 09 Aug 1995 00:00:00"); ``` Renvoie `807937200000` dans le fuseau GMT-0300 et d'autres valeurs pour d'autres fuseaux car aucune indication de fuseau n'est fournie et que la chaîne n'est pas au format ISO, elle est donc traitée comme un temps local. ```js -Date.parse('Thu, 01 Jan 1970 00:00:00 GMT'); +Date.parse("Thu, 01 Jan 1970 00:00:00 GMT"); ``` Renvoie `0` quel que soit le fuseau local car l'indicateur GMT est fourni. ```js -Date.parse('Thu, 01 Jan 1970 00:00:00'); +Date.parse("Thu, 01 Jan 1970 00:00:00"); ``` Renvoie `14400000` pour le fuseau GMT-0400 et d'autres valeurs dans d'autres fuseaux car aucune indication de fuseau n'est fournie et la chaîne n'est pas au format ISO, elle est donc traitée comme un temps local. ```js -Date.parse('Thu, 01 Jan 1970 00:00:00 GMT-0400'); +Date.parse("Thu, 01 Jan 1970 00:00:00 GMT-0400"); ``` Renvoie `14400000` quel que soit le fuseau car l'indicateur GMT est fourni. diff --git a/files/fr/web/javascript/reference/global_objects/date/setdate/index.md b/files/fr/web/javascript/reference/global_objects/date/setdate/index.md index 06297bd1ad271b..f3273640d4ec65 100644 --- a/files/fr/web/javascript/reference/global_objects/date/setdate/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/setdate/index.md @@ -13,7 +13,7 @@ La méthode **`setDate()`** définit le jour du mois (relatif au début du mois ## Syntaxe ```js -dateObj.setDate(valeurJour) +dateObj.setDate(valeurJour); ``` ### Paramètres @@ -39,12 +39,12 @@ Si on fournit un nombre négatif, la date sera déterminée à rebours à partir ```js var theBigDay = new Date(1962, 6, 7); // 1962-07-06T23:00:00.000Z -theBigDay.setDate(24); // 1962-07-23T23:00:00.000Z -theBigDay.setDate(32); // 1962-07-31T23:00:00.000Z -theBigDay.setDate(22); // 1962-08-21T23:00:00.000Z -theBigDay.setDate(0); // 1962-07-30T23:00:00.000Z -theBigDay.setDate(98); // 1962-10-05T23:00:00.000Z -theBigDay.setDate(-50); // 1962-08-10T23:00:00.000Z +theBigDay.setDate(24); // 1962-07-23T23:00:00.000Z +theBigDay.setDate(32); // 1962-07-31T23:00:00.000Z +theBigDay.setDate(22); // 1962-08-21T23:00:00.000Z +theBigDay.setDate(0); // 1962-07-30T23:00:00.000Z +theBigDay.setDate(98); // 1962-10-05T23:00:00.000Z +theBigDay.setDate(-50); // 1962-08-10T23:00:00.000Z ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/date/sethours/index.md b/files/fr/web/javascript/reference/global_objects/date/sethours/index.md index 8dda6499d82d94..127143a0092c71 100644 --- a/files/fr/web/javascript/reference/global_objects/date/sethours/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/sethours/index.md @@ -19,7 +19,7 @@ dateObj.setHours(valeurHeures[, valeurMinutes[, valeurSecondes[, valeurMs]]]) ### Versions antérieures à JavaScript 1.3 ```js -dateObj.setHours(valeurHeures) +dateObj.setHours(valeurHeures); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/date/setmilliseconds/index.md b/files/fr/web/javascript/reference/global_objects/date/setmilliseconds/index.md index a63e8ffcb44250..85c8535d50aaef 100644 --- a/files/fr/web/javascript/reference/global_objects/date/setmilliseconds/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/setmilliseconds/index.md @@ -13,7 +13,7 @@ La méthode **`setMilliseconds()`** définit les millièmes de secondes pour la ## Syntaxe ```js -dateObj.setMilliseconds(valeurMs) +dateObj.setMilliseconds(valeurMs); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/date/setminutes/index.md b/files/fr/web/javascript/reference/global_objects/date/setminutes/index.md index d9d62411385d07..fbd45b8a9e4b9b 100644 --- a/files/fr/web/javascript/reference/global_objects/date/setminutes/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/setminutes/index.md @@ -19,7 +19,7 @@ dateObj.setMinutes(valeurMinutes[, valeurSecondes[, valeurMs]]) ### Versions antérieures à JavaScript 1.3 ```js -dateObj.setMinutes(valeurMinutes) +dateObj.setMinutes(valeurMinutes); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/date/setmonth/index.md b/files/fr/web/javascript/reference/global_objects/date/setmonth/index.md index 809f02a2c32bd4..cf175abdc4ce98 100644 --- a/files/fr/web/javascript/reference/global_objects/date/setmonth/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/setmonth/index.md @@ -19,7 +19,7 @@ dateObj.setMonth(valeurMois[, valeurJour]) ### Versions antérieures à JavaScript 1.3 ```js -dateObj.setMonth(valeurMois) +dateObj.setMonth(valeurMois); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/date/setseconds/index.md b/files/fr/web/javascript/reference/global_objects/date/setseconds/index.md index 67ea97bca59500..9b7bc92d39e03b 100644 --- a/files/fr/web/javascript/reference/global_objects/date/setseconds/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/setseconds/index.md @@ -19,7 +19,7 @@ dateObj.setSeconds(valeurSecondes[, valeurMs]) ### Versions antérieures à JavaScript 1.3 ```js -dateObj.setSeconds(valeurSecondes) +dateObj.setSeconds(valeurSecondes); ``` ### Paramètres @@ -45,7 +45,7 @@ Si un paramètre utilisé est en dehors des limites attendues, `setSeconds()` te ```js var leGrandJour = new Date(); -leGrandJour.setSeconds(30) +leGrandJour.setSeconds(30); ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/date/settime/index.md b/files/fr/web/javascript/reference/global_objects/date/settime/index.md index 7919b9b25f6036..d9136bf04edcb3 100644 --- a/files/fr/web/javascript/reference/global_objects/date/settime/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/settime/index.md @@ -13,7 +13,7 @@ La méthode **`setTime()`** met l'objet {{jsxref("Date")}} à jour par rapport a ## Syntaxe ```js -dateObj.setTime(valeurTemps) +dateObj.setTime(valeurTemps); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/date/setutcdate/index.md b/files/fr/web/javascript/reference/global_objects/date/setutcdate/index.md index 54ae98c9854999..994e49a3d92aa2 100644 --- a/files/fr/web/javascript/reference/global_objects/date/setutcdate/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/setutcdate/index.md @@ -13,7 +13,7 @@ La méthode **`setUTCDate()`** définit le jour du mois pour la date, selon UTC. ## Syntaxe ```js -dateObj.setUTCDate(valeurJour) +dateObj.setUTCDate(valeurJour); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/date/setutcmilliseconds/index.md b/files/fr/web/javascript/reference/global_objects/date/setutcmilliseconds/index.md index e25e2625c18b31..5ecf75dd5aee68 100644 --- a/files/fr/web/javascript/reference/global_objects/date/setutcmilliseconds/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/setutcmilliseconds/index.md @@ -13,7 +13,7 @@ La méthode **`setUTCMilliseconds()`** définit les millièmes de secondes pour ## Syntaxe ```js -dateObj.setUTCMilliseconds(valeurMs) +dateObj.setUTCMilliseconds(valeurMs); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/date/setyear/index.md b/files/fr/web/javascript/reference/global_objects/date/setyear/index.md index d7388c9d49e1a7..e4be0f0d8c2f27 100644 --- a/files/fr/web/javascript/reference/global_objects/date/setyear/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/setyear/index.md @@ -11,7 +11,7 @@ La méthode **`setYear()`** définit l'année pour pour la date, selon l'heure l ## Syntaxe ```js -dateObj.setYear(valeurAnnée) +dateObj.setYear(valeurAnnée); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/date/todatestring/index.md b/files/fr/web/javascript/reference/global_objects/date/todatestring/index.md index e72c660a44cf9f..85f9c2b6fa26a8 100644 --- a/files/fr/web/javascript/reference/global_objects/date/todatestring/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/todatestring/index.md @@ -18,7 +18,7 @@ La méthode **`toDateString()`** renvoie la date contenue dans un objet {{jsxref ## Syntaxe ```js -dateObj.toDateString() +dateObj.toDateString(); ``` ### Valeur de retour @@ -38,7 +38,7 @@ La méthode `toDateString()` est particulièrement utile car, pour les moteurs i ```js var d = new Date(1993, 6, 28, 14, 39, 7); -console.log(d.toString()); // écrit Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) +console.log(d.toString()); // écrit Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) console.log(d.toDateString()); // écrit Wed Jul 28 1993 ``` diff --git a/files/fr/web/javascript/reference/global_objects/date/toisostring/index.md b/files/fr/web/javascript/reference/global_objects/date/toisostring/index.md index a51806fbba189a..13e1d5c8bdf4ad 100644 --- a/files/fr/web/javascript/reference/global_objects/date/toisostring/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/toisostring/index.md @@ -13,7 +13,7 @@ La méthode **`toISOString()`** renvoie une chaîne de caractères au format ISO ## Syntaxe ```js -dateObj.toISOString() +dateObj.toISOString(); ``` ### Valeur de retour @@ -37,28 +37,34 @@ L'exemple ci-dessus analyse une chaîne de caractères non-standard, qui peut do Cette méthode fut standardisée avec la cinquième édition d'ECMAScript. Afin d'utiliser cette méthode avec les moteurs qui n'en disposent pas nativement, on pourra utiliser ce fragment de code : ```js -if ( !Date.prototype.toISOString ) { - ( function() { - +if (!Date.prototype.toISOString) { + (function () { function pad(number) { - if ( number < 10 ) { - return '0' + number; + if (number < 10) { + return "0" + number; } return number; } - Date.prototype.toISOString = function() { - return this.getUTCFullYear() + - '-' + pad( this.getUTCMonth() + 1 ) + - '-' + pad( this.getUTCDate() ) + - 'T' + pad( this.getUTCHours() ) + - ':' + pad( this.getUTCMinutes() ) + - ':' + pad( this.getUTCSeconds() ) + - '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + - 'Z'; + Date.prototype.toISOString = function () { + return ( + this.getUTCFullYear() + + "-" + + pad(this.getUTCMonth() + 1) + + "-" + + pad(this.getUTCDate()) + + "T" + + pad(this.getUTCHours()) + + ":" + + pad(this.getUTCMinutes()) + + ":" + + pad(this.getUTCSeconds()) + + "." + + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + + "Z" + ); }; - - }() ); + })(); } ``` diff --git a/files/fr/web/javascript/reference/global_objects/date/tojson/index.md b/files/fr/web/javascript/reference/global_objects/date/tojson/index.md index c4162096636c9c..e71e1479904785 100644 --- a/files/fr/web/javascript/reference/global_objects/date/tojson/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/tojson/index.md @@ -13,7 +13,7 @@ La méthode **`toJSON()`** renvoie une chaîne représentant l'objet {{jsxref("D ## Syntaxe ```js -dateObj.toJSON() +dateObj.toJSON(); ``` ### Valeur de retour @@ -29,7 +29,7 @@ Les instances de {{jsxref("Date")}} identifient un instant précis dans le temps ### Utiliser `toJSON()` ```js -var jsonDate = (new Date()).toJSON(); +var jsonDate = new Date().toJSON(); var retourVersDate = new Date(jsonDate); console.log(jsonDate); //2015-10-26T07:46:36.611Z diff --git a/files/fr/web/javascript/reference/global_objects/date/tolocaledatestring/index.md b/files/fr/web/javascript/reference/global_objects/date/tolocaledatestring/index.md index bb9711206f6c08..a5539f8cd0e38b 100644 --- a/files/fr/web/javascript/reference/global_objects/date/tolocaledatestring/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/tolocaledatestring/index.md @@ -15,9 +15,9 @@ Les arguments `locales` et `options` permettent aux applications de définir le ## Syntaxe ```js -toLocaleDateString() -toLocaleDateString(locales) -toLocaleDateString(locales, options) +toLocaleDateString(); +toLocaleDateString(locales); +toLocaleDateString(locales, options); ``` ### Paramètres @@ -119,7 +119,12 @@ Les résultats fournis par `toLocaleDateString()` peuvent être personnalisés g let date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // fournir le jour de la semaine avec une date longue -let options = {weekday: "long", year: "numeric", month: "long", day: "numeric"}; +let options = { + weekday: "long", + year: "numeric", + month: "long", + day: "numeric", +}; console.log(date.toLocaleDateString("de-DE", options)); // → "Donnerstag, 20. Dezember 2012" diff --git a/files/fr/web/javascript/reference/global_objects/date/tolocalestring/index.md b/files/fr/web/javascript/reference/global_objects/date/tolocalestring/index.md index c910280c2519dd..83fffa7c056464 100644 --- a/files/fr/web/javascript/reference/global_objects/date/tolocalestring/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/tolocalestring/index.md @@ -17,9 +17,9 @@ Les anciennes implémentations ignoraient ces arguments, la locale et le format ## Syntaxe ```js -toLocaleString() -toLocaleString(locales) -toLocaleString(locales, options) +toLocaleString(); +toLocaleString(locales); +toLocaleString(locales, options); ``` ### Paramètres @@ -113,7 +113,12 @@ Les résultats fournis par `toLocaleString()` peuvent être personnalisés grâc let date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // obtenir le jour de la semaine avec une date longue -let options = {weekday: "long", year: "numeric", month: "long", day: "numeric"}; +let options = { + weekday: "long", + year: "numeric", + month: "long", + day: "numeric", +}; console.log(date.toLocaleString("de-DE", options)); // → "Donnerstag, 20. Dezember 2012" @@ -126,7 +131,7 @@ console.log(date.toLocaleString("en-US", options)); // → "Thursday, December 20, 2012, UTC" // parfois, même les USA ont besoin d'avoir une heure sur 24h -console.log(date.toLocaleString("en-US", {hour12: false})); +console.log(date.toLocaleString("en-US", { hour12: false })); // → "12/19/2012, 19:00:00" ``` @@ -139,7 +144,8 @@ Ainsi, IE et Edge ajoutent des caractères de contrôle bidirectionnels autour d Aussi, mieux vaut ne pas comparer un résultat fourni par `toLocaleString()` avec une valeur statique : ```js example-bad -"1/1/2019, 01:00:00" === new Date("2019-01-01T00:00:00Z").toLocaleString("en-US"); +"1/1/2019, 01:00:00" === + new Date("2019-01-01T00:00:00Z").toLocaleString("en-US"); // true pour Firefox et les autres // false pour IE et Edge ``` diff --git a/files/fr/web/javascript/reference/global_objects/date/tolocaletimestring/index.md b/files/fr/web/javascript/reference/global_objects/date/tolocaletimestring/index.md index 9c4a508f241d08..fb0f539087f709 100644 --- a/files/fr/web/javascript/reference/global_objects/date/tolocaletimestring/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/tolocaletimestring/index.md @@ -15,9 +15,9 @@ Les anciennes implémentations ignorent ces arguments, la locale utilisée et le ## Syntaxe ```js -toLocaleTimeString() -toLocaleTimeString(locales) -toLocaleTimeString(locales, options) +toLocaleTimeString(); +toLocaleTimeString(locales); +toLocaleTimeString(locales, options); ``` ### Paramètres @@ -95,12 +95,12 @@ Les résultats fournis par `toLocaleTimeString()` peuvent être personnalisés g var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // une application peut vouloir utiliser UTC et le montrer -var options = {timeZone: "UTC", timeZoneName: "short"}; +var options = { timeZone: "UTC", timeZoneName: "short" }; console.log(date.toLocaleTimeString("en-US", options)); // → "3:00:00 AM GMT" // parfois, même les USA ont besoin du format sur 24h -console.log(date.toLocaleTimeString("en-US", {hour12: false})); +console.log(date.toLocaleTimeString("en-US", { hour12: false })); // → "19:00:00" ``` diff --git a/files/fr/web/javascript/reference/global_objects/date/tostring/index.md b/files/fr/web/javascript/reference/global_objects/date/tostring/index.md index dbfc6020fae43d..755c49c631c3d1 100644 --- a/files/fr/web/javascript/reference/global_objects/date/tostring/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/tostring/index.md @@ -13,7 +13,7 @@ La méthode **`toString()`** renvoie une chaîne de caractères représentant l' ## Syntaxe ```js -dateObj.toString() +dateObj.toString(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/totimestring/index.md b/files/fr/web/javascript/reference/global_objects/date/totimestring/index.md index 4af7aeacc5389f..d268b53cd63fba 100644 --- a/files/fr/web/javascript/reference/global_objects/date/totimestring/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/totimestring/index.md @@ -13,7 +13,7 @@ La méthode **`toTimeString()`** renvoie la partie « heure » de l'objet `Date` ## Syntaxe ```js -dateObj.toTimeString() +dateObj.toTimeString(); ``` ### Valeur de retour @@ -33,7 +33,7 @@ La méthode `toTimeString()` est particulièrement utile parce que les moteurs i ```js var d = new Date(1993, 6, 28, 14, 39, 7); -console.log(d.toString()); // Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) +console.log(d.toString()); // Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) console.log(d.toTimeString()); // 14:39:07 GMT-0600 (PDT) ``` diff --git a/files/fr/web/javascript/reference/global_objects/date/toutcstring/index.md b/files/fr/web/javascript/reference/global_objects/date/toutcstring/index.md index 5827783fac1c98..7012ca3e13be5e 100644 --- a/files/fr/web/javascript/reference/global_objects/date/toutcstring/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/toutcstring/index.md @@ -13,7 +13,7 @@ La méthode **`toUTCString()`** convertit une date en une chaîne de caractères ## Syntaxe ```js -dateObj.toUTCString() +dateObj.toUTCString(); ``` ### Valeur de retour diff --git a/files/fr/web/javascript/reference/global_objects/date/valueof/index.md b/files/fr/web/javascript/reference/global_objects/date/valueof/index.md index 64707cba2c4aa0..6110cf4eedb043 100644 --- a/files/fr/web/javascript/reference/global_objects/date/valueof/index.md +++ b/files/fr/web/javascript/reference/global_objects/date/valueof/index.md @@ -13,7 +13,7 @@ La méthode **`valueOf()`** renvoie la valeur primitive d'un objet {{jsxref("Dat ## Syntaxe ```js -date.valueOf() +date.valueOf(); ``` ### Valeur de retour @@ -34,7 +34,7 @@ Cette méthode est souvent appelée en interne par le moteur JavaScript et n'est ```js var x = new Date(56, 6, 17); -var maVar = x.valueOf(); // maVar vaut -424713600000 +var maVar = x.valueOf(); // maVar vaut -424713600000 ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/decodeuri/index.md b/files/fr/web/javascript/reference/global_objects/decodeuri/index.md index 4369e44e069776..21239ae7756032 100644 --- a/files/fr/web/javascript/reference/global_objects/decodeuri/index.md +++ b/files/fr/web/javascript/reference/global_objects/decodeuri/index.md @@ -13,7 +13,7 @@ La méthode **`decodeURI()`** permet de décoder un Uniform Resource Identifier ## Syntaxe ```js -decodeURI(encodedURI) +decodeURI(encodedURI); ``` ### Paramètres @@ -38,7 +38,9 @@ Cette méthode remplace chaque séquence d'échappement présente dans l'URI enc ### Décoder une URL cyrillique ```js -decodeURI("https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"); +decodeURI( + "https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B", +); // "https://developer.mozilla.org/ru/docs/JavaScript_шеллы" ``` @@ -46,8 +48,8 @@ decodeURI("https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D ```js try { - var a = decodeURI('%E0%A4%A'); -} catch(e) { + var a = decodeURI("%E0%A4%A"); +} catch (e) { console.error(e); } diff --git a/files/fr/web/javascript/reference/global_objects/decodeuricomponent/index.md b/files/fr/web/javascript/reference/global_objects/decodeuricomponent/index.md index 9015a848b5610e..fc8df9dd6d43f8 100644 --- a/files/fr/web/javascript/reference/global_objects/decodeuricomponent/index.md +++ b/files/fr/web/javascript/reference/global_objects/decodeuricomponent/index.md @@ -13,7 +13,7 @@ La fonction **`decodeURIComponent()`** permet de décoder un composant d'un Unif ## Syntaxe ```js -decodeURIComponent(encodedURI) +decodeURIComponent(encodedURI); ``` ### Paramètres diff --git a/files/fr/web/javascript/reference/global_objects/encodeuri/index.md b/files/fr/web/javascript/reference/global_objects/encodeuri/index.md index b6f18b2d3d9abf..1e7030b36068b8 100644 --- a/files/fr/web/javascript/reference/global_objects/encodeuri/index.md +++ b/files/fr/web/javascript/reference/global_objects/encodeuri/index.md @@ -13,7 +13,7 @@ La fonction **`encodeURI()`** encode un Uniform Resource Identifier (URI) en rem ## Syntaxe ```js -encodeURI(URI) +encodeURI(URI); ``` ### Paramètres @@ -36,8 +36,8 @@ A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # `encodeURI()` est différente de {{jsxref("encodeURIComponent")}}. Par exemple : ```js -var set1 = ";,/?:@&=+$#"; // Caractères réservés -var set2 = "-_.!~*'()"; // Caractères non-réservés +var set1 = ";,/?:@&=+$#"; // Caractères réservés +var set2 = "-_.!~*'()"; // Caractères non-réservés var set3 = "ABC abc 123"; // Caractères alphanumériques et espace console.log(encodeURI(set1)); // ;,/?:@&=+$# @@ -49,19 +49,19 @@ console.log(encodeURIComponent(set2)); // -_.!~*'() console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (l'espace est encodé en %20) ``` -Une exception {{jsxref("URIError")}} sera levée si on tente d'encoder un caractère *surrogate* (demi-codet) qui ne fait pas partie d'une paire : +Une exception {{jsxref("URIError")}} sera levée si on tente d'encoder un caractère _surrogate_ (demi-codet) qui ne fait pas partie d'une paire : ```js // On a une paire de codets surrogate -console.log(encodeURI('\uD800\uDFFF')); +console.log(encodeURI("\uD800\uDFFF")); // Ici, seul le caractère "haut" // ce qui déclenche une "URIError: malformed URI sequence" -console.log(encodeURI('\uD800')); +console.log(encodeURI("\uD800")); // Ici, seul le caractère "bas" // ce qui déclenche une "URIError: malformed URI sequence" -console.log(encodeURI('\uDFFF')); +console.log(encodeURI("\uDFFF")); ``` `encodeURI()` ne permet pas de former des requêtes HTTP GET ou POST (par exemple avec {{domxref("XMLHTTPRequest")}}) car "&", "+" et "=" ne sont pas encodés et sont traités comme des caractères spéciaux (toutefois, la méthode. {{jsxref("encodeURIComponent")}} pourra être utilisée pour encoder ces caractères). @@ -70,7 +70,7 @@ Si on souhaite suivre la [RFC3986](http://tools.ietf.org/html/rfc3986) qui conce ```js function fixedEncodeURI(str) { - return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); + return encodeURI(str).replace(/%5B/g, "[").replace(/%5D/g, "]"); } ``` diff --git a/files/fr/web/javascript/reference/global_objects/encodeuricomponent/index.md b/files/fr/web/javascript/reference/global_objects/encodeuricomponent/index.md index 1142fbb67a3dce..28cca5c6b226ee 100644 --- a/files/fr/web/javascript/reference/global_objects/encodeuricomponent/index.md +++ b/files/fr/web/javascript/reference/global_objects/encodeuricomponent/index.md @@ -32,9 +32,9 @@ Une nouvelle chaîne de caractères qui représente un composant d'URI obtenu en La méthode `encodeURIComponent()` diffère de la méthode `encodeURI()` par rapport aux caractères qui sont encodés : ```js -var set1 = ";,/?:@&=+$"; // Caractères réservés -var set2 = "-_.!~*'()"; // Caractères non-réservés -var set3 = "#"; // Croisillon +var set1 = ";,/?:@&=+$"; // Caractères réservés +var set2 = "-_.!~*'()"; // Caractères non-réservés +var set3 = "#"; // Croisillon var set4 = "ABC abc 123"; // Caractères alphanumériques et espace console.log(encodeURI(set1)); // ;,/?:@&=+$ @@ -52,13 +52,13 @@ Une exception {{jsxref("URIError")}} sera levée lorsqu'on utilise cette fonctio ```js // la paire de demi-codets : OK -console.log(encodeURIComponent('\uD800\uDFFF')); +console.log(encodeURIComponent("\uD800\uDFFF")); // seul le demi-codet supérieur : "URIError: malformed URI sequence" -console.log(encodeURIComponent('\uD800')); +console.log(encodeURIComponent("\uD800")); // seul le demi-codet inférieur : "URIError: malformed URI sequence" -console.log(encodeURIComponent('\uDFFF')); +console.log(encodeURIComponent("\uDFFF")); ``` Afin d'éviter des requêtes inattendues vers le serveur, il est conseillé d'utiliser la fonction `encodeURIComponent()` pour n'importe quel paramètre qui aurait été saisi par l'utilisateur et qui ferait partie d'un URI. Ainsi, si un utilisateur peut saisir "`Thym &access=admin`" dans une variable `commentaire` et qu'on n'utilise pas `encodeURIComponent()`, on obtiendra la chaîne `commentaire=Thym%20&access=admin`. On voit ici que l'esperluette (&) et le signe égal forment une nouvelle paire clé/valeur. Au lieu d'avoir une clé POST `commentaire` égale à "`Thym &access=admin`", on aura deux clés POST, l'une égale à "`Thym`" et une seconde (`access`) égale à `admin`. @@ -68,9 +68,9 @@ Pour [`application/x-www-form-urlencoded`](https://www.whatwg.org/specs/web-apps Pour utiliser une fonction qui respecte la [RFC 3986](https://tools.ietf.org/html/rfc3986), plus stricte (qui réserve les caractères !, ', (, ), et \* même si ces caractères n'ont pas d'usage normalisé), on pourra utiliser la fonction suivante : ```js -function fixedEncodeURIComponent (str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return '%' + c.charCodeAt(0).toString(16); +function fixedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16); }); } ``` @@ -80,37 +80,43 @@ function fixedEncodeURIComponent (str) { Dans l'exemple qui suit, on utilise une méthode spéciale pour l'encodage afin d'utiliser les paramètres d'en-tête de réponse `Content-Disposition` et `Link` (pour, par exemple, représenter des noms de fichiers en UTF-8) : ```js -var nomFichier = 'mon fichier(2).txt'; -var header = "Content-Disposition: attachment; filename*=UTF-8''" - + encodeRFC5987ValueChars(nomFichier); +var nomFichier = "mon fichier(2).txt"; +var header = + "Content-Disposition: attachment; filename*=UTF-8''" + + encodeRFC5987ValueChars(nomFichier); console.log(header); // affiche "Content-Disposition: attachment; filename*=UTF-8''mon%20fichier%282%29.txt" - -function encodeRFC5987ValueChars (str) { - return encodeURIComponent(str). - // Bien que la RFC 3986 réserve "!", RFC 5987 ne réserve pas ce caractère, - // il n'est donc pas nécessaire l'échapper - replace(/['()]/g, escape). // c'est-à-dire %27 %28 %29 - replace(/\*/g, '%2A'). - // Selon la RFC 5987 ce qui suit n'est pas nécessairement requis - // on peut donc bénéficier d'un peu plus de lisibilité : |`^ - replace(/%(?:7C|60|5E)/g, unescape); +function encodeRFC5987ValueChars(str) { + return ( + encodeURIComponent(str) + // Bien que la RFC 3986 réserve "!", RFC 5987 ne réserve pas ce caractère, + // il n'est donc pas nécessaire l'échapper + .replace(/['()]/g, escape) // c'est-à-dire %27 %28 %29 + .replace(/\*/g, "%2A") + // Selon la RFC 5987 ce qui suit n'est pas nécessairement requis + // on peut donc bénéficier d'un peu plus de lisibilité : |`^ + .replace(/%(?:7C|60|5E)/g, unescape) + ); } // Voici une autre version équivalente function encodeRFC5987ValueChars2(str) { - return encodeURIComponent(str). - // Bien que la RFC 3986 réserve "!", RFC 5987 ne réserve pas ce caractère, - // il n'est donc pas nécessaire l'échapper - replace(/['()*]/g, c => '%' + c.charCodeAt(0).toString(16)). // i.e., %27 %28 %29 %2a - // on notera que l'encodage valide pour "*" est %2A et qui faut donc appeler toUpperCase() - // pour encoder exactement. - - // Selon la RFC 5987 ce qui suit n'est pas nécessairement requis - // on peut donc bénéficier d'un peu plus de lisibilité : |`^ - replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(parseInt(hex, 16))); + return ( + encodeURIComponent(str) + // Bien que la RFC 3986 réserve "!", RFC 5987 ne réserve pas ce caractère, + // il n'est donc pas nécessaire l'échapper + .replace(/['()*]/g, (c) => "%" + c.charCodeAt(0).toString(16)) // i.e., %27 %28 %29 %2a + // on notera que l'encodage valide pour "*" est %2A et qui faut donc appeler toUpperCase() + // pour encoder exactement. + + // Selon la RFC 5987 ce qui suit n'est pas nécessairement requis + // on peut donc bénéficier d'un peu plus de lisibilité : |`^ + .replace(/%(7C|60|5E)/g, (str, hex) => + String.fromCharCode(parseInt(hex, 16)), + ) + ); } ``` diff --git a/files/fr/web/javascript/reference/global_objects/error/columnnumber/index.md b/files/fr/web/javascript/reference/global_objects/error/columnnumber/index.md index 11f4a24a3ba80f..37c3ff47476b08 100644 --- a/files/fr/web/javascript/reference/global_objects/error/columnnumber/index.md +++ b/files/fr/web/javascript/reference/global_objects/error/columnnumber/index.md @@ -15,7 +15,7 @@ La propriété **`columnNumber`** contient le numéro de la colonne, dans la lig ```js var e = new Error("Ne peut pas lire la donnée"); throw e; -console.log(e.columnNumber) // 0 +console.log(e.columnNumber); // 0 ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/error/error/index.md b/files/fr/web/javascript/reference/global_objects/error/error/index.md index 3166c8772c37f0..571246c6e1cd9b 100644 --- a/files/fr/web/javascript/reference/global_objects/error/error/index.md +++ b/files/fr/web/javascript/reference/global_objects/error/error/index.md @@ -11,11 +11,11 @@ Le constructeur **`Error`** permet de créer un objet représentant une erreur. ## Syntaxe ```js -new Error() -new Error(message) -new Error(message, options) -new Error(message, nomFichier) -new Error(message, nomFichier, numeroLigne) +new Error(); +new Error(message); +new Error(message, options); +new Error(message, nomFichier); +new Error(message, nomFichier, numeroLigne); ``` ### Paramètres @@ -23,10 +23,12 @@ new Error(message, nomFichier, numeroLigne) - `message` {{Optional_Inline}} - : Une description de l'erreur, compréhensible par un humain. - `options` {{Optional_Inline}} + - : Un objet avec les propriétés suivantes : - `cause` {{Optional_Inline}} - : Une propriété qui indique la cause spécifique de l'erreur. Lors de l'interception puis du renvoi d'une erreur avec un autre message d'erreur, cette propriété devrait être utilisée afin de transmettre le message d'erreur original. + - `nomFichier` {{Optional_Inline}} {{Non-standard_inline}} - : La valeur de la propriété `nomFichier` pour l'objet `Error` créé. Par défaut, il s'agit du nom du fichier contenant le code qui a invoqué le constructeur `Error()`. - `numeroLigne` {{Optional_Inline}} {{Non-standard_inline}} diff --git a/files/fr/web/javascript/reference/global_objects/error/index.md b/files/fr/web/javascript/reference/global_objects/error/index.md index 567051bfc91043..7bc6a9f33476d7 100644 --- a/files/fr/web/javascript/reference/global_objects/error/index.md +++ b/files/fr/web/javascript/reference/global_objects/error/index.md @@ -87,15 +87,14 @@ Il est possible de ne gérer que certains types d'erreur particuliers en testant ```js try { - toto.truc() + toto.truc(); } catch (e) { if (e instanceof EvalError) { - console.error(e.name + ' : ' + e.message) + console.error(e.name + " : " + e.message); } else if (e instanceof RangeError) { - console.error(e.name + ' : ' + e.message) + console.error(e.name + " : " + e.message); } // ... etc - else { // Si aucun cas ne correspond, on laisse l'erreur // non-gérée @@ -131,7 +130,7 @@ function faireTruc() { try { faireTruc(); } catch (err) { - switch(err.message) { + switch (err.message) { case "Echoue d'une certaine façon": gererUneFacon(err.cause); break; @@ -148,7 +147,7 @@ Il est aussi possible d'utiliser la propriété `cause` des [types d'erreur pers class MonErreur extends Error { constructor(/* des arguments */) { // Il faut passer les paramètres `message` et `options` - // pour que la propriété "cause" soit initialisée. + // pour que la propriété "cause" soit initialisée. super(message, options); } } @@ -168,7 +167,7 @@ Voir [cette question (en anglais) sur StackOverflow](https://stackoverflow.com/q ```js class ErreurSpecifique extends Error { - constructor(toto = 'truc', ...params) { + constructor(toto = "truc", ...params) { // On passe les arguments restants (y compris ceux // de l'éditeur tiers) au constructeur parent super(...params); @@ -179,7 +178,7 @@ class ErreurSpecifique extends Error { Error.captureStackTrace(this, ErreurSpecifique); } - this.name = 'ErreurSpecifique'; + this.name = "ErreurSpecifique"; // Les informations de débogage spécifiques this.toto = toto; this.date = new Date(); @@ -187,12 +186,12 @@ class ErreurSpecifique extends Error { } try { - throw new ErreurSpecifique('truc', 'trucMessage'); -} catch(e) { - console.error(e.name); // ErreurSpecifique - console.error(e.toto); // truc + throw new ErreurSpecifique("truc", "trucMessage"); +} catch (e) { + console.error(e.name); // ErreurSpecifique + console.error(e.toto); // truc console.error(e.message); // trucMessage - console.error(e.stack); // stacktrace + console.error(e.stack); // stacktrace } ``` @@ -203,7 +202,7 @@ try { ```js function ErreurSpecifique(toto, message, fileName, lineNumber) { var instance = new Error(message, fileName, lineNumber); - instance.name = 'ErreurSpecifique'; + instance.name = "ErreurSpecifique"; instance.toto = toto; Object.setPrototypeOf(instance, Object.getPrototypeOf(this)); if (Error.captureStackTrace) { @@ -217,19 +216,19 @@ ErreurSpecifique.prototype = Object.create(Error.prototype, { value: Error, enumerable: false, writable: true, - configurable: true - } + configurable: true, + }, }); -if (Object.setPrototypeOf){ +if (Object.setPrototypeOf) { Object.setPrototypeOf(ErreurSpecifique, Error); } else { ErreurSpecifique.__proto__ = Error; } try { - throw new ErreurSpecifique('truc', 'trucMessage'); -} catch(e){ + throw new ErreurSpecifique("truc", "trucMessage"); +} catch (e) { console.error(e.name); // ErreurSpecifique console.error(e.toto); // truc console.error(e.message); // trucMessage diff --git a/files/fr/web/javascript/reference/global_objects/error/linenumber/index.md b/files/fr/web/javascript/reference/global_objects/error/linenumber/index.md index 3e02c17b897887..795429d7da49da 100644 --- a/files/fr/web/javascript/reference/global_objects/error/linenumber/index.md +++ b/files/fr/web/javascript/reference/global_objects/error/linenumber/index.md @@ -15,16 +15,16 @@ La propriété **`lineNumber`** contient le numéro de la ligne qui a déclench ```js var e = new Error("Ne peut pas lire la donnée"); throw e; -console.log(e.lineNumber) // 2 +console.log(e.lineNumber); // 2 ``` ### Alternative en utilisant l'événement `error` ```js window.addEventListener("error", function (e) { - console.log(e.lineNumber); //5 + console.log(e.lineNumber); //5 }); -var e = new Error('Ne peut pas lire la donnée'); +var e = new Error("Ne peut pas lire la donnée"); throw e; ``` diff --git a/files/fr/web/javascript/reference/global_objects/error/stack/index.md b/files/fr/web/javascript/reference/global_objects/error/stack/index.md index 3a62c146117fa1..ce510ba35ea3a9 100644 --- a/files/fr/web/javascript/reference/global_objects/error/stack/index.md +++ b/files/fr/web/javascript/reference/global_objects/error/stack/index.md @@ -23,34 +23,34 @@ Les différents navigateurs définissent cette valeur à différents instants. P Le code HTML suivant démontre l'utilisation de la propriété `stack`. ```html - - + + Exemple de Trace de Pile - + + ``` En supposant que ce code a été enregistré comme `C:\exemple.html` sur un système de fichier Windows, il produira un message d'alerte dans une nouvelle fenêtre avec le texte suivant : À partir de Firefox 30 et ultérieur, ce message contiendra le numéro de colonne ([bug Firefox 762556](https://bugzil.la/762556)) : -```html +```plain trace@file:///C:/exemple.html:9:17 b@file:///C:/exemple.html:16:13 a@file:///C:/exemple.html:19:13 @@ -59,7 +59,7 @@ a@file:///C:/exemple.html:19:13 De Firefox 14 à Firefox 29 : -``` +```plain trace@file:///C:/exemple.html:9 b@file:///C:/exemple.html:16 a@file:///C:/exemple.html:19 @@ -68,7 +68,7 @@ a@file:///C:/exemple.html:19 Firefox 13 et antérieur aurait produit à la place le texte suivant : -``` +```plain Error("monError")@:0 trace()@file:///C:/exemple.html:9 b(3,4,"\n\n",(void 0),[object Object])@file:///C:/exemple.html:16 @@ -82,7 +82,7 @@ a("premier appel, premierarg")@file:///C:/exemple.html:19 ```js try { - new Function('throw new Error()')(); + new Function("throw new Error()")(); } catch (e) { console.log(e.stack); } diff --git a/files/fr/web/javascript/reference/global_objects/error/tostring/index.md b/files/fr/web/javascript/reference/global_objects/error/tostring/index.md index 3c00992559efc2..e3c3950d15e0b0 100644 --- a/files/fr/web/javascript/reference/global_objects/error/tostring/index.md +++ b/files/fr/web/javascript/reference/global_objects/error/tostring/index.md @@ -11,7 +11,7 @@ La méthode **`toString()`** renvoie une représentation de l'objet {{jsxref("Er ## Syntaxe ```js -e.toString() +e.toString(); ``` ### Valeur de retour @@ -27,19 +27,16 @@ Error.prototype.toString = function () { "use strict"; var obj = Object(this); - if (obj !== this) - throw new TypeError(); + if (obj !== this) throw new TypeError(); var name = this.name; - name = (name === undefined) ? "Error" : String(name); + name = name === undefined ? "Error" : String(name); var msg = this.message; - msg = (msg === undefined) ? "" : String(msg); + msg = msg === undefined ? "" : String(msg); - if (name === "") - return msg; - if (msg === "") - return name; + if (name === "") return msg; + if (msg === "") return name; return name + ": " + msg; }; diff --git a/files/fr/web/javascript/reference/global_objects/escape/index.md b/files/fr/web/javascript/reference/global_objects/escape/index.md index b65c678692ca90..e0e39c5c9f1ebb 100644 --- a/files/fr/web/javascript/reference/global_objects/escape/index.md +++ b/files/fr/web/javascript/reference/global_objects/escape/index.md @@ -18,7 +18,7 @@ La fonction **`escape()`** permet de renvoyer une nouvelle chaîne de caractère ## Syntaxe ```js -escape(str) +escape(str); ``` ### Paramètres @@ -39,12 +39,12 @@ La forme hexadécimale des caractères dont la valeur du codet est inférieure ## Exemples ```js -escape("abc123"); // "abc123" -escape("äöü"); // "%E4%F6%FC" -escape("ć"); // "%u0107" +escape("abc123"); // "abc123" +escape("äöü"); // "%E4%F6%FC" +escape("ć"); // "%u0107" // caractères spéciaux -escape("@*_+-./"); // "@*_+-./" +escape("@*_+-./"); // "@*_+-./" ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/eval/index.md b/files/fr/web/javascript/reference/global_objects/eval/index.md index 7cc8982ce79234..d4984fea7b1a43 100644 --- a/files/fr/web/javascript/reference/global_objects/eval/index.md +++ b/files/fr/web/javascript/reference/global_objects/eval/index.md @@ -15,7 +15,7 @@ La fonction **`eval()`** permet d'évaluer du code JavaScript représenté sous ## Syntaxe ```js -eval(str) +eval(str); ``` ### Paramètres @@ -39,7 +39,7 @@ Si l'argument passé à `eval()` n'est pas une chaîne de caractères, `eval()` ```js eval(new String("2 + 2")); // renvoie un objet String contenant "2 + 2" -eval("2 + 2"); // renvoie 4 +eval("2 + 2"); // renvoie 4 ``` Ce comportement peut être résolu de façon générique en utilisant la méthode `toString()`. @@ -53,11 +53,12 @@ Si la fonction `eval` est utilisée de manière indirecte, en l'invoquant par un ```js function test() { - var x = 2, y = 4; - console.log(eval("x + y")); // Appel direct, portée locale, résultat de 6 + var x = 2, + y = 4; + console.log(eval("x + y")); // Appel direct, portée locale, résultat de 6 var geval = eval; console.log(geval("x + y")); // Appel indirect, portée globale, lance une exception ReferenceError car `x` n'est pas défini - (0, eval)('x + y'); // un autre exemple d'appel indirect. + (0, eval)("x + y"); // un autre exemple d'appel indirect. } ``` @@ -74,23 +75,19 @@ De plus, les moteurs JavaScript modernes convertissent le code JavaScript en cod Avec `eval()` : ```js -function looseJsonParse(obj){ - return eval("(" + obj + ")"); +function looseJsonParse(obj) { + return eval("(" + obj + ")"); } -console.log(looseJsonParse( - "{a:(4-1), b:function(){}, c:new Date()}" -)) +console.log(looseJsonParse("{a:(4-1), b:function(){}, c:new Date()}")); ``` Avec `Function` : ```js -function looseJsonParse(obj){ - return Function('"use strict";return (' + obj + ')')(); +function looseJsonParse(obj) { + return Function('"use strict";return (' + obj + ")")(); } -console.log(looseJsonParse( - "{a:(4-1), b:function(){}, c:new Date()}" -)) +console.log(looseJsonParse("{a:(4-1), b:function(){}, c:new Date()}")); ``` Dans le premier cas, l'évaluation de `c: new Date()` sera beaucoup plus lente car `Date` peut faire référence à une variable déclarée avant. Dans le second cas, la fonction est évaluée dans la portée globale et le moteur peut donc utiliser {{jsxref("Date")}} directement. @@ -98,15 +95,21 @@ Dans le premier cas, l'évaluation de `c: new Date()` sera beaucoup plus lente c Autrement dit, dans le premier cas, on aurait pu avoir un code comme : ```js -function Date(n){ - return ["Monday","Tuesday","Wednesday","Thursaday","Friday","Saturday","Sunday"][n%7 || 0]; +function Date(n) { + return [ + "Monday", + "Tuesday", + "Wednesday", + "Thursaday", + "Friday", + "Saturday", + "Sunday", + ][n % 7 || 0]; } -function looseJsonParse(obj){ - return eval("(" + obj + ")"); +function looseJsonParse(obj) { + return eval("(" + obj + ")"); } -console.log(looseJsonParse( - "{a:(4-1), b:function(){}, c:new Date()}" -)) +console.log(looseJsonParse("{a:(4-1), b:function(){}, c:new Date()}")); ``` Auquel cas, le navigateur doit effectuer une recherche coûteuse afin de vérifier s'il y a des variables locales `Date`. @@ -114,17 +117,21 @@ Auquel cas, le navigateur doit effectuer une recherche coûteuse afin de vérifi Pour obtenir un résultat identique, on peut tout à fait se passer d'`eval()` : ```js -function Date(n){ - return ["Monday","Tuesday","Wednesday","Thursaday","Friday","Saturday","Sunday"][n%7 || 0]; +function Date(n) { + return [ + "Monday", + "Tuesday", + "Wednesday", + "Thursaday", + "Friday", + "Saturday", + "Sunday", + ][n % 7 || 0]; } -function runCodeWithDateFunction(obj){ - return Function('"use strict";return (' + obj + ')')()( - Date - ); +function runCodeWithDateFunction(obj) { + return Function('"use strict";return (' + obj + ")")()(Date); } -console.log(runCodeWithDateFunction( - "function(Date){ return Date(5) }" -)) +console.log(runCodeWithDateFunction("function(Date){ return Date(5) }")); ``` 1\. Le code passé à `runCodeWithDateFunction` peut être minifié. @@ -143,16 +150,16 @@ Enfin, pour la plupart des cas, on doit pouvoir éviter de passer par ```js var obj = { a: 20, b: 30 }; -var nomPropriété = getNomProp(); //une méthode qui renvoie "a" ou "b" +var nomPropriété = getNomProp(); //une méthode qui renvoie "a" ou "b" -eval( "var résultat = obj." + nomPropriété ); +eval("var résultat = obj." + nomPropriété); ``` Cependant, `eval()` n'est pas du tout nécessaire. Il est beaucoup plus simple, plus sécurisé, plus rapide, d'utiliser les [accesseurs de propriétés](/fr/docs/Web/JavaScript/Reference/Opérateurs/Opérateurs_de_membres) : ```js var obj = { a: 20, b: 30 }; -var nomPropriété = getNomProp(); // une méthode qui renvoie "a" or "b" +var nomPropriété = getNomProp(); // une méthode qui renvoie "a" or "b" var résultat = obj[nomPropriété]; // obj[ "a" ] correspond à obj.a ``` @@ -165,7 +172,7 @@ Les fonctions JavaScript sont des [citoyens de premier rang du langage](https:// setTimeout(function() { ... }, 1000); // au lieu de elt.setAttribute("onclick", "...") on utilisera : -elt.addEventListener("click", function() { ... } , false); +elt.addEventListener("click", function() { ... } , false); ``` [Les fermetures (_closures_)](/fr/docs/Web/JavaScript/Guide/Closures) sont utiles lorsqu'on souhaite obtenir des fonctions paramétrées sans avoir à concaténer des chaînes de caractères. @@ -195,7 +202,7 @@ var x = 2; var y = 39; var z = "42"; eval("x + y + 1"); // renvoie 42 -eval(z); // renvoie 42 +eval(z); // renvoie 42 ``` ### Utiliser `eval()` pour une chaîne d'instructions @@ -205,7 +212,7 @@ Dans l'exemple qui suit, `eval()` est utilisée pour évaluer la chaîne de cara ```js var x = 5; var str = "if (x == 5) {console.log('z vaut 42'); z = 42;} else z = 0; "; -console.log("z vaut "+eval(str)); +console.log("z vaut " + eval(str)); ``` ### Le résultat d'`eval()` est celui de la dernière expression @@ -215,12 +222,12 @@ console.log("z vaut "+eval(str)); ```js var str = "if ( a ) { 1+1; } else { 1+2; }"; var a = true; -var b = eval(str); // renvoie 2 +var b = eval(str); // renvoie 2 console.log("b vaut : " + b); a = false; -b = eval(str); // renvoie 3 +b = eval(str); // renvoie 3 console.log("b vaut : " + b); ``` @@ -230,10 +237,10 @@ console.log("b vaut : " + b); Pour qu'une fonction soit restituée lors de l'évaluation, il est nécessaire d'encadrer l'expression contenue dans la chaîne de caractères avec des parenthèses : ```js -var fctStr1 = "function a() {}" -var fctStr2 = "(function a() {})" -var fct1 = eval(fctStr1) // renvoie undefined -var fct2 = eval(fctStr2) // renvoie une function +var fctStr1 = "function a() {}"; +var fctStr2 = "(function a() {})"; +var fct1 = eval(fctStr1); // renvoie undefined +var fct2 = eval(fctStr2); // renvoie une function ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/evalerror/evalerror/index.md b/files/fr/web/javascript/reference/global_objects/evalerror/evalerror/index.md index 09f37ee09b80a3..ecaabb630ec7ee 100644 --- a/files/fr/web/javascript/reference/global_objects/evalerror/evalerror/index.md +++ b/files/fr/web/javascript/reference/global_objects/evalerror/evalerror/index.md @@ -11,10 +11,10 @@ Le **constructeur `EvalError()`** permet de créer un objet représentant une er ## Syntaxe ```js -new EvalError() -new EvalError(message) -new EvalError(message, nomFichier) -new EvalError(message, nomFichier, numeroLigne) +new EvalError(); +new EvalError(message); +new EvalError(message, nomFichier); +new EvalError(message, nomFichier, numeroLigne); ``` ### Paramètres @@ -34,15 +34,15 @@ new EvalError(message, nomFichier, numeroLigne) ```js try { - throw new EvalError('Coucou', 'unFichier.js', 10); + throw new EvalError("Coucou", "unFichier.js", 10); } catch (e) { console.log(e instanceof EvalError); // true - console.log(e.message); // "Coucou" - console.log(e.name); // "EvalError" - console.log(e.fileName); // "unFichier.js" - console.log(e.lineNumber); // 10 - console.log(e.columnNumber); // 0 - console.log(e.stack); // "@Scratchpad/2:2:9\n" + console.log(e.message); // "Coucou" + console.log(e.name); // "EvalError" + console.log(e.fileName); // "unFichier.js" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // "@Scratchpad/2:2:9\n" } ``` diff --git a/files/fr/web/javascript/reference/global_objects/evalerror/index.md b/files/fr/web/javascript/reference/global_objects/evalerror/index.md index 5d40c472abddb0..0a458b77cb1ace 100644 --- a/files/fr/web/javascript/reference/global_objects/evalerror/index.md +++ b/files/fr/web/javascript/reference/global_objects/evalerror/index.md @@ -36,15 +36,15 @@ L'objet **`EvalError`** indique une erreur relative à la fonction [`eval()`](/f ```js try { - throw new EvalError('Coucou', 'unFichier.js', 10); + throw new EvalError("Coucou", "unFichier.js", 10); } catch (e) { console.log(e instanceof EvalError); // true - console.log(e.message); // "Coucou" - console.log(e.name); // "EvalError" - console.log(e.fileName); // "unFichier.js" - console.log(e.lineNumber); // 10 - console.log(e.columnNumber); // 0 - console.log(e.stack); // "@Scratchpad/2:2:9\n" + console.log(e.message); // "Coucou" + console.log(e.name); // "EvalError" + console.log(e.fileName); // "unFichier.js" + console.log(e.lineNumber); // 10 + console.log(e.columnNumber); // 0 + console.log(e.stack); // "@Scratchpad/2:2:9\n" } ``` diff --git a/files/fr/web/javascript/reference/global_objects/finalizationregistry/finalizationregistry/index.md b/files/fr/web/javascript/reference/global_objects/finalizationregistry/finalizationregistry/index.md index 495ecacdd15514..c3c635ea8538ac 100644 --- a/files/fr/web/javascript/reference/global_objects/finalizationregistry/finalizationregistry/index.md +++ b/files/fr/web/javascript/reference/global_objects/finalizationregistry/finalizationregistry/index.md @@ -33,7 +33,7 @@ new FinalizationRegistry(function(valeurTenue) { ... }) On crée le registre en fournissant la fonction de rappel : ```js -const registre = new FinalizationRegistry(valeurTenue => { +const registre = new FinalizationRegistry((valeurTenue) => { // .... }); ``` diff --git a/files/fr/web/javascript/reference/global_objects/finalizationregistry/index.md b/files/fr/web/javascript/reference/global_objects/finalizationregistry/index.md index 01edeb998660a4..593897129f9be6 100644 --- a/files/fr/web/javascript/reference/global_objects/finalizationregistry/index.md +++ b/files/fr/web/javascript/reference/global_objects/finalizationregistry/index.md @@ -17,12 +17,12 @@ Un objet **`FinalizationRegistry`** permet de déclencher une fonction de rappel On crée le registre en passant la fonction de rappel en paramètre : ```js -const registre = new FinalizationRegistry(valeurTenue => { +const registre = new FinalizationRegistry((valeurTenue) => { // … }); ``` -Ensuite, avec la méthode `register` on inscrit au registre les différents objets pour lesquels on veut que la fonction de rappel de nettoyage soit appelée. Cette fonction prend en argument la valeur courante et une *valeur tenue* pour celle-ci : +Ensuite, avec la méthode `register` on inscrit au registre les différents objets pour lesquels on veut que la fonction de rappel de nettoyage soit appelée. Cette fonction prend en argument la valeur courante et une _valeur tenue_ pour celle-ci : ```js registre.register(unObjet, "une valeur"); @@ -68,7 +68,7 @@ Une utilisation correcte de `FinalizationRegistry` nécessite une réflexion suf Voici quelques sujets spécifiques inclus dans [le document explicatif de la proposition correspondante](https://github.com/tc39/proposal-weakrefs/blob/master/reference.md) : -> [Les ramasses-miettes](https://fr.wikipedia.org/wiki/Ramasse-miettes_(informatique)) sont compliqués. Si une application ou une bibliothèque dépend d'un ramasse-miettes nettoyant un registre FinalizationRegistry ou appelant un finaliseur de façon précise et prédictible, qu'elle se prépare à être déçue : le nettoyage pourra avoir lieu bien plus tard que prévu voire pas du tout. Ce comportement grandement variable est dû : +> [Les ramasses-miettes]() sont compliqués. Si une application ou une bibliothèque dépend d'un ramasse-miettes nettoyant un registre FinalizationRegistry ou appelant un finaliseur de façon précise et prédictible, qu'elle se prépare à être déçue : le nettoyage pourra avoir lieu bien plus tard que prévu voire pas du tout. Ce comportement grandement variable est dû : > > - Au fait qu'un objet peut être récupéré par le ramasse-miettes bien plus tôt qu'un autre, même s'il devient inaccessible au même temps, par exemple en raison du ramassage générationnel. > - À l'action du ramasse-miettes qui peut être divisée dans le temps en utilisant des techniques incrémentales et concurrentes. @@ -95,14 +95,14 @@ Quelques notes à propos des fonctions de rappel de nettoyage : On crée le registre en y passant la fonction de rappel : ```js -const registre = new FinalizationRegistry(valeurTenue => { +const registre = new FinalizationRegistry((valeurTenue) => { // .... }); ``` ### Enregistrer des objets en vue de leur nettoyage -Ensuite, on enregistre les objets pour lesquels on souhaite avoir la fonction de rappel de nettoyage exécutée. Pour cela, on appelle la méthode `register` en lui passant l'objet et une *valeur tenue* correspondante : +Ensuite, on enregistre les objets pour lesquels on souhaite avoir la fonction de rappel de nettoyage exécutée. Pour cela, on appelle la méthode `register` en lui passant l'objet et une _valeur tenue_ correspondante : ```js registre.register(unObjet, "une valeur"); diff --git a/files/fr/web/javascript/reference/global_objects/finalizationregistry/register/index.md b/files/fr/web/javascript/reference/global_objects/finalizationregistry/register/index.md index 85f436bd72d596..f733ed83bb030b 100644 --- a/files/fr/web/javascript/reference/global_objects/finalizationregistry/register/index.md +++ b/files/fr/web/javascript/reference/global_objects/finalizationregistry/register/index.md @@ -45,7 +45,7 @@ registry.register(cible, "une valeur", cible); La ligne suivante enregistre l'objet `cible` et passe un autre objet comme valeur tenue. L'absence de jeton de désenregistrement indique que `cible` ne peut pas être retiré du registre) : ```js -registry.register(cible, {"utile": "info à propos de la cible"}); +registry.register(cible, { utile: "info à propos de la cible" }); ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/finalizationregistry/unregister/index.md b/files/fr/web/javascript/reference/global_objects/finalizationregistry/unregister/index.md index 94f36b710d14de..1389ef223ae882 100644 --- a/files/fr/web/javascript/reference/global_objects/finalizationregistry/unregister/index.md +++ b/files/fr/web/javascript/reference/global_objects/finalizationregistry/unregister/index.md @@ -35,9 +35,11 @@ Cet exemple illustre l'enregistrement d'un objet en l'utilisant lui-même comme ```js class Bidule { - #cleanup = label => { - // ^^^^^−−−−− valeur tenue - console.error(`La méthode \`release\` n'a jamais été appelée pour l'objet avec l'étiquette "${label}"`); + #cleanup = (label) => { + // ^^^^^−−−−− valeur tenue + console.error( + `La méthode \`release\` n'a jamais été appelée pour l'objet avec l'étiquette "${label}"`, + ); }; #registry = new FinalizationRegistry(this.#cleanup); @@ -57,8 +59,8 @@ class Bidule { * Libère les ressources tenues par cette instance de `Bidule` . */ release() { - this.#registry.unregister(this); - // ^^^^−−−−− jeton de désenregistrement + this.#registry.unregister(this); + // ^^^^−−−−− jeton de désenregistrement } } ``` @@ -67,9 +69,11 @@ Dans l'exemple qui suit, on illustre l'enregistrement en utilisant un autre obje ```js class Bidule { - #cleanup = label => { - // ^^^^−−−−− valeur tenue - console.error(`La méthode \`release\` n'a jamais été appelée pour \`Bidule\` pour le fichier "${file.name}"`); + #cleanup = (label) => { + // ^^^^^−−−−− valeur tenue + console.error( + `La méthode \`release\` n'a jamais été appelée pour \`Bidule\` pour le fichier "${file.name}"`, + ); }; #registry = new FinalizationRegistry(this.#cleanup); diff --git a/files/fr/web/javascript/reference/global_objects/float32array/float32array/index.md b/files/fr/web/javascript/reference/global_objects/float32array/float32array/index.md index de0460a4e37f84..8be7f95e5fbfe5 100644 --- a/files/fr/web/javascript/reference/global_objects/float32array/float32array/index.md +++ b/files/fr/web/javascript/reference/global_objects/float32array/float32array/index.md @@ -45,7 +45,7 @@ console.log(float32.length); // 2 console.log(float32.BYTES_PER_ELEMENT); // 4 // À partir d'un tableau -const arr = new Float32Array([21,31]); +const arr = new Float32Array([21, 31]); console.log(arr[1]); // 31 // À partir d'un autre tableau typé @@ -58,7 +58,9 @@ const buffer = new ArrayBuffer(16); const z = new Float32Array(buffer, 0, 4); // À partir d'un itérable -const iterable = function*(){ yield* [1,2,3]; }(); +const iterable = (function* () { + yield* [1, 2, 3]; +})(); const float32 = new Float32Array(iterable); // Float32Array[1, 2, 3] ``` diff --git a/files/fr/web/javascript/reference/global_objects/float32array/index.md b/files/fr/web/javascript/reference/global_objects/float32array/index.md index 21a117217d235d..dce632ed737d2c 100644 --- a/files/fr/web/javascript/reference/global_objects/float32array/index.md +++ b/files/fr/web/javascript/reference/global_objects/float32array/index.md @@ -125,7 +125,7 @@ console.log(float32.length); // 2 console.log(float32.BYTES_PER_ELEMENT); // 4 // Construction à partir d'un tableau -var arr = new Float32Array([21,31]); +var arr = new Float32Array([21, 31]); console.log(arr[1]); // 31 // Construction à partir d'un tableau typé @@ -138,7 +138,9 @@ var buffer = new ArrayBuffer(16); var z = new Float32Array(buffer, 0, 4); // Construction à partir d'un itérable -var iterable = function*(){ yield* [1,2,3]; }(); +var iterable = (function* () { + yield* [1, 2, 3]; +})(); var float32 = new Float32Array(iterable); // Float32Array[1, 2, 3] ``` diff --git a/files/fr/web/javascript/reference/global_objects/float64array/float64array/index.md b/files/fr/web/javascript/reference/global_objects/float64array/float64array/index.md index bf6608252d7c45..1c2286e135a751 100644 --- a/files/fr/web/javascript/reference/global_objects/float64array/float64array/index.md +++ b/files/fr/web/javascript/reference/global_objects/float64array/float64array/index.md @@ -45,7 +45,7 @@ console.log(float64.length); // 2 console.log(float64.BYTES_PER_ELEMENT); // 8 // À partir d'un tableau -const arr = new Float64Array([21,31]); +const arr = new Float64Array([21, 31]); console.log(arr[1]); // 31 // À partir d'un autre tableau typé @@ -58,7 +58,9 @@ const buffer = new ArrayBuffer(32); const z = new Float64Array(buffer, 0, 4); // À partir d'un itérable -const iterable = function*(){ yield* [1,2,3]; }(); +const iterable = (function* () { + yield* [1, 2, 3]; +})(); const float64 = new Float64Array(iterable); // Float64Array[1, 2, 3] ``` diff --git a/files/fr/web/javascript/reference/global_objects/float64array/index.md b/files/fr/web/javascript/reference/global_objects/float64array/index.md index 82acd1b4ea5111..42134859b1ee7c 100644 --- a/files/fr/web/javascript/reference/global_objects/float64array/index.md +++ b/files/fr/web/javascript/reference/global_objects/float64array/index.md @@ -125,7 +125,7 @@ console.log(float64.length); // 2 console.log(float64.BYTES_PER_ELEMENT); // 8 // Construction à partir d'un tableau -var arr = new Float64Array([21,31]); +var arr = new Float64Array([21, 31]); console.log(arr[1]); // 31 // Construction à partir d'un autre tableau typé @@ -138,7 +138,9 @@ var buffer = new ArrayBuffer(32); var z = new Float64Array(buffer, 0, 4); // Construction à partir d'un itérable -var iterable = function*(){ yield* [1,2,3]; }(); +var iterable = (function* () { + yield* [1, 2, 3]; +})(); var float64 = new Float64Array(iterable); // Float64Array[1, 2, 3] ``` diff --git a/files/fr/web/javascript/reference/global_objects/function/apply/index.md b/files/fr/web/javascript/reference/global_objects/function/apply/index.md index c444f0665270ef..eb41d1a642a809 100644 --- a/files/fr/web/javascript/reference/global_objects/function/apply/index.md +++ b/files/fr/web/javascript/reference/global_objects/function/apply/index.md @@ -17,7 +17,7 @@ La méthode **`apply()`** appelle une fonction en lui passant une valeur `this` ## Syntaxe ```js -fun.apply(thisArg, [argsArray]) +fun.apply(thisArg, [argsArray]); ``` ### Paramètres @@ -60,10 +60,11 @@ Function.prototype.construct = function (aArgs) { > **Note :** La méthode {{jsxref("Object.create()")}} utilisée ci-avant est relativement nouvelle. Pour une autre méthode qui utilise les `closure`, on pourra utiliser : > > ```js -> Function.prototype.construct = function(aArgs) { -> var fConstructeur = this, fNouveauConstructeur = function() { -> fConstructeur.apply(this, aArgs); -> }; +> Function.prototype.construct = function (aArgs) { +> var fConstructeur = this, +> fNouveauConstructeur = function () { +> fConstructeur.apply(this, aArgs); +> }; > fNouveauConstructeur.prototype = fConstructeur.prototype; > return new fNouveauConstructeur(); > }; @@ -72,10 +73,10 @@ Function.prototype.construct = function (aArgs) { Exemple d'utilisation : ```js -function MonConstructeur () { - for (var nProp = 0; nProp < arguments.length; nProp++) { - this["propriété" + nProp] = arguments[nProp]; - } +function MonConstructeur() { + for (var nProp = 0; nProp < arguments.length; nProp++) { + this["propriété" + nProp] = arguments[nProp]; + } } var monTableau = [4, "Coucou monde !", false]; @@ -127,13 +128,11 @@ var max = Math.max.apply(null, nombres); var min = Math.min.apply(null, nombres); /* vs. algorithme trivial avec une boucle */ -max = -Infinity, min = +Infinity; +(max = -Infinity), (min = +Infinity); for (var i = 0; i < nombres.length; i++) { - if (nombres[i] > max) - max = nombres[i]; - if (nombres[i] < min) - min = nombres[i]; + if (nombres[i] > max) max = nombres[i]; + if (nombres[i] < min) min = nombres[i]; } ``` @@ -145,8 +144,10 @@ function minimumDuTableau(tab) { var QUANTUM = 32768; for (var i = 0, longueur = tab.length; i < len; i += QUANTUM) { - var submin = Math.min.apply(null, - tab.slice(i, Math.min(i + QUANTUM, longueur))); + var submin = Math.min.apply( + null, + tab.slice(i, Math.min(i + QUANTUM, longueur)), + ); min = Math.min(submin, min); } diff --git a/files/fr/web/javascript/reference/global_objects/function/arguments/index.md b/files/fr/web/javascript/reference/global_objects/function/arguments/index.md index f9f06151ee5a01..8bf680d7b5dc9b 100644 --- a/files/fr/web/javascript/reference/global_objects/function/arguments/index.md +++ b/files/fr/web/javascript/reference/global_objects/function/arguments/index.md @@ -19,11 +19,13 @@ La valeur de la propriété `arguments` est normalement `null` si la fonction n' ## Exemples ```js -function f(n) { g(n-1); } +function f(n) { + g(n - 1); +} function g(n) { console.log("avant : " + g.arguments[0]); - if(n>0) f(n); + if (n > 0) f(n); console.log("après : " + g.arguments[0]); } diff --git a/files/fr/web/javascript/reference/global_objects/function/bind/index.md b/files/fr/web/javascript/reference/global_objects/function/bind/index.md index 83fd098b6ffeb8..d47f60bf9ca250 100644 --- a/files/fr/web/javascript/reference/global_objects/function/bind/index.md +++ b/files/fr/web/javascript/reference/global_objects/function/bind/index.md @@ -56,11 +56,13 @@ Une erreur courante lorsqu'on débute en JavaScript est d'extraire une méthode ```js this.x = 9; // en dehors de tout contexte, - // pour un navigateur, this est - // l'objet window +// pour un navigateur, this est +// l'objet window var module = { x: 81, - getX: function() { return this.x; } + getX: function () { + return this.x; + }, }; module.getX(); // 81 @@ -91,8 +93,7 @@ var leadingThirtysevenList = list.bind(null, 37); var list2 = leadingThirtysevenList(); // [37] var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3] - -function sommeArguments(arg1, arg2){ +function sommeArguments(arg1, arg2) { return arg1 + arg2; } @@ -107,17 +108,16 @@ Par défaut à l'intérieur de {{domxref("window.setTimeout()")}}, le mot-clé ` ```js function Fleur() { - this.nbPétales = Math.floor( Math.random() * 12 ) + 1; + this.nbPétales = Math.floor(Math.random() * 12) + 1; } // On déclare floraison après un délai d'une seconde -Fleur.prototype.floraison = function() { - window.setTimeout( this.declare.bind( this ), 1000 ); +Fleur.prototype.floraison = function () { + window.setTimeout(this.declare.bind(this), 1000); }; -Fleur.prototype.declare = function() { - console.log('Je suis une fleur avec ' + - this.nbPétales + ' pétales !'); +Fleur.prototype.declare = function () { + console.log("Je suis une fleur avec " + this.nbPétales + " pétales !"); }; var fleur = new Fleur(); @@ -137,19 +137,18 @@ function Point(x, y) { this.y = y; } -Point.prototype.toString = function() { +Point.prototype.toString = function () { return this.x + "," + this.y; }; var p = new Point(1, 2); p.toString(); // "1,2" - var emptyObj = {}; var YAxisPoint = Point.bind(emptyObj, 0 /* x */); // non supporté dans le polyfill ci dessous, // fonctionne avec le bind natif : -var YAxisPoint = Point.bind(null,0 /* x */); +var YAxisPoint = Point.bind(null, 0 /* x */); var axisPoint = new YAxisPoint(5); axisPoint.toString(); // "0,5" diff --git a/files/fr/web/javascript/reference/global_objects/function/call/index.md b/files/fr/web/javascript/reference/global_objects/function/call/index.md index bb988b759ef581..e6c7301c3e5a71 100644 --- a/files/fr/web/javascript/reference/global_objects/function/call/index.md +++ b/files/fr/web/javascript/reference/global_objects/function/call/index.md @@ -49,16 +49,16 @@ function Product(name, price) { function Food(name, price) { Product.call(this, name, price); - this.category = 'food'; + this.category = "food"; } function Toy(name, price) { Product.call(this, name, price); - this.category = 'toy'; + this.category = "toy"; } -var cheese = new Food('feta', 5); -var fun = new Toy('robot', 40); +var cheese = new Food("feta", 5); +var fun = new Toy("robot", 40); ``` ### Utiliser `call()` pour invoquer une fonction anonyme @@ -67,15 +67,15 @@ Dans cet exemple (purement inventé), on crée une fonction anonyme et on utilis ```js var animaux = [ - {espece: 'Lion', nom: 'Roi'}, - {espece: 'Éléphant', nom: 'Dumbo'} + { espece: "Lion", nom: "Roi" }, + { espece: "Éléphant", nom: "Dumbo" }, ]; for (var i = 0; i < animaux.length; i++) { (function (i) { this.print = function () { - console.log('#' + i + ' ' + this.espece + ' : ' + this.nom); - } + console.log("#" + i + " " + this.espece + " : " + this.nom); + }; this.print(); }).call(animaux[i], i); } @@ -93,7 +93,7 @@ function saluer() { var personne1 = { nom: "Sénèque", - role: "philosophe" + role: "philosophe", }; saluer.call(personne1); // Sénèque est un philosophe. @@ -104,10 +104,10 @@ saluer.call(personne1); // Sénèque est un philosophe. Dans l'exemple qui suit, on appelle la fonction `afficher()` sans lui passer d'argument. C'est donc l'objet global qui est utilisé comme contexte : ```js -var prenom = 'Archibald'; +var prenom = "Archibald"; function afficher() { - console.log('prenom vaut ' + this.prenom); + console.log("prenom vaut " + this.prenom); } afficher.call(); // prenom est Archibald @@ -116,12 +116,12 @@ afficher.call(); // prenom est Archibald > **Note :** La valeur de `this` sera {{jsxref("undefined")}} en mode strict. > > ```js -> 'use strict'; +> "use strict"; > -> var prenom = 'Archibald'; +> var prenom = "Archibald"; > > function afficher() { -> console.log('prenom vaut ' + this.prenom); +> console.log("prenom vaut " + this.prenom); > } > > afficher.call(); // Cannot read the property prenom' of undefined diff --git a/files/fr/web/javascript/reference/global_objects/function/caller/index.md b/files/fr/web/javascript/reference/global_objects/function/caller/index.md index 494d44807f32fd..86f4cbbc7edcce 100644 --- a/files/fr/web/javascript/reference/global_objects/function/caller/index.md +++ b/files/fr/web/javascript/reference/global_objects/function/caller/index.md @@ -21,8 +21,16 @@ La propriété spéciale `__caller__` qui renvoyait l'objet qui dans lequel éta Dans une fonction récursive, cette propriété ne peut pas être utilisée pour reconstituer la pile d'appels (_call stack_). Par exemple, si on a : ```js -function f(n) { g(n - 1); } -function g(n) { if (n > 0) { f(n); } else { stop(); } } +function f(n) { + g(n - 1); +} +function g(n) { + if (n > 0) { + f(n); + } else { + stop(); + } +} f(2); ``` @@ -35,16 +43,16 @@ f(2) -> g(1) -> f(1) -> g(0) -> stop() Et ceci est vrai : ```js -stop.caller === g && f.caller === g && g.caller === f +stop.caller === g && f.caller === g && g.caller === f; ``` Donc si on essaie d'obtenir la pile de cette façon : ```js var f = stop; -var stack = 'Stack trace:'; +var stack = "Stack trace:"; while (f) { - stack += '\n' + f.name; + stack += "\n" + f.name; f = f.caller; } ``` @@ -60,9 +68,9 @@ Dans l'exemple suivant, on verifie la propriété `caller` de la fonction. ```js function maFonction() { if (maFonction.caller == null) { - return 'Fonction appelée au plus haut niveau !'; + return "Fonction appelée au plus haut niveau !"; } else { - return 'Fonction appelée par ' + maFonction.caller; + return "Fonction appelée par " + maFonction.caller; } } ``` diff --git a/files/fr/web/javascript/reference/global_objects/function/displayname/index.md b/files/fr/web/javascript/reference/global_objects/function/displayname/index.md index b7a66a11b903c7..d036bcc1f6234c 100644 --- a/files/fr/web/javascript/reference/global_objects/function/displayname/index.md +++ b/files/fr/web/javascript/reference/global_objects/function/displayname/index.md @@ -13,13 +13,15 @@ La propriété **`function.displayName`** renvoie le nom affiché de la fonction Lorsque la propriété `displayName` est définie, elle renvoie le nom affiché de la fonction : ```js -function faireTruc() { } +function faireTruc() {} console.log(faireTruc.displayName); // "undefined" -var logMessage = function(contenu) { console.log(contenu) }; +var logMessage = function (contenu) { + console.log(contenu); +}; -logMessage.displayName = 'Afficher les messages dans le journal'; +logMessage.displayName = "Afficher les messages dans le journal"; console.log(logMessage.displayName); // "Afficher les messages dans le journal" ``` @@ -28,15 +30,19 @@ Il est possible de définir une fonction avec un nom d'affichage grâce à une { ```js var objet = { - uneMéthode: function () {} + uneMéthode: function () {}, }; -objet.uneMéthode.displayName = 'uneMéthode'; +objet.uneMéthode.displayName = "uneMéthode"; console.log(objet.uneMéthode.displayName); // "uneMéthode" -try { uneMéthode } catch(e) { console.log(e); } +try { + uneMéthode; +} catch (e) { + console.log(e); +} // ReferenceError: uneMéthode is not defined ``` @@ -45,14 +51,14 @@ La propriété `displayName` peut être changée dynamiquement : ```js var objet = { // anonyme - uneMéthode: function(valeur) { + uneMéthode: function (valeur) { this.displayName = "uneMéthode (" + valeur + ")"; - } + }, }; console.log(objet.uneMéthode.displayName); // "undefined" -objet.uneMéthode("123") +objet.uneMéthode("123"); console.log(objet.uneMéthode.displayName); // "uneMéthode (123)" ``` @@ -63,8 +69,8 @@ On souhaite généralement utiliser cette propriété dans les consoles et profi Le code suivant devrait afficher quelque chose comme "function Ma Fonction()": ```js -var a = function () { }; -a.displayName = 'Ma Fonction'; +var a = function () {}; +a.displayName = "Ma Fonction"; a; ``` diff --git a/files/fr/web/javascript/reference/global_objects/function/function/index.md b/files/fr/web/javascript/reference/global_objects/function/function/index.md index 8a040c89b2ab39..143015062ecf62 100644 --- a/files/fr/web/javascript/reference/global_objects/function/function/index.md +++ b/files/fr/web/javascript/reference/global_objects/function/function/index.md @@ -45,7 +45,7 @@ Le code qui suit crée un objet `Function` qui prend deux arguments. ```js // Crée une fonction qui prend deux arguments et qui en renvoie la somme -const additionneur = new Function('a', 'b', 'return a + b'); +const additionneur = new Function("a", "b", "return a + b"); // Appeler la fonction additionneur(2, 6); @@ -62,7 +62,9 @@ Les arguments `"a"` et `"b"` sont les noms formels des arguments utilisés dans // On peut voir ici que le résultat de new Function est appelé. // Ainsi, on peut invoquer juste après la fonction qui vient d'être créée. -const sommeTableau = new Function('const sommeTableau = (arr) => arr.reduce((precedente, courante) => precedente + courante); return sommeTableau')(); +const sommeTableau = new Function( + "const sommeTableau = (arr) => arr.reduce((precedente, courante) => precedente + courante); return sommeTableau", +)(); // On appelle la fonction sommeTableau([1, 2, 3, 4]); @@ -70,17 +72,21 @@ sommeTableau([1, 2, 3, 4]); // Si on n'appelle pas new Function au moment de la création, // on peut toujours utiliser la méthode Function.call() ensuite -const plusGrandNombre = new Function('function plusGrandNombre (arr) { return Math.max(...arr) }; return plusGrandNombre'); +const plusGrandNombre = new Function( + "function plusGrandNombre (arr) { return Math.max(...arr) }; return plusGrandNombre", +); // On appelle la fonction plusGrandNombre.call({}).call({}, [2, 4, 1, 8, 5]); // 8 // Une déclaration de fonction ne nécessite pas d'instruction return -const direCoucou = new Function('return function (nom) { return `Coucou, ${nom}` }')(); +const direCoucou = new Function( + "return function (nom) { return `Coucou, ${nom}` }", +)(); // On appelle la fonction -direCoucou('monde'); +direCoucou("monde"); // Coucou, monde ``` diff --git a/files/fr/web/javascript/reference/global_objects/function/index.md b/files/fr/web/javascript/reference/global_objects/function/index.md index 6d4836719aba8d..e618792e854632 100644 --- a/files/fr/web/javascript/reference/global_objects/function/index.md +++ b/files/fr/web/javascript/reference/global_objects/function/index.md @@ -47,24 +47,24 @@ Les fonctions créées avec le constructeur `Function()` ne créent pas de ferme var x = 10; function creerFonction1() { - var x = 20; - return new Function('return x;'); - // ce x fait référence à la variable globale x + var x = 20; + return new Function("return x;"); + // ce x fait référence à la variable globale x } function creerFonction2() { - var x = 20; - function f() { - return x; - // ce x fait référence à la variable locale x juste avant - } - return f; + var x = 20; + function f() { + return x; + // ce x fait référence à la variable locale x juste avant + } + return f; } var f1 = creerFonction1(); -console.log(f1()); // 10 +console.log(f1()); // 10 var f2 = creerFonction2(); -console.log(f2()); // 20 +console.log(f2()); // 20 ``` Bien que ce code fonctionne dans les navigateurs web, `f1()` déclenchera une erreur `ReferenceError` avec Node.js, car `x` ne sera pas trouvé. En effet, la portée de plus haut niveau de Node n'est pas la portée globale et `x` sera local au module. diff --git a/files/fr/web/javascript/reference/global_objects/function/length/index.md b/files/fr/web/javascript/reference/global_objects/function/length/index.md index 52f95383229b23..8db3d61efb90c3 100644 --- a/files/fr/web/javascript/reference/global_objects/function/length/index.md +++ b/files/fr/web/javascript/reference/global_objects/function/length/index.md @@ -27,12 +27,12 @@ La propriété `length` du prototype de {{jsxref("Function")}} vaut 0. ```js console.log(Function.length); /* 1 */ -console.log((function() {}).length); /* 0 */ -console.log((function(a) {}).length); /* 1 */ -console.log((function(a, b) {}).length); /* 2 etc. */ -console.log((function(...args) {}).length); +console.log(function () {}.length); /* 0 */ +console.log(function (a) {}.length); /* 1 */ +console.log(function (a, b) {}.length); /* 2 etc. */ +console.log(function (...args) {}.length); // 0, le paramètre du reste n'est pas compté -console.log((function(a, b = 1, c) {}).length); +console.log(function (a, b = 1, c) {}.length); // 1, seuls les paramètres avant les valeurs par // défaut sont comptés ``` diff --git a/files/fr/web/javascript/reference/global_objects/function/name/index.md b/files/fr/web/javascript/reference/global_objects/function/name/index.md index 1a0fe3e4517bd2..56169c735235df 100644 --- a/files/fr/web/javascript/reference/global_objects/function/name/index.md +++ b/files/fr/web/javascript/reference/global_objects/function/name/index.md @@ -28,7 +28,7 @@ faireUnTruc.name; // "faireUnTruc" Lorsqu'on crée une fonction avec `new Function(...)` ou simplement `Function(...)`, on crée uniquement des objets dont le nom est "anonymous". ```js -(new Function).name; // "anonymous" +new Function().name; // "anonymous" ``` ### Inférence des noms de fonction @@ -36,9 +36,9 @@ Lorsqu'on crée une fonction avec `new Function(...)` ou simplement `Function(.. Les variables et les méthodes permettent d'inférer (c'est-à-dire de « deviner ») le nom des fonctions anonymes en fonction de leur position syntaxique (cette fonctionnalité est apparue avec ECMAScript 2015). ```js -var f = function() {}; +var f = function () {}; var objet = { - uneMéthode: function() {} + uneMéthode: function () {}, }; console.log(f.name); // "f" @@ -49,11 +49,15 @@ On peut définir une fonction avec un nom grâce à une {{jsxref("Opérateurs/L_ ```js var objet = { - uneMéthode: function objet_maMéthode() {} + uneMéthode: function objet_maMéthode() {}, }; console.log(objet.uneMéthode.name); // logs "objet_maMéthode" -try { objet_maMéthode } catch(e) { console.log(e); } +try { + objet_maMéthode; +} catch (e) { + console.log(e); +} // ReferenceError: objet_maMéthode is not defined ``` @@ -62,10 +66,10 @@ On ne peut pas changer le nom d'une fonction, cette propriété est uniquement e ```js var objet = { // anonyme - uneMéthode: function() {} + uneMéthode: function () {}, }; -objet.uneMéthode.name = 'uneMéthode'; +objet.uneMéthode.name = "uneMéthode"; console.log(object.uneMéthode.name); // une chaîne vide, uneMéthode est anonyme ``` @@ -75,7 +79,7 @@ Pour modifier le nom, on pourrait cependant utiliser la méthode {{jsxref("Objec ```js var o = { - toto(){} + toto() {}, }; o.toto.name; // "toto"; ``` @@ -85,7 +89,7 @@ o.toto.name; // "toto"; {{jsxref("Function.bind()")}} produit une fonction dont le nom sera la chaîne "bound " suivi du nom de la fonction. ```js -function toto() {}; +function toto() {} toto.bind({}).name; // "bound toto" ``` @@ -95,8 +99,8 @@ Lorsqu'on utilise les propriétés d'accesseur [`get`](/fr/docs/Web/JavaScript/R ```js var o = { - get toto(){}, - set toto(x){} + get toto() {}, + set toto(x) {}, }; var descripteur = Object.getOwnPropertyDescriptor(o, "toto"); @@ -109,7 +113,7 @@ descripteur.set.name; // "set toto"; On peut utiliser la notation `obj.constructor.name` pour vérifier la « classe » d'un objet (attention aux avertissements ci-après) : ```js -function Toto() {} // Syntaxe ES2015 : class Toto {} +function Toto() {} // Syntaxe ES2015 : class Toto {} var instanceDeToto = new Toto(); console.log(instanceDeToto.constructor.name); // affiche "Toto" dans la console @@ -128,8 +132,8 @@ Avec `static name()`, `Toto.name` ne contient plus le nom de la classe mais une ```js function Toto() {} -Object.defineProperty(Toto, 'name', { writable: true }); -Toto.name = function() {}; +Object.defineProperty(Toto, "name", { writable: true }); +Toto.name = function () {}; ``` Il est donc parfois erroné de penser que `Function.name` pointe toujours vers le nom de la classe. @@ -142,8 +146,8 @@ Si un symbole ({{jsxref("Symbol")}}) est utilisé comme nom d'une fonction et qu var sym1 = Symbol("Toto"); var sym2 = Symbol(); var o = { - [sym1]: function(){}, - [sym2]: function(){} + [sym1]: function () {}, + [sym2]: function () {}, }; o[sym1].name; // "[Toto]" @@ -155,25 +159,25 @@ o[sym2].name; // "" Attention à l'utilisation de `Function.name` lorsque le code source est transformé par certains outils. En effet, ceux-ci réduisent généralement la taille d'un programme en compressant les espaces et en modifiant parfois les noms de variables. Ainsi, un fragment de code comme : ```js -function Toto() {}; +function Toto() {} var toto = new Toto(); -if (Toto.constructor.name === 'Toto') { +if (Toto.constructor.name === "Toto") { console.log("'toto' est une instance de 'Toto'"); } else { - console.log('Oups !'); + console.log("Oups !"); } ``` pourrait être compressé en : ```js -function a() {}; +function a() {} var b = new a(); -if (b.constructor.name === 'Toto') { +if (b.constructor.name === "Toto") { console.log("'toto' est une instance de 'Toto'"); } else { - console.log('Oups !'); + console.log("Oups !"); } ``` diff --git a/files/fr/web/javascript/reference/global_objects/generator/index.md b/files/fr/web/javascript/reference/global_objects/generator/index.md index c174d850c21e23..e43d1b850c2067 100644 --- a/files/fr/web/javascript/reference/global_objects/generator/index.md +++ b/files/fr/web/javascript/reference/global_objects/generator/index.md @@ -34,10 +34,9 @@ var g = gen(); // "Generator { }" ### Un itérateur infini ```js -function* idMaker(){ - var index = 0; - while(true) - yield index++; +function* idMaker() { + var index = 0; + while (true) yield index++; } var gen = idMaker(); // "Generator { }" @@ -72,11 +71,11 @@ function* fibonacci() { } var it = fibonacci(); -console.log(it); // "Generator { }" -console.log(it.next()); // 1 +console.log(it); // "Generator { }" +console.log(it.next()); // 1 console.log(it.send(10)); // 20 -console.log(it.close()); // undefined -console.log(it.next()); // throws StopIteration (le générateur est clôturé) +console.log(it.close()); // undefined +console.log(it.next()); // throws StopIteration (le générateur est clôturé) ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/generator/next/index.md b/files/fr/web/javascript/reference/global_objects/generator/next/index.md index 8bedab4230cf48..fdbe20d90362c4 100644 --- a/files/fr/web/javascript/reference/global_objects/generator/next/index.md +++ b/files/fr/web/javascript/reference/global_objects/generator/next/index.md @@ -11,7 +11,7 @@ La méthode **`next()`** renvoie un objet possédant deux propriétés `done` et ## Syntaxe ```js -gen.next(valeur) +gen.next(valeur); ``` ### Paramètres @@ -44,10 +44,10 @@ function* gen() { } var g = gen(); // "Generator { }" -g.next(); // "Object { value: 1, done: false }" -g.next(); // "Object { value: 2, done: false }" -g.next(); // "Object { value: 3, done: false }" -g.next(); // "Object { value: undefined, done: true }" +g.next(); // "Object { value: 1, done: false }" +g.next(); // "Object { value: 2, done: false }" +g.next(); // "Object { value: 3, done: false }" +g.next(); // "Object { value: undefined, done: true }" ``` ### Envoyer des valeurs à un générateur @@ -56,7 +56,7 @@ Ici, `next` est appelé avec une valeur. On notera ici que le premier appel n'af ```js function* gen() { - while(true) { + while (true) { var value = yield null; console.log(value); } diff --git a/files/fr/web/javascript/reference/global_objects/generator/return/index.md b/files/fr/web/javascript/reference/global_objects/generator/return/index.md index 49442a03ab5d39..6483b5e1a3e44b 100644 --- a/files/fr/web/javascript/reference/global_objects/generator/return/index.md +++ b/files/fr/web/javascript/reference/global_objects/generator/return/index.md @@ -11,7 +11,7 @@ La méthode **`return()`** renvoie la valeur fournie et termine le générateur. ## Syntaxe ```js -gen.return(valeur) +gen.return(valeur); ``` ### Paramètres @@ -38,9 +38,9 @@ function* gen() { var g = gen(); -g.next(); // { value: 1, done: false } +g.next(); // { value: 1, done: false } g.return("toto"); // { value: "toto", done: true } -g.next(); // { value: undefined, done: true } +g.next(); // { value: undefined, done: true } ``` > **Note :** Si `done` vaut `true`, `return(valeur)` renverra la même chose que `next()` : `undefined`. Si aucun argument n'est fourni, la propriété `value` de l'objet renvoyé sera la même qu'avec un appel à `.next()`. Si un argument est fourni, c'est lui qui sera utilisé comme valeur pour l'attribut `value` du résultat. diff --git a/files/fr/web/javascript/reference/global_objects/generator/throw/index.md b/files/fr/web/javascript/reference/global_objects/generator/throw/index.md index 7a00812d79af42..1d6f2385e57f01 100644 --- a/files/fr/web/javascript/reference/global_objects/generator/throw/index.md +++ b/files/fr/web/javascript/reference/global_objects/generator/throw/index.md @@ -11,7 +11,7 @@ La méthode **`throw()`** lève une erreur dans un générateur. ## Syntaxe ```js -gen.throw(exception) +gen.throw(exception); ``` ### Paramètres @@ -38,10 +38,10 @@ Dans l'exemple suivant, on utilise un générateur simple et on génère une exc ```js function* gen() { - while(true) { + while (true) { try { - yield 42; - } catch(e) { + yield 42; + } catch (e) { console.log("Erreur interceptée !"); } } diff --git a/files/fr/web/javascript/reference/global_objects/generatorfunction/index.md b/files/fr/web/javascript/reference/global_objects/generatorfunction/index.md index 31f62324f3ccd9..09cfe7f6923073 100644 --- a/files/fr/web/javascript/reference/global_objects/generatorfunction/index.md +++ b/files/fr/web/javascript/reference/global_objects/generatorfunction/index.md @@ -9,7 +9,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/GeneratorFunction En JavaScript, chaque fonction génératrice est en réalité un objet `GeneratorFunction`. Il n'existe pas d'objet global avec le nom `GeneratorFunction`, mais il est possible de créer un constructeur `GeneratorFunction()` avec le code suivant : ```js -const GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor; +const GeneratorFunction = Object.getPrototypeOf(function* () {}).constructor; ``` ## Description @@ -31,8 +31,8 @@ Invoquer un constructeur de fonction génératrice comme une fonction (sans util ### Créer un générateur en utilisant le constructeur `GeneratorFunction()` ```js -const GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor; -const g = new GeneratorFunction('a', 'yield a * 2'); +const GeneratorFunction = Object.getPrototypeOf(function* () {}).constructor; +const g = new GeneratorFunction("a", "yield a * 2"); const iterator = g(10); console.log(iterator.next().value); // 20 ``` diff --git a/files/fr/web/javascript/reference/global_objects/globalthis/index.md b/files/fr/web/javascript/reference/global_objects/globalthis/index.md index bdeb09a1d9338a..3317d4d1b9a2d9 100644 --- a/files/fr/web/javascript/reference/global_objects/globalthis/index.md +++ b/files/fr/web/javascript/reference/global_objects/globalthis/index.md @@ -13,7 +13,7 @@ La propriété globale **`globalThis`** renvoie l'objet global de plus haut nive ## Syntaxe ```js -globalThis +globalThis; ``` ## Description @@ -39,15 +39,21 @@ Avant l'introduction de `globalThis`, la seule façon qui permettait d'obtenir l ```js var getGlobal = function () { - if (typeof self !== 'undefined') { return self; } - if (typeof window !== 'undefined') { return window; } - if (typeof global !== 'undefined') { return global; } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } throw new Error("impossible de trouver l'objet global"); }; var globals = getGlobal(); -if (typeof globals.setTimeout !== 'function') { +if (typeof globals.setTimeout !== "function") { // pas de setTimeout pour cet environnement } ``` @@ -55,7 +61,7 @@ if (typeof globals.setTimeout !== 'function') { Avec `globalThis`, il n'est plus nécessaire de parcourir les différents mots-clés des différents environnements : ```js -if (typeof globalThis.setTimeout !== 'function') { +if (typeof globalThis.setTimeout !== "function") { // pas de setTimeout pour cet environnement } ``` diff --git a/files/fr/web/javascript/reference/global_objects/infinity/index.md b/files/fr/web/javascript/reference/global_objects/infinity/index.md index 23d0b8d49cb2fa..d358e12a99206d 100644 --- a/files/fr/web/javascript/reference/global_objects/infinity/index.md +++ b/files/fr/web/javascript/reference/global_objects/infinity/index.md @@ -15,7 +15,7 @@ La propriété globale **`Infinity`** est une valeur numérique représentant l' ## Syntaxe ```js -Infinity +Infinity; ``` ## Description @@ -29,11 +29,11 @@ D'après la spécification ECMAScript 5, `Infinity` est en lecture seule. ## Exemples ```js -console.log(Infinity); // Infinity -console.log(Infinity + 1); // Infinity +console.log(Infinity); // Infinity +console.log(Infinity + 1); // Infinity console.log(Math.pow(10, 1000)); // Infinity -console.log(Math.log(0)); // -Infinity -console.log(1 / Infinity); // 0 +console.log(Math.log(0)); // -Infinity +console.log(1 / Infinity); // 0 ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/int16array/index.md b/files/fr/web/javascript/reference/global_objects/int16array/index.md index 1e6aa0467a457d..c8e13df479ebbe 100644 --- a/files/fr/web/javascript/reference/global_objects/int16array/index.md +++ b/files/fr/web/javascript/reference/global_objects/int16array/index.md @@ -125,7 +125,7 @@ console.log(int16.length); // 2 console.log(int16.BYTES_PER_ELEMENT); // 2 // Construction à partir d'un tableau -var arr = new Int16Array([21,31]); +var arr = new Int16Array([21, 31]); console.log(arr[1]); // 31 // Construction à partir d'un autre TypedArray @@ -138,7 +138,9 @@ var buffer = new ArrayBuffer(8); var z = new Int16Array(buffer, 0, 4); // Construction à partir d'un itérable -var iterable = function*(){ yield* [1,2,3]; }(); +var iterable = (function* () { + yield* [1, 2, 3]; +})(); var int16 = new Int16Array(iterable); // Int16Array[1, 2, 3] ``` diff --git a/files/fr/web/javascript/reference/global_objects/int16array/int16array/index.md b/files/fr/web/javascript/reference/global_objects/int16array/int16array/index.md index 8e9b30e4896cd7..74cf045b925fb9 100644 --- a/files/fr/web/javascript/reference/global_objects/int16array/int16array/index.md +++ b/files/fr/web/javascript/reference/global_objects/int16array/int16array/index.md @@ -45,7 +45,7 @@ console.log(int16.length); // 2 console.log(int16.BYTES_PER_ELEMENT); // 2 // À partir d'un tableau -const arr = new Int16Array([21,31]); +const arr = new Int16Array([21, 31]); console.log(arr[1]); // 31 // À partir d'un autre tableau typé @@ -58,7 +58,9 @@ const buffer = new ArrayBuffer(8); const z = new Int16Array(buffer, 0, 4); // À partir d'un itérable -const iterable = function*(){ yield* [1,2,3]; }(); +const iterable = (function* () { + yield* [1, 2, 3]; +})(); const int16 = new Int16Array(iterable); // Int16Array[1, 2, 3] ``` diff --git a/files/fr/web/javascript/reference/global_objects/int32array/index.md b/files/fr/web/javascript/reference/global_objects/int32array/index.md index 6c27c2077d314e..5c1b72807beac2 100644 --- a/files/fr/web/javascript/reference/global_objects/int32array/index.md +++ b/files/fr/web/javascript/reference/global_objects/int32array/index.md @@ -125,7 +125,7 @@ console.log(int32.length); // 2 console.log(int32.BYTES_PER_ELEMENT); // 4 // Construction à partir d'un tableau -var arr = new Int32Array([21,31]); +var arr = new Int32Array([21, 31]); console.log(arr[1]); // 31 // Construction à partir d'un autre TypedArray @@ -138,7 +138,9 @@ var buffer = new ArrayBuffer(16); var z = new Int32Array(buffer, 0, 4); // Construction à partir d'un itérable -var iterable = function*(){ yield* [1,2,3]; }(); +var iterable = (function* () { + yield* [1, 2, 3]; +})(); var int32 = new Int32Array(iterable); // Int32Array[1, 2, 3] ``` diff --git a/files/fr/web/javascript/reference/global_objects/int32array/int32array/index.md b/files/fr/web/javascript/reference/global_objects/int32array/int32array/index.md index d44851d174d905..b9e1c2983532b0 100644 --- a/files/fr/web/javascript/reference/global_objects/int32array/int32array/index.md +++ b/files/fr/web/javascript/reference/global_objects/int32array/int32array/index.md @@ -1,7 +1,7 @@ --- title: Constructeur Int32Array() slug: Web/JavaScript/Reference/Global_Objects/Int32Array/Int32Array -translation_of: Web/JavaScript/Reference/Global_Objects/Int32Array/Int32Array +translation_of: Web/JavaScript/Reference/Global_Objects/Int32Array/Int32Array --- {{JSRef}} @@ -44,7 +44,7 @@ console.log(int32.length); // 2 console.log(int32.BYTES_PER_ELEMENT); // 4 // À partir d'un tableau -const arr = new Int32Array([21,31]); +const arr = new Int32Array([21, 31]); console.log(arr[1]); // 31 // À partir d'un autre tableau typé @@ -57,7 +57,9 @@ const buffer = new ArrayBuffer(16); const z = new Int32Array(buffer, 0, 4); // À partir d'un itérable -const iterable = function*(){ yield* [1,2,3]; }(); +const iterable = (function* () { + yield* [1, 2, 3]; +})(); const int32_from_iterable = new Int32Array(iterable); // Int32Array[1, 2, 3] ``` diff --git a/files/fr/web/javascript/reference/global_objects/int8array/index.md b/files/fr/web/javascript/reference/global_objects/int8array/index.md index d2cc44dffa6afe..11b1b30b9d2481 100644 --- a/files/fr/web/javascript/reference/global_objects/int8array/index.md +++ b/files/fr/web/javascript/reference/global_objects/int8array/index.md @@ -125,7 +125,7 @@ console.log(int8.length); // 2 console.log(int8.BYTES_PER_ELEMENT); // 1 // Construction à partir d'un tableau -var arr = new Int8Array([21,31]); +var arr = new Int8Array([21, 31]); console.log(arr[1]); // 31 // Construction à partir d'un autre TypedArray @@ -138,7 +138,9 @@ var buffer = new ArrayBuffer(8); var z = new Int8Array(buffer, 1, 4); // Construction à partir d'un itérable -var iterable = function*(){ yield* [1,2,3]; }(); +var iterable = (function* () { + yield* [1, 2, 3]; +})(); var int8 = new Int8Array(iterable); // Int8Array[1, 2, 3] ``` diff --git a/files/fr/web/javascript/reference/global_objects/int8array/int8array/index.md b/files/fr/web/javascript/reference/global_objects/int8array/int8array/index.md index 0107330f1e502a..2080576e2b39fb 100644 --- a/files/fr/web/javascript/reference/global_objects/int8array/int8array/index.md +++ b/files/fr/web/javascript/reference/global_objects/int8array/int8array/index.md @@ -45,7 +45,7 @@ console.log(int8.length); // 2 console.log(int8.BYTES_PER_ELEMENT); // 1 // À partir d'un tableau -const arr = new Int8Array([21,31]); +const arr = new Int8Array([21, 31]); console.log(arr[1]); // 31 // À partir d'un autre tableau typé @@ -58,7 +58,9 @@ const buffer = new ArrayBuffer(8); const z = new Int8Array(buffer, 1, 4); // À partir d'un itérable -const iterable = function*(){ yield* [1,2,3]; }(); +const iterable = (function* () { + yield* [1, 2, 3]; +})(); const int8 = new Int8Array(iterable); // Int8Array[1, 2, 3] ``` diff --git a/files/fr/web/javascript/reference/global_objects/internalerror/index.md b/files/fr/web/javascript/reference/global_objects/internalerror/index.md index f58f5387fd8013..e188f3e0dcaebb 100644 --- a/files/fr/web/javascript/reference/global_objects/internalerror/index.md +++ b/files/fr/web/javascript/reference/global_objects/internalerror/index.md @@ -45,7 +45,7 @@ function boucle(x) { if (x >= 10) { // "x >= 10" représente la condition d'arrêt return; - } + } // faire des trucs boucle(x + 1); // l'appel récursif } diff --git a/files/fr/web/javascript/reference/global_objects/internalerror/internalerror/index.md b/files/fr/web/javascript/reference/global_objects/internalerror/internalerror/index.md index 72bd555f9d9e87..40b67e3ee630ec 100644 --- a/files/fr/web/javascript/reference/global_objects/internalerror/internalerror/index.md +++ b/files/fr/web/javascript/reference/global_objects/internalerror/internalerror/index.md @@ -11,10 +11,10 @@ Le constructeur **`InternalError()`** permet de créer une erreur qui s'est prod ## Syntaxe ```js -new InternalError() -new InternalError(message) -new InternalError(message, nomFichier) -new InternalError(message, nomFichier, numeroLigne) +new InternalError(); +new InternalError(message); +new InternalError(message, nomFichier); +new InternalError(message, nomFichier, numeroLigne); ``` ### Paramètres @@ -31,7 +31,7 @@ new InternalError(message, nomFichier, numeroLigne) ### Créer une nouvelle exception `InternalError` ```js -new InternalError('Échec du moteur'); +new InternalError("Échec du moteur"); ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/intl/collator/collator/index.md b/files/fr/web/javascript/reference/global_objects/intl/collator/collator/index.md index f80919ecb3fef2..c52692d8f53d30 100644 --- a/files/fr/web/javascript/reference/global_objects/intl/collator/collator/index.md +++ b/files/fr/web/javascript/reference/global_objects/intl/collator/collator/index.md @@ -12,9 +12,9 @@ Le constructeur **`Intl.Collator()`** crée un objet [`Intl.Collator`](/fr/docs/ ## Syntaxe ```js -new Intl.Collator() -new Intl.Collator(locales) -new Intl.Collator(locales, options) +new Intl.Collator(); +new Intl.Collator(locales); +new Intl.Collator(locales, options); ``` ### Paramètres @@ -45,7 +45,7 @@ new Intl.Collator(locales, options) - `trad` - `unihan` - `zhuyin` - > **Note :** Cette option peut également être définie via la propriété "`collation`" du paramètre `options`. + > **Note :** Cette option peut également être définie via la propriété "`collation`" du paramètre `options`. - `kn` - : Indique si une collation numérique devrait être utilisée (par exemple pour avoir "1" < "2" < "10"). Les valeurs possibles sont "`true`" et "`false`". Cette option peut également être indiquée via la propriété "`numeric`" du paramètre `options`. - `kf` @@ -61,6 +61,7 @@ new Intl.Collator(locales, options) - : Indique si la comparaison est utilisée pour trier ou pour rechercher des correspondances. Les valeurs possibles sont "`sort`" et "`search`", la valeur par défaut est "`sort`". - `sensitivity` + - : Indique les différences dans les chaînes de caractères qui entraînent un résultat non nul. Les valeurs possibles sont : - "`base`" : Seules les chaînes de caractères pour lesquelles les lettres de base sont différentes sont considérées comme différentes. Avec cette option, on a : a ≠ b, a = á, a = A. @@ -102,7 +103,7 @@ new Intl.Collator(locales, options) - `trad` - `unihan` - `zhuyin` - > **Note :** Cette option peut également être définie via la clé d'extension Unicode `co` ; si des valeurs sont fournies aux deux endroits, c'est la propriété d'`options` qui a la priorité. + > **Note :** Cette option peut également être définie via la clé d'extension Unicode `co` ; si des valeurs sont fournies aux deux endroits, c'est la propriété d'`options` qui a la priorité. ## Exemples @@ -111,9 +112,9 @@ new Intl.Collator(locales, options) Dans l'exemple suivant, on illustre la comparaison de deux chaînes de caractères et le résultat obtenu selon que l'une est située avant ou après, ou de façon équivalente selon l'ordre lexicographique de la langue : ```js -console.log(new Intl.Collator().compare('a', 'c')); // → une valeur négative -console.log(new Intl.Collator().compare('c', 'a')); // → une valeur positive -console.log(new Intl.Collator().compare('a', 'a')); // → 0 +console.log(new Intl.Collator().compare("a", "c")); // → une valeur négative +console.log(new Intl.Collator().compare("c", "a")); // → une valeur positive +console.log(new Intl.Collator().compare("a", "a")); // → 0 ``` On notera que les résultats obtenus avec les lignes précédentes peuvent varier d'un navigateur à l'autre et entre les différentes versions. En effet, les valeurs numériques obtenues sont spécifiques aux implémentations et la spécification n'impose que le signe de la valeur obtenue. diff --git a/files/fr/web/javascript/reference/global_objects/intl/collator/compare/index.md b/files/fr/web/javascript/reference/global_objects/intl/collator/compare/index.md index 860adb1fa42f4f..def8b3fb53bd93 100644 --- a/files/fr/web/javascript/reference/global_objects/intl/collator/compare/index.md +++ b/files/fr/web/javascript/reference/global_objects/intl/collator/compare/index.md @@ -13,7 +13,7 @@ La méthode **`Intl.Collator.prototype.compare()`** compare deux chaînes de car ## Syntaxe ```js -collator.compare(chaine1, chaine2) +collator.compare(chaine1, chaine2); ``` ### Paramètres @@ -45,10 +45,13 @@ Ici, on utilise la fonction de l'accesseur `compare` pour trouver les chaînes ```js var a = ["Congrès", "congres", "Assemblée", "poisson"]; -var collator = new Intl.Collator("fr", {usage: "search", sensitivity: "base"}); +var collator = new Intl.Collator("fr", { + usage: "search", + sensitivity: "base", +}); var s = "congres"; var matches = a.filter(function (v) { - return collator.compare(v, s) === 0; + return collator.compare(v, s) === 0; }); console.log(matches.join(", ")); // → "Congrès, congres" diff --git a/files/fr/web/javascript/reference/global_objects/intl/collator/index.md b/files/fr/web/javascript/reference/global_objects/intl/collator/index.md index 5a3cd1e8513f87..070cbe8cb498fb 100644 --- a/files/fr/web/javascript/reference/global_objects/intl/collator/index.md +++ b/files/fr/web/javascript/reference/global_objects/intl/collator/index.md @@ -34,9 +34,9 @@ L'objet **`Intl.Collator`** permet de comparer des chaînes de caractères en te L'exemple qui suit illustre les différents résultats qu'on peut obtenir en comparant deux chaînes de caractères : ```js -console.log(new Intl.Collator().compare('a', 'c')); // → une valeur négative -console.log(new Intl.Collator().compare('c', 'a')); // → une valeur positive -console.log(new Intl.Collator().compare('a', 'a')); // → 0 +console.log(new Intl.Collator().compare("a", "c")); // → une valeur négative +console.log(new Intl.Collator().compare("c", "a")); // → une valeur positive +console.log(new Intl.Collator().compare("a", "a")); // → 0 ``` Les résultats indiqués ici sont génériques et, en pratique, peuvent varier entre les navigateurs et les versions des navigateurs. En effet les valeurs obtenues dépendent de l'implémentation. Les spécifications indiquent uniquement le signe (positif ou négatif) du résultat. @@ -47,11 +47,11 @@ Les résultats fournis par [`Collator.prototype.compare()`](/fr/docs/Web/JavaScr ```js // en allemand, 'ä' est équivalent à 'a' pour le tri -console.log(new Intl.Collator('de').compare('ä', 'z')); +console.log(new Intl.Collator("de").compare("ä", "z")); // → une valeur négative // en suédois, 'ä' arrive après 'z' -console.log(new Intl.Collator('sv').compare('ä', 'z')); +console.log(new Intl.Collator("sv").compare("ä", "z")); // → une valeur positive ``` @@ -61,11 +61,11 @@ Les résultats fournis par [`Collator.prototype.compare()`](/fr/docs/Web/JavaScr ```js // en allemand, 'ä' est composé de la lettre de base 'a' -console.log(new Intl.Collator('de', {sensitivity: 'base'}).compare('ä', 'a')); +console.log(new Intl.Collator("de", { sensitivity: "base" }).compare("ä", "a")); // → 0 // en suédois, 'ä' et 'a' sont distincts en termes de base -console.log(new Intl.Collator('sv', {sensitivity: 'base'}).compare('ä', 'a')); +console.log(new Intl.Collator("sv", { sensitivity: "base" }).compare("ä", "a")); // → une valeur positive ``` diff --git a/files/fr/web/javascript/reference/global_objects/intl/collator/resolvedoptions/index.md b/files/fr/web/javascript/reference/global_objects/intl/collator/resolvedoptions/index.md index 087a437f115a94..0df870c70c55b8 100644 --- a/files/fr/web/javascript/reference/global_objects/intl/collator/resolvedoptions/index.md +++ b/files/fr/web/javascript/reference/global_objects/intl/collator/resolvedoptions/index.md @@ -13,7 +13,7 @@ La méthode **`Intl.Collator.prototype.resolvedOptions()`** renvoie un nouvel ob ## Syntaxe ```js -collator.resolvedOptions() +collator.resolvedOptions(); ``` ### Valeur de retour @@ -36,15 +36,15 @@ L'objet renvoyé par cette méthode contient les propriétés suivantes : ## Exemples ```js -var de = new Intl.Collator('de', { sensitivity: 'base' }) +var de = new Intl.Collator("de", { sensitivity: "base" }); var usedOptions = de.resolvedOptions(); -usedOptions.locale; // "de" -usedOptions.usage; // "sort" -usedOptions.sensitivity; // "base" +usedOptions.locale; // "de" +usedOptions.usage; // "sort" +usedOptions.sensitivity; // "base" usedOptions.ignorePunctuation; // false -usedOptions.collation; // "default" -usedOptions.numeric; // false +usedOptions.collation; // "default" +usedOptions.numeric; // false ``` ## Spécifications diff --git a/files/fr/web/javascript/reference/global_objects/intl/collator/supportedlocalesof/index.md b/files/fr/web/javascript/reference/global_objects/intl/collator/supportedlocalesof/index.md index 968c5d2f500ce9..630e7d55e457f9 100644 --- a/files/fr/web/javascript/reference/global_objects/intl/collator/supportedlocalesof/index.md +++ b/files/fr/web/javascript/reference/global_objects/intl/collator/supportedlocalesof/index.md @@ -41,7 +41,7 @@ Si on dispose d'un environnement (un navigateur par exemple) qui supporte la com ```js var locales = ["ban", "id-u-co-pinyin", "de-ID"]; -var options = {localeMatcher: "lookup"}; +var options = { localeMatcher: "lookup" }; console.log(Intl.Collator.supportedLocalesOf(locales, options).join(", ")); // → "id-u-co-pinyin, de-ID" ``` diff --git a/files/fr/web/javascript/reference/global_objects/intl/datetimeformat/datetimeformat/index.md b/files/fr/web/javascript/reference/global_objects/intl/datetimeformat/datetimeformat/index.md index 0d4fff6d6aa327..1b347c71a82fd6 100644 --- a/files/fr/web/javascript/reference/global_objects/intl/datetimeformat/datetimeformat/index.md +++ b/files/fr/web/javascript/reference/global_objects/intl/datetimeformat/datetimeformat/index.md @@ -12,9 +12,9 @@ Le constructeur **`Intl.DateTimeFormat()`** permet de créer des objets [`Intl.D ## Syntaxe ```js -new Intl.DateTimeFormat() -new Intl.DateTimeFormat(locales) -new Intl.DateTimeFormat(locales, options) +new Intl.DateTimeFormat(); +new Intl.DateTimeFormat(locales); +new Intl.DateTimeFormat(locales, options); ``` ### Paramètres @@ -179,19 +179,19 @@ console.log(new Intl.DateTimeFormat().format(date)); ### Utiliser timeStyle et dateStyle ```js -let o = new Intl.DateTimeFormat("fr" , { - timeStyle: "short" +let o = new Intl.DateTimeFormat("fr", { + timeStyle: "short", }); console.log(o.format(Date.now())); // "09:45" -let o2 = new Intl.DateTimeFormat("fr" , { - dateStyle: "short" +let o2 = new Intl.DateTimeFormat("fr", { + dateStyle: "short", }); console.log(o2.format(Date.now())); // "29/12/2021" -let o3 = new Intl.DateTimeFormat("fr" , { +let o3 = new Intl.DateTimeFormat("fr", { timeStyle: "medium", - dateStyle: "short" + dateStyle: "short", }); console.log(o3.format(Date.now())); // "29/12/2021 09:46:55" ``` @@ -203,16 +203,34 @@ On utilise l'option `dayPeriod` pour produire une chaîne de caractères qui ind ```js let date = Date.UTC(2012, 11, 17, 4, 0, 42); -console.log(new Intl.DateTimeFormat('en-GB', { hour: 'numeric', hourCycle: 'h12', -dayPeriod: 'short', timeZone: 'UTC' }).format(date)); +console.log( + new Intl.DateTimeFormat("en-GB", { + hour: "numeric", + hourCycle: "h12", + dayPeriod: "short", + timeZone: "UTC", + }).format(date), +); // > 4 at night" (même formatage pour en-GB quelle que soit la valeur de dayPeriod) -console.log(new Intl.DateTimeFormat('fr', { hour: 'numeric', hourCycle: 'h12', - dayPeriod: 'narrow', timeZone: 'UTC' }).format(date)); +console.log( + new Intl.DateTimeFormat("fr", { + hour: "numeric", + hourCycle: "h12", + dayPeriod: "narrow", + timeZone: "UTC", + }).format(date), +); // > "4 mat." (même formatage pour fr avec narrow ou short) -console.log(new Intl.DateTimeFormat('fr', { hour: 'numeric', hourCycle: 'h12', - dayPeriod: 'long', timeZone: 'UTC' }).format(date)); +console.log( + new Intl.DateTimeFormat("fr", { + hour: "numeric", + hourCycle: "h12", + dayPeriod: "long", + timeZone: "UTC", + }).format(date), +); // > "4 du matin" ``` @@ -222,17 +240,24 @@ On utilise l'option `timeZoneName` pour produire une chaîne de caractères repr ```js var date = Date.UTC(2021, 11, 17, 3, 0, 42); -const timezoneNames = ['short', 'long', 'shortOffset', 'longOffset', 'shortGeneric', 'longGeneric'] +const timezoneNames = [ + "short", + "long", + "shortOffset", + "longOffset", + "shortGeneric", + "longGeneric", +]; for (const zoneName of timezoneNames) { - var formatter = new Intl.DateTimeFormat('fr', { - timeZone: 'Europe/Paris', + var formatter = new Intl.DateTimeFormat("fr", { + timeZone: "Europe/Paris", timeZoneName: zoneName, }); - console.log(zoneName + " : " + formatter.format(date) ); + console.log(zoneName + " : " + formatter.format(date)); } -// Résultat attendu : +// Résultat attendu : // short : 17/12/2021, UTC+1 // long : 17/12/2021, heure normale d'Europe centrale // shortOffset : 17/12/2021, UTC+1 diff --git a/files/fr/web/javascript/reference/global_objects/intl/datetimeformat/format/index.md b/files/fr/web/javascript/reference/global_objects/intl/datetimeformat/format/index.md index de8d78e3887d3a..98eb8bd7ca17cd 100644 --- a/files/fr/web/javascript/reference/global_objects/intl/datetimeformat/format/index.md +++ b/files/fr/web/javascript/reference/global_objects/intl/datetimeformat/format/index.md @@ -13,7 +13,7 @@ La méthode **`Intl.DateTimeFormat.prototype.format()`** est un accesseur format ## Syntaxe ```js -dateTimeFormat.format(date) +dateTimeFormat.format(date); ``` ### Paramètres @@ -32,7 +32,12 @@ L'accesseur `format` permet de formater une date en une chaîne de caractères e On peut utiliser la fonction renvoyée par l'accesseur `format` pour formater une date. Par exemple selon la locale serbe : ```js -var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"}; +var options = { + weekday: "long", + year: "numeric", + month: "long", + day: "numeric", +}; var dateTimeFormat = new Intl.DateTimeFormat("sr-RS", options); console.log(dateTimeFormat.format(new Date())); // → "недеља, 7. април 2013." @@ -44,7 +49,7 @@ On peut également utiliser la fonction renvoyée par l'accesseur `format` pour ```js var a = [new Date(2012, 08), new Date(2012, 11), new Date(2012, 03)]; -var options = {year: "numeric", month: "long"}; +var options = { year: "numeric", month: "long" }; var dateTimeFormat = new Intl.DateTimeFormat("pt-BR", options); var formatted = a.map(dateTimeFormat.format); console.log(formatted.join("; ")); @@ -60,12 +65,12 @@ Aussi, mieux vaut ne pas comparer un résultat fourni par `format()` avec une va ```js example-bad let d = new Date("2019-01-01T00:00:00.000000Z"); let formattedDate = Intl.DateTimeFormat(undefined, { - year: 'numeric', - month: 'numeric', - day: 'numeric', - hour: 'numeric', - minute: 'numeric', - second: 'numeric' + year: "numeric", + month: "numeric", + day: "numeric", + hour: "numeric", + minute: "numeric", + second: "numeric", }).format(d); "1.1.2019, 01:00:00" === formattedDate;