what is the meaning of use two bracket in javascript array - javascript

I want to change the date format in javaScript and I find this code of "Mike Christensen" that is very nice.
But my question is about what is meaning of use two bracket in javascript array code at var month line 3.
var mydate = new Date(form.startDate.value);
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"] [mydate.getMonth()];
var str = month + ' ' + mydate.getFullYear();

He is indexing the month array using the month number that he gets it from mydate.getMonth()
Here in this code ,mydate.getMonth() is 11 and as is he indexing month array month[11] would be december
var mydate = new Date();
console.log(mydate.getMonth());
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"] [mydate.getMonth()];
console.log(month);
var str = month + ' ' + mydate.getFullYear();
Hope you understand

The first pair of brackets is creating of array, consider it like this
var month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
The next pair of brackets is a retrieving operation for the array by index.
someArr[index]
in your case
month[11]
That's it, the author just take an element of the just created array by index, where index is extracted from another variable.

doing this: is a very cheap way to init the var month with only elements in the array declared previously...(something that will save you to write one line more but IMHO decrease the readability of the code... )
so breaking that down:
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"] [mydate.getMonth()];
is the same as
var monthOptionsArray = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var monthIndex = mydate.getMonth();
var monthActual = monthOptionsArray[monthIndex];
Example:
var mydate = new Date();
console.log(mydate.getMonth());
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]; monthI = month[1];
console.log(monthI);
var str = month + ' ' + mydate.getFullYear();

Related

How can change the format of Date in javascript?

I have a date like 2019-02-01. how can I change it to February 2019?
You can just do this:
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
const d = new Date("2019/02/01");
const dateString = `${monthNames[d.getMonth()]} ${d.getFullYear()}`;
console.log(dateString);
This will return the month in English, no matter the system's language.
Note that you should use new Date("2019/02/01") (with slashes) to specify a date in your timezone. If you use new Date("2019-02-01"), then it will assume UTC time, and weird stuff will happen (see this answer for more info on this).
const d = new Date("2019/02/01");
const m = d.toLocaleString('default', { month: 'long' });
console.log(m, d.getFullYear());
/* you can use the following code to convert date to the required format. */
var todaysDate = new Date();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var formatted_date = months[todaysDate.getMonth()] + " " + todaysDate.getDate() + " " + todaysDate.getFullYear();

How to get previous month name on given some month (in words not numerical value)? [duplicate]

This question already has answers here:
How to get previous month (DECEMBER) name
(6 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I want a function that gives the full name of prev month for any given month[not just current month]
Ex: prevMonth(August) = July; prevMonth(January)= December.
I'm new to js and can't figure out how to use this array to get the result:
monthsarray: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
Are expecting a simple solution like this?
var monthsarray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
function prevMonth(curMonth) {
var curMonthIndex = monthsarray.indexOf(curMonth);
var prevMonthIndex;
if (curMonthIndex == 0) prevMonthIndex = monthsarray.length - 1;
else if (curMonthIndex == monthsarray.length - 1) prevMonthIndex = 0;
else prevMonthIndex = curMonthIndex - 1;
return monthsarray[prevMonthIndex];
}
console.log(prevMonth("August"));
console.log(prevMonth("December"));
let monthsarray1= ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] ;
let m="May";
console.log(pvsMonth(m))
function pvsMonth(m){
let ln=monthsarray1.length
let idx=monthsarray1.indexOf(m)
if(idx==0){
return monthsarray1[ln-1]
}else{
return monthsarray1[idx-1]
}
}
function prevMonth(month) {
const index = monthsarray.indexOf(month);
if (index > 0) {
return monthsarray[index - 1];
}
if (index === 0) {
return monthsarray[monthsarray.length - 1];
}
throw new Error('Invalid Month given');
}

Results from loop don't work correctly

I want to loop through an array.
Any index which has a length larger than 3 I want to abbreviate.
I want to place the new abbreviated months into a new array.
I want to test that it works by writing the results to the console.
I can get the code to run, however the results don't come out the way I'd hope. From my understanding the loop runs true, running the if statement, which runs true, running the code block. After that the loop should iterate and continue as long as i < months.length, but it doesn't.
var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];
for (var i = 0; i < months.length; i++) {
if (months[i].length > 3) {
monthsAbbrev = months[i].slice(0, 3);
}
}
console.log(monthsAbbrev);
You can do it simply with Array.prototype.map()
var months = ["January", "Febuary"]; //sample data for better understanding
var monthsAbbrev = months.map(v => v.substr(0,3));
console.log(monthsAbbrev); //["Jan", "Feb"]
By the way you are not pushing anything into your target array in your code, that is the problem.
Beside the pushing, you can omit the check for length > 3, because slice is already doing it and that prevent to miss some month, like 'May'.
var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];
for (var i = 0; i < months.length; i++) {
monthsAbbrev.push(months[i].slice(0, 3));
}
console.log(monthsAbbrev);
You need to add the months to your monthsAbbrev array. One way you can do this is by using the .push() function:
var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];
for (var i = 0; i < months.length; i++) {
if (months[i].length > 3) {
monthsAbbrev.push(months[i].slice(0, 3));
}
}
console.log(monthsAbbrev);
You just had to push to the array formed. Rest you already had it.
var months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var monthsAbbrev = [];
for (var i = 0; i < months.length; i++) {
if (months[i].length > 3) {
monthsAbbrev.push(months[i].slice(0, 3));
}
}
console.log(monthsAbbrev);

Assign value in for loop

I am trying to get the actual month from a loop. When I step through it in developer tools and month[i] == 4 it doesn't assign actualMonth to checkMonth
Do I have to assign getMonth to month[] and then try and query the value?
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = "";
for (var i = 0; i < month.length; i++) {
var checkMonth = month[i];
console.log(month[i]);
if (getMonth == month[i]) {
actualMonth = checkMonth;
}
}
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
Too simple?
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = month[getMonth];
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
Change your if to if (month[getMonth] == month[i]) {
Do it like this :
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = "";
for (var i = 0; i < month.length; i++) {
var checkMonth = month[i];
console.log(month[i]);
if (month[getMonth] == month[i]) { //Compare get month like this
actualMonth = checkMonth;
}
}
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
Your problem is that you are comparing an integer and string:
var getMonth = new Date().getMonth(); // This return number from 0 to 11
The code Date().getMonth() returns an integer, and your month list has strings on it
Your code should be:
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = month[getMonth];
console.log(actualMonth);
}
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);
To get the actual month you only need to access the month list with getMonth as index
slightly Modification required
var showCurrentMonth = function() {
var getMonth = new Date().getMonth();
console.log(getMonth);
var month = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
var actualMonth = "";
for (var i = 0; i < month.length; i++) {
var checkMonth = month[i];
if (getMonth == i) {
actualMonth = checkMonth;
}
}
console.log(actualMonth);
};
window.addEventListener('DOMContentLoaded', showCurrentMonth, false);

breaking up a string in jQuery

I have this string...
var myDate = "November 15, 2010";
.....and I need to do this...
$("#request_showdate_1i").val('2010');
$("#request_showdate_2i").val('November');
$("#request_showdate_3i").val('15');
Any ideas how to break this string up?
You can for example use a regular expression:
var parts = /(\S+) (\d+), (\d+)/.exec(myDate);
$("#request_showdate_1i").val(parts[3]);
$("#request_showdate_2i").val(parts[1]);
$("#request_showdate_3i").val(parts[2]);
You can use the Date object, example on jsFiddle
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var d = new Date("November 15, 2010");
$("#request_showdate_1i").val(d.getFullYear()); // 2010
$("#request_showdate_2i").val(months[d.getMonth()]); // November from array
$("#request_showdate_3i").val(d.getDate()); // 15
#Guffa's answer seems worth a try, but have you thought about using the datepart features of Javascript?
3 divs to hold the different date parts
<div class="day"></div>
<div class="month"></div>
<div class="year"></div>
And some Javascript magic
var myDate = new Date("November 15, 2010");
var month_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
$(".day").text(myDate.getDate());
$(".month").text(month_names[myDate.getMonth()]);
$(".year").text(myDate.getFullYear());
Here's a jsFiddle sample.

Categories

Resources