The function in the tutorial copied below returns Thu Apr 27 2006 00:00:00 GMT+0900 (Japan Standard Time)
Can someone explain what the number pairs 11.4, 8,2 and 5,2 do, and why is one of the numbered pairs followed by -1? I assume those numbered pairs are passed into function number at as values for start and length? is that correct? by why those specific numbers and what`s with the -1?
function extractDate(paragraph) {
function numberAt(start, length) {
return Number(paragraph.slice(start, start + length));
}
return new Date(numberAt(11, 4), numberAt(8, 2) - 1,
numberAt(5, 2));
}
show(extractDate("died 27-04-2006: Black Leclère"));
4 Answers 4
It's telling your method where to start cutting off a piece of the paragraph and how many characters it should cut.
11,4 mean that it should start at the 11th character and chop of 4 characters from there. Keep in mind you start from 0.
d i e d 2 7 - 0 4 - 2 0 0 6 : B l a c k L e c l è r e
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
11, 4 - 11th character = 2. Then 4 characters from there = 6 | So 2006
8, 2 - 8th char = 0. 2 from there = 4| so 04
Basically, your method cuts those pieces and then creates a date with that.
EDIT By cut, I mean that it returns a part of that string, but doesn't do anything to the original string.
See here for reference : http://www.w3schools.com/jsref/jsref_slice_array.asp
3 Comments
extract date gets a "paragraph" string, in which case, it is
"died 27-04-2006: Black Leclère"
now your number at just gets a number starting from the nth character of your string input. so int your first number at(numberAt(11,4), it gets the 11th character and the next 4 letters..which in the string "died 27-04-2006: Black Leclère" is '2006'. numberAt(8,2) gives you the 8th character which is 0 and only gets 2 characters so it returns '04'. you subtract 1 from it so it gives you '03' then numberAt(5,2) gives you '27'.
Comments
The function numberAt() returns a number. It does this by extracting a string from the paragraph, and converting that string to a number. The function's parameters start, and length specify what part of the paragraph should be extracted.
So numberAt(11,4) would extract a 4-digit string, starting with the 12'th character in the paragraph. Assuming that this string contains only digits, it will be converted to a 4-digit number, and returned.
The - 1 is part of an arithmetic expression: numberAt(8,2) - 1. The result will be one less than whatever number is returned by numberAt(8,2).
Comments
The pairs correspond to start location and length of substrings (e.g. 11,4 means the substring starting at the 12th character and ending on the 15th inclusive).
11,4 is the year. 8,2 is the month. 5,2 is the day. The -1 is there because as JohnP mentions, months for the Date() function start at 0 for January (starting index) and not 1 (popular vernacular).
EDIT: Cleared up some wording.