Beginning JavaScript - create table - javascript

I have to create an array using a for loop to produce the numbers 0-24. Then print these numbers in order in a 5x5 "table" using a for loop.
The output should be: 0 1 2 3 4 x 5 6 7 8 9 x 10 11 12 13 14 x... 20 21 22 23 24
I can't figure out how to create the table.
Here is my code:
// Calculate numbers 0-24
var numbers = [];
for (var 0; i < 25; i++) {
numbers[i] = i;
}
// Create table
for (var row = 0; row < 4; row++) {
document.write('<tr>');
for (var col = 0; col < 4; col++) {
document.write('<td>' + numbers + '</td>');
}
document.write('</tr>');
}

The problem is that you are accessing the array without any index. Try this instead:
var numbers = [];
for ( var 0; i<25; i++)
{
numbers[i]= i;
}
//Create table
var i = 0;
var table = "<table>";
for (var row=0; row<5; row++) //Changed from 4 to 5
{
table += "<tr>";
for (var col=0; col<5; col++) //Changed from 4 to 5
{
table += "<td>" + numbers[i] + "</td>"; //numbers to numbers[i]
i++;
}
table += "</tr>";
}
table += "</table>";
document.write(table);
Update: Taking from what #Jon P answered I updated my answer to only write once.

This looks like a homework assignment so I'll make some suggestions instead of an out right answer.
Dont use document.write.
Create a table stub on the page using HTML and give it an ID. Find out how to get element by id. Find out how to update the inner html of that element. Only update the document once.
Use a tool like Firebug for Firefox or Developer tools for Chrome to inspect what is rendered to the page so you can work out what went wrong (or right).
Start your search for knowledge here: https://developer.mozilla.org/en-US/docs/Web/JavaScript
For an added bonus you may be able to do this without nested for loops with the help of the % operator

Supremely overkill, but maybe you will find these functions useful!
// creates an array that contains a sequence of numbers from 0 to size-1
function range(size) {
size = Math.max(0, size);
var result = [];
while (size--) { result.unshift(size); }
return result;
}
// splits an array into chunks of a certain size.
function chunk(array, size) {
if (!array || !array.length || size < 1) { return array };
return [array.slice(0, size)].concat(chunk(array.slice(size), size));
}
// takes a 2D array and converts it to an HTML table.
function createHTMLTable(table) {
var html = table.map(function(row) {
row = row.map(function(cell) { return "<td>"+ cell +"</td>"; });
row = row.join('');
return "<tr>"+ row +"</tr>";
});
html = html.join('');
return "<table>"+ html +"</table>";
}
function renderHTML(html) {
document.write(html);
}
var numbers = range(25);
var table = chunk(numbers, 5);
var tableHTML = createHTMLTable(table);
renderHTML(tableHTML);

Related

Multiplication table in a console for entered number

Good day,
I need to make a method that makes the multiplication table in console.log.
This method should receive a number to which it outputs the multiplication table.
The table should be appeared in the console (console.log). For example, if the number 5 came to the input, we get:
Important note:
In the last line between the numbers, exactly one space should be output.
In each column, the numbers should be aligned to the right.
I have searched everywhere, but I have not found a similar solution to this particular problem anywhere.
I don't quite understand how we can indent and add numbers on the sides. I only got it this way:
function multiplicationTable(value) {
let table = '';
for (let i = 1; i <= value; i++) {
let tableString = '';
for (let j = 1; j <= value; j++) {
tableString += ' ' + (i * j) + ' ';
}
tableString += '\n';
table += tableString;
}
return table;
}
console.log(multiplicationTable(5));
Try something like this :
function multiplicationTable(value) {
let table = '\n';
let maxLength = (value * value).toString().length;
for (let i = 0; i <= value; i++) {
let tableString = '';
for (let j = 0; j <= value; j++) {
let product = i * j;
let padding = ' '.repeat(maxLength - product.toString().length + 1);
tableString += padding + (product || ' ');
}
table += tableString + '\n';
}
console.log(table);
}
multiplicationTable(5);
Explanation :
let table = '\n'; creates an empty string with a newline character, which will be used to store the multiplication table.
let maxLength = (value * value).toString().length; finds the length of the largest number that will appear in the table, which is value * value. This length will be used to set the width of each column in the table.
for (let i = 0; i <= value; i++) creates a for loop that will iterate value + 1 times, where i is the row number. The 0 in i = 0 is because we want the first row to display the column headers (i.e. the numbers 0, 1, 2, ..., value).
let tableString = ''; creates an empty string that will be used to store each row of the table.
for (let j = 0; j <= value; j++) creates a nested for loop that will iterate value + 1 times, where j is the column number. The 0 in j = 0 is because we want the first column to display the row headers (i.e. the numbers 0, 1, 2, ..., value).
let product = i * j; calculates the product of the row and column numbers, which is the number that will appear in the table at that position.
let padding = ' '.repeat(maxLength - product.toString().length + 1); adds spaces to the left of the product so that each column has the same width. maxLength is the width of each column, and product.toString().length is the length of the product. The + 1 in maxLength - product.toString().length + 1 adds an extra space to the left of each product.
tableString += padding + (product || ' '); adds the padding and product (or an empty string, ' ', if i or j is 0) to the tableString. This creates the row of the table.
table += tableString + '\n'; adds the tableString and a newline character to the table. This creates a new row in the table.

Javascript snake pattern grid

I am trying to draw a grid on screen numbered in a snake pattern in Javascript, I have a working grid but it follows the pattern of
12345
67890
And what I need is
12345
09876
I have seen this done with modulo and have tried to implement but im having trouble getting the right number sequence.
Here is my function
function createGrid(length, height) {
var ledNum = 0;
for (var rows = 0; rows < height; rows++) {
for (var columns = 0; columns < length; columns++) {
var backwards = ledNum + columns;
if (rows % 2 == 0 || rows != 0) {
$("#container").append("<div class='grid' id='" + ledNum + "'>" + //HERE IS MY PROBLEM+"</div>");
}
else if (!rows % 2 == 0) {
$("#container").append("<div class='grid' id='" + ledNum + "'>" + ledNum + "</div>");
}
ledNum++;
};
};
$(".grid").width(960 / length);
$(".grid").height(960 / height);
};
How do I work out the true modulo case to show the numbers correctly in snake pattern?
I am not well versed with 2d arrays but perhaps that might be a better way?
The best way I can think of is to use an object with arrays and exploit its inbuilt functions to ease your job...for example
function createGrid(length,height) {
var lednum = 0;
var grid = [];
for (var row = 0; row < height; row++) {
grid[row] = [];
for (var col = 0; col < length; col++) {
if ((row % 2) === 0) {
grid[row].push(lednum);
} else {
grid[row].unshift(lednum);
}
lednum++;
}
}
return grid;
}
console.log(createGrid(10, 10))
Then you can just print out above grid
Update : How to print above data. You could simply use two for loops.
var length = 10;
var height = 15;
var brNode = document.createElement('br');
var grid = createGrid(length, height));
for (var row = 0; row < height; row++) {
var rowPrint = "";
for (var col = 0; col < length; col++) {
rowPrint += String(grid[row][col]) + " ";
}
var rowNode = document.createTextNode(rowPrint)
$("#container").appendChild(rowNode);
$("#container").appendChild(brNode);
}
Note that this will create rows of textNode broken by <br/> tags. if you want it formatted in some other way..well you have the preformatted data..all you need to do is traverse through it and print it how you want.
This general idea seems to work...
// Input variables
var data = 'abcdefghijklmnopqrstuvwxyz';
var width = 5;
// The actual algorithm.
var rows = Math.ceil(data.length / width);
for (var y = 0; y < rows; y++) {
var rowText = "";
for (var x = 0; x < width; x++) {
// Basically, for every other row (y % 2 == 1),
// we count backwards within the row, as it were, while still
// outputting forward.
var offset = y * width + (y % 2 == 1 ? width - 1 - x : x);
rowText += data[offset] || " ";
}
console.log(rowText);
}
$ node so51356871.js
abcde
jihgf
klmno
tsrqp
uvwxy
z
As I mentioned in comments, there is a lot wrong with the boolean logic in your code:
The first if condition always evaluates to true, except in the first iteration
The second if condition is therefor only evaluated once, and it will be false.
I would split the functionality in two parts:
Create a 2D array with the numbers in "snake" sequence
Create the DOM elements from such a matrix, using some CSS to control the line breaks
function createSnake(width, height) {
const numbers = [...Array(width*height).keys()];
return Array.from({length:height}, (_, row) =>
numbers.splice(0, width)[row % 2 ? "reverse" : "slice"]()); // 2D array
}
function createGrid(matrix) {
$("#grid").empty().append(
[].concat(...matrix.map(row => row.map((val,i) =>
$("<div>").addClass("grid").toggleClass("newline", !i).text(val))))
);
}
// Demo generating a 3 x 3 grid
createGrid(createSnake(3,3));
.grid {
float: left;
padding: 3px;
}
.newline {
clear:left
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grid"></div>

Why is my javascript code returning TypeError undefined? [duplicate]

This question already has answers here:
'Length' Property Undefined while iterating Array
(3 answers)
Closed 6 years ago.
class CustomTable
{
constructor(div_id, headings) {
this.div = div_id;
this.header_titles = headings;
this.item_list = new Array();
var _this = this;
this.add_item = function(items)
{
_this.item_list.push(items);
console.log(_this.item_list);
}
this.remove_item = function(item_index)
{
_this.item_list.splice(item_index, 1);
console.log(_this.item_list);
}
this.drawTable = function()
{
var t = "<table class='table' style='width:100%'>";
t += "<thead>";
t += " <tr>";
t += " <th>#</th>";
for (var i = 0; i < _this.header_titles.length; i++)
{ t += "<th>" + _this.header_titles[i] + "</th>"; }
t += " <th>Add</th>";
t += " </tr>";
t += "</thead>";
t += "<tbody>";
for (var i = 0; i < _this.item_list.length; i++)
{
t += "<tr>";
t += "<td>" + i + "</td>";
console.log(i);
var subitem_count = _this.item_list[i].length;
// ^^^^^^^^^^^^^^^^^^
// This errors out: TypeError undefined
for (var j = 0; j < subitem_count; i++)
{
t += "<td>" + _this.item_list[i][j] + "</td>"
}
t += "</tr>"
}
t += "</tbody>";
t += "</table>";
document.getElementById(_this.div).innerHTML = t;
}
}
}
var ct = new CustomTable("server_list",["Server Name","IP Address", "RAM in GB"]);
ct.add_item(["QMM-TRGEXCH01","192.168.0.225","2GB"]);
ct.add_item(["QMM-SRCEXCH01","192.168.0.226","2GB"]);
ct.add_item(["QMM-TRGAGENT01","192.168.0.227","2GB"]);
ct.add_item(["QMM-SRCAGENT01","192.168.0.228","2GB"]);
ct.add_item(["QMM-MIGCONSOLE","192.168.0.229","2GB"]);
ct.drawTable();
Please view this JSFiddle
I have searched everywhere and can't figure out why Javascript keeps erroring out. The variable is in scope and I have checked it using
_this.item_list[i].constructor === Array
and it is an Array.
I get this error at first iteration.
console.log(i); // i = 0 at error
So its not that the code is iterating out of bounds. That might be an issue with the code as well but there is something else wrong. Please look at the fiddle, I have updated it and remove the = from all for loops but I still get the same error.
It is because you are trying to invoke a method on element at unavailable index.
for (var i = 0; i <= _this.item_list.length
is supposed to be
for (var i = 0; i < _this.item_list.length
Array out of bounds issue - You are trying to access the element at index 6 which is undefined
As per your logic, if they are 5 elements in _this.item_list you are iterating elements at index 0, 1, 2, 3, 4, 5 but you should only be iterating upto 4 as the index starts at 0 and not 1
You will have to replace all instances of <= in your for-loop to <
Also your inner loop has a bug.
for (var j = 0; j < subitem_count; i++)
supposed to be
for (var j = 0; j < subitem_count; j++)
You should be incrementing j and not i in the inner loop.
Check Fiddle

Improve table rendering, fastest table render

So I have to render a table with 1000 rows and 1000 columns. Accordingly this link, it seems like the best way is to build the HTML string in javascript and then inserted it into the DOM all in one go. I made a simple example of this, and compare it with couple other methods. At the end, this is really the fastest way which I came out with. But still this is not satisfying enough. So my question is, is there a faster way, than the following example.
var startTime = new Date().getTime(),
tableString = "<table>",
body = document.getElementsByTagName('body')[0],
div = document.createElement('div'),
finalResult = 0,
endTime = 0,
result = 0;
for (row = 0; row < 1000; row += 1) {
tableString += "<tr>";
for (col = 0; col < 1000; col += 1) {
tableString += "<td>" + "testing" + "</td>";
}
tableString += "</tr";
}
tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);
endTime = new Date().getTime();
console.log(endTime - startTime);
A massive amount of string concatenation will get you into runtime trouble, no matter what language.
The fastet way will be to go through the native JavaScript DOM API, while constructing your table within a document fragment. At the end of your function, insert that document fragment at the desired position in your document.
Something like this will create a table with 1000 rows and 20 cells per row:
function makeTable() {
var fragment = document.createDocumentFragment();
for (var i = 0; i < 1000; i++) {
var row = document.createElement('tr');
fragment.appendChild(row);
for (var j = 0; j < 20; j++) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(i.toString() + ', ' + j.toString()));
row.appendChild(cell);
}
}
var target = document.getElementById('target');
target.appendChild(fragment);
}
JSFiddle: http://jsfiddle.net/KbNLb/4/
EDIT Just saw you did 1000x1000 - that is one million cells, that will be slow no matter what. I really hope on million table cells is not your actual use case. ;-)

Count numbers and output one char at time

I've tried hard, but I just can't figure it out.
I want to output numbers, but only one character of the number at time. I need to create something like this:
This should be created within a for-loop:
http://jsfiddle.net/jv7H8/
But as you can see there is more than one character in a cell when number > 10.
The desired result should be for example:
1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1, 1, 2, 1, 3, 1, 4....
Any suggestions? :)
First concatenate the numbers into a string:
var s = '';
for (var i = 1; i <= 42; i++) s += i.toString();
Then loop the characters in the string:
for (var i = 0; i < s.length; i++) {
// output s[i]
}
Here is your jsfiddle updated with my approach: http://jsfiddle.net/jv7H8/2/
The pertinent aspects that I changed was adding a for loop that processed through the length of the number you were going to output:
var str = number.toString(); // the current number as you're looping through
for (var k = 0; k < str.length; k++) {
var oneLetterAtATime = str.charAt(k); // get the digits one at a time
output += "<td>" + oneLetterAtATime + "</td>";
}
number++;
Edit: If you need there to only be nineteen columns, then you'll need to update your column counter for every instance where you are displaying another <td> but not looping back around to increment your column counter. I.e.,
if (k > 0) {
j++;
}
Here is an updated version displaying how this would work: http://jsfiddle.net/jv7H8/21/
Notably, there isn't a very good way to not go past the 19th column when you are in the middle of displaying a number in the 19th column that has more than one digit.
Take all the characters in a string like this:
var t = '';
var limit=100;
for (var j = 1; j<= limit; j++) t += j.toString();
var output='';
for (var j = 0; j < t.length; j++) {
output=output+','+t[i];
}
alert(output);
Please check your updated fiddle here
This will server your purpose.
Following is the code, most of it is your code only:
rows = 3;
columns = 19;
number = 1;
var str = "";
output = '<table style="width:100%;">';
for(var i = 0; i < rows; i++) {
output += "<tr>";
for(var j = 0; j < columns; j++) {
output += "<td>" + number + "</td>";
str +=number;
number++;
}
output += "</tr>";
}
output += "</table>";
$("#game").html(output);
var strvalue="";
$.each(str, function(e,v){
if (e > 0){
strvalue = strvalue + ", "+ v;
}
else{
strvalue += v;
}
});
alert(strvalue);

Categories