'undefined' Unexpected on Array Loop + charAt - javascript

In this code I write line by line every word of the textarea, separated by white space, but on the last word undefined appears and I don't know why
window.onload = function() {
var btn2 = document.getElementById("separar");
btn2.addEventListener("click", function() {
palavrasSeparadas();
}, false);
}
var c = new Array();
function palavrasSeparadas() {
var t2 = document.getElementById("texto").value;
for (var i = 0; i < t2.length; i++) {
//charAt retorna o caracter daquela posição
c[i] = t2.charAt(i);
}
var conteudo = "";
for (var j = 0; j <= c.length; j++) {
if (c[j] != ' ') {
conteudo += c[j];
} else {
conteudo += "<br>"
}
}
document.getElementById("msgS").innerHTML = conteudo;
}
<form id="form1" name="form1" method="post" action="">
<textarea id="texto" name="texto"></textarea>
<br>
<input type="button" id="separar" name="separar" value="Separação">
</form>
<br>
<div id="msgS"></div>
<br>

Your loop goes one value too far. With j <= c.length in the last loop execution, when j = c.length, you try to access c at c.length. But as array index starts with 0, your array is only c.length-1 long. Use j < c.length in the loop.
for (var j = 0; j < c.length; j++) {
if (c[j] != ' ') {
conteudo += c[j];
}else {
conteudo += "<br>"
}
}

In your second for loop, you use less than or equal to rather than just less than. As such, you are also trying to print the index at c.length, which is undefined. Instead, you should write:
for (var j = 0; j < c.length; j++) {
if (c[j] != ' ') {
conteudo += c[j];
}else {
conteudo += "<br>"
}
}
This is a fencepost error.

Related

Multiplication Table in javascript and how about to align the row

I tried to a do Multiplication Table in JS and I want to print in <p> element out (Use DOM and not use document.write method).
I tried to use " " or "\t" to align column , but when number is double digit (from x3 column) , it got typographic issue.
Does it any ways could solve this problem?
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
for (var j = 1; j <= 9; j++) {
s = s + j + "*" + i + " = " + (i * j) + " ";
}
s = s + "<br>";
}
p1.innerHTML = s;
<pre id="printout"></pre>
Instead of printing table column wise, print row wise.
And wrap your each table in a div, so that aligning them becomes easy.
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
s = s + "<div>";
for (var j = 1; j <= 9; j++) {
s = s + i + "*" + j + " = " + (i*j) + "<Br/>" ;
}
s = s + "</div>";
}
p1.innerHTML = s;
Little bit CSS
#printout {
display:flex;
flex-wrap:wrap;
}
#printout div {
padding:10px;
min-width:100px
}
https://jsfiddle.net/wkg92rud/
Inspiring from #Andreas suggestion, Using <table>
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
let row = document.createElement("tr");
for (var j = 1; j <= 9; j++) {
let col = document.createElement("td");
col.innerText = j + "*" + i + " = " + (i * j);
row.append(col);
}
p1.append(row);
}
td {
padding: 2px 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<table id="printout"></table>
</body>
</html>
#Dalvik method is the correct way, styling and alignment should be done through CSS.
However, in other environments like command line, or if you are doing this as an exercise to learn JS you can use string padding, here is an example:
const p1 = document.getElementById("printout");
const LONGEST_ENTRY = 9; // Longest string you will have is 9 characters long
const entries = []
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
const entry = `${j}*${i} = ${(i*j)}`.padEnd(LONGEST_ENTRY, " ") ; // use string interpolation, then pad the string with spaces until the length of LONGEST_ENTRY is reached
entries.push(entry); // store all the entries in an array
}
entries.push("<br/>"); // add a line break at the end of each row
}
p1.innerHTML = entries.join(''); // join all the elements
Here is a jsfiddle as an example

How I can find specific words in the string and add class (Javascript)

There is a text in P element. In this text you can select some terms with a mouse click. But I want to display some previously selected words in a different class
I want to find special words in this text and add class.
Related part
var previosSelectedWords = 'aute,dolor,ex,sed,velit'; // previos selected words
var PSW = previosSelectedWords.split(',');
for (var i = 0; i < words.length; i++) {
if (PSW[i] == words[i]) {
wrapped.push('<span class="previosSelecteds">' + words[i] + '</span>');
} else {
wrapped.push('<span>' + words[i] + '</span>');
}
}
But it doesn't show the pre-selected words. What could be the reason?
The problem was your loop: You used the same loop and the same index for both arrays.
// Loop through each word and wrap
for (var j = 0; j < PSW.length; j++) {
for (var i = 0; i < words.length; i++) {
if (PSW[j] == words[i]) {
var prevS = '<span class="previosSelecteds">' + words[i] + '</span>';
words[i] = prevS;
}
}
}
for (var i = 0; i < words.length; i++) {
if (!words[i].includes('previosSelecteds')) {
wrapped.push('<span>' + words[i] + '</span>');
}
else {
wrapped.push(words[i]);
}
}

New line in an output tag in JavaScript

I'm trying to show a pyramid of stars in an output tag and I can't get a new line to appear after every row? The output tag has id "result" and i can get the error messages to work if a user doesnt insert a number.
function teken(){
var resultaat =document.getElementById("result");
document.getElementById("result").innerText = "";
if(isNaN(getal.value)){
document.getElementById("result").innerText = "Een GETAL als ingave aub";
} else if(getal.value>10 || getal.value<2){
document.getElementById("result").innerText = "Getal moet groter dan 2 en kleiner dan 10 zijn"
} else {
for(var i = 1; i<= getal.value; i++){
for(var j = 1 ; j<=i;j++){
resultaat.value += "*";
}
resultaat.innerHTML += "<br>"
}
}
Thanks in advance!
Per my comment above, I think you just need resultaat.innerHTML += "*" instead of .value. Here's a trimmed down version of your code (with that edit) that works:
var resultaat = document.getElementById("result");
var n = 5;
for (var i = 1; i <= n; i++) {
for (var j = 1; j <= i; j++) {
resultaat.innerHTML += "*";
}
resultaat.innerHTML += "<br>"
}
<div id="result"></div>

javascript function crashes my browser

I coded a simple program which take 2 textareas and combine every single line of one textarea with all the lines in the second textarea and my browser crushes after 6000 lines.
The resul of my check needs to get to 100,000 lines.
This is the javascript code:
function go() {
var lines1 = $('#text1').val().split(/\n/);
var lines2 = $('#text2').val().split(/\n/);
var textarea1 = [];
var textarea2 = [];
var textarea3 = [];
for (var i = 0; i < lines1.length; i++) {
if (/\S/.test(lines1[i])) {
textarea1.push($.trim(lines1[i]));
}
}
for (var j = 0; j < lines2.length; j++) {
if (/\S/.test(lines2[j])) {
textarea2.push($.trim(lines2[j]));
}
}
for (var k = 0; k < lines1.length; k++) {
for (var q = 0; q < lines2.length; q++) {
textarea3.push($.trim(lines1[k] + ' ' + lines2[q]));
var msg = textarea3.join("\n");
document.getElementById('text3').value = msg;
}
}
}
This is the HTML:
<textarea name="textarea" id="text1"></textarea>
<textarea name="textarea" id="text2"></textarea>
<input type="button" value="GO!" onclick="go()">
<br />
<textarea name="textarea" id="text3"></textarea>
The problem is with this code
for (var k=0; k < lines1.length ; k++) {
for (var q=0; q < lines2.length ; q++) {
textarea3.push($.trim(lines1[k] + ' ' + lines2[q]));
var msg = textarea3.join("\n");
document.getElementById('text3').value = msg;
}
}
If there are 1K lines in textarea1 and 1K in testarea2 then you will modify the DOM (by changing the value of textarea3) 1M times which is insane. So instead of updating the DOM every time try to do it outside the loop.
Try to provide maxlength attribute in textarea and then check I think it will work.
and in your for loops first store all the content in a variable and then outside for loop write it into textarea rather than each time assigning the DOM value inside for loop.

Populating multidimensional array

The code below came as an included file with a beginner puzzle app tutorial I'm working through. The code works, however now that I've completed the tutorial, I'm trying to read through the files that came preloaded which were not explained.
I'm really tripped up over the "spacecount" variable, and what exactly it's doing. Can anyone comment each line in plain english, so that I can better understand how exactly the code below is populating the rowCount array. Thank you so much.
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i]="";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols-1) rowCount[i] += spaceCount + " ";
} else {
if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}
Here's a slightly more legible version:
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i] = "";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols - 1) {
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}​
The confusing parts are probably the if blocks in the middle.
if (puzzle[i][j] == "#") { // If a puzzle piece is `#` (a space?)
spaceCount++; // Increment the spaceCount by 1.
if (j == totalCols - 1) { // Only if we are on the last column, add the text
// to the row.
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) { // If the current piece isn't a `#` but
// spaces have already been counted,
// add them to the row's text and reset `spaceCount`
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}​
From what I can tell, this code counts the number of consecutive pound signs and appends this text to each row.

Categories

Resources