JavaScript/CheatSheet: Difference between revisions
mNo edit summary |
mNo edit summary |
||
(22 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
== Data | == Style guides == | ||
* [https://github.com/airbnb/javascript AirBnb] | |||
== Comments == | |||
<pre> | |||
// single-line comment | |||
/* | |||
multi-line comment | |||
*/ | |||
</pre> | |||
== Data types & variable declaration == | |||
<pre> | <pre> | ||
var num = 8; | var num = 8; // number | ||
var strg = "Joe"; | var strg = "Joe"; // string | ||
var vobj = {first: "John", last:"Doe"}; | var vobj = {first: "John", last:"Doe"}; // object | ||
var booli = false; | var booli = false; // boolean | ||
var arr = ["HTML","CSS","JS"]; | var arr = ["HTML","CSS","JS"]; // array | ||
var a; typeof a; | var a; typeof a; // undefined | ||
var a = null; | var a = null; // value null | ||
const pi = 3.14; | // newer declarations (>2015) | ||
const pi = 3.14; // | |||
let num = 8; // | |||
typeof strg | typeof strg // =string | ||
</pre> | </pre> | ||
Line 22: | Line 36: | ||
</pre> | </pre> | ||
* Methods | |||
<pre> | <pre> | ||
concat() | concat() both = array1.concat(array2) // joins two or more arrays | ||
join() text = array.join() // joins array to form one long string | |||
map() newAr = array.map(Math.sqrt) // return a new array after function | |||
join() | pop() // remove last element | ||
map() | shift() // remove first element | ||
pop() | unshift() // add new element to beginning | ||
push() | push() // add new element to end | ||
reduce() | reduce() | ||
reverse() | reverse() // reverse the order of elements | ||
slice() array,slice(start, end) | |||
slice() | splice() array.splice(position, n, "New"); // at position, remove n-elements and insert new elements | ||
splice() | forEach() array.forEach(function) // calls a function for each element | ||
sort() | sort() | ||
filter() | |||
</pre> | |||
* Properties | |||
<pre> | |||
length | |||
</pre> | |||
== Objects (key : value) == | |||
<pre> | |||
var user = { firstname: "Peter", lastname: "Johnson" } | |||
user.phone = "01234" | |||
</pre> | |||
<pre> | |||
user.firstname | |||
user["firstname"] | |||
</pre> | |||
<pre> | |||
var result = arrayName.filter(obj => { | |||
return obj.key === value | |||
}) | |||
</pre> | </pre> | ||
Line 63: | Line 101: | ||
includes() if (string.includes(".prn")) {} | includes() if (string.includes(".prn")) {} | ||
</pre> | </pre> | ||
<pre> | |||
single-quote | |||
var str = 'test' // use single-quotes for strings | |||
back-tick | |||
var str = `text and ${variable}` // use back-ticks when multiline or interpolation | |||
double-quote | |||
var str = "test" | |||
</pre> | |||
* Remove ANSI colors from string | * Remove ANSI colors from string | ||
Line 81: | Line 131: | ||
== Conversions == | == Conversions == | ||
<pre> | <pre> | ||
string = integer.toString() | string = integer.toString() # integer -> string | ||
String(123) # integer -> string | |||
toExponential() | |||
toFixed() | |||
toPrecision() | |||
integer = parseInt(string) + 1 | integer = parseInt(string) + 1 # string -> integer | ||
float = parseFloat(string) # string -> float | |||
jsonvar = JSON.parse(string) # string -> json | |||
number = Number("1.23") # string -> number | |||
</pre> | </pre> | ||
* Date & Time | |||
<pre> | |||
dt = new Date(); | |||
Number(dt) # date -> number | |||
dt.getTime() # date -> number | |||
String(dt) # date -> string | |||
dt.toString() # date -> string | |||
</pre> | |||
== Functions == | == Functions == | ||
Line 216: | Line 281: | ||
} | } | ||
</pre> | </pre> | ||
__FORCETOC__ | |||
== Random == | |||
<pre> | |||
Math.random(); float (0.0 - 1.0) | |||
Math.floor(Math.random() * 10); int (0 - 9) | |||
Math.floor(Math.random() * 11); int (0 - 10) | |||
Math.floor(Math.random() * (max - min) ) + min; | |||
</pre>__FORCETOC__ | |||
[[Category:Programming]] |
Latest revision as of 15:14, 28 September 2024
Style guides
Comments
// single-line comment /* multi-line comment */
Data types & variable declaration
var num = 8; // number var strg = "Joe"; // string var vobj = {first: "John", last:"Doe"}; // object var booli = false; // boolean var arr = ["HTML","CSS","JS"]; // array var a; typeof a; // undefined var a = null; // value null // newer declarations (>2015) const pi = 3.14; // let num = 8; // typeof strg // =string
Arrays
var title = new Array(); title[0] = "Mr."; title[1] = "Mrs."; element = title.slice(-1);
- Methods
concat() both = array1.concat(array2) // joins two or more arrays join() text = array.join() // joins array to form one long string map() newAr = array.map(Math.sqrt) // return a new array after function pop() // remove last element shift() // remove first element unshift() // add new element to beginning push() // add new element to end reduce() reverse() // reverse the order of elements slice() array,slice(start, end) splice() array.splice(position, n, "New"); // at position, remove n-elements and insert new elements forEach() array.forEach(function) // calls a function for each element sort() filter()
- Properties
length
Objects (key : value)
var user = { firstname: "Peter", lastname: "Johnson" } user.phone = "01234"
user.firstname user["firstname"]
var result = arrayName.filter(obj => { return obj.key === value })
Strings
charAt() charCodeAt() concat() fromCharCode() indexOf() lastIndexOf() match() replace() zpl = zpl.replace("1234567890",msg.serialnumber) search() slice() checksum = String(sum).slice(-1) # get last digit split() substr() substring() toLowerCase() toUpperCase() valueOf() trim() remove whitespace from both sides trimStart() trimEnd() includes() if (string.includes(".prn")) {}
single-quote var str = 'test' // use single-quotes for strings back-tick var str = `text and ${variable}` // use back-ticks when multiline or interpolation double-quote var str = "test"
- Remove ANSI colors from string
payload = payload.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
- add leading zeros
var string = "000000" + integer.toString() string = string.substr(string.length-6)
Conversions
string = integer.toString() # integer -> string String(123) # integer -> string toExponential() toFixed() toPrecision() integer = parseInt(string) + 1 # string -> integer float = parseFloat(string) # string -> float jsonvar = JSON.parse(string) # string -> json number = Number("1.23") # string -> number
- Date & Time
dt = new Date(); Number(dt) # date -> number dt.getTime() # date -> number String(dt) # date -> string dt.toString() # date -> string
Functions
function addition(number1, number2) { return number1 + number2; } var person = { name: 'Peter', getName: function () { return this.name; } } person.getName()
Operators
+ Addition - Subtraction * Multiplication / Division (...) Grouping operator, operations within brackets are executed earlier than those outside % Modulus (remainder ) ++ Increment numbers -- Decrement numbers == Equal to === Equal value and equal type != Not equal !== Not equal value or not equal type > Greater than < Less than >= Greater than or equal to <= Less than or equal to ? Ternary operator && Logical and || Logical or ! Logical not & AND statement | OR statement ~ NOT ^ XOR << Left shift >> Right shift >>> Zero fill right shift
if - else
if (condition) { // if condition is met } else { // if condition is not met }
switch
switch(var) { case 1: // code break; case 2: // code break; default: // code }
Loops
for (var i = 0; i < 10; i++){ } while (i < 10) { i++; } do { i++; } while (i < 10); break continue
Escape Characters
\' Single quote \" Double quote \\ Backslash \b Backspace \f Form feed \n New line \r Carriage return \t Horizontal tabulator \v Vertical tabulator
Dates & Times
d = new Date(); var year = d.getFullYear(); var month = d.getMonth() + 1;
function ISO8601_week_no() { dt = new Date(); var tdt = new Date(dt.valueOf()); var dayn = (dt.getDay() + 6) % 7; tdt.setDate(tdt.getDate() - dayn + 3); var firstThursday = tdt.valueOf(); tdt.setMonth(0, 1); if (tdt.getDay() !== 4) { tdt.setMonth(0, 1 + ((4 - tdt.getDay()) + 7) % 7); } return 1 + Math.ceil((firstThursday - tdt) / 604800000); }
Random
Math.random(); float (0.0 - 1.0) Math.floor(Math.random() * 10); int (0 - 9) Math.floor(Math.random() * 11); int (0 - 10) Math.floor(Math.random() * (max - min) ) + min;