Here's the code I'm running
function howOldAreYou(day,month,year) {
var age;
age = (day) + (2015-year) + (month*12);
return age
};
document.write(howOldAreYou(parseFloat(prompt("yo day"))),(parseFloat(prompt("yo month"))),(parseFloat(prompt("yo year"))));
I know I got the age formula wrong, but I should get some added number back, and instead I'll get this: If I put it "1" in the first prompt, "2" in the second, and "3" in the third, I'll get this on the document "NaN23". I feel like it's a small parenthesis problem, but I can't figure it out, and help is appreciated.
Because the howOldAreYou function is being called after the first prompt, so you're passing, for example: howOldAreYou(1, undefined, undefined)
Design choices aside, you can make what you're doing work like this:
function howOldAreYou(day,month,year) {
var age;
age = (day) + (2015-year) + (month*12);
return age
};
var day = parseFloat(prompt("yo day"));
var month = parseFloat(prompt("yo month"));
var year = parseFloat(prompt("yo year"));
document.write(howOldAreYou(day, month, year));
Or, to keep it how you originally had it, the correct format would be:
document.write(
howOldAreYou(parseFloat(prompt("yo day")),
parseFloat(prompt("yo month")),
parseFloat(prompt("yo year"))));
Related
sunday();
function sunday()
{
let result;
let text1;
let year;
for (year = 2014; year <= 2050; year++)
{
var d = new Date(year, 0, 1);
if (d.getDay() === 0 )
console.log("1st January is being a Sunday "+year);
text1+=year.toString();//not get stored in variable text1
result=text1.toString();//same problem here also
}
}
please tell me why i cant store those years into text1(variable) even after i convert into string format also when i check console everything is works perectly in console result but it wont work when i store and try to display through paragraph using .innerhtml property help me to display it inside paragraph inner text
You have a syntax error near your if statement, you forgot to insert brackets.
Also, you can't append a text to a variable only defined with let.
If it's a string, you should do let text1 = ""
Furthermore, it is not very useful to append multiple results to the same string, which only gives something like this : "20172030" etc... by appending years. I think what you are trying to do is use arrays, which can be initialized by doing : let text1 = []
The code works and should look like this :
function sunday(){
let result;
let text1 = [];
let year;
for (year = 2014; year <= 2050; year++){
var d = new Date(year, 0, 1);
if (d.getDay() == 0 ){
console.log("1st January is being a Sunday "+year);
text1.push(year.toString());
console.log(text1);
result = text1.join(",");
console.log(result)
}
}
}
sunday()
There seem to be several problems here
Firstly you are not initializing the variable text1 with a string value. So the value of this will become a string undefined in a string concatenating context (your += in text1+=year.toString())
See these examples for a demonstration
let x
x+="2021"
console.log(x) // Output undefined2021
let x = "" // x is initialized with an empty string
x+="2021"
console.log(x) // Output 2021
Then we do not know, in which context you are calling the function. At least you do not return any value from it. If you add return text1 at the end of the function, your code might work.
hi this is my first question, sorry if it is stupid but i stumble upon this code
function format(input){
var num = input.value.replace(/\./g,'');
if(!isNaN(num)){
num = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{1})/g,'$1.');
num = num.split('').reverse().join('').replace(/^[\.]/,'');
input.value = num;
}
else{ alert('just numeric values please');
input.value = input.value.replace(/[^\d\.]*/g,'');
}
}
i don't really understand how it works, but basically it formats an input in real time to this format "9.9.9.9.9" but i want it to have it like this "9.9.9.9.9.". How can i add that last period?
thanks beforehand
If all you need to do is add the period to the end of the string, just do:
num + ".";
For your entire function, if you are taking a string like "12345" and just want to put a period after each number and at the end, then there are easier ways to do it than what you have:
text = text.replace(/(.)/g, '$1.');
Will do it.
input.value = num+'.';
or like this
var num = b.split('').reverse().join('').replace(/^[\.]/,'').replace(/$/, ".");
/$/ means end of the string
or like this
var num = b.split('').reverse().join('').replace(/^(.{1})(.+)/, '$2$1');
Take a look at this post:
Move n characters from front of string to the end
enjoy
I saw one of the masters doing this:
var example = '';
Then later he continued with this:
example += '<div>just a div</div>';
I wanna know if there's any difference from doing this:
var example;
example += '<div>just a div</div>';
I don't really know if by doing the second method I'm doing wrong and I have to code like shown if the first example.
Updated!
Thank you so much for your answers, Ok I got it I need to define my variable to be able to work woth it, but then another question came... This master also is doing this:
var guess;
and then he does:
guess += myfunction( upper );
where myfunction was declared as follows:
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
So, why here is different? Can any of you answer this please?
Thank you!
Second update!
Again Thanks!
I decided to post the whole code the JS master was doing, at this point I don't understand, so probably you'll be able to clear my doubts.
var randomNumber = myFunction( 10 );
var guess;
var attempts = 0;
var answer = false;
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
do{
guess = prompt( "I created a number from 1 till 10, can you guess it?");
attempts += 1;
if( parseInt( guess ) === randomNumber ){
answer = true;
}
}while( ! answer )
document.write( "Took you " + attempts + " attempts to guess the number " + randomNumber);
Please have a look at:
var guess;
and how later is being declared, so why here works perfectly but in my first example I have to put the '' when declaring my variable?
I hope my question is clear enough for you!
Thank you for your time and patient!
When you do:
var example;
example += '<div>just a div</div>';
You end up with:
`"undefined<div>just a div</div>"`
This is because when you don't initialize a variable, it is undefined, which can be converted to a sensible string "undefined" when you try to add it to another string.
When you do:
var guess;
guess += myfunction( upper );
function myFunction( upper ){
return Math.floor( Math.random() * upper ) + 1;
}
You are adding a number to undefined. This results in NaN (not a number) because undefined cannot be converted into a sensible number.
You can check this yourself next time by opening up your browser's developer tools and running the code in the console.
Edit:
When you do:
var guess;
guess = prompt( "I created a number from 1 till 10, can you guess it?");
There's no issue because you are simply assigning a string to the guess variable. In the previous examples you were adding something to a variable, which means if they are different types then JavaScript has to try to do something sensible.
If you don't initialize your variable it has a value of undefined.
In your last example, you are really saying example = undefined + '<div>just a div</div>' and undefined will be converted to a string and output that way. Probably not what you want.
In general it is a good idea to initialize your variables before you use them which is why var example = '' is preferable in this case.
var myvar
myvar += 'asdf'
console.log(myvar) // prints undefinedasdf
var othervar = ''
othervar += 'sdfasdf'
console.log(othervar) // prints sdfasdf
If you don't initialize the variable then it will be undefined
Appending to undefined object doesn't help.
var example = '';
Here you are initializing an empty string to the variable and therefore appending a string to another string will give the desired output of string concatenation.
Output:
"undefined<div>just a div</div>"
"<div>just a div</div>"
Yes there is a difference the first snipet from the master creates a variable example and gives it a default value, the second statement concatinates the value with 'just a div'
.Your code has an error as it is adding a value to a non-existed value as variable example has no default value.
First off my apologies if I did something incorrectly with asking a question, I'm very new to stackoverflow and javascript as well. I am having an issue with passing a property through my getPassword function and I've searched around and couldn't truly pinpoint an answer. The code I created is designed for an object called "student" with two properties; FirstName and LastName.
Using a couple of dialogue boxes the information related to each student is entered. At the end, a prompt should display and asks the user "Do you want to add more student?" If the answer is "Yes", It asks the next student's information. If the answer is anything else, It stops asking. Then the information is displayed on the webpage. I want to have a property called "UID" The format of UID is FirstName_PSWD. For calculating the "PSWD" the function called "generatePassword" is used. This function randomly creates a 6-digit password including characters and numbers. For example: if username is John, then UID may be "John_X12bn231". I can not seem to get this password function to work, what might I be doing wrong? I am also aware that there might be other errors in my code, which I do apologize for i am very much a beginner.
var student={FirstName:"", LastName:""};
var studentlist=[];
var i=0;
function generatePassword() {
var length = 4,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
function Register() {
var next="Yes";
while (next="Yes"){
student.FirstName=prompt("Please enter the name");
student.LastName=prompt("Please enter the last name");
studentlist.push(student);
document.getElementById("demo").innerHTML += "<li> <b>First Name:</b> "+ studentlist[i].FirstName + "," +
"<b>Last Name: </b>"+ studentlist[i].LastName + "," + "</li>";
next = prompt ("Do you want to add more data?", "Yes")
i++;
}
}
Two mistakes:
var student={FirstName:""; LastName:""};
Should be -> var student={FirstName:"", LastName:""};
var i==0; -> var i = 0;
Try after changes and tell me if it works ;d
Btw. Javascript is a frontend. Your users will be able to check how you generate the password, because all your code can be read.
The problem statement is like this: I have a contract. On renewal on every month the contract name should append with renewal identifier. For example at beginning the name is myContract then on first renewal name should be myContract-R1, next renewal name should be myContract-R2 and so on.. On each renewal, the name should automatically change. So in Jquery how can I do this?
This is a JavaScript question, not a jQuery question. jQuery adds little to JavaScript's built-in string manipulation.
It sounds like you want to take a string in the form "myContract" or "myContract-Rx" and have a function that appends "-R1" (if there's no "-Rx" already) or increments the number that's there.
There's no shortcut for that, you have to do it. Here's a sketch that works, I expect it could be optimized:
function incrementContract(name) {
var match = /^(.*)-R([0-9]+)$/.exec(name);
if (match) {
// Increment previous revision number
name = match[1] + "-R" + (parseInt(match[2], 10) + 1);
}
else {
// No previous revision number
name += "-R1";
}
return name;
}
Live copy
You can use a regular expression for this:
s = s.replace(/(-R\d+)?$/, function(m) {
return '-R' + (m.length === 0 ? 1 : parseInt(m.substr(2), 10) + 1);
});
The pattern (-R\d+)?$ will match the revision number (-R\d+) if there is one (?), and the end of the string ($).
The replacement will return -R1 if there was no revision number before, otherwise it will parse the revision number and increment it.
how you get renewal number? Calculating from date, or getting from database?
var renewal = 1,
name = 'myContract',
newname = name+'R'+renewal;
or maybe like
$(function(){
function renew(contract){
var num_re = /\d+/,
num = contract.match(num_re);
if (num==null) {
return contract+'-R1';
} else {
return contract.replace(num_re,++num[0]);
}
}
var str = 'myContract';
new_contract = renew(str); // myContract-1
new_contract = renew(new_contract); // myContract-2
new_contract = renew(new_contract); // myContract-3
});
Here jQuery can't help you. It's pure JavaScript working with strings
P.S. I have here simple reg exp, that's not concrete for your example (but it works). Better use reg-exp from example of T.J. Crowder