Why do I get undefined here? - javascript

function myFunc() {
var word = document.getElementById("Text1").value;
var num = parseInt(document.getElementById("Text2").value);
var numstr = num.split(",");
var wordstr = word.split("");
for (i = 0; i < word.length; i++) {
}
document.getElementById("myDiv").innerHTML += (wordstr[(numstr[i])-1]);
}
did I parseInt incorrectly? I've tried toString(), with ParseInt it doesn't do anything and without it I get 'undefined'

The parseInt() function parses a string and returns an integer.
You check your input with id "Text2" and show your HTML here to clearify the issue.

Without knowing more about your problem, it looks like you are misunderstanding how parseInt() works. Despite the misleading name, it will read your string character by character, attempting to create an integer. It will stop as soon as it finds a character that can't be part of an integer.
If you pass it "1,2,3,4" then it will read the 2 fine, but as a comma cannot be parsed as part of an integer, it will return the number 2. It doesn't make sense to call split on a number.
As others have said, you really need to give us more details for us to be able to help, but I suspect a large part of the problem is not understanding what some of these functions do.
Maybe you could explain what you're trying to achieve, then we can help you get there. Right now, your code isn't clear enough without extra information.

Related

Correctly format a whole number to a 2 decimal places output in JS but put 0 in front [duplicate]

I have a script which returns a price for a product. However, the price may or may not include trailing zeros, so sometimes I might have 258.22 and other times I might have 258.2. In the latter case, I need to add the trailing zero. How would I go about doing this?
You can use javascript's toFixed method (source), you don't need jQuery. Example:
var number = 258.2;
var rounded = number.toFixed(2); // rounded = 258.20
Edit: Electric Toolbox link has succumbed to linkrot and blocks the Wayback Machine so there is no working URL for the source.
Javascript has a function - toFixed - that should do what you want ... no JQuery needed.
var n = 258.2;
n.toFixed (2); // returns 258.20
I don't think jQuery itself has any string padding functions (which is what you're looking for). It's trivial to do, though:
function pad(value, width, padchar) {
while (value.length < width) {
value += padchar;
}
return value;
}
Edit The above is great for strings, but for your specific numeric situation, rosscj2533's answer is the better way to go.

Is there a way to make JavaScript read strings as strings when multipying by numbers?

I am (using JavaScript) trying to get an output of 50 dashes as a banner like this:
"--------------------------------------------------"
I have so far tried the following:
let a = []
for (var i = 0; i < 50; i++) {
a.push("-")
}
console.log(...a)
and
console.log("-" * 50)
These do not work, as in the first one, there are spaces in between the dashes.
The second one returns NaN, which is not what I need either.
The regular way I used to do this in Python was:
print("-" * 50)
This gave the perfect result of "----------------------------------------------------".
The print() function being Python's equivalent of console.log().
However, this does not work in JavaScript, as said before.
I also figured out that this does not work due to the fact that the string is parsed as a number.
Is there a way to achieve the "----------------------------------------------------" banner in JavaScript without typing it manually, or is there a way to make sure that "-" is not parsed as a number?
No, javascript lack of that feature. But you could use repeat() on ECMAScript6:
console.log("-".repeat(50))
This is Mozilla's reference https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/repeat
let a = []
for (var i = 0; i < 50; i++) {
a.push("-")
}
a=a.toString();
a=a.replace(/,/g,'');
console.log(a);
if you want to use an Array:
let a = Array(50).fill('-').join('')
console.log(a)

JavaScript while loop simple JS

i've got a question. I've started this course on Udemy for JavaScript and we got to "while" loops. Now i get what while loops do, and i tried to create a simple number guessing game, but the thing back fired on me.
Here's the code:
var num = Number(prompt("What is the secret number?"));
while(num !== 354){
var num = prompt("Guess the number!!!");
}
alert("Correct number!!");
I've tried without Number () in var, i've tried with if and else, but it's not working. I mean it works, but when i type in any number it gives me "Guess the number!!!" info, but when i type in number "354" it gives me the same information. Now this is not a project, just exercise, but don't understand...
Thank you in advance guys
This is a data Type issue. Specifically your input is still capturing a string and the while loop is expecting a valid type Number.
A simple method to ensure your data type is always what you need in this case would be parseInt()
Other methods:
Casting: using the Number() function. Note: this has some limitation with Strings, particularly spaces.
parseFloat(): This will take an argument and spit out the Float value.
I added this to the num variable within while()
var num = Number(prompt("What is the secret number?"));
while(parseInt(num) !== 354){
var num = prompt("Guess the number!!!");
}
alert("Correct number!!");
Replace the strict comparison with type-converting one. This way your comparison captures both numeric and string data types.
Also, you don't really need to redeclare your variable in the loop body, you can safely omit var there then.
var num = prompt("What is the secret number?");
while(num != 354){
num = prompt("Guess the number!!!");
}
alert("Correct number!!");
This code is working (i used similar and edited it), but that one is not, where is the difference:
var answer = Number(prompt("What is the secret number?"));
while(answer !== 354){
var answer = prompt("Guess the number!!!");
}
alert("Yay, we made it!!!");

RegEx change function name and parameter of string

I'm awful with RegEx to begin with. Anyway I tried my best and think I got pretty far, but I'm not exactly there yet...
What I have:
A javascript source file that I need to process in Node.js. Can look like that:
var str = "require(test < 123)\n\nrequire(test2 !== test)\n\nfunction(dontReplaceThisParam) {\n console.log(dontReplaceThisParam)\n}";
What I came up with:
console.log(str.replace(/\(\s*([^)].+?)\s*\)/g, 'Debug$&, \'error_1\''))
Theres a few problems:
I want that the string error gets inside the paranthesis so it acts as a second parameter.
All function calls, or I think even everything with paranthesis will be replaced. But only function calls to "require(xxx)" should be touched.
Also, the error codes should somehow increment if possible...
So a string like "require(test == 123)" should convert to "requireDebug(test == 123, 'error_N')" but only calls to "require"...
What currently gets outputted by my code:
requireDebug(test < 123), 'error_1'
requireDebug(test2 !== test), 'error_1'
functionDebug(dontReplaceThisParam), 'error_1' {
console.logDebug(dontReplaceThisParam), 'error_1'
}
What I need:
requireDebug(test < 123, 'error_1')
requireDebug(test2 !== test, 'error_2')
function(dontReplaceThisParam) {
console.log(dontReplaceThisParam)
}
I know I could just do things like that manually but we're talking here about a few hundred source files. I also know that doing such things is not a very good way, but the debugger inside the require function is not working so I need to make my own debug function with an error code to locate the error. Its pretty much all I can do at the moment...
Any help is greatly appreciated!
Start the regex with require, and since you need an incrementing counter, pass a function as the second arg to replace, so that you can increment and insert the counter for each match.
var str = "require(test < 123)\n\nrequire(test2 !== test)\n\nfunction(dontReplaceThisParam) {\n console.log(dontReplaceThisParam)\n}";
var counter = 0;
console.log(str.replace(/require\(\s*([^)].+?)\s*\)/g, (s, g2) =>
`requireDebug(${g2}, \'error_${++counter}\')`
));
Other than that, your code was unaltered.

Make parseFloat convert variables with commas into numbers

I'm trying to get parseFloat to convert a userInput (prompt) into a number.
For example:
var userInput = prompt("A number","5,000")
function parse_float(number) {
return parseFloat(number)
}
When userInput = 5,000, parse_Float(userInput) returns 5.
However, if the user was inputting a value to change something else (ie: make a bank deposit or withdrawl) Then I to work properly, parse.Float(userInput) needs to return 5000, not 5.
If anyone could tell me how to do this it would help me so much. Thanks in advance.
Your answer is close, but not quite right.
replace doesn't change the original string; it creates a new one. So you need to create a variable to hold the new string, and call parseFloat on that.
Here's the fixed code:
function parseFloatIgnoreCommas(number) {
var numberNoCommas = number.replace(/,/g, '');
return parseFloat(numberNoCommas);
}
I also renamed the function to parseFloatIgnoreCommas, which better describes what it does.
This is the function I use to scrub my user inputted numbers from a form. It handles anything a user may put in with a number like $ or just accidentally hitting a key.
I copied the following out of an object:
cleanInput : function(userValue){
//clean the user input and scrub out non numerals
var cleanValue = parseFloat(userValue.replace(/[^0-9\.]+/g,""));
return cleanValue;
},
To make it non-object just change the first line to cleanInput(){....
I have put together info from the comments to form a basic answer:
The answer seems to simply be to set parse_float to run :
number.replace(/,/g, "")
return parseFloat(number)
The complete code would look like this:
var userInput = prompt("A number","523,000,321,312,321")
function parse_float(number) {
number.replace(/,/g, "")
return parseFloat(number)
}
returns: 523000321312321

Categories