JavaScript: innerHTML outputs undefined, although console.log outputs the right value - javascript

I am trying to make a calculator app in JS, and I am struggling with the sine and cosine functions.
The line before
document.getElementByID("screenPar").innerHTML = result;
is
console.log(result);
, and in the console, the correct value shows up, however on the calculator's screen, it says undefined. My function:
function calcSin(){
try{ //Checks for syntax errors
if(calcString[calcString.length-1] == "+" || calcString[calcString.length-1] == "-" || calcString[calcString.length-1] == "*" || calcString[calcString.length-1] == "/"){
throw "Syntax Error"
}
}
catch(err){
document.getElementById("screenPar").innerHTML = err;
return 1;
}
if(calcString[calcString.length-1] == "$"){ //If last character in string is '$', clears screen
clearScreen();
document.getElementById("screenPar").style.color = "black";
}
else{
var evalRes = eval(calcString);
console.log(evalRes + typeof evalRes);
var result = Math.round(Math.sin(evalRes));
console.log(result + typeof result);
clearScreen();
console.log(result);
document.getElementById("screenPar").innerHTML = result;
}
}
calcString is a string of the inputted expression, for instance "3*4*5".
The console outputs the correct value, but innerHTML puts undefined in the paragraph.
I uploaded the code to a free hosting site: brokenCalculator.
What am I missing?

The function you've shown is fine. Something else replaces the screenPar value to undefined.
P.S. Use .textContent instead of .innerHTML unless you desire to add a text as an HTML code.

<button onclick="addToCalcString(calcSin())"...>
Above onclick event you are calling function inside a function. When you click, 1st the calcSin() is getting called and below line is executing fine
document.getElementById("screenPar").innerHTML = result;
But after that the addToCalcString(char) is executing, in which calcString is undefined
document.getElementById("screenPar").innerHTML = calcString;

Related

Finding subString in String

I'm trying to find the substring in string using O(N) complexity. The following is the code I have written. It returns undefined and I don't know why. Please let me know what is going wrong in my code.
let omg = "omg";
let omgi = "omjiklmonomgib";
function stringSearch(smallString, bigString) {
let left = 0;
let right = left+(smallString.length - 1);
while (left > right) {
if (smallString[left] === bigString[left]) {
if (smallString[right] === bigString[right]) {
left++;
right--;
if (left === right) {
if (smallString[right] === bigString[left]) {
return true;
} else if (right === left + 1) {
if (smallString[right] === bigString[right] && smallString[left] === bigString[left]) {
return true;
} else {
left = right + 1;
right = left + (smallString.length - 1);
}
}
}
}
}
}
}
console.log(stringSearch(omg, omgi)); //Undefined
From what I understand, you're just remaking String.prototype.match. Try checking this out, as it would probably be an easier way to do what you're saying. Sorry, missed the O(N) complexity part.
If you really wanna make a custom one, I can give you some tips.
First of all, you should have a "cache" variable (one for all, not left and right) and another variable which will be found (it'll be a boolean, so set it to false). The "cache" variable will store the text, and the other one will store whether you found the smallString.
Basically, you loop through every character and store however long smallString characters in the "cache" variable. Once the "cache" variable is the same length as smallString, run an if statement on it. If it's not equal to the smallString, remove the first character of the "cache". Next iteration in the loop, it'll add another character. You then do the same as before, run an if statement and if it's not equal remove the first character and continue the loop until you find it, or the string ends. If you found it, set the boolean to true.
Something like this:
function stringSearch(smallString, bigString, caseSensitive=true) {
if(!caseSensitive) { // if caseSensitive is false, make everything lower case
smallString = smallString.toLowerCase();
bigString = bigString.toLowerCase();
}
let cache = ""; // string cache
let found = false; // result
for(i=0;i<bigString.length;i++) { // loop through every character in bigString
cache+=bigString[i]; // add the current character to the cache
if(cache.length == smallString.length) { // check if the cache's length is the same as the smallString's length
if(cache == smallString) { // check if the cache is equal to the smallString
found = true; // set found to true
break; // break the loop (stop it from going on)
} else {
cache = cache.substring(1); // set cache to itself but remove the first character
}
}
}
return found; // return result
}
// example:
console.log("String 'hello, world' has 'hello': "+stringSearch("hello", "hello, world"));
console.log("String 'HELLO WORLD' has 'hello': "+stringSearch("hello", "HELLO WORLD"));
console.log("String 'HELLO WORLD' has 'hello' (not case sensitive): "+stringSearch("hello", "HELLO WORLD", false));
console.log("String 'hey hi hello WORLD' has 'hello': "+stringSearch("hello", "hey hi hello WORLD"));
console.log("String 'hey hi hello' has 'hello': "+stringSearch("hello", "hey hi hello"));
console.log("String 'hey lol o' has 'hello': "+stringSearch("hello", "hey lol o"));
I see a couple of issues. First, the code doesn't have a return statement for every logical branch. I mean that, for every condition in an if, then, else statement, the code should have a return statement or some sort of control-flow statement (e.g. a recursive call or a continue) that will eventually lead to a return statement.
The second issue is the while loop. Supposedly, right should be greater than left from the beginning of the function (unless the length of smallString is 0) because right is the length of smallerString minus 1. The while condition is left > right, so nothing inside of the while will be executed unless smallString has a negative length (which it doesn't).
By the way, if you want to check the entire bigString, you will need to iterate over bigString, not smallString. If you are only checking smallString.length characters, you won't be checking the entire bigString. Figuring out how to write this function is a good exercise, so I will leave the writing of it to you and refrain from providing an implementation myself. Keep up the good work!

Error indexOf with number negative jQuery, JavaScript

I have a function which collects the value of an input that is in string format, being in this format I need to delete the words and only leave the numbers using the replace option, previously I used the first indexOf tag (it works correctly) to know if in the value of the input it contains the character "-" and to know if the numeric that is inside the string is negative positive, once the character is detected and all the words have been eliminated, what I do in the case that in the first IndexOf is equal to 0 is to convert the replaced value to negative, after that another function calls the first function and collects the variable that contains the replaced result and passed to negative, in this second function it contains another indexOF (it does NOT work correctly) that reads if the character "-" in the variable that we have passed since the first function. I have the problem in this second IndexOf which gives me the following error: impuesto1.indexOf is not a function.
First function (working correctly)
function value_impuestos(){
if(un_articulo == true)
{
impuestos1=$("#impuestos1-1").val();
negativo_positivo=impuestos1.indexOf("-");
impuesto = impuestos1.replace(/[^0-9\.]+/g, "");
if(negativo_positivo==0)
{
x = impuesto;
impuesto = x * -1;
impuesto=parseFloat(impuesto);
}
}
}
Second function (NO working correctly)
$("select[id=impuestos1-1]").change(function(){
value_impuestos();
impuesto1=impuesto;
alert(impuesto1); //result correct, example : -7
positivo_negativo=impuesto1.indexOf("-") > -1; //ERROR
if(positivo_negativo==false)
{
}
});
It might be simple, but:
Here is a working example. The change event is fired when you click out of the text box.
let impuesto = 0;
let un_articulo = true;
function value_impuestos(impuestos1){
if(un_articulo)
{
negativo_positivo = impuestos1.indexOf("-");
impuesto = impuestos1.replace(/[^0-9\.]+/g, "");
try {
impuesto=parseFloat(impuesto);
}
catch(err) {
console.error(err)
}
console.log('value_impuestos:', impuesto)
console.log('impuesto type:', typeof impuesto)
if(negativo_positivo == 0)
{
impuesto = impuesto * -1;
}
return impuesto
}
}
$(function() {
$("input[id=impuestos1-1]").change(function(e){
let impuesto1 = value_impuestos($(this).val());
console.log('change:', impuesto1)
if(impuesto1 > -1)
{
console.log('positive or 0')
}else{
console.log('negative')
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<form>
<input type="text" id="impuestos1-1" />
</form>
</body>

Reverse a string in JavaScript: Why is my answer not passing the test?

I am struggling with a JavaScript test, my answer isn't passing and I can't see why?
Here's the question:
Write a function that returns the reverse of a given string. Although many languages have a built in function to reverse a string, you should do it manually, building up the output character by character.
For example, "Hello" returns "olleH"
And this is what I have so far...
stringReverse = function(input) {
// Your code goes here
var inputA = input.split('');
var inputL = inputA.length;
var beta = new Array(inputL);
for (var i=0; i<inputL; i++) {
var alpha = inputA.pop();
beta.splice(i,1,alpha);
}
var newStr = beta.join('');
return console.log(newStr);
};
My output looks correct, however it isn't passing the tests. I get the following message:
Started
olleH
FA
F
F
Failures:
1) SolutionTests Test1
Message:
Expected undefined to equal 'olleH'.
Stack:
Error: Expected undefined to equal 'olleH'.
at Object. (/sandboxes/deer/SolutionSpec.js:7:40)
2) SolutionTests Test2
Message:
Expected undefined to equal 'A'.
Stack:
Error: Expected undefined to equal 'A'.
at Object. (/sandboxes/deer/SolutionSpec.js:11:36)
3) SolutionTests Test3
Message:
Expected undefined to equal ''.
Stack:
Error: Expected undefined to equal ''.
at Object. (/sandboxes/deer/SolutionSpec.js:15:35)
3 specs, 3 failures
Finished in 0.014 seconds
return console.log(newStr);
This returns the undefined value. I think you mean:
return newStr;
Change the last line to return newStr instead of return console.log(newStr). Currently your programs prints the correct answer, but doesn't return anything. The test is looking only at the return value, which is undefined.
So heres your issue, your doing return console.log(newStr). This runs console.log which does not have an output and that returns that lack of an output hence the undefined. Just simply do return newStr;
its because you are console logging the return instead of returning newStr.
try this:
stringReverse = function(input) {
var inputA = input.split('');
var inputL = inputA.length;
var beta = new Array(inputL);
for (var i=0; i<inputL; i++) {
var alpha = inputA.pop();
beta.splice(i,1,alpha);
}
var newStr = beta.join('');
return newStr;
};
you can also do this in only one line:
stringReverse = function(input) {
return input.split("").reverse().join("");
}
its because you return the return value of console.log which is undefined!
Change:
return console.log(newStr);
to
console.log(newStr);
return newStr;
Greetings!

Cicle around prompt not working

I need to make a cicle around prompt. The object of prompt - grab custumer input value and push it to eval function for making a result (converting whole string to digits with math operators('+', '*', etc...)).
The appointment of circle - is to check the result of eval function and if eval(a) != digit -> repeat prompt each time when user input in prompt non-digit values ('a', ',', etc...)
The other part of code only for catching an errors.
do {
var a = prompt('your number', '10-2*4');
} while (eval(a) != 'number');
try {
console.log( eval(a) ); //must display 2
} catch (e) {
console.log('Error: ', e);
}
Your test of eval(s) != 'number' should be something like typeof eval(+s) !='number'
You could make it a recursive function:
function doPrompt(){
try {
// if this line throws error will go to catch
var res = eval(prompt('your number', '10-2*4'));
// do it again if we don't have a number, or return number
return typeof +res ==='number' ? +res : doPrompt()
}catch(e){
return doPrompt();
}
};
var res = doPrompt();
console.log(res)
This would be a lot cleaner using an <input> instead which would allow for better ability to display errors to user. Using prompt is not very flexible

Jquery Functions does not work on function parameter

I have a jquery function which receives a parameter from it callers. Calling split() on the parameter throws error. Here is the function
function formatNairaCurrency(value) {
var formatedWithoutNaira;
var formattedAmount
//check if value is in kobo format
var splittedValue = value.split(".");//Throws error
if (splittedValue.length === 2) {
formatedWithoutNaira = isNaN(splittedValue[0]) ? "" : splittedValue[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
formattedAmount = "₦" + formatedWithoutNaira + splittedValue[1];
} else {
formatedWithoutNaira = isNaN(value) ? "" : value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
formattedAmount = "₦" + formatedWithoutNaira + ".00";
}
return formattedAmount;}
The call var splittedValue = value.split("."); throws the error value.split is not a function
What am I missing?
I am calling this in a .cshtml file. This works in another function even on the same .js file. The difference is that the value was not a parameter but a value from a text box.
Your help is greatly appreciated.
If i understand your intention correctly you are trying to use split for string. Your error could be caused by the fact that value is not string. You need to debug or throw to console 'value'.
Edit: For example if
value is null, or value is undefinded this would most definitely cause your error. Testing for those conditions:
(value === null)
(typeof value === 'undefined')
If your value is number - that would cause error too. You need to cast number to string first. You can do it by
var valueAsString = value.toString();
valueAsString.split('.');

Categories

Resources