I want the sum not the string, how? - javascript

This gives me the string: "01234" instead of 1+2+3+4=10, why?
I'd like to get the sum of the numbers not of the string.
Thanks.
<script type="text/javascript">
var i=1;
var totale=0;
var index = Array();
var domanda = 0;
while (domanda !== "end") {
domanda = prompt("Write a number, the total so far is: "+totale);
index[i]=domanda;
totale += index[i];
i++;
}
document.writeln("total: " + totale);
document.writeln("ended");
</script>

Because prompt() (which you should not be using) returns a string.
Wrapping the return in a parseInt(domanda) would fix it.

You need to parseInt the value coming back from the prompt, otherwise you're concatenating strings.
index[i]= parseInt(domanda);
You'll probably want to check whether the input value is a number too.

Use JavaScript's built in parseInt, this creates an int of anything passed into it, so: parseInt(value);

Just like this:
index[i]=Number(domanda);
Full script
<script type="text/javascript">
var i=1;
var totale=0;
var index = Array();
var domanda = 0;
do {
domanda = prompt("Write a number, the total so far is: "+totale);
if (domanda !== "end" && !isNaN(Number(domanda)))
{
index[i]=Number(domanda);
totale += index[i];
i++;
}
} while (domanda !== "end")
document.writeln("total: " + totale);
document.writeln("ended");
</script>

Related

JavaScript - How would i add var into an array with prompts and get the average with a button

This is my code. I know that it is wrong but I need some help to start a prompt list. My goal is to get 4 marks with a button then you input and have it in an array. It then gets averaged and that gets shown with an alert.
<html>
<head>
<title>Quiz</title>
</head>
<body>
Average your marks
<button onclick="myFunction()">Start</button>
<script type="text/javascrypt">
var student = []
var student[0] = prompt("Name:");
var student[1] = prompt("mark=");
var student[2] = prompt("mark=");
var student[3] = prompt("mark=");
var student[4] = prompt("mark=");
var student[5] = student[1] + student[2] + student[3] + student[4] / 4;
function myFunction() {
if (confirm(student) == true)
}
</script>
</body>
</html>
i actually think you are almost there:
change every avArray to student. and the first time to var student = []
edit:
also write function instead of fuction
edit 2
finally: because you use var you define a variable. so only use var with var student = []
var student[0] is wrong because student is already defined. so use student[0] =
Because prompt always returns a string you want to use Number to make it a number that you can calculate with.
So your final code would look something like this:
var name = prompt("Name:");
var grades = [];
grades[0] = Number(prompt("mark="));
grades[1] = Number(prompt("mark="));
grades[2] = Number(prompt("mark="));
grades[3] = Number(prompt("mark="));
var average = (grades[0] + grades[1] + grades[2] + grades[3]) / 4;
function myFunction() {
confirm(name + ": " + average)
}
Average your marks:
<button onclick="myFunction()">Start</button>
You want to make sure that you are adding int values, not String values - which are the return result of prompt.
Try this:
// Forces the user to input an int by retrying until an int is input
function intPrompt(msg) {
while (true) {
var num = parseInt(prompt(msg));
if (!isNaN(num)) return num;
}
}
Now here's the code that will read 4 marks from the user and average them:
alert((intPrompt('mark 1') + intPrompt('mark 2') + intPrompt('mark 3') + intPrompt('mark 4')) / 4);
Quite a few errors, here are some I've spotted so far:
<script type="text/javascrypt">
Spell javascript correctly
var student[0] = prompt("Name:");
You use var only when defining the student the first time, remove it from the next appearances of student.
if (confirm(student) == true)
Student is an array, not a string. You will need to convert it to a string in some way to use it for confirm AFAIK.
var student[5] = student[1] + student[2] + student[3] + student[4] / 4;
I just tested this line out, and averaging doesn't work correctly, you need to prevent concatenation, maybe proper brackets.
Calculation of average is not the perfect one and you try to put everything into array, even if it does not belong there.
Check the example: http://codepen.io/anon/pen/rWxMEP
<html>
<head>
<title>Quiz</title>
<body>
Average your marks<button onclick=myFunction()>Start</button>
<script type="text/javascrypt">
let name;
let studentMarks = [];
const numOfMarks = 4;
let sumMark = 0;
let msg;
let myFunction = function() {
name = prompt("Name");
if (name.length !== 0){
for(i = 0; i < numOfMarks; i++){
msg = "Enter mark (" + parseInt(parseInt(numOfMarks)-parseInt(i) )+" left)";
studentMarks[i] = prompt(msg);
sumMark += parseFloat(studentMarks[i]);
}
alert(name + "'s average mark is "+ sumMark/numOfMarks);
}
}
</script>
</body>
</html>

Increment numbers at end of alphanumeric string in JavaScript

I have alphanumeric strings that will always end in a number, but which may have other numbers embedded early on.
I need to increment the numeric ending and return new ID numbers.
Example:
A48-DBD7-398
Which will be incremented in a loop:
A48-DBD7-398
A48-DBD7-399
A48-DBD7-400
How do I separate out the numeric tail from the rest of the string, and then save the two parts into different variables?
I found several other S.O. questions that split numbers out of a string, but they cannot handle mixed alphanumeric characters in the first part -- or else they split out ALL the numbers, regardless where they are. I need to get only the trailing digits.
Update
I found a case where my solution does not work:
ABC123-DE45-1
Duplicates as:
ABC2
ABC3
ABC4
JS Fiddle demo
If you are interested in a different approach you could do something like this:
$('button').click(function () {
var value = $('#in').val(); // get value
for (var i = 1; i <= 5; i++) {
value = value.replace(/(\d+)$/, function (match, n) {
return ++n; // parse to int and increment number
}); // replace using pattern
$('#result')[0].innerHTML += '<br>' + value;
}
});
My 2 cents: use regex to identify the pattern and increment the last part.
function incrementAlphanumeric(str) {
const numPart = str.match(/(0?[1-9])+$|0?([1-9]+?0+)$/)[0];
const strPart = str.slice(0, str.indexOf(numPart));
const isLastIndexNine = numPart.match(/9$/);
// If we have a leading zero (e.g. - 'L100A099')
// or there is no prefix - we should just increment the number
if (isLastIndexNine || strPart != null) {
return strPart + numPart.replace(/\d+$/, (n) => ++n );
}
// Increment the number and add the missing zero
else {
return strPart + '0' + numPart.replace(/\d+$/, (n) => ++n );
}
}
works with the following formats for example:
TEST01A06
TEST-100-A100
TEST0001B-101
TEST001A100
TEST001A91
TEST1101
TEST1010
1010
Demo Repl - https://repl.it/#EdoMagen/Increment-alphanumeric-string
Here is another solution, in case it helps
$('button').click(function() {
var ser = $('#in').val();
var arr = ser.split("-");
var num = parseInt(arr[arr.length - 1]);
arr.splice(-1, 1);
var str = arr.join ('-');
for (n = 1; n <= 5; n++) {
num++;
ser = str + '-' + num;
$('#result').html($('#result').html() + '<br>' + ser);
}
});
div{width:80%;margin-top:30px;background:wheat;}
<input id="in" type="text" value="ABC123-DE45-1" />
<button>Go</button>
<div id="result"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I figured it out, and am posting the question for future seekers.
JS Fiddle demo
HTML:
<input id="in" type="text" value="A48-DBD7-395" />
<button>Go</button>
<div id="result"></div>
js/jQ:
$('button').click(function(){
var ser = $('#in').val();
var num = parseInt(ser.match(/\d+$/));
var pos = ser.indexOf(num);
var str = ser.slice(0,pos);
for (n=1;n<=5;n++){
num++;
ser = str + num;
$('#result').html( $('#result').html() +'<br>'+ser);
}
});
const s = "A48-DBD7-398";
s.split('-').reduce((a,b)=>{
if(Number(b)){b = Number(b) + 1}
return a +'-'+ b;
})
> "A48-DBD7-399"

Calculate parseint with decimal

I found this in another post:
<script language='javascript'>
function AddInputs()
{
var total = 0;
var coll = document.getElementsByClassName('add')
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById('Display');
Display.innerHTML = total;
}
</script>
It works, but 1.50, 1.50, and 1.50 = 3 which isn't accurate. I'm new to JS (only know PHP), but I looked into it and figure it has something to do with parseInt since 1.50 isn't a whole number. Is there something I can replace parseInt with to calculate it so that the three 1.50 actually equals 4.50?
Try to use parseFloat() instead of parseInt()
Also use <script type="text/javascript"> instead of <script language="javascript"> that will be more standard and correct
parseInt will convert any decimal to an integer so parseInt(1.5) becomes 1. That is why parseInt(1.5) + parseInt(1.5) + parseInt(1.5) = 3. If you want it to equal 4.5 then just replace parseInt with parseFloat:
function AddInputs()
{
var total = 0;
var coll = document.getElementsByClassName('add')
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseFloat(ele.value);
}
var Display = document.getElementById('Display');
Display.innerHTML = total;
}
When you call parseInt on 1.50 you're getting the integer part of that value (1 in this case). Just replace parseInt with parseFloat and you'll get the value you expect.
Beside parseFloat you can also use Number to convert a string to a numeric value.
document.querySelector('#add').addEventListener('click', addNumber)
var total = 0;
function addNumber(e) {
total += Number(document.querySelector('#plus').value);
document.querySelector('#result').innerHTML = 'total: '+total.toFixed(2);
}
<input id="plus" type="number" placeholder="type a number"/>
<button id="add">add to total</button>
<div id="result"></div>

Get the next key from array from string with symbols

I'm working on a simple but difficult problem for me right now, I'm use to work in jQuery but need this to be done in Javascript.
So simple as it is, the user inputs a string lets say:
"hey, wanna hang today?". It should output the next character in my array, so it would be like this: "ifz, xboob iboh upebz?".
And I have tried everything I can come up with. Hopefully some of you guys see the problem right away.
I have set up a short jsFiddle that shows similar to what I got.
function gen() {
var str = document.getElementById('str').value,
output = document.getElementById('output');
var alph = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','æ','ø','å','a'];
for (var i=0;i<str.length;i++) {
var index = str[i].charAt(0),
e = alph.indexOf(index);
console.log(alph[e + 1]);
output.innerHTML += alph[e + 1];
}
}
If you only want to skip to next letter with those chars and leave the others like space and ? as they are:
var index = str[i].charAt(0),
e = alph.indexOf(index);
if(e == -1){
output.innerHTML += index;
}else{
output.innerHTML += alph[e + 1];
}
Update: using #David Thomas method, you could do the following: (wouldnt work for 'å' though)
var index= str[i].toLowerCase().charCodeAt(0);
if((index > 96 && index < 123)){ // a to z
output.innerHTML += String.fromCharCode(str[i].charCodeAt(0)+1);
}else{
output.innerHTML += str[i];
}
}
I'd personally recommend the following approach, which should work with any alphabet for which there's a Unicode representation and, somewhat importantly, doesn't require a hard-coded array of letters/punctuation for each language:
function gen() {
var str = document.getElementById('str').value,
strTo = '',
output = document.getElementById('output');
for (var i = 0; i < str.length; i++) {
strTo += String.fromCharCode(str[i].charCodeAt(0) + 1);
}
output.textContent = strTo;
}
// hey, wanna hang today? -> ifz-!xboob!iboh!upebz#
JS Fiddle demo.
References:
String.prototype.charCodeAt().
String.prototype.fromCharCode().
Why does gen(',') === 'a'?
var alph = 'abcdefghijklmnopqrstuvwxyz';
var e = alph.indexOf(',');
console.log(e);
// -1
console.log(alph[e + 1]);
// 'a'
You need to take this case into account; otherwise, any characters that aren't in alph will map to 'a'.
(I see that you've also duplicated 'a' at the start and end of alph. This works, though it's more common either to use the modulus operator % or to check explicitly if e === alph.length - 1.)
You just have to add an array with the non respected characters:
var ex = ['?','!',' ','%','$','&','/']
In whole
for (var i=0;i<str.length;i++) {
var index = str[i].charAt(0)
if (alph.indexOf(index) >-1) {
var e = alph.indexOf(index);
output.innerHTML += alph[e + 1];
} else {
var e = index;
output.innerHTML += e;
}
}
JSFIDDLE: http://jsfiddle.net/TRNCFRMCN/hs15f0kd/8/.

javascript storing array values

Im trying to get the total combined value of a set of numbers.
Im getting the numbers as the text in an element tag storing them in an array then adding them all together. My problem is that its not inserting the numbers into the array as pairs.. it adding them as single integers .what am doing wrong.
check the jsfiddle too see example
http://jsfiddle.net/Wd78j/
var z = $('.impressions').text();
var x = [];
for(var i = 0; i < z.length; i++){
x.push(parseInt(z[i]));
}
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
When you get text, it's taking all the numbers and concatenating them into a string. The below takes each element one at a time and pushes it.
var x = [];
$('.impressions').each( function( ) {
var z = $(this).text();
x.push(parseInt(z, 10));
})
Of course, you could build the sum up inside that each function, but I did it like this to more closely mirror your code.
text() returns the concatenated text of all of your impressions elements, of which you're adding together each character.
You want to loop through each impressions element, and keep a running sum going. Something like this should work
var sum = 0;
$('.impressions').each(function(){
sum = sum + (+$(this).text());
});
Updated Fiddle
Or to keep your original structure (don't forget the radix parameter to parseInt):
var z = $('.impressions');
var x = [];
z.each(function(){
x.push(parseInt($(this).text(), 10));
});
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
Updated fiddle
You are iterating over a string, you could just use $.map to build the array instead, if you need it, otherwise just iterate and sum up the values :
var x = $.map($('.impressions'), function(el,i) {return parseInt($(el).text(), 10);}),
total = 0,
n = x.length;
while(n--) total += x[n] || 0;
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
FIDDLE

Categories

Resources