I'm trying to use basic operators to create my own custom array in JavaScript, I guess.
This book I'm reading, "Eloquent JavaScript", has an exercise in Chapter 1 that asks me to make a pyramid using the "print" function. There's no print function in any of my interpreters, and it doesn't say how to make a print function. So, I don't have a print function, and I'm using alerts.
Here's the code.
var line = "";
var counter = 0;
while (counter < 10) {
line = line + "#";
print(line);
counter = counter + 1;
}
So, I was trying to use alerts, instead:
var line = "";
var counter = 0;
while (counter < 10) {
line = line + "#";
alert(line);
counter = counter + 1;
}
But the alert isn't a triangle. It's a bunch of boxes where the number of pound signs grows each time.
I want to create a string concatenation and then print out the entire result.
This is what I came up with:
string = "";
counter = 0;
signs = "#";
while (counter < 10){
string = string + signs + "\n";
signs = signs + "#";
counter = counter + 1;
}
alert(string);
So, I am just wondering, is there a better way to create arrays without knowing how to create array variable?
Your first pound-sign (tip of pyramid) should be spaced half the length of your base of your pyramid. So, if your base is 10 # signs long, then the top of your pyramid should be spaced out to 4 spaces then print the # sign.
Second, to make a true pyramid, you'll need to print top to bottom so your second row is progressively getting larger. Think in odd numbers:
// Example
Tip: 1 char
2nd row: 3 chars
3rd row: 5 chars
4th row: 7 chars
5th row: 9 chars
6th row: 11 chars
etc
Your newline character is wrong. It should be a \n. If printing to HTML, then use <BR>.
Alternatively, you can use console.log to print your characters.
The newline character is "\n" not "/n". (The "escape" character in general is backslash not forward slash.)
Also, you have a typo that you said sings = ... instead of signs = ...
EDIT: OK, so you've updated your question to correct both of those problems. Regarding your new question:
So, I am just wondering, is there a better way to create arrays
without knowing how to create array variable?
It sounds like you don't really understand what an array variable is: an array is a data structure that allows you to store data items that are selected by indices. Why do you think you need an array for this "pyramid" functionality?
As an aside, your code could be improved using += and ++:
a = a + b; can be abbreviated as a += b;
a = a + 1; can be abbreviated as a++;
This should work
var stringBuilder = "";
counter = 0;
signs = "#";
while (counter < 10){
stringBuilder = stringBuilder + signs + "\n";
signs = signs + "#";
counter = counter + 1;
}
alert(stringBuilder);
Newline is backslash and "n"
You need only one newline character that is within the loop
The following code should work:
string = "";
counter = 0;
signs = "#";
while (counter < 10){
string = string + signs + "\n";
signs = signs + "#";
counter = counter + 1;
}
alert(string);
The major differences are as follows:
You can't include the newline character in the string you are building, otherwise newlines from previous iterations will still be included in subsequent iterations.
The newline character is \n and not /n.
string can start off as being empty, since you will be appending a "#" each time.
This would be another way to do it:
<script>
string = ""; height = 10;
for(i = 1; i <= height; i++){
string += Array(i).join('#') + '<br>';
}
document.write(string);
</script>
Output:
#
##
###
####
#####
######
#######
########
#########
Now with some more modification:
<script>
string = ""; height = 10;
for(i = 1; i <= height; i++){
string += Array(height-i+1).join(' ') + Array(2*i).join('#') + '<br>';
}
document.write(string);
</script>
<style>body{font-family:monospace;}</style>
You get this:
#
###
#####
#######
#########
###########
#############
###############
#################
###################
Related
I'm trying to insert a randomly selected string into each instance of whitespace within another string.
var boom = 'hey there buddy roe';
var space = ' ';
var words = ['cool','rad','tubular','woah', 'noice'];
var random_words = words[Math.floor(Math.random()*words.length)];
for(var i=0; i<boom.length; i++) {
boom.split(' ').join(space + random_words + space);
}
Output comes to:
=> 'hey woah there woah buddy woah roe'
I am randomly selecting an item from the array, but it uses the same word for each instance of whitespace. I want a word randomly generated each time the loop encounters whitespace.
What I want is more like:
=> 'hey cool there noice buddy tubular roe'
Thanks for taking a look.
(This is beta for a Boomhauer twitter bot, excuse the variables / strings 😅)
Maybe you can use regex instead however, you are not seeing the result you desire because you are randomly selecting one word and then replacing all occurrences of a space with it.
The regular expression below replaces occurrences of a space with a dynamic value returned by a callback. You could compare this callback to your for-loop but instead, it's iterating over the spaces found and by doing so you can replace each occurrence with a 'unique' random word.
const boom = 'hey there buddy roe';
const words = ['cool', 'rad', 'tubular', 'woah', 'noice'];
const random = () => Math.floor(Math.random() * words.length);
let replace = boom.replace(/ /g, () => ` ${words[random()]} `);
console.log(replace);
The problem is, that random_words is set to a single word.
Try this instead:
var boom = 'hey there buddy roe';
var words = ['cool','rad','tubular','woah', 'noice'];
boom.replace(/ /g, (space)=> space + words[Math.floor(Math.random()*words.length)] + space);
To get the effect you desire, you need to do the word selecting inside the loop, not outside of it.
for(var i=0; i<boom.length; i++) {
// get a new number every loop
var random_words = words[Math.floor(Math.random()*words.length)];
boom.split(' ').join(space + random_words + space);
}
What is wrong with OP's code: random_words is initialized once only, with a random word. Intention there is, however, to select random word for every whitespace encountered instead.
You can either go with:
for(var i=0; i<boom.length; i++) {
boom.split(' ').join(space + words[Math.floor(Math.random()*words.length)] + space);
}
... or make random_words a function that returns a random word, then call it in your 'boom' loop. With every call, a new word selection will occur.
You need to recalculate the random word on each loop. Right now you have picked out a single random word, stored it in the random_words variable, and you reuse it each time. You could modify your code like this:
var boom = 'hey there buddy roe';
var space = ' ';
var words = ['cool','rad','tubular','woah', 'noice'];
function getRandomWord() {
return words[Math.floor(Math.random()*words.length)];
}
// Uses the same because the value given to join is not recalculated each time:
console.log(boom.split(' ').join(space + getRandomWord() + space));
// You could do this with a standard for loop:
let result = "";
let split = boom.split(' ')
for(var i=0; i<split.length; i++) {
result += split[i] + space;
if (i === split.length - 1) break;
result += getRandomWord() + space;
}
console.log(result);
// Or you can use a reduce:
let otherResult = boom.split(' ').reduce((res, word, index, split) => {
if (index === split.length - 1) return res + space + word;
return res + space + word + space + getRandomWord();
});
console.log(otherResult)
I would like to do something like this with JavaScript. This is my code for creating the first half:
<script>
var numberOfLines = 10;
var str = '*';
var space = ' ';
for (var i = 0; i < numberOfLines; i++){
document.write(str + '<br>');
str = str + "*";
}
</script>
How can I finish it?
You can use Array.join to create your repeated characters. Use a monospaced font to preserve the space width.
document.addEventListener("DOMContentLoaded", function(event) {
var output = "";
var numberOfLines = 10;
for (lineNum = 0; lineNum < numberOfLines; lineNum++) {
output += Array(lineNum + 2).join("*") + Array(((numberOfLines * 2) - (2 * (lineNum))) -1).join(" ") + Array(lineNum + 2).join("*") + "<br>";
}
document.getElementById("result").innerHTML = output;
});
#result {font-family: monospace;}
<div id="result"></div>
This is not perfect but very close:
var numberOfLines = 10;
var str = '*';
var arr = [" "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "];
var spaces = arr.join("");
for (var i = 0; i < numberOfLines; i++) {
document.write(str + spaces + str + '<br>');
str = str + "*";
arr.splice(-1,1);
arr.splice(-1,1);
spaces = arr.join("");
}
While simple in concept, there's actually a lot to consider when doing this, so lets analyze your code and build from there.
for (var i = 0; i < numberOfLines; i++) {
document.write(str + '<br');
str = str + "*";
}
this will loop through numberOfLines times. It will also output str numberOfLines times. Each loop, you're printing to the document; however, you would like to add a lot of spaces to str as well as a dynamic number of * characters before printing, and each time it will be a different number of spaces. Therefore, you either need to re-build str on each iteration of the loop, or build the entire string str prior to using document.write()
There are many different ways you can accomplish this, I'll go through two:
With a function
You can create a function to build each line. To do this, your function will need to know a few things:
How many lines will there be?
Which line are we currently on?
What character should you use for the visible parts of the triangle?
What character should you use for the invisible parts of the triangle?
So we can start by creating a function, we'll call it generateTriangleLine.
To generate a line, we will want to look at how many of the visible character we want to show, and how many of the invisible. Because there are two sides to this, we will want to output twice as many characters as the current line number:
function generateTriangleLine(visible, invisible, numberOfLines, currentLine) {
// Let's initialize the line so that it has no characters:
var line = '';
// We want to output twice as many characters as there are lines
// So we will loop from 0 to (but not including) numberOfLines * 2
for (var i=0; i<numberOfLines*2; i++) {
if (i<=currentLine || i>=(2*numberOfLines - currentLine - 1)) {
// If we are at the beginning, or the end of the line, we want to output characters.
// We want to add as many visible characters as the line number we are on!
// At the end of the line, 2*numberOfLines = 20. If currentLine starts at 0,
// we will want to draw one visible character, so we need to subtract one from this.
line += visible;
} else {
// If we aren't at the beginning or end, just add the invisible character.
line += invisible;
}
}
// And we want to return the line:
return line;
}
In our code, we can then loop through numberOfLines times, generating each line using our function:
for (var i=0; i<numberOfLines; i++) {
// We'll add a <br> to each line, so that it is drawn appropriately.
document.write(generateTriangleLine('*', ' ', numberOfLines, i) + '<br>');
}
If we run this, we'll get the appropriate output, but it won't necessarily be formatted correctly. This is because most fonts that you read on a daily basis have different widths for each character. The easiest way we can fix this is by wrapping our output in <pre> tags:
document.write('<pre>');
for (var i=0; i<numberOfLines; i++) {
// We'll add a <br> to each line, so that it is drawn appropriately.
document.write(generateTriangleLine('*', ' ', numberOfLines, i) + '<br>');
}
document.write('</pre>');
With a nested for loop to generate the entire output
The other approach we can take is exactly the same as with the function above, but instead of calling a function to generate each line, we generate each line within for loops, and then output everything at the end altogether:
// The first loop will be for each line.
for (var i = 0; i < numberOfLines; i++) {
// The nested for loop will be for each character on each line
// Remember, we have twice as many characters as we do lines
for (var x = 0; x < numberOfLines * 2; x++) {
// Just like we did in the function, we want to check
// if we're at the beginning or the end of the line
// Again, we subtract one from the end so that we still output at least one * on
// the first line.
if (x <= i || x >= (numberOfLines*2) - i - 1) {
// If we are at the beginning or end, output the *
str += "*";
} else {
// Otherwise, output the space
str += space;
}
}
str += '<br>';
}
Once again, we will get the correct output; however, we need to adjust for the letter widths so we can wrap our text in <pre> tags.
Keep in mind, there are numerous ways to solve problems with programming. I've only provided a couple of examples. I would highly encourage you to practice by coming up with your own way of doing this using the skills you learn from the various responses!
This question already has answers here:
How to remove spaces from a string using JavaScript?
(15 answers)
Looping through array and removing items, without breaking for loop
(17 answers)
Closed 6 years ago.
I created a function to delete the spaces out of a string and return the strings length with out spaces, however the function is deleting more then just the spaces. Also is there a better way of accomplishing this, assuming this function can be fixed.
let string="This string is going to lose characters";
function charLength(str){
let strArray=str.split("");
let output="";
for(let i=0; i < strArray.length; i++){
if(strArray[i]===" "){
strArray.splice(strArray[i],1);
}
else{
output+=strArray[i];
}
}
return output.length // + " " output, if I were to add this you would see its deleting characters
}
charLength(string);//returns "27 Thistringsoingooseharacters", not "33 Thisstringisgoingtolosecharacters"
When you remove a character from the string you'll have to go back one step (i--) st the loop won't skip a character (for(... ; i++)). Like this:
if (strArray[i] === " ") {
strArray.splice(strArray[i], 1);
i--; // ge back one step if we remove one character.
}
Snippet:
let string = "This string is not going to lose characters";
function charLength(str) {
let strArray = str.split("");
let output = "";
for (let i = 0; i < strArray.length; i++) {
if (strArray[i] === " ") {
strArray.splice(strArray[i], 1);
i--;
} else {
output += strArray[i];
}
}
return output;
}
console.log(charLength(string));
If you want to count characters that are not spaces:
Then just make a counter that will count the characters that are not spaces like this:
let string = "This string is not going to lose characters";
function charLength(str) {
let counter = 0; // the counter
for (let i = 0; i < str.length; i++) { // for each character in the string
if(str.charAt(i) !== ' ') // if the character is not a space
counter++; // increment the counter
}
return counter;
}
console.log(charLength(string));
The reason why characters get lost, is because the list is modified inside the loop.
for(let i=0; i < strArray.length; i++){
if(strArray[i]===" "){
strArray.splice(strArray[i],1); // Items are removed here
...
When you remove an character i, the next character will take its place.
You could maybe use the replace function instead like this:
string.replace(/ /gi, "").length
Use regex.
var str = 'This string is going to lose characters';
// The substituted value will be contained in the result variable
const result = str.replace(/\s/g, '');
console.log('Substitution result: ', result.length);
You don't need a regex: str.replace(" ","") is already doing that.
Instead of this line here:
strArray.splice(strArray[i],1);
Try using this:
strArray.splice(strArray[i],0);
Just replaces the 1 with 0
This is much simpler than you are doing. You can just use the .replace() string method which can take a string literal to replace or a regular expression.
function charLength(str){
// Create a new string that is the same as the passed in one, but with the spaces stripped out
// The syntax / / denotes a regular expresion (regEx) object
// The s+ denotes to look for one or more spaces in a row
// The g denotes a global search and replace througout the string
var newStr = str.replace(/\s+/g, "");
console.log("\"" + str + "\" has: " + str.length + " characters.");
console.log("\"" + newStr + "\" has: " + newStr.length + " characters.");
}
charLength("This string is going to lose characters");
You could use eiter a regular expression for filtering space
var string = "This string is going to lose characters",
result = [...string].filter(RegExp.prototype.test.bind(RegExp('[^ ]'))).join('');
console.log(result);
console.log(result.length);
Or just test for space.
var string = "This string is going to lose characters",
result = [...string].filter(a => a !== ' ').join('');
console.log(result);
console.log(result.length);
so I need to be able to enter a string and have it reversed. I must have one library JS file and one regular JS file. Here is my library JS file:
function reverseString(string) {
var reversedString= "";
for(var i = string.length -; i >=; --i) {
reversedString = reversedString + string[i];
}
return reversedString;
}
and here is my regular one
var stringEntered = prompt("Enter a string:")
var newString = reverseString(stringEntered);
document.write("the reverse of the string \" + stringEntered + \ " is \" + newString + ".")
I entered it the exact same way my professor showed us, and I when I try to run my HTML file (which is coded to call both these files), nothing happens. What am I missing?
There're a lot of syntax issues. Here's a working code:
function reverseString(string) {
var reversedString = "";
// This loop had a lot of basic syntax issues and also
// "i" was starting from the length value, while a string
// is a character array and array indexes start from 0 instead of 1
for (var i = string.length - 1; i >= 0; --i) {
reversedString = reversedString + string[i];
}
return reversedString;
}
var stringEntered = prompt("Enter a string:");
var newString = reverseString(stringEntered);
// Here I found a mess of "/" characters
// I've changed the horrible document.write with alert so you can check the result without opening the debugger...
alert("the reverse of the string " + stringEntered + " is " + newString + ".")
Here is a concise method of reversing a string:
function reverseString(string) {
return string.split('').reverse().join('');
}
var str = prompt("Enter a string", "a racecar dad");
alert(reverseString(str));
Turn it into an array, reverse the array, turn it back into a string.
Edit: Sorry, didn't see #SidneyLiebrand's comment telling you to do the same.
I am trying to break up this string by first splitting it into sections divided by ';'. Then I want to split those sections divided by ','. It is not working though and I am about to break my computer. Could someone please help me figure this out.
You can play around with my jsfiddle if you want... http://jsfiddle.net/ChaZz/
var myString = "Call 1-877-968-7762 to initiate your leave.,-30,0,through;You are eligible to receive 50% pay.,0,365,through;Your leave will be unpaid.,365,0,After;";
var mySplitResult = myString.split(";");
for(i = 0; i < mySplitResult.length -1; i++){
var mySplitResult2 = i.split(",");
for(z = 0; z < mySplitResult2.length -1; i++) {
//document.write("<br /> Element " + i + " = " + mySplitResult[i]);
document.write("<br/>Element" + z + " = " + mySplitResult[z]);
}
}
i is a number, as that's how you defined it.
To split the string, you need to access the i member of the Array.
var mySplitResult2 = mySplitResult[i].split(",");
If I may, if you have to split with character a then character b, the simplest would be :
string.split('a').join('b').split('b')