How to multiply a variable? - javascript

<script type = "text/javascript">
//Add spaces between menu links
//Placement: Global Header
//Coded by Game
var spaces = "2"; //Edit number of spaces between menu links (1,2 or 3)
var a = document.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].parentNode.parentNode.className == "menubg" && a[i].innerHTML.match(/Home|new topics|help|search|members|calendar|admin|profile|logout|register|login/i)) {
if (spaces == "1") {
a[i].innerHTML += " ";
}
if (spaces == "2") {
a[i].innerHTML += " ";
}
if (spaces == "3") {
a[i].innerHTML += " ";
}
}
}
</script>
The code above is meant to let the useer add spaces between their menu items. It works fine. But how do I make it to where they can add as many spaces as they would like, instead of limiting them to 3? Maybe somehow they would add their number in the var 'spaces' and the code would multiply &nbsp by that numvber?

Just use a loop:
var spaces = 2;
[..]
for(var i = 0; i < spaces; ++ i)
a[i].innerHTML += "&nbsp";

I would generate the string in a separate method, like:
function getSpaces(count) {
var spaces = "";
for(var i = 0; i < count; i++) {
spaces += "&nbsp";
}
return spaces;
}
and then
a[i].innerHTML = getSpaces(2); //etc
This way you set innerHTML and access the array only one time, and also don't have repeated code.

Avoid innerHTML if you can, since it deletes and recreates the entire content of the element. Prefer appendChild and createTextNode instead. For instance:
a[i].appendChild(document.createTextNode(new Array(spaces + 1).join("\u00A0")));

Why don't you just create a loop inside your if clause that adds an every time you go through the loop?

Related

How do I print a list of elements in array in JavaScript?

I'm very new to JavaScript and am trying to solve this challenge. I want to print out "A" on the first line, then "AB" on the second, then "ABC" on the third, until I print out "A....Z". Also, when I get to E, I want to replace it with 3. So far, I have created an array containing all the letters. I started with a for loop, but haven't gotten far. Any help would be appreciated!
Here you are:
var array = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
for (var i = 0; i < array.length; i++) {
var str = '';
for (var j = 0; j <= i; j++) {
if (array[j] == 'E') str += '3';
else str += array[j];
}
document.querySelector('span').innerHTML = document.querySelector('span').innerHTML + str + '<br />';
}
<span></span>
Hope this helps.
Go simple in the first draft. Save all the alphabets in an array. Use for loop to print. And print "3" for every fifth looping.
If your array is named ar then i think you can do this
for(var i = 0;i<ar.length;i++){
for(var j = 0;j<=i;j++){
if(ar[j]==='E')
ar[j]='3';
console.info("---->>"+ar[j]);
}
console.log("");
}

Eloquent Javascript: Chessboard

Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess board.
My code keeps creating an 8 x 8 structure with all hashes.
Can someone offer some advice to edit my code?
var size = 8;
var str = "";
var altern = false;
var line = 1;
while (line <= size) {
var character = 1;
while (character <= size) {
if (altern) {
if (character % 2 === 0) {
str += "#";
console.log(character);
console.log(str);
} else {
str += " ";
console.log(character);
console.log(str);
}
} else {
if (character % 2 === 0) {
str += " ";
console.log(character);
console.log(str);
} else {
str += "#";
console.log(character);
console.log(str);
}
}
altern = !altern;
character++;
}
str += "\n";
line++;
}
console.log(str);
By using both altern and character % 2 you select the branch with the # every iteration. Use only one of the two.
I couldn't figure out how to answer this myself until I found OP's code. Here is what I found would work:
var size = prompt("What is the size?");
var str = "";
var line = 0;
//Instead of using 1, use 0. It'll make sense in the next comment.
while (line < size) {
var character = 0; // Changed this to 0 as well.
while (character < size) {
if (line % 2 === 0){
/*Instead of using logic negate(altern = !altern), you could use one of the variables
you already have. Changing line = 1 to line = 0, we now can write the conditon above.
Where the first line holds true, because 0 % 2 === 0 is true.*/
if (character % 2 === 0) {
str += " "; // I switched the string values around, to get what is resembled in the book.
console.log(character);
console.log(str);
} else {
str += "#"; // Here
console.log(character);
console.log(str);
}
} else {
if (character % 2 === 0) {
str += "#"; // Here
console.log(character);
console.log(str);
} else {
str += " "; // Here
console.log(character);
console.log(str);
}
}
character++;
}
str += "\n";
line++;
}
alert(str);
//Changed this so the final result is easier to see, rather than in the jumbled mess of the console.
I suspect that you want to toggle altern with each new line, not with each square.
You have a loop inside a loop here. Move your altern toggle code from the inner loop to the outer loop.
while (line <= size) {
var character = 1;
while (character <= size) {
// inner loop code here
character++;
}
// Outer loop end code. HERE is where you toggle altern
str += "\n";
line++;
altern = !altern;
}
Below one works but I replaced spaces with Os (capital o's) and a little change in your code.
var size = 8;
var str = "";
var altern = false;
var line = 1;
while (line <= size) {
var character = 1;
while (character <= size) {
console.log('altern: ' + altern + 'character: ' + character);
if (altern) {
if (character % 2 === 0) {
str += "O";
console.log(character);
console.log(str);
} else {
str += "#";
console.log(character);
console.log(str);
}
} else {
if (character % 2 === 0) {
str += "O";
console.log(character);
console.log(str);
} else {
str += "#";
console.log(character);
console.log(str);
}
}
altern = !altern;
character++;
}
str += "\n";
line++;
}
// console.log(str);
alert(str);
This one works, but not, I suggest you to try to re-write this code in a better way. Hint: pay attention to what #koenpeters said.
Instead of using all those loops you could do this:
var width = 8,
height = 8,
str = new Array(1 + (width * height + height) / 2).join('# ').replace(new RegExp('(.{' + width + '}).', 'g'), '$1\n');
Works as long as width isn't even while at the same time height is odd.
If you just need it for this one specific case you could also get rid of a bit of the overhead and just use this:
var str = new Array(37).join('# ').replace(/(.{8})./g, '$1\n')
Instead of a while loop and over-repetition of your cases based on location (i.e. even vs odd) use two for loops and one case statement for whether a location needs a # vs " ". Store them to a var, then print the var once it is complete.
var board = "";
var countX = 0;
var countY = 0;
var size = 8;
for(var i = 0; i < size; i++) {
for(var j = 0; j < size; j++) {
if((countX + countY) % 2 == 0) {
board += " ";
}
else {
board += "#";
}
countX++;
}
board += "\n";
countY++;
}
console.log(board);
board output:
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
i would have tackle this problem by first using a while loop to printing out a line of 8 harsh (########) symbol , then repeat it 8 times vertically using another loop, write a test condition that changes the value of y when the value of both iteration are even numbers.
const size = 8
for(let i = 0; i < size; i++){
let y = " "
let cols = 0;
if(i % 2 == 0){
y = "";
}else{
y = " ";
}
while(cols < size){
if( cols % 2 == 0){
y = y + "#"}
else{
y = y + " "
}
rows++
}
console.log(y)
}
Nested For Loop will work the best for this solution as below ---
//to get the input from the user for any size of the array
var charSize=prompt('Enter Number');
var boardChar = "";
//outer loop
for (let i = 1; i <= charSize; i++) {
//inner loop
for (let j = 1; j <= charSize; j++) {
//Check for even column
let evenCol = (i + j) % 2;
if (evenCol == 0) {
boardChar += " ";
} else {
boardChar += "#";
}
}
boardChar += "\n";
}
console.log(boardChar);
//OUTPUT
[Output Image][1]
The essential thing to realise is that given the N th row, its first square will be black if N is odd, and white otherwise.
Also, if the first square of a given row is black, then for a given column M, the square will be black if M is odd, and white if M is even.
Similarly, if the first square is white, then for a column M, the square will be white if M is odd, and black otherwise.
Hope that helps.
EDIT:
try this if you’re a fan of unreadable code:
for i in range(8):
s = ''
for j in range(8):
if (i - j%2) % 2 == 0:
s = s + "#"
else: s = s + 'O'
print s
I also learn JavaScript currently. I was stuck on that for one day. The only thing, that I realize, that if you want to do something useful in JavaScript use loops.
I don't have an idea about complicated coding, but loops could easily do things, that seems at first to be complicated.
Here is my version:
let b = "" //**just create an empty string, because if you won't do that, loop will print out symbols, numbers etc in a single column, but if you use empty string you can in future write symbols inside that string, which allows you to expand string horisontally
let size = 8 //**since loops start at 0 to infinity, you must take it into account,
for (let i = 0; i < size; i++) //**create first loop --> (; ; ). As you can see inside body of loop (the expression, that will be executed until loop is valid) I have just b = b + "#", which means, that my first "for" loop will do looping :) 8 times and will store inside "b" variable THE LAST VALUE (it will be ########), you can check this out in a single sheet (and you will see, that this looping is still going vertically, but the point is that it stores the LAST VALUE)
{ b = b + "#"} //**that is the body of first loop which is described clearly above
for (let a = 0; a < size; a++) //**inside second loop, we create the same routine, and proceed inside that loop with value of "b" from first loop. Notice, that first loop is enclosed {}, so it act independantly.
{
if (a % 2 == 0) //**just condition, which allows us to distribute different strings (rows) of code (I hope you understand what is inside parenthesis
{console.log (" " + b)} //**Since we want to see our chessboard we should print this out onto screen, for that we use "console.log" but again, notice, that here WE DON'T change value of variable "b", we just operate with it, but it will stay the same "########"
else{
console.log (b)} //** And if "if" fails, we will proceed with "########" value, which is NEW origin of "b" variable
}

Print range using for-loop JavaScript

I need to print a range of numbers in a range using a function and a for-loop.
Again I'm stuck on the return value. I believe my code is sufficient for the task but if you have a better idea I'm all ears.
function printRange(rangeStart, rangeStop) {
var text = "";
for (var i = rangeStart; i < rangeStop; i++) {
text += i + ',';
}
return text;
var result = text;
}
printRange(20, 47);
The 'result' is ought to print the numbers 20,21,22...,46,47 but of course it doesn't...
Any help is appreciated.
Regards, Thomas
There are two things you need to fix - your code doesn't print rangeStop, but it does include a trailing comma.
You can fix the former by changing your loop end condition to use <=, and String.prototype.slice can do the latter.
function printRange(rangeStart, rangeStop) {
var text = "";
for (var i = rangeStart; i <= rangeStop; i++) {
text += i + ',';
}
return text.slice(0, -1);
}
document.write(printRange(20, 47));
function printAllNum(rangeStart, rangeEnd){
for(let i = rangeStart; i <= rangeEnd; i++) {
document.write(i + " ")}
}
printAllNum(1,20);

Javascript slice method testing issue

another Javascript newbie question here. Suppose I get an alert if there isn't any space in the input string. but I don't get any alert at all. I got this code block from a book and trying to learn by doing in jsfiddle. Am I missing something here? thank you!
var str = prompt("enter some text");
var numChars = str.length;
for (var i = 0; i < numChars; i++){
if (str.slice(i, i + 2 ) === " ") {
alert("no double spaces");
break;
}
}
http://jsfiddle.net/5ruW2/
If you change the if statement to check for double spaces, with two spaces between the quotes, and change the alert to read "Double Spaces!" it works.
var str = prompt("enter some text");
var numChars = str.length;
for (i = 0; i < numChars; i++) {
if (str.slice(i, i + 2) === " ") {
alert("Double Spaces!");
}
}

How do I count letters in JavaScript?

I have written this function (which is not working) which is supposed to count the letters in a global variable (paraText), and then insert it to count. How do I solve this?
This is a school project so I have to follow sertain rules. I have tried almost all answers but I can't get it to work :( maybe if you look at all the code you can see what I'm doing wrong.
"use strict";
var paraText = "";
var antalParagrafer = 0;
function addLetter(c) {
if(!paraText) {
addParagraph();
}
else { //add c to saved textnode
var tNod = document.createTextNode(c);
paraText.appendChild(tNod);
}
}
//function is called when enter is pressed
function addParagraph() {
/*create a new paragraph with related textnode
textnode is saved to the global textnodevariable
add paragraph to the div with id "output"
you also need to mark the paragraph with the class even/odd
depending on the class of the previous paragraph*/
var div = document.getElementById("output");
var nyParagraf = document.createElement("p");
div.appendChild(nyParagraf);
antalParagrafer += 1;
nyParagraf.className = (antalParagrafer % 2 === 0 ? 'even' : 'odd');
paraText = nyParagraf;
}
//function is called when count letters is pressed
function countLetters() {
var count=0;
for(var i = 0; i < paraText.length; i++) {
var c = paraText.charAt(i);
if (c >= 'a' && c <= 'z') count++;
}
return count;
}
I'd just strip out the non-letters and then use the length of what's left:
var count = paraText.replace(/[^a-zA-Z]/g, '').length;
Your function works otherwise fine (although it's perhaps not as elegant as it could be), but count = count ++ is wrong; either use
count++;
or
count = count + 1;
The statement count = count++ doesn't increase the counter, because the value of count++ is what's in the variable before it is increased, so you increse the variable, then assign back the value that was before.
Using a simple comparison gives better performance than using a regular expression for each character in the string:
function countLetters() {
var count=0;
for(var i = 0; i < paraText.length; i++) {
var c = paraText.charAt(i);
if (c >= 'a' && c <= 'z') count++;
}
return count;
}

Categories