jeudi 4 août 2022
Des bouts de code de javascript qui m'ont été parfois utiles
Table générale
Table
<script type="text/javascript"> ... </script>
<script src="filename.js"></script>
setTimeout(function () { }, 1000);
function addNumbers(a, b) {return a + b;}x = addNumbers(1, 2);
document.getElementById("elementID").innerHTML = "Hello World!";
console.log(a); // write to the browser consoledocument.write(a); // write to the HTMLalert(a); // an alert boxconfirm("Really?"); // yes/no dialog, returns true/false depending on user clickprompt("Your age?","0"); // input dialog. Second argument is the initial value
/* Multi linecomment */// One line comment
for (var i = 0; i < 10; i++) {document.write(i + ": " + i*3 + "\<br /\>");}
var sum = 0;for (var i = 0; i < a.length; i++) {sum + = a[i];} // parsing an array
html = "";for (var i of custOrder) {html += "\<li\>" + i + "\</li\>";}
var i = 1; // initializewhile (i < 100) { // enters the cycle if statement is truei *= 2; // increment to avoid infinite loopdocument.write(i + ", "); // output}
var i = 1; // initializedo { // enters cycle at least oncei *= 2; // increment to avoid infinite loopdocument.write(i + ", "); // output} while (i < 100) // repeats cycle if statement is true at the end
for (var i = 0; i < 10; i++) {if (i == 5) { break; } // stops and exits the cycledocument.write(i + ", "); // last output number is 4}
for (var i = 0; i < 10; i++) {if (i == 5) { continue; } // skips the rest of the cycledocument.write(i + ", "); // skips 5}
if ((age >= 14) && (age < 19)) { // logical conditionstatus = "Eligible."; // executed if condition is true} else { // else block is optionalstatus = "Not eligible."; // executed if condition is false}
switch (new Date().getDay()) { // input is current daycase 6: // if (day == 6)text = "Saturday";break;case 0: // if (day == 0)text = "Sunday";break;default: // else...text = "Whatever";}
var a; // variablevar b = "init"; // stringvar c = "Hi" + " " + "Joe"; // = "Hi Joe"var d = 1 + 2 + "3"; // = "33"var e = [2,3,5,8]; // arrayvar f = false; // booleanvar g = /()/; // RegExvar h = function(){}; // function objectconst PI = 3.14; // constantvar a = 1, b = 2, c = a + b; // one linelet z = 'zzz'; // block scope local variable
"use strict"; // Use strict mode to write secure codex = 1; // Throws an error because variable is not declared
false, true // boolean18, 3.14, 0b10011, 0xF6, NaN // number"flower", 'John' // stringundefined, null , Infinity // special
a = b + c - d; // addition, substractiona = b * (c / d); // multiplication, divisionx = 100 % 48; // modulo. 100 / 48 remainder = 4a++; b--; // postfix increment and decrement
| symb | operator | example | result |
|---|---|---|---|
| & | AND | 5 & 1 (0101 & 0001) | 1 (1) |
| | | OR | 5 | 1 (0101 | 0001) | 5 (101) |
| ~ | NOT | ~ 5 (~0101) | 10 (1010) |
| ^ | XOR | 5 ^ 1 (0101 ^ 0001) | 4 (100) |
| << | left shift | 5 << 1 (0101 << 1) | 10 (1010) |
| >> | right shift | 5 >> 1 (0101 >> 1) | 2 (10) |
| >>> | zero fill right shift | 5 >>> 1 (0101 >>> 1) | 2 (10) |
a * (b + c) // groupingperson.age // memberperson[age] // member!(a == b) // logical nota != b // not equaltypeof a // type (number, object, function...)x << 2 x >> 3 // minary shiftinga = b // assignmenta == b // equalsa != b // unequala === b // strict equala !== b // strict unequala < b a > b // less and greater thana <= b a >= b // less or equal, greater or eqa += b // a = a + b (works with - * %...)a && b // logical anda || b // logical or
var age = 18; // numbervar name = "Jane"; // stringvar name = {first:"Jane", last:"Doe"}; // objectvar truth = false; // booleanvar sheets = ["HTML","CSS","JS"]; // arrayvar a; typeof a; // undefinedvar a = null; // value null
var student = { // object namefirstName:"Jane", // list of properties and valueslastName:"Doe",age:18,height:170,fullName : function() { // object functionreturn this.firstName + " " + this.lastName;}};student.age = 19; // setting valuestudent[age]++; // incrementingname = student.fullName(); // call object function
var abc = "abcdefghijklmnopqrstuvwxyz";var esc = 'I don\'t \n know'; // \n new linevar len = abc.length; // string lengthabc.indexOf("lmno"); // find substring, -1 if doesn't containabc.lastIndexOf("lmno"); // last occuranceabc.slice(3, 6); // cuts out "def", negative values count from behindabc.replace("abc","123"); // find and replace, takes regular expressionsabc.toUpperCase(); // convert to upper caseabc.toLowerCase(); // convert to lower caseabc.concat(" ", str2); // abc + " " + str2abc.charAt(2); // character at index: "c"abc[2]; // unsafe, abc[2] = "C" doesn't workabc.charCodeAt(2); // character code at index: "c" -> 99abc.split(","); // splitting a string on commas gives an arrayabc.split(""); // splitting on characters128.toString(16); // number to hex(16), octal (8) or binary (2)
<button onclick="myFunction();">Click here</button>
onclick, oncontextmenu, ondblclick, onmousedown, onmouseenter, onmouseleave, onmousemove, onmouseover, onmouseout, onmouseup
onkeydown, onkeypress, onkeyup
onabort, onbeforeunload, onerror, onhashchange, onload, onpageshow, onpagehide, onresize, onscroll, onunload
onblur, onchange, onfocus, onfocusin, onfocusout, oninput, oninvalid, onreset, onsearch, onselect, onsubmit
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop
oncopy, oncut, onpaste
onabort, oncanplay, oncanplaythrough, ondurationchange, onended, onerror, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, onsuspend, ontimeupdate, onvolumechange, onwaiting
animationend, animationiteration, animationstart
transitionend, onmessage, onmousewheel, ononline, onoffline, onpopstate, onshow, onstorage, ontoggle, onwheel, ontouchcancel, ontouchend, ontouchmove, ontouchstart
var pi = 3.141;pi.toFixed(0); // returns 3pi.toFixed(2); // returns 3.14 - for working with moneypi.toPrecision(2) // returns 3.1pi.valueOf(); // returns numberNumber(true); // converts to numberNumber(new Date()) // number of milliseconds since 1970parseInt("3 months"); // returns the first number: 3parseFloat("3.5 days"); // returns 3.5Number.MAX_VALUE // largest possible JS numberNumber.MIN_VALUE // smallest possible JS numberNumber.NEGATIVE_INFINITY// -InfinityNumber.POSITIVE_INFINITY// Infinity
var pi = Math.PI; // 3.141592653589793Math.round(4.4); // = 4 - roundedMath.round(4.5); // = 5Math.pow(2,8); // = 256 - 2 to the power of 8Math.sqrt(49); // = 7 - square rootMath.abs(-3.14); // = 3.14 - absolute, positive valueMath.ceil(3.14); // = 4 - rounded upMath.floor(3.99); // = 3 - rounded downMath.sin(0); // = 0 - sineMath.cos(Math.PI); // OTHERS: tan,atan,asin,acos,Math.min(0, 3, -2, 2); // = -2 - the lowest valueMath.max(0, 3, -2, 2); // = 3 - the highest valueMath.log(1); // = 0 natural logarithmMath.exp(1); // = 2.7182pow(E,x)Math.random(); // random number between 0 and 1Math.floor(Math.random() * 5) + 1; // random integer, from 1 to 5
E, PI, SQRT2, SQRT1_2, LN2, LN10, LOG2E, Log10E
Sun Aug 07 2022 05:37:43 GMT+0200 (heure d’été d’Europe centrale)
var d = new Date();
1659843463170 miliseconds passed since 1970
Date("2017-06-23"); // date declarationDate("2017"); // is set to Jan 01Date("2017-06-23T12:00:00-09:45"); // date - time YYYY-MM-DDTHH:MM:SSZDate("June 23 2017"); // long date formatDate("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)"); // time zone
var d = new Date();a = d.getDay(); // getting the weekdaygetDate(); // day as a number (1-31)getDay(); // weekday as a number (0-6)getFullYear(); // four digit year (yyyy)getHours(); // hour (0-23)getMilliseconds(); // milliseconds (0-999)getMinutes(); // minutes (0-59)getMonth(); // month (0-11)getSeconds(); // seconds (0-59)getTime(); // milliseconds since 1970
var d = new Date();d.setDate(d.getDate() + 7); // adds a week to a datesetDate(); // day as a number (1-31)setFullYear(); // year (optionally month and day)setHours(); // hour (0-23)setMilliseconds(); // milliseconds (0-999)setMinutes(); // minutes (0-59)setMonth(); // month (0-11)setSeconds(); // seconds (0-59)setTime(); // milliseconds since 1970)
var dogs = ["Bulldog", "Beagle", "Labrador"];var dogs = new Array("Bulldog", "Beagle", "Labrador"); // declarationalert(dogs[1]); // access value at index, first item being [0]dogs[0] = "Bull Terier"; // change the first itemfor (var i = 0; i < dogs.length; i++) { // parsing with array.lengthconsole.log(dogs[i]);}
dogs.toString(); // convert to string: results "Bulldog,Beagle,Labrador"dogs.join(" * "); // join: "Bulldog * Beagle * Labrador"dogs.pop(); // remove last elementdogs.push("Chihuahua"); // add new element to the enddogs[dogs.length] = "Chihuahua"; // the same as pushdogs.shift(); // remove first elementdogs.unshift("Chihuahua"); // add new element to the beginningdelete dogs[0]; // change element to undefined (not recommended)dogs.splice(2, 0, "Pug", "Boxer"); // add elements (where, how many to remove, element list)var animals = dogs.concat(cats,birds); // join two arrays (dogs followed by cats and birds)dogs.slice(1,4); // elements from [1] to [4-1]dogs.sort(); // sort string alphabeticallydogs.reverse(); // sort string in descending orderx.sort(function(a, b){return a - b}); // numeric sortx.sort(function(a, b){return b - a}); // numeric descending sorthighest = x[0]; // first item in sorted array is the lowest (or highest) valuex.sort(function(a, b){return 0.5 - Math.random()}); // random order sort
concat, copyWithin, every, fill, filter, find, findIndex, forEach, indexOf, isArray, join, lastIndexOf, map, pop, push, reduce, reduceRight, reverse, shift, slice, some, sort, splice, toString, unshift, valueOf
eval(); // executes a string as if it was script codeString(23); // return string from number(23).toString(); // return string from numberNumber("23"); // return number from stringdecodeURI(enc); // decode URI. Result: "my page.asp"encodeURI(uri); // encode URI. Result: "my%page.asp"decodeURIComponent(enc); // decode a URI componentencodeURIComponent(uri); // encode a URI componentisFinite(); // is variable a finite, legal numberisNaN(); // is variable an illegal numberparseFloat(); // returns floating point number of stringparseInt(); // parses a string and returns an integer
var a = str.search(/CheatSheet/i);
| modifier | comment |
|---|---|
| i | perform case-insensitive matching |
| g | perform a global match |
| m | perform multiline matching |
| pattern | comment |
|---|---|
| \ | Escape character |
| \d | find a digit |
| \s | find a whitespace character |
| \b | find match at beginning or end of a word |
| n+ | contains at least one n |
| n* | contains zero or more occurrences of n |
| n? | contains zero or one occurrences of n |
| ^ | Start of string |
| $ | End of string |
| \uxxxx | find the Unicode character |
| . | Any single character |
| (a|b) | a or b |
| (...) | Group section |
| [abc] | In range (a, b or c) |
| [0-9] | any of the digits between the brackets |
| [^abc] | Not in range |
| \s | White space |
| a? | Zero or one of a |
| a* | Zero or more of a |
| a*? | Zero or more, ungreedy |
| a+ | One or more of a |
| a+? | One or more, ungreedy |
| a{2} | Exactly 2 of a |
| a{2,} | 2 or more of a |
| a{,5} | Up to 5 of a |
| a{2,5} | 2 to 5 of a |
| a{2,5}? | 2 to 5 of a, ungreedy |
| [:punct:] | Any punctuation symbol |
| [:space:] | Any space character |
| [:blank:] | Space or tab |
try { // block of code to tryundefinedFunction();}catch(err) { // block to handle errorsconsole.log(err.message);}
throw "My error message"; // throw a text
var x = document.getElementById("mynum").value; // get input valuetry {if(x == "") throw "empty"; // error casesif(isNaN(x)) throw "not a number";x = Number(x);if(x > 10) throw "too high";}catch(err) { // if there's an errordocument.write("Input is " + err); // output errorconsole.error(err); // write the error in console}finally {document.write("</br />Done"); // executed regardless of the try / catch result}
| name | value |
|---|---|
| RangeError | A number is "out of range" |
| ReferenceError | An illegal reference has occurred |
| SyntaxError | A syntax error has occurred |
| TypeError | A type error has occurred |
| URIError | An encodeURI() error has occurred |
var str = '{"names":[' + // crate JSON object'{"first":"Hakuna","lastN":"Matata" },' +'{"first":"Jane","lastN":"Doe" },' +'{"first":"Air","last":"Jordan" }]}';obj = JSON.parse(str); // parsedocument.write(obj.names[1].first); // access
var myObj = { "name":"Jane", "age":18, "city":"Chicago" }; // create objectvar myJSON = JSON.stringify(myObj); // stringifywindow.location = "demo.php?x=" + myJSON; // send to php
myObj = { "name":"Jane", "age":18, "city":"Chicago" };myJSON = JSON.stringify(myObj); // storing datalocalStorage.setItem("testJSON", myJSON);text = localStorage.getItem("testJSON"); // retrieving dataobj = JSON.parse(text);document.write(obj.name);
function sum (a, b) {return Promise(function (resolve, reject) {setTimeout(function () { // send the response after 1 secondif (typeof a !== "number" || typeof b !== "number") { // testing input typesreturn reject(new TypeError("Inputs must be numbers"));}resolve(a + b);}, 1000);});}var myPromise = sum(10, 5);myPromsise.then(function (result) {document.write(" 10 + 5: ", result);return sum(null, "foo"); // Invalid data and return another promise}).then(function () { // Won't be called because of the error// The catch handler is called instead, after another second}).catch(function (err) {console.error(err); // => Please provide two numbers to sum.});
pending, fulfilled, rejected
Promise.length, Promise.prototype
Promise.all(iterable), Promise.race(iterable), Promise.reject(reason), Promise.resolve(value)
console.log([1, 2, 3, 4].reduce((sum, e) => sum + e));
Cf. Array.prototype.reduce() que j'ai encore «réduite» en n'utilisant pas de valeur initiale.
let a = [1, 2, 3, 4];let b = [a[0]];for(let i=1; i<a.length; i++) b.push(b[i - 1] + a[i]);console.log(b); // Array(4) [ 1, 3, 6, 10 ]
En C on peut dédier une structure à une suite de champs de bits qui permet soit de compacter l'information soit pour qu'elle corresponde à une représentation fixe (mot d'état de communication). Il m'a semblé qu'aucun objet de js ne correspond à cette situation et j'ai voulu en implémenter un.
function BitsFields(){this.format = undefined;this.stuff = function(data) // data is an array of short numbers{let stuffed = BigInt(data[0]);for(let n=1; n<this.format.length; n++){stuffed <<= BigInt(this.format[n]);stuffed |= BigInt(data[n]);}return stuffed;}this.unstuff = function(v){let data = [];for(let n=this.format.length-1; n>=0; n--){data.unshift(v & ((1n << BigInt(this.format[n])) -1n));v >>= BigInt(this.format[n]);}return data;}}
La fonction BitsFields() est un constructeur d'objet de type champ de bits. On crée une instance avec :
let bf = new BitsFields();
Pour que cette instance devienne opérationnelle il faut définir le champ format qui donne les longueurs en bits des différents nombres (ou mots) qui composent l'objet. On fera par exemple :
bf.format = [8, 1, 8, 1, 16];
On a dans cet exemple deux données qui tiennent sur un octet (8 bits) suivies chacune d'un bit (par exemple true, false) et pour finir un champ sur deux octets (16 bits).
On peut alors produire un nombre (en js ils sont tous de 64 bits, dont 51 forment la mantisse), par exemple :
let v = bf.stuff([45, 1, 100, 0, 2358]);
Dans ce nombre v sont fourrés les cinq nombres 45, 1, 100, 0, 2358. La représentation en binaire de v est :
0010110110110010000000100100110110└─ 45 ─┘↑└─ 100 ┘↑└──── 2358 ────┘1 0
On y voit que v est composé de cinq champs binaires de longueurs respectives 8, 1, 8, 1, 16 bits.
Admettons qu'on l'empile dans une pile. Lorsqu'on va le dépiler on voudrait récupérer nos cinq nombres. On fera :
let a = bf.unstuff(v);
On aura alors a == [45, 1, 100, 0, 2358].
Remarques importantes
BigInt et à la fin de unstuff je suis revenu à Number. Je ne suis pas sûr qu'il ne peut pas y avoir de mauvaises surprises. data et format ont la même longueur. Je suppose que l'utilisateur sait ce qu'il fait. Sinon je ne sais pas ce qui se passe. Fichiers joints bitsf.js et test_bitsf.html, ce dernier donne un exemple d'utilisation du constructeur BitsFields.