I'm a JS learner and want to create an app that will calculate the average from input values. So far I've managed to push the entered input values into an array. However, when I want to display them, the previous value is repeated. So I'm near the end. But now I'm stuck. Can you lend me hand with that?
Enter
</button>
<p id="numbersEntered"></p>
<button id="avg" type="button">Average</button>
<p id="average"></p>
let numbersEntered = document.querySelector("#numbersEntered");
let inputEl = document.querySelector("#input");
// buttons
let enter = document.querySelector("#enter");
let numArr = [];
enter.addEventListener("click", displayNums);
function displayNums() {
let newNumber = inputEl.value;
numArr.push(newNumber);
console.log(numArr);
for (let i = 0; i < numArr.length; i++) {
numbersEntered.innerHTML += numArr[i] + ",";
}
}
You can just clear the innerHTML before appending;
function displayNums() {
let newNumber = inputEl.value;
numArr.push(newNumber);
numbersEntered.innerHTML = ""; //Clear the innerHTML
for (let i = 0; i < numArr.length; i++) {
numbersEntered.innerHTML += numArr[i] + ",";
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
Instead of appending numArr to innerHTML, simply overwrite it instead. Also, since you're only writing plain text, it is recommended to use textContent instead of innerHTML:
function displayNums() {
let newNumber = inputEl.value;
numArr.push(newNumber);
console.log(numArr);
numbersEntered.textContent = numArr.join(', ');
}
There is no need to use a for loop when you can use Array.prototype.join to print the array out.
Related
Here is my code can someone just explain why I am getting undefined?? I have split the words and then reverse them and after reversing I tried to store them in a different array.
Thank you
const text = document.querySelector("#text");
const reverseText = document.querySelector("#reverseText");
let words = text.innerHTML.split("").reverse();
console.log(words);
let reversedWords = [];
let counter = 0;
for (var i = 0; i <= words.length - 1; i++) {
if (words[i] != " ") {
reversedWords[counter] += words[i];
} else {
counter++;
}
}
console.log(reversedWords);
<p id="text">hello nixit</p>
<p id="reverseText"></p>
Your issue is that the first time you try and access reversedWords[counter], it is undefined because you've initialised reversedWords to be an empty array.
Without changing much of your code (because you said you're doing it this way as a challenge), you could try initialising reversedWords to have the appropriate number of elements, initialised to empty strings
const content = text.textContent;
const words = content.split("").reverse();
const reversedWords = Array.from({ length: content.split(" ").length }, () => "");
You're using an array so you need to push things into it, and then join it up into a new string once the iteration is done.
const text = document.querySelector('#text');
const reverseText = document.querySelector('#reverseText');
function reverse(str) {
// `split` the string on the spaces
const words = str.split(' ');
const reversedWords = [];
for (let i = 0; i < words.length; i++) {
// For each word split, reverse, and then rejoin it
const word = words[i].split('').reverse().join('');
// And then add the word to the array
reversedWords.unshift(word);
}
// Return the completed array
return reversedWords;
}
const str = text.textContent;
reverseText.textContent = JSON.stringify(reverse(str));
<p id="text">hello nixit</p>
<p id="reverseText"></p>
Additional documentation
unshift
I suggest using a string instead of an array. Then you can split it to turn it into an array.
const reversedChars = 'hello nixit'.split("").reverse()
const reversedWords = ''
reversedChars.forEach(char => {
reversedWords += char
})
const reversedWordsArray = reversedWords.split(' ')
console.log(reversedWords)
// Output: tixin olleh
console.log(reversedWordsArray)
// Output: [ 'tixin', 'olleh' ]
Thanks to #phil and #Andy,
I am new learner who will learn and read all the use of Array.from() and than use it, but till than I have made something like this.
const text = document.querySelector("#text");
const reverseText = document.querySelector("#reverseText");
let words = text.innerHTML.split("").reverse();
let reversedWords = new Array();
let counter = 0;
let firstChar = 0;
for (var i = 0; i <= words.length - 1; i++) {
if (words[i] != " ") {
if (firstChar === 0) {
reversedWords[counter] = words[i];
firstChar++;
} else {
reversedWords[counter] += words[i];
}
} else {
firstChar = 0;
counter++;
}
}
reversedWords.forEach(word => reverseText.textContent += word + " ");
<p id="text">hello nixit
<p>
<p id="reverseText">
<p>
I've been attempting to create a typing animation program that creates an animation of typing a word. Every period of time (1 second), it adds a letter to the output, seemingly "typing" the word out. Here is my code:
let input = document.querySelector("#input");
let text = document.querySelector("#text");
let run = document.querySelector("#run");
let str = input.value;
run.onclick = function() {
text.innerText = "";
str = input.value;
let chars = [];
for (let i = 0; i < str.length; i++) {
chars[i] = str.charAt(i);
}
for (let i = 0; i < chars.length; i++) {
setTimeout(function() {
text.innerText += chars[i];
}, 1000)
}
}
Here's one implementation using setInterval.
As Andy mentioned in the comments, just search and you'll find plenty of other implementations and answers here at SO.
const input = document.querySelector("#input"); // Custom text to animate
const text = document.querySelector("#text"); // Where animation is going to appear
const run = document.querySelector("#run"); // Initiate the animation
run.addEventListener("click", function() {
text.innerText = ""; // Clear the animation element before starting again
const str = input.value; // Get the custom text input value
const chars = str.split(""); // Split the text string value and add it to an array: "123" => ["1","2","3"]
const interval = setInterval(()=>{
if ( !chars.length ){
return clearInterval(interval); // Stop the animation once we're out of characters.
}
text.textContent += chars.shift(); // Remove the first character from the array and append it to the text display element
}, 100 );
});
<input id="input" value="Hello world" />
<p id="text"></p>
<button id="run">Run animation</button>
I'm working on a Racker Rank problem whose function in JavaScript receives a single parameter (input).
Input Format:
The first line contains an integer, (the number of test cases).
Each line of the subsequent lines contain a String.
I need to print the even-indexed and odd-indexed characters of each string (S) separated by a space on a single line (see the Sample below for more detail).
2
Hacker
Rank
Hce akr
Rn ak
Is there a way to read the input line-by-line and save each string in a specific variable? If I achieve that I know how to solve the problem by iterating through the string. Otherwise, I'm lost. If not, how else could I handle the input? Thanks!
Readline doesn't seem to be the way to go.
function processData(input) {
//Enter your code here
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
What I have tried without success:
function processData(input) {
let myArray = input.split("\n");
let even_indexed = "";
let odd_indexed = "";
for (let i = 1; i <= myArray.length; i++) {
let str = myArray[i];
let len = str.length;
for (let j = 0; j < len; j++){
if (j % 2 == 0) { //check if the index is even;
even_indexed.concat(str[j]);
}
else {
odd_indexed.concat(str[j]);
}
}
}
console.log("%s %s", even_indexed, odd_indexed);
}
Can't you just use split() method with a newline operator?
<script>
let x= `Hey
I'm
a
multiline
string`
console.log(x.split("\n"))
</script>
The result will be an array on which every element represents a line of your input.
I made this pretty quickly so I apologize for it being kinda messy and I know there are probably more efficient ways of doing this, but it does what you are asking for.
let input = `This
is
a
multiline
string`
let splitWords = [];
input.split(/\r?\n/).forEach(function(e){ // Split the array by \n (newline) and/or \r (carriage return)
currentLine = {evenIndex: [], oddIndex: []}
for(let i = 0; i < e.length; i++){
if((i + 1)%2 === 0){
currentLine.evenIndex.push(e[i]);
}
else{
currentLine.oddIndex.push(e[i]);
}
}
splitWords.push(currentLine);
});
splitWords.forEach(function(e){
console.log(e.oddIndex.join('') + " " + e.evenIndex.join(''))
});
This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 4 years ago.
I have made a piece of code that generates a random code of 12 characters. I am using Math.random and for-loops to do this. On the page you can write in an input how many codes you want.
What I want to do is save the generated codes in an array, however I can't do this because the for-loop and Math.random creates the code number by number and places them after each other. How can I add the whole 12 digit code to my array (so I can use it later)?
I've tried array.push with no luck. What works is outputting the numbers to DOM object in HTML, like this:
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
But that doesn't put the 12 digit code into a variable. I've also tried this:
var codeNumber = "";
codeNumber += mathRandom;
But that ends up in the variable value having only 1 digit.
<input type="number" id="numberOfCodes">
<button onclick="codeGen()">Generate</button>
<div id="result"></div>
<script>
var numberOfCodes = document.querySelector("#numberOfCodes");
var arr = [];
function codeGen() {
x = numberOfCodes.value;
for (a = 0; a < x; a++) {
generate();
console.log("Generated code");
}
}
function generate() {
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
var result = document.querySelector("#result");
result.innerHTML += mathRandom;
}
}
</script>
</div>
</body>
</html>
I expect the codes created (after some changes) to be added to the array, so that I can later use the codes on the page. Each individual 12-digit code needs to have its own place in the array.
This should work:
var result = [], stringResult;
for (i = 0; i < 12; i++) {
var mathRandom = Math.floor(Math.random() * 9);
result.push(mathRandom);
}
stringResult = result.join(''); // concatenates all the elements
console.log(stringResult);
The problem with your code is that + sign attempts to determine types of the operands and to choose the right operation, concatenation or addition. When adding stuff to innerHtml it treats the number as string. That is why it worked.
You'll want to refactor things so generating a single code is encapsulated in a single function (generate() here), then use that function's output, like this. (I hope the comments are enlightening enough.)
var numberOfCodes = document.querySelector("#numberOfCodes");
var resultDiv = document.querySelector("#result");
function codeGen() {
var nToGenerate = parseInt(numberOfCodes.value);
for (var a = 0; a < nToGenerate; a++) {
var code = generate(); // generate a code
// you could put the code in an array here!
// for the time being, let's just put it in a new <div>
var el = document.createElement("div");
el.innerHTML = code;
resultDiv.appendChild(el);
}
}
function generate() {
var code = ""; // define a local variable to hold the code
for (i = 0; i < 12; i++) { // loop 12 times...
code += Math.floor(Math.random() * 9); // append the digit...
}
return code; // and return the value of the local variable
}
<input type="number" id="numberOfCodes" value=8>
<button onclick="codeGen()">Generate</button>
<div id="result"></div>
As this answer shows, this should work for you:
function makeRandCode() {
var code = "";
var ints = "1234567890";
for (var i = 0; i < 12; i++) {
code += ints.charAt(Math.floor(Math.random() * ints.length));
}
return code;
}
console.log(makeRandCode());
The problem is that you are adding numbers and what you really want is to concatenate them, the solution is to transform those numbers into String, then save them in the variable where you want to store them. An example:
2 + 2 = 4 and '2'+'2'='22'
Just use .toString() before save it in to the variable.
here is the deal, i have the following jquery code that should add the array values to specific #id, buf it does not replace the code, only add more, and i need a little help to make it replace the html on othe link click.
Code:
function changeClass(curClass){
switch(curClass){
case "Schoolgirl":
case "Fighter":
var charSkillsNames = ["text1","text2","text4","text5"];
//loop show array values
listSkillsNames(charSkillsNames);
break;
}
}
function listSkillsNames(arr){
var length = arr.length,
element = null;
$("#skills").html(function(){
for (var i = 0; i < length; i++) {
element = arr[i];
$(this).append("<li>"+element+"</li>");
}
});
}
this works well but i need it to replace the html inside the "#skills" id when i click on the link that makes it work
PS: problem is really here
The issue is that you don't empty the HTML of #skills element. Use $("#skills").html("") to empty it.
function listSkillsNames(arr){
var length = arr.length,
element = null;
var $skills = $("#skills");
$skills.html(""); // empty the HTML
for (var i = 0; i < length; i++) {
element = arr[i];
$skills.append("<li>"+element+"</li>"); // append new items
}
}
The problem is because you are keep appending new items to the element always without removing the existing items.
Just empty the skill element, also there is no need to use the .html(function(){}) here
function listSkillsNames(arr) {
var length = arr.length,
element = null;
var $skill = $("#skills").empty();
for (var i = 0; i < length; i++) {
element = arr[i];
$skill.append("<li>" + element + "</li>");
}
}