I'm not exactly sure what you're trying to do, but does this help? Instead of manually working out how to put the correct ordinal suffix ('st', 'nd', 'rd', etc.) on the numbers, I googled a function.
The ordinal_suffix_of
function works like this:
This first part is the start of the function. Hopefully this is self-explanatory. We're creating a function that accepts one parameter, that will be named i
inside the function.
function ordinal_suffix_of(i) {
This next part defines j
and k
. You can declare multiple variables while only typing var
once by using commas, as this code does:
var j = i % 10,
k = i % 100;
This would do exactly the same thing:
var j = i % 10;
var k = i % 100;
The percent sign (%
) is called "modulus" and is a mathematical operator. What it does is divide the left operand by the right operand and returns the remainder. So in the case of j
, it's being assigned remainder of dividing i
by 10
. If i
was 14
, for example, j
would be 4
. If i
was 179
, j
would be 9
. The same thing happens for k
except that it's divided by 100
instead of 10
.
What it's effectively doing is extracting the last 1 digit (for j
) and the last 2 digits (for k
) and then just checking (in the if
statements) what ordinal suffixes they should have.
The reason for k
is that you always want numbers ending in 1
, 2
, or 3
to have the suffixes st
, nd
, and rd
except when the number ends in 11
, 12
, or 13
, in which case it should get the suffix th
. So for example, 112
should be 112th
, and 313513
should be 313513th
. k
handles this by making it so that if the number ends in 11
, 12
, or 13
we only add th
. Note that 11 % 100
will result in 11
, so this works for 11
, 12
, and 13
as well.
var bandsString = "";
var newBandString = "";
var bandsListArray = ["Linkin Park", "Atmosphere", "Rage Against The Machine", "Immortal Technique", "System of a Down"];
for (var i = 0; i < bandsListArray.length; i++) {
var currentBand = bandsListArray[i];
bandsString += "<li> My #" + (i + 1) + " band is " + currentBand + "</li>";
}
for (var i = 0; i < bandsListArray.length; i++) {
var newBandList = bandsListArray[i];
newBandString += "<li>My " + ordinal_suffix_of(i + 1) + " band is " + newBandList + "</li>";
}
function ordinal_suffix_of(i) {
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
document.write(bandsString);
document.write(newBandString);
– Henry Merida Jun 22 '17 at 03:02