Numbers and Math
var pi = 3.141;
pi.toFixed(0); returns 3
pi.toFixed(2); returns 3.14 - for working with money
pi.toPrecision(2) returns 3.1
pi.valueOf(); returns number
Number(true); converts to number
Number(new Date()) number of milliseconds since 1970
parseInt("3 months"); returns the first number: 3
parseFloat("3.5 days"); returns 3.5
Number.MAX_VALUE largest possible JS number
Number.MIN_VALUE smallest possible JS number
Number.NEGATIVE_INFINITY -Infinity
Number.POSITIVE_INFINITY Infinity
var pi = Math.PI; 3.141592653589793
Math.round(4.4); = 4 - rounded
Math.round(4.5); = 5
Math.pow(2,8); = 256 - 2 to the power of 8
Math.sqrt(49); = 7 - square root
Math.abs(-3.14); = 3.14 - absolute, positive value
Math.ceil(3.14); = 4 - rounded up
Math.floor(3.99); = 3 - rounded down
Math.sin(0); = 0 - sine
Math.cos(Math.PI); OTHERS: tan,atan,asin,acos,
Math.min(0, 3, -2, 2); = -2 - the lowest value
Math.max(0, 3, -2, 2); = 3 - the highest value
Math.log(1); = 0 natural logarithm
Math.exp(1); = 2.7182pow(E,x)
Math.random(); random number between 0 and 1
Math.floor(Math.random() * 5) + 1; random integer, from 1 to 5
|
Miscellaneous
Parsing / Serializing JSON
obj = JSON.parse(str);
var myJSON = JSON.stringify(object);
decode URI. Result: "my page.asp"
decodeURI(enc);
encode URI. Result: "my%page.asp"
encodeURI(uri);
Decode a URI component
decodeURIComponent(enc);
Encode a URI component
encodeURIComponent(uri);
Is variable a finite, legal number
isFinite();
is variable an illegal number
isNaN();
Parses a string into a float / integer
parseFloat();
parseInt();
TRY / CATCH / THROW
try {
undefinedFunction();
}
catch(err) {
console.log(err.message);
}
throw "My error message";
STRICT MODE
"use strict";
x = 1; // Throws an error because variable is not defined
|
|
|
Events
Mouse
onclick, oncontextmenu, ondblclick, onmousedown, onmouseenter, onmouseleave, onmousemove, onmouseover, onmouseout, onmouseup
Keyboard
onkeydown, onkeypress, onkeyup
Frame
onabort, onbeforeunload, onerror, onhashchange, onload, onpageshow, onpagehide, onresize, onscroll, onunload
Form
onblur, onchange, onfocus, onfocusin, onfocusout, oninput, oninvalid, onreset, onsearch, onselect, onsubmit
Drag
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop
Clipboard
oncopy, oncut, onpaste
Media
onabort, oncanplay, oncanplaythrough, ondurationchange, onended, onerror, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, onsuspend, ontimeupdate, onvolumechange, onwaiting
Animation
animationend, animationiteration, animationstart
Miscellaneous
transitionend, onmessage, onmousewheel, ononline, onoffline, onpopstate, onshow, onstorage, ontoggle, onwheel, ontouchcancel, ontouchend, ontouchmove, ontouchstart
|
Arrays
var dogs = ["Bulldog", "Beagle", "Labrador"];
var dogs = new Array("Bulldog", "Beagle", "Labrador");
Access value at index, first item being [0]
alert(dogs[1]);
Change the first item
dogs[0] = "Bull Terier";
Iterate through Array
for (var i = 0; i < dogs.length; i++) {
console.log(dogs[i]);
}
METHODS
convert to string: results "Bulldog,Beagle,Labrador"
dogs.toString();
join: "Bulldog Beagle Labrador"
dogs.join(" * ");
remove last element
dogs.pop();
add new element to the end
dogs.push("Chihuahua");
the same as push
dogs[dogs.length] = "Chihuahua";
remove first element
dogs.shift();
add new element to the beginning
dogs.unshift("Chihuahua");
change element to undefined (not recommended)
delete dogs[0];
add elements (where, how many to remove, element list)
dogs.splice(2, 0, "Pug", "Boxer");
join two arrays (dogs followed by cats and birds)
var animals = dogs.concat(cats,birds);
elements from [1] to [4-1]
dogs.slice(1,4);
sort string alphabetically
dogs.sort();
sort string in descending order
dogs.reverse();
numeric sort
x.sort(function(a, b){return a - b});
numeric descending sort
x.sort(function(a, b){return b - a});
first item in sorted array is the lowest (or highest) value
highest = x[0];
random order sort
x.sort(function(a, b){return 0.5 - Math.random()});
|
|
|
Date & Time
var d = new Date();
= Fri Aug 03 2018 15:52:36 GMT-0300 (Uruguay Standard Time)
= 1533322356511 (miliseconds passed since 1970)
Number(d)
Date declaration
Date("2017-06-23");
(set to Jan 01)
Date("2017");
Date("2017-06-23T12:00:00-09:45");
Date("June 23 2017");
Date("Jun 23 2017 07:45:00 GMT+0100 (Tokyo Time)");
var d = new Date();
getting the weekday
a = d.getDay();
day as a number (1-31)
d.getDate();
weekday as a number (0-6)
d.getDay();
four digit year (yyyy)
d.getFullYear();
hour (0-23)
d.getHours();
milliseconds (0-999)
d.getMilliseconds();
minutes (0-59)
d.getMinutes();
month (0-11)
d.getMonth();
seconds (0-59)
d.getSeconds();
milliseconds since 1970
d.getTime();
SET DATES
adds a week to a date
d.setDate(d.getDate() + 7);
day as a number (1-31)
d.setDate();
year (optionally month and day)
d.setFullYear();
hour (0-23)
d.setHours();
milliseconds (0-999)
d.setMilliseconds();
minutes (0-59)
d.setMinutes();
month (0-11)
d.setMonth();
seconds (0-59)
d.setSeconds();
milliseconds since 1970)
d.setTime();
|
Strings
var abc = "abcdefghijklmnopqrstuvwxyz";
\n new line
var esc = 'I don\'t \n know';
string length
var len = abc.length;
find substring, -1 if doesn't contain
abc.indexOf("lmno");
last occurance
abc.lastIndexOf("lmno");
cuts out "def", negative values count from behind
abc.slice(3, 6);
find and replace, takes regular expressions
abc.replace("abc","123");
convert to upper case
abc.toUpperCase();
convert to lower case
abc.toLowerCase();
abc + " " + str2
abc.concat(" ", str2);
character at index: "c"
abc.charAt(2);
unsafe, abc[2] = "C" doesn't work
abc[2];
character code at index: "c" -> 99
abc.charCodeAt(2);
splitting a string on commas gives an array
abc.split(",");
splitting on characters
abc.split("");
number to hex(16), octal (8) or binary (2)
128.toString(16);
|
|