Addition Assignment confusion, again JavaScript - javascript

According to Mozilla, the Addition Assignment operator
adds the value of the right operand to a variable
and assigns the result to the variable. The types of the two operands determine the behavior of the addition.
Here's the behavior of the addition:
If both expressions are numeric, then add.
If both expressions are strings, then concatenate.
If expression is numeric and the other is a string , then concatenate.
Basically, text+=i is the same as text = text + i; that is a fact.
Ok, if the above is true, then why in Code Version 2 below when I variable-ize the string "The number is " to the variable text,
doesn't it write the string each time with the new number as code version 1 does?
And for the answer I don't want another way to write it. I need to figure out why it doesn't work the same way if text+=i is the same as text = text + i.
I'm getting better at JavaScript every day, but believe it or not this simple += is holding me back from further understanding it because too many examples are using +=.
Here is the Code Version 1:
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
Here is the Code Version 2 with var text variable-ized with the string "The number is ":
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text ="The number is ";
var i;
for (i = 0; i < 5; i++) {
text = text + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

You are writing different code.
a = a + b is indeed the same as a += b.
var text = "";
text += "The number is " + i + "<br>";
Is the same as:
var text = "";
text = text + "The number is " + i + "<br>";
But it's not the same as:
var text = "The number is ";
text = text + i + "<br>";
Which is what you had.

For a question like this, it can be very helpful to use console.log to see what is happening.
var text ="";
var i;
console.log("First approach");
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
console.log("Iteration: "+i+" Text: "+text);
}
console.log("Second approach");
text ="The number is ";
for (i = 0; i < 5; i++) {
text = text + i + "<br>";
console.log("Iteration: "+i+" Text: "+text);
}
The code runs differently because in the first case you concatenate the entire string of "The number is ..." and in the second case, you initialize the string with "The number is " and then only concatenate the digits.

Related

How do I execute a for loop statement in javascript?

A pretty dumb question but I'm having trouble using a simple for loop, the i value is increased... I believe it is because the for loop has not met the required conditions.. but not sure what's going wrong
var text = "";
var i;
for (i = 0.0; i >= 5 / 360; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
What went wrong: it does not print out anything...
The problem is the condition becomes false in the first instance of the loop , 5/360 would be 0.013888 which is less than 0.0 , So it would not enter to append the text which you are trying to do. So the loop exists and the object text has only the initial value which was initialized.
For example , if you change the snippet as below it would generate a text:
for (i = 0.0; i <= 5/360 ; i++) {
text = text + "The number is " + i + "<br>";
}
The number is 0
So Kindly check the condition as per you requirement in order to generate text
The condition for your loop is that i >= 5 / 360, which is not true when the loop starts. I recommend i <= 5 / 360
++ increments by one. Since the expression to be evaluated is less than one, try incrementing by a lesser value using +=.
For example:
var text = "";
for (var i = 0.0; i <= 5 / 360; i+=.005) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
<div id="demo"></div>
For more info, see these JavaScript references:
for statement
addition assignment
for ([initialization]; [condition]; [final-expression])
Operator: x += y
Meaning: x = x + y
there are 3 conditions in for loop as
1.initial value ex i=0
2.until which value loop should iterates ex i<=10
3.should vale has to be increment ++ or to be decreases -- after each iterations
in above given condition middle condition is wrong, it gets false value from its 1st iteration hence it is not able to complete even 1st iteration
var text = "";
var i;
for (i = 0.0; i <= 5 / 360; i++) {
text += "The number is " + i + "<br>";
console.log(text)
}

user input output multiplication table

I need to make a multiplication table that displays the users input from 1-9, so if they enter 3 it will display the multiplication table for 3 from 1-9. it must do this with each number.
I have a for loop working for only 1 number and I dont know what else to do, I'm still really new to this so I'm not sure how to make it work for me.
prompt ("please enter a number");
var a = 1;
var b;
for (var i = 1; i <= 9; i++){
b= a*i
document.write("" + a + "*" + i + "=", + b +"<br>");
}
If I enter any number from 1-9 it must display the multiplication from 1-9 for that one number. Must work for each number entered.
the variable a should have the value received from the prompt and not 1
var a = prompt ("please enter a number");
var b;
for (var i = 1; i <= 9; i++){
b= a*i
document.write("" + a + "*" + i + "=", + b +"<br>");
}
You need to create variable for the prompt and add it inside your document.write
var question = prompt("please enter a number");
var a = 1;
var b;
for (var i = 1; i <= 9; i++) {
b = a * i
document.write(question + " " + "* " + i + " " + " = ", + b + "<br>");
}
You have to assign the return of the prompt function to your a variable.
Also, you have to cast this string value to a number to make sure your calculations are correct.
In the snippet below:
I wrapped the call to prompt with the Number function to get a number (MDN doc about Number).
I changed the var keywords to let and const as this is preferred over var, which declares global variables.
I replaced the string concatenation with a template string, which is easier to read when building complex strings (MDN doc on template literals).
const a = Number(prompt('please enter a number'));
for (let i = 1; i <= 9; i++) {
const b = a * i;
document.write(`${a} * ${i} = ${b}<br>`);
}

javascript replace string/html from array

I try to create a system replacement for ToolTip.
I already create a version but its not quite optimal (search a better way to do it)
here's a fiddle : http://jsfiddle.net/forX/Lwgrug24/
I create a dictionary (array[key]->value). the array is order by length of the key.
each key is a word or an expression, the value is the definition of the expression.
So, I replace the expression by a span (could/should be a div). The span is used for the tooltip (I use the data-title as tooltip text).
because some word is reused in expression, I need to remove expression already with tooltip (in real life think of father/grandfather, you dont want the definition of father inside grandfather). For replacement I use a ramdom value. That's the worst of this code.
You could make comment or post a new way to do it. maybe someone already did it.
Clarification :
I think my way to do it is wrong by using a string for replacement. Or it could be more secure. How should I do it?
html :
<div class="container">
one two three four five six seven eight nine ten
</div>
javascript :
$(function() {
var list = [
{'k':'one two three four five','v':'First five number.'},
{'k':'four five six seven','v':'middle number.'},
{'k':'six seven eight','v':'second middle number.'},
{'k':'two','v':'number two.'},
{'k':'six','v':'number six.'},
{'k':'ten','v':'number ten.'}
];
$(".container").each(function(){
var replacement = new Array();
for (i = 0; i < list.length; i++) {
var val = list[i];
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
replacement[rString + "_k"] = htmlEncode(val["k"]);
replacement[rString + "_v"] = htmlEncode(val["v"]);
var re = new RegExp("(" + val["k"] + ")","g");
$(":contains('" + val["k"] + "')",$(this).parent()).html(function(_, html) {
var newItem = '<span class="itemWithDescription" '
+ 'data-title="' + rString + "_v" + '">'
+ rString + "_k"
+ '</span>';
return html.replace(re, newItem);
});
}
for (var k in replacement){
$(this).html($(this).html().replace(k,replacement[k]));
console.log("Key is " + k + ", value is : " + replacement[k]);
}
});
$(document).tooltip({
items:'.itemWithDescription',
tooltipClass:'Tip',
content: function(){
var title = $(this).attr("data-title");
if (title == ""){
title = $(this).attr("title"); //custom tooltips
}
return title;
}
});
});
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
function htmlEncode(value){
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
I added a little thing. on the random function, I put a | and } for every char, its bigger but there's not much chance to have a conflic with an expression.
for (var i = length; i > 0; --i) result += '|' + ( chars[Math.round(Math.random() * (chars.length - 1))] ) + '}' ;
http://jsfiddle.net/forX/Lwgrug24/3/

I don't know how to fix my reverse array/string

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.

Splitting string 2 times with javascript

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')

Categories