21. JavaScript array iteration method
The array iteration method operates on each array item.
Array.forEach()
The forEach() method calls the function (callback function) once for each array element.
example
var txt = ""; var numbers = [45, 4, 9, 16, 25]; numbers.forEach(myFunction); function myFunction(value, index, array) { txt = txt + value + "<br>"; }
Try it yourself
Note: this function accepts 3 parameters:
Project value
Item index
Array itself
The above example uses only the value parameter. This example can be rewritten as:
example
var txt = ""; var numbers = [45, 4, 9, 16, 25]; numbers.forEach(myFunction); function myFunction(value) { txt = txt + value + "<br>"; } Array.map()
The map() method creates a new array by executing a function on each array element.
The map() method does not execute functions on array elements that have no values.
The map() method does not change the original array.
This example multiplies each array value by 2:
example
var numbers1 = [45, 4, 9, 16, 25]; var numbers2 = numbers1.map(myFunction); function myFunction(value, index, array) { return value * 2; }
Try it yourself
Note that the function has three parameters:
Project value
Item index
Array itself
When the callback function only uses the value parameter, the index and array parameters can be omitted:
example
var numbers1 = [45, 4, 9, 16, 25]; var numbers2 = numbers1.map(myFunction); function myFunction(value) { return value * 2; }
Array.filter()
The filter() method creates a new array containing the array elements that passed the test.
This example creates a new array with elements with a value greater than 18:
example
var numbers = [45, 4, 9, 16, 25]; var over18 = numbers.filter(myFunction); function myFunction(value, index, array) { return value > 18; }
Try it yourself
Note that this function accepts three parameters:
Project value
Item index
Array itself
In the above example, the callback function does not use the index and array parameters, so they can be omitted:
example
var numbers = [45, 4, 9, 16, 25]; var over18 = numbers.filter(myFunction); function myFunction(value) { return value > 18; }
Array.reduce()
The reduce() method runs the function on each array element to generate (reduce) a single value.
The reduce() method works from left to right in the array. See also reduceRight().
The reduce() method does not reduce the original array.
This example determines the sum of all numbers in the array:
example
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduce(myFunction); function myFunction(total, value, index, array) { return total + value; }
Try it yourself
Note that this function accepts four parameters:
Total (initial value / previously returned value)
Project value
Item index
Array itself
The above example does not use the index and array parameters. You can rewrite it to:
example
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduce(myFunction); function myFunction(total, value) { return total + value; }
Try it yourself
The reduce() method can accept an initial value:
example
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduce(myFunction, 100); function myFunction(total, value) { return total + value; }
Array.reduceRight()
The reduceRight() method runs the function on each array element to generate (reduce) a single value.
The reducereight () method works from right to left in the array. See also reduce().
The reduceRight() method does not reduce the original array.
This example determines the sum of all numbers in the array:
example
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduceRight(myFunction); function myFunction(total, value, index, array) { return total + value; }
Try it yourself
Note that this function accepts four parameters:
Total (initial value / previously returned value)
Project value
Item index
Array itself
The above example does not use the index and array parameters. You can rewrite it to:
example
var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduceRight(myFunction); function myFunction(total, value) { return total + value; }
Array.every()
The every() method checks whether all array values pass the test.
This example checks whether all array values are greater than 18:
example
var numbers = [45, 4, 9, 16, 25]; var allOver18 = numbers.every(myFunction); function myFunction(value, index, array) { return value > 18; }
Try it yourself
Note that this function accepts three parameters:
Project value
Item index
Array itself
If the callback function only uses the first parameter (value), other parameters can be omitted:
example
var numbers = [45, 4, 9, 16, 25]; var allOver18 = numbers.every(myFunction); function myFunction(value) { return value > 18; }
Array.some()
The some() method checks whether some array values pass the test.
This example checks whether some array values are greater than 18:
example
var numbers = [45, 4, 9, 16, 25]; var someOver18 = numbers.some(myFunction); function myFunction(value, index, array) { return value > 18; }
Try it yourself
Note that this function accepts three parameters:
Project value
Item index
Array itself
Array.indexOf()
The indexOf() method searches the array for element values and returns their positions.
Note: the location of the first project is 0, the location of the second project is 1, and so on.
example
Retrieve the item "Apple" in the array:
var fruits = ["Apple", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
grammar
array.indexOf(item, start)
Item is required. The item to retrieve.
Start is optional. Where to start the search. Negative values start at the given position from the end and search to the end.
Array.indexOf() returns - 1 if no item is found.
If the item appears more than once, the first occurrence is returned.
Array.lastIndexOf()
Array.lastIndexOf() is similar to Array.indexOf(), but searches from the end of the array.
example
Retrieve the item "Apple" in the array:
var fruits = ["Apple", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");
grammar
array.lastIndexOf(item, start)
Item is required. The item to retrieve.
Start is optional. Where to start the search. Negative values start at the given position from the end and search to the beginning.
Array.find()
The find() method returns the value of the first array element that passes the test function.
This example finds (returns) the value of the first element greater than 18:
example
var numbers = [4, 9, 16, 25, 29]; var first = numbers.find(myFunction); function myFunction(value, index, array) { return value > 18; }
Try it yourself
Note that this function accepts three parameters:
Project value
Item index
Array itself
Array.findIndex()
The findIndex() method returns the index of the first array element that passes the test function.
This example finds the index of the first element greater than 18:
example
var numbers = [4, 9, 16, 25, 29]; var first = numbers.findIndex(myFunction); function myFunction(value, index, array) { return value > 18; }
Try it yourself
Note that this function accepts three parameters:
Project value
Item index
Array itself
22. Date
example
var d = new Date();
Try it yourself
JavaScript date output
By default, JavaScript uses the browser's time zone and displays the date as a full-text string:
Tue Apr 02 2019 09:01:19 GMT+0800 (China standard time)
Later, you will learn more about how to display dates in this tutorial.
Create Date object
The Date object is created by a new Date() constructor.
There are four ways to create a new date object:
new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)
new Date()
new Date() creates a new date object with the current date and time:
example
var d = new Date();
Try it yourself
Date objects are static. The computer time is ticking, but the date object will not.
new Date(year, month, ...)
new Date(year, month,...) creates a new date object with the specified date and time.
Seven numbers specify year, month, day, hour, minute, second and millisecond respectively (in this order):
example
var d = new Date(2018, 11, 24, 10, 33, 30, 0);
Try it yourself
Note: JavaScript calculates the month from 0 to 11.
January is 0. December is 11.
Six numbers specify year, month, day, hour, minute and second:
example
var d = new Date(2018, 11, 24, 10, 33, 30);
Try it yourself
Five numbers specify year, month, day, hour, and minute:
example
var d = new Date(2018, 11, 24, 10, 33);
Try it yourself
Four numbers specify year, month, day, and hour:
example
var d = new Date(2018, 11, 24, 10);
Try it yourself
Three numbers specify year, month and day:
example
var d = new Date(2018, 11, 24);
Try it yourself
Two numbers specify the year and month:
example
var d = new Date(2018, 11);
Try it yourself
You cannot omit the month. If only one parameter is provided, it is considered milliseconds.
example
var d = new Date(2018);
Try it yourself
Last century
One and two digit years will be interpreted as 19xx:
example
var d = new Date(99, 11, 24);
Try it yourself
example
var d = new Date(9, 11, 24);
Try it yourself
new Date(dateString)
new Date(dateString) creates a new date object from the date string:
example
var d = new Date("October 13, 2014 11:13:00");
Try it yourself
Date strings are described in the next chapter.
JavaScript stores the date in milliseconds
JavaScript stores the date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (coordinated universal time).
Zero time is 00:00:00 UTC, January 1, 1970.
The current time is 1554166879383 milliseconds after January 1, 1970.
new Date(milliseconds)
new Date(milliseconds) creates a new date object with zero hour plus milliseconds:
example
var d = new Date(0);
Try it yourself
January 1, 1970 plus 100 million milliseconds is about March 3, 1973:
example
var d = new Date(100000000000);
Try it yourself
January 1, 1970 minus 100 million milliseconds is about October 31, 1966:
example
var d = new Date(-100000000000);
Try it yourself
example
var d = new Date(86400000);
Try it yourself
One day (24 hours) is 86 400000 milliseconds.
Date method
When you create a Date object, you can manipulate it in many ways.
The date method allows you to use local time or UTC (universal or GMT) time to get and set the year, month, day, hour, minute, second and millisecond of the date object.
The date method and time zone are described in the next chapter.
Display date
JavaScript (by default) will output the date in full text string format:
Wed Mar 25 2015 08:00:00 GMT+0800 (China standard time)
When a date object is displayed in HTML, it is automatically converted to a string using the toString() method.
example
d = new Date(); document.getElementById("demo").innerHTML = d;
Try it yourself
Equivalent to:
d = new Date(); document.getElementById("demo").innerHTML = d.toString();
Try it yourself
The toUTCString() method converts the date to a UTC string (a date display standard).
example
var d = new Date(); document.getElementById("demo").innerHTML = d.toUTCString();
Try it yourself
The toDateString() method converts the date to a more readable format:
example
var d = new Date(); document.getElementById("demo").innerHTML = d.toDateString();
23. JavaScript date formatting
There are four JavaScript date input formats:
The ISO format follows strict standards in JavaScript.
Other formats are unclear and may be browser specific.
JavaScript date output
Regardless of the input format, JavaScript will output the full-text string format by default:
Mon Feb 19 2018 06:00:00 GMT+0800 (China standard time)
JavaScript ISO date
ISO 8601 is an international standard for date and time.
The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:
Instance (full date)
var d = new Date("2018-02-19");
Try it yourself
The calculated date is relative to your time zone.
Depending on your time zone, the above results will vary from February 18 to February 19.
ISO date (year and month)
The date can also be written without specifying a specific date (YYYY-MM):
var d = new Date("2015-03");
Try it yourself
The time zone will change the results between February 28 and March 1.
ISO date (year only)
You can write the date without specifying the specific month and day (YYYY):
var d = new Date("2018");
Try it yourself
The time zone will change the results between December 31, 2017 and January 1, 2018.
ISO date (full date plus hours, minutes and seconds)
You can also add hours, minutes and seconds to write dates (YYYY-MM-DDTHH:MM:SS):
var d = new Date("2018-02-19T12:00:00");
Try it yourself
Dates and times are separated by the capital letter T.
UTC time is defined by the capital letter Z.
If you want to modify the time relative to UTC, delete Z and replace with + HH:MM or - HH:MM:
example
var d = new Date("2018-02-19T12:00:00-08:30");
Try it yourself
UTC (Universal Time Coordinated) is equivalent to GMT (Greenwich mean time).
Note: UTC, coordinated universal time, also known as world unified time, world standard time and international coordinated time.
Omitting T or Z in the date time string will produce different results in different browsers.
time zone
When setting a date, if no time zone is specified, JavaScript uses the browser's time zone.
When obtaining the date, if the time zone is not specified, the result will be converted to the browser time zone.
In other words, if the date / time is created in GMT (Greenwich mean time), the date / time will be converted to CST (China standard time) if the user browses from China.
JavaScript short date
Short dates usually use syntax such as "MM/DD/YYYY":
example
var d = new Date("02/19/2018");
Try it yourself
warning
In some browsers, months without leading zeros or their will generate errors:
var d = new Date("2018-2-19");
The behavior of "YYYY / MM / DD" is undefined.
Some browsers try to guess the format. Some will return NaN.
var d = new Date("2018/02/19");
The behavior of "DD-MM-YYYY" is also undefined.
Some browsers try to guess the format. Some will return NaN.
var d = new Date("19-02-2018");
JavaScript long date
Long dates are usually written in the syntax of "MMM DD YYYY":
example
var d = new Date("Feb 19 2018");
Try it yourself
Months and days can appear in any order:
example
var d = new Date("19 Feb 2018");
Try it yourself
Moreover, the month can be written in full name (January) or abbreviation (Jan):
example
var d = new Date("February 19 2018");
Try it yourself
example
var d = new Date("Feb 19 2018");
Try it yourself
Commas are ignored and case insensitive:
example
var d = new Date("FEBRUARY, 25, 2015");
Try it yourself
JavaScript full date
JavaScript accepts date strings in "full JavaScript format":
example
var d = new Date("Mon Feb 19 2018 06:55:23 GMT+0100 (W. Europe Standard Time)");
Try it yourself
JavaScript ignores errors in date names and time brackets:
example
var d = new Date("Fri Mar 26 2018 09:56:24 GMT+0100 (Tokyo Time)");
24. JavaScript method for obtaining date
The date method allows you to get and set date values (year, month, day, hour, minute, second, millisecond)
Date acquisition method
The get method is used to get a part of the date (information from the date object). The following are the most commonly used methods (sorted alphabetically):
getTime() method
The getTime() method returns the number of milliseconds since January 1, 1970:
example
var d = new Date(); document.getElementById("demo").innerHTML = d.getTime();
Try it yourself
getFullYear() method
The getFullYear() method returns the date year as a four digit number:
example
var d = new Date(); document.getElementById("demo").innerHTML = d.getFullYear();
Try it yourself
getMonth() method
getMonth() returns the month of the date in numbers (0-11):
example
var d = new Date();
document.getElementById("demo").innerHTML = d.getMonth();
In JavaScript, the first month (January) is month number 0, so December returns month number 11.
You can use the name array and use getMonth() to return the month as the name:
example
var d = new Date(); var months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; document.getElementById("demo").innerHTML = months[d.getMonth()];
Try it yourself
getDate() method
The getDate() method returns the day of the date in numbers (1-31):
example
var d = new Date(); document.getElementById("demo").innerHTML = d.getDate();
Try it yourself
getHours() method
The getHours() method returns the number of hours of the date in numbers (0-23):
example
var d = new Date(); document.getElementById("demo").innerHTML = d.getHours();
Try it yourself
getMinutes() method
The getMinutes() method returns the number of minutes of the date in numbers (0-59):
example
var d = new Date(); document.getElementById("demo").innerHTML = d.getMinutes();
Try it yourself
getSeconds() method
The getSeconds() method returns the number of seconds of the date in numbers (0-59):
example
var d = new Date(); document.getElementById("demo").innerHTML = d.getSeconds();
Try it yourself
getMilliseconds() method
The getMilliseconds() method returns the number of milliseconds of the date as a number (0-999):
example
var d = new Date(); document.getElementById("demo").innerHTML = d.getMilliseconds();
Try it yourself
getDay() method
The getDay() method returns the weekday of the date in numbers (0-6):
example
var d = new Date(); document.getElementById("demo").innerHTML = d.getDay();
Try it yourself
In JavaScript, the first day of the week (0) means "Sunday", even though some countries in the world think the first day of the week is "Monday".
You can use the name array and use getDay() to return the week name as the name:
example
var d = new Date(); var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; document.getElementById("demo").innerHTML = days[d.getDay()];
Try it yourself
UTC date method
The UTC date method is used to process UTC dates (universal time zone dates):
25. JavaScript setting date method
Use the set date method to set the date value (year, month, day, hour, minute, second, millisecond) of the date object.
Date setting method
The setting method is used to set a part of the date. The following are the most commonly used methods (sorted alphabetically):
setFullYear() method
The setFullYear() method sets the year of the date object. This example is set to 2020:
example
<script> var d = new Date(); d.setFullYear(2020); document.getElementById("demo").innerHTML = d; </script>
The setFullYear() method can optionally set the month and day:
example
<script> var d = new Date(); d.setFullYear(2020, 11, 3); document.getElementById("demo").innerHTML = d; </script>
setMonth() method
The setMonth() method sets the month of the date object (0-11):
example
<script> var d = new Date(); d.setMonth(11); document.getElementById("demo").innerHTML = d; </script>
setDate() method
The setDate() method sets the date of the date object (1-31):
example
<script> var d = new Date(); d.setDate(15); document.getElementById("demo").innerHTML = d; </script>
Try it yourself
The setDate() method can also be used to add days to the date:
example
<script> var d = new Date(); d.setDate(d.getDate() + 50); document.getElementById("demo").innerHTML = d; </script>
Try it yourself
If you add days and switch between months or years, the changes are automatically processed by the Date object.
setHours() method
The setHours() method sets the hour of the date object (0-23):
example
<script> var d = new Date(); d.setHours(22); document.getElementById("demo").innerHTML = d; </script>
Try it yourself
setMinutes() method
The setMinutes() method sets the minutes of the date object (0-59):
example
<script> var d = new Date(); d.setMinutes(30); document.getElementById("demo").innerHTML = d; </script>
Try it yourself
setSeconds() method
The setSeconds() method sets the number of seconds of the date object (0-59):
example
<script> var d = new Date(); d.setSeconds(30); document.getElementById("demo").innerHTML = d; </script>
Try it yourself
Comparison date
Dates can be easily compared.
The following example compares today with January 16, 2049:
example
var today, someday, text; today = new Date(); someday = new Date(); someday.setFullYear(2049, 0, 16); if (someday > today) { text = "Today is before January 16, 2049"; } else { text = "Today, after January 16, 2049"; } document.getElementById("demo").innerHTML = text;
Try it yourself
JavaScript counts months from 0 to 11. January is 0. December is November.