1. JavaScript Numbers
1)
var myNumber = 128;
myNumber.toString(16); // returns 80
myNumber.toString(8); // returns 200
myNumber.toString(2); // returns 10000000
2)Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.
var x = 2 / 0; // x will be Infinity
var y = -2 / 0; // y will be -Infinity
typeof Infinity; // returns "number"
3)NaN - Not a Number
var x = 100 / "Apple"; // x will be NaN (Not a Number)
var x = 100 / "10"; // x will be 10
// You can use the global JavaScript function isNaN() to find out if a value is a number.
var x = 100 / "Apple";
isNaN(x); // returns true because x is Not a Number
// Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN:
var x = NaN;
var y = 5;
var z = x + y; // z will be NaN
// Or the result might be a concatenation:
var x = NaN;
var y = "5";
var z = x + y; // z will be NaN5
2. JavaScript Number Methods
1)The toExponential() Method
指数表記で表した文字列を返します
var x = 9.656;
// The parameter is optional. If you don't specify it, JavaScript will not round the number.
x.toExponential(); // returns 9.656e+0
x.toExponential(2); // returns 9.66e+0
x.toExponential(4); // returns 9.6560e+0
x.toExponential(6); // returns 9.656000e+0
2)The toFixed() Method
toFixed() returns a string, with the number written with a specified number of decimals:
var x = 9.656;
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560
x.toFixed(6); // returns 9.656000
3)The toPrecision() Method
toPrecision() returns a string, with a number written with a specified length:
var x = 9.656;
x.toPrecision(); // returns 9.656
x.toPrecision(2); // returns 9.7
x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns 9.65600
4)Converting Variables to Numbers
There are 3 JavaScript methods that can be used to convert variables to numbers:
**The Number() method
The parseInt() method
The parseFloat() method**
a)Number()
x = true;
Number(x); // returns 1
x = false;
Number(x); // returns 0
// Used on Date(), the Number() method returns the number of milliseconds since 1.1.1970.
x = new Date();
Number(x); // returns 1404568027739
x = "10"
Number(x); // returns 10
x = "10 20"
Number(x); // returns NaN
b)parseInt()
parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN
c)parseFloat()
parses a string and returns a number. Spaces are allowed. Only the first number is returned:
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
5)Number Properties
Property | Description |
---|---|
MAX_VALUE | Returns the largest number possible in JavaScript |
MIN_VALUE | Returns the smallest number possible in JavaScript |
NEGATIVE_INFINITY | Represents negative infinity (returned on overflow) |
NaN | Represents a “Not-a-Number” value |
POSITIVE_INFINITY | Represents infinity (returned on overflow) |
source:
x = Number.MAX_VALUE; // 1.7976931348623157e+308
x = Number.MIN_VALUE; // 5e-324
x = Number.NEGATIVE_INFINITY; // -Infinity
x = Number.NaN; // NaN
x = Number.POSITIVE_INFINITY; // Infinity
//[**]Number properties belongs to the JavaScript's number object wrapper called Number.
//These properties can only be accessed as Number.MAX_VALUE.
//Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined:
var x = 6;
var y = x.MAX_VALUE; // y becomes undefined
3. JavaScript Math Object
1)Math.min() and Math.max()
Math.min(0, 150, 30, 20, -8, -200); // returns -200
Math.max(0, 150, 30, 20, -8, -200); // returns 150
2)Math.random()
Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)
3)Math.round()
Math.round() rounds a number to the nearest integer:
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4
Math.round(4.5); // returns 5
4)Math.ceil()
Math.ceil() rounds a number up to the nearest integer:
Math.ceil(4.4); // returns 5
5)Math.floor()
Math.floor() rounds a number down to the nearest integer:
Math.floor(4.7); // returns 4
6)Math.abs(x)
Math.abs(-7.25); // 7.25
7)math.pow()
Math.pow(4, 3); // 64
8)Math.sqrt()
Math.sqrt(9); // 3
4. JavaScript Dates
1)Creating Date Objects
There are 4 ways of initiating a date:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month[, day, hours, minutes, seconds, milliseconds])
[]JavaScript counts months from 0 to 11. January is 0. December is 11.**
2)Displaying Dates
d = new Date();
d.toString(); // Thu Jun 30 2016 14:44:27 GMT+0900 (東京 (標準時))
d.toUTCString(); // Thu, 30 Jun 2016 05:44:39 GMT
d.toDateString(); // Thu Jun 30 2016
3)
When setting a date, without specifying the time zone, JavaScript will use the browser’s time zone.
When getting a date, without specifying the time zone, the result is converted to the browser’s time zone
In other words: If a date/time is created in GMT (Greenwich Mean Time), the date/time will be converted to CDT (Central US Daylight Time) if a user browses from central US.
5. JavaScript Date Formats
There are generally 4 types of JavaScript date formats:
**ISO Dates
Long Dates
Short Dates
Full Format**
1)JavaScript ISO Dates [-]
ISO 8601 is the international standard for the representation of dates and times.
The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:
var d = new Date("2015-03-25"); // Wed Mar 25 2015 09:00:00 GMT+0900 (東京 (標準時))
//The computed date will be relative to your time zone.
//Depending on your time zone, the result above will vary between March 24 and March 25. [**?why]
var d = new Date("2015-03"); // Sun Mar 01 2015 09:00:00 GMT+0900 (東京 (標準時))
//Time zones will vary the result above between February 28 and March 01. [**why?]
new Date("2015"); // Thu Jan 01 2015 09:00:00 GMT+0900 (東京 (標準時))
//Time zones will vary the result above between December 31 2014 and January 01 2015. [**why?]
var d = new Date("2015-03-25T12:00:00"); // Wed Mar 25 2015 12:00:00 GMT+0900 (東京 (標準時))
//The T in the date string, between the date and time, indicates UTC time.
//UTC (Universal Time Coordinated) is the same as GMT (Greenwich Mean Time).
2)JavaScript Short Dates [/]
var d = new Date("03/25/2015");
var d = new Date("2015/03/25");
[**]Leading Zero WARNING !
In most browsers, months or days with no leading zeroes will be interpreted as short dates:
var d = new Date("2015-3-25"); // Invalid Date
var d = new Date("2015-03-25"); // Wed Mar 25 2015 09:00:00 GMT+0900 (東京 (標準時))
var d = new Date("2015/3/25"); // Wed Mar 25 2015 00:00:00 GMT+0900 (東京 (標準時))
var d = new Date("2015/03/25"); // Wed Mar 25 2015 00:00:00 GMT+0900 (東京 (標準時))
3)JavaScript Long Dates [MMM DD YYYY]
var d = new Date("Mar 25 2015");
var d = new Date("25 Mar 2015");
var d = new Date("January 25 2015");
var d = new Date("January 25 2015");
var d = new Date("JANUARY, 25, 2015"); // Commas are ignored. Names are case insensitive
4)Full Date Format
JavaScript will accept date strings in “full JavaScript format”:
var d = new Date(“Wed Mar 25 2015 09:56:24 GMT+0100 (W. Europe Standard Time)”);
// Wed Mar 25 2015 17:56:24 GMT+0900 (東京 (標準時))
JavaScript will ignore errors both in the day name and in the time parentheses:
var d = new Date(“Fri Mar 25 2015 09:56:24 GMT+0100 (Tokyo Time)”);
6. JavaScript Date Methods
1)Date Get Methods
Method | Description |
---|---|
getDate() | Get the day as a number (1-31) |
getDay() | Get the weekday as a number (0-6)sun:0 |
getFullYear() | Get the four digit year (yyyy) |
getHours() | Get the hour (0-23) |
getMilliseconds() | Get the milliseconds (0-999) |
getMinutes() | Get the minutes (0-59) |
getMonth() | Get the month (0-11) |
getSeconds() | Get the seconds (0-59) |
getTime() | Get the time (milliseconds since January 1, 1970) |
~
<script>
var d = new Date();
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("demo").innerHTML = days[d.getDay()];
</script>
2)Date Set Methods
Method | Description |
---|---|
setDate() | Set the day as a number (1-31) |
setFullYear() | Set the year (optionally month and day) |
setHours() | Set the hour (0-23) |
setMilliseconds() | Set the milliseconds (0-999) |
setMinutes() | Set the minutes (0-59) |
setMonth() | Set the month (0-11) |
setSeconds() | Set the seconds (0-59) |
setTime() | Set the time (milliseconds since January 1, 1970) |
The setDate() method can also be used to add days to a date:
<script>
var d = new Date();
d.setDate(d.getDate() + 50);
</script>
3)Date.parse()
returns the number of milliseconds between the date and January 1, 1970
4)Compare Dates
day1 < day2 : day1 is bofore day2
7. JavaScript Arrays
1)Adding Array Elements
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // Banana,Orange,Apple,Mango,Lemon
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
// Adding elements with high indexes can create undefined "holes" in an array:
fruits[10] = "Lemon"; // Banana,Orange,Apple,Mango,,,,,,,Lemon fruits[6] undefined
</script>
2)In JavaScript, arrays always use numbered indexes.
WARNING !!
If you use a named index, JavaScript will redefine the array to a standard object.
After that, all array methods and properties will produce incorrect results.
<script>
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return undefined
typeof person // object
</script>
3)How to Recognize an Array
a)Array.isArray() [ECMAScript 5]
var fruits = ["Banana", "Orange", "Apple", "Mango"];
Array.isArray(fruits); // true
b)create your own isArray() function
<script>
function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
// arrayName.constructor : function Array() { [native code] }
</script>
c)instanceof
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits instanceof Array // returns true
8. JavaScript Array Methods
1)Converting Arrays to Strings
a)toString()
b)join()
var fruits = ["Banana", "Orange","Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * "); // Banana * Orange * Apple * Mango
2)pop()
The pop() method returns the value that was “popped out”
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop(); // the value of x is "Mango"
</script>
3)push()
The push() method returns the new array length:
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi"); // the value of x is 5
</script>
4)Shifting Elements
Shifting is equivalent to popping, working on the first element instead of the last.
The shift() method removes the first array element and “shifts” all other elements to a lower index.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Orange,Apple,Mango
The unshift() method adds a new element to an array (at the beginning), and “unshifts” older elements:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Lemon,Banana,Orange,Apple,Mango
The shift() method returns the string that was “shifted out”.
The unshift() method returns the new array length.
5)Deleting Elements
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined
// [**]Using delete may leave undefined holes in the array. Use pop() or shift() instead.
</script>
6)Splicing an Array
The splice() method can be used to add new items to an array:
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi"); // Banana,Orange,Lemon,Kiwi,Apple,Mango
fruits.splice(2, 1, "Lemon", "Kiwi"); //Banana,Orange,Lemon,Kiwi,Mango
fruits.splice(0, 1); // Removes the first element of fruits
// The first parameter (2) defines the position where new elements should be added (spliced in).
// The second parameter (0) defines how many elements should be removed.
// The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
</script>
7)Joining Arrays
The concat() method creates a new array by concatenating two arrays:
<script>
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias","Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and myBoys
// The concat() method can take any number of array arguments:
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias","Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3
</script>
8)Slicing an Array
The slice() method slices out a piece of an array into a new array.
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1); // citrus: Orange,Lemon,Apple,Mango
// The slice() method can take two arguments like slice(1,3).
// The method then selects elements from the start argument, and up to (but not including) the end argument.
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3); //citrus: Orange,Lemon
9. JavaScript Sorting Arrays
1) Sorting an Array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
2)Reversing an Array
The reverse() method reverses the elements in an array.
You can use it to sort an array in descending order:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
fruits.reverse(); // Reverses the order of the elements
3)compare function
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// Use the same trick to sort an array descending:
points.sort(function(a, b){return b - a});
// Sorting an Array in Random Order];
points.sort(function(a, b){return 0.5 - Math.random()});
// Sorting Object Arrays
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}];
cars.sort(function(a, b){return a.year - b.year});
// Comparing string
cars.sort(function(a, b){
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});