Saltar al contenido
Underc0de /foro

[JavaScript] FV Manual

🌐 This is an automatic translation of a topic from Underc0de, the largest Spanish-speaking hacking and IT community. Read the original (Spanish) and reply →
Alex ·
JavaScript<br />(FV Manual)<br />
<br /><br />Before we start:<br />- F.V. Manual means "practical computing manual", but truly, truly PRACTICAL.<br />- Throughout the text I keep referring to TuCarpeta (YourFolder); this is a subdirectory on your<br />computer where you should save all the programs from this "your manual".<br />- All programs and exercises in the manual have been tested without problems in<br />Microsoft Internet Explorer 5.0<br />- My advice is that you type each of the programs again, exactly as I indicate in the text,<br />using Windows Notepad. Only if the<br />program doesn't work and you can't find the error, copy it from Word into<br />Notepad and save it under another name, so you can compare it with yours and thus<br />find the error.<br />Keep in mind that you learn more by finding your own mistakes than by moving ahead without making<br />any mistakes<br /><br />INDEX<br /><br />
    <br />
    • Introduction to programming in JavaScript
    <br />
    • Self-assessment exercises 1
    <br />
    • Programming Structures
    <br />
    • Self-assessment exercises 2
    <br />
    • Functions and Arrays
    <br />
    • Self-assessment exercises 3
    <br />
    • Visual Programming
    <br />
    • Self-assessment exercises 4
    <br />
    • Programming in HTML
    <br />
    • Self-assessment exercises 5
    <br />
    • Object-Oriented Programming
    <br />
    • JavaScript and the Web
    <br />
    • Self-assessment solutions 1
    <br />
    • Self-assessment solutions 2
    <br />
    • Self-assessment solutions 3
    <br />
    • Self-assessment solutions 4
    <br />
    • Self-assessment solutions 5
    <br />
<br /><br />Author: Fermí Vilà<br /><br />Regards!
Alex ·
I.- Introduction to programming in JavaScript
<br /><br />
1.- Introduction
<br /><br />- Of all the services the INTERNET offers, there is no doubt that the most popular is the<br />WWW (World Wide Web).<br /><br />The WWW is nothing more than millions of pages in electronic format, with the most diverse contents and<br />topics, which we can access thanks to a computer + modem +<br />browser.<br /><br />- A WEB page is nothing more than a text file (ASCII), written in HTML format<br />(Hyper Text Markup Language).<br /><br />- HTML is a language based on pairs of tags. A tag is a code between<br /><>, if it is an opening tag, or a code between </ > if it is a closing tag.<br />Browsers (Internet browsers) are able to translate these tags<br />so that they display the page visually.<br /><br />- Structure of an HTML file<br /><br />Basically it consists of four pairs of tags:<br /><br /><HTML><br /><HEAD><br /><TITLE>Nuestra primera página</TITLE><br /></HEAD><br /><BODY><br />..........................<br />..........................<br />..........................<br /></BODY><br /></HTML><br /><br />• The pair <HTML> and </HTML><br />Determines that a file is HTML<br /><br />• The pair <HEAD> and </HEAD><br />Determines the header of the HTML file, which may contain a title.<br /><br />• The pair <TITLE> and </TITLE><br />Encloses the "title": a text phrase that will appear in the browser frame<br />(first line), when running the HTML file<br /><br />• The pair <BODY> and </BODY><br />Encloses the content of the html page, that is, what will be displayed in the<br />browser.<br /><br />The best-known browsers are:<br /><br />• Netscape Comunicator<br />• Microsoft Internet Explorer<br /><br />- Run "Notepad", that is:<br /><br />[Start]<br />Programs<br />Accessories<br />Notepad<br /><br />- Type:<br /><br />
Código: html5
<HTML><br /><HEAD><br /><TITLE>PROG000.HTM</TITLE><br /></HEAD><br /><BODY><br /><P>Esto aparecerá en el navegador porque es un párrafo</P><br /><P>Esto es otro párrafo</P><br /><P>Observa lo que aparece en la línea de título</P><br /><P>La línea de título es la frase que aparece en el marco<br />del navegador, línea superior</P><br /><P>¿Está claro para qué sirven los tags P, /P?</P><br /></BODY><br /></HTML>
<br /><br />- Save the previous file with the name PROG000.HTM in TuCarpeta<br /><br />- Run "Windows Explorer". Go to TuCarpeta and double click on<br />PROG000.HTM<br /><br />This way, your computer's browser runs (I'll assume it's Internet<br />Explorer) and the page PROG000.HTM is "loaded"<br /><br />The browser shows us the HTML page "visually"; to see its code you must do:<br /><br />View menu<br />Source code<br /><br />- Programming in HTML is of no use to a normal user, since on the<br />market there are tools that avoid the need to enter<br />the "tags" manually: HotMetal, FontPage, Word, etc.<br />What does make sense is studying programming in JavaScript.<br /><br />- JavaScript is a programming language created by the company Netscape (creator of<br />one of the best-known browsers)<br />It is the most used programming language on the Internet to add interactivity to<br />Web pages<br /><br />- Don't confuse JavaScript with Java. Java is a general-purpose programming<br />language like C++ or Visual Basic.<br /><br />- A JavaScript program is integrated into a Web page (among the HTML code) and it is the<br />browser that interprets (executes) it. That is, JavaScript is an<br />interpreted language, not compiled (no object or exe file of any kind is generated).<br /><br />- To program in JavaScript we only need a text editor (we will use Windows<br />Notepad) and a browser (we will use Microsoft Internet Explorer) to<br />run it.<br /><br />- Why JavaScript and not another programming language?<br /><br />Because:<br /><br />• It is modern (it is only a few years old)<br />• It is simple (its big brother, Java, is quite a bit more complex)<br />• It is useful (the development of the Internet is expected to be very fast in the coming years)<br />• It is powerful: it allows modern OOP (object-oriented programming)<br />• It is cheap: we only need a text editor ("Notepad" is included in<br />Windows) and a browser (it's free, whether "Internet Explorer" or<br />"Netscape").<br />• It is visual: it allows modern "visual programming" (windows, buttons, colors,<br />forms, etc.).<br /><br />In short: it is ideal for a first introductory programming course.<br />And keep in mind that there is a "saying" in computing that states: "If you master<br />one programming language, you know them all".
Alex ·
2.- Basic syntax
<br /><br />- Using Windows "Notepad", write the following program:<br /><br />
Código: HTML5
<HTML><br /><HEAD><br /><TITLE>PROG001.HTM</TITLE><br /><SCRIPT LANGUAGE="JavaScript"><br />alert("¡Hola Mundo!");<br /></SCRIPT><br /></HEAD><br /><BODY><br /><P><br />Programa 1 en JavaScript<br /></P><br /></BODY><br /></HTML>
<br /><br />- Save the previous file in TuCarpeta with the name Prog001.htm<br /><br />- Run the program Prog001.htm, that is:<br /><br />• Run "Windows Explorer"<br />• Go to TuCarpeta<br />• Double-click on Prog001.htm<br />- Study of Prog001.htm:<br />• A "JavaScript" program is written integrated into an HTML page, therefore<br />it is nothing more than a text file containing a series of pairs of tags<br />corresponding to the Web page (at least the pair: <HTML>, </HTML>),<br />plus the characteristic pair of tags of a JavaScript program. This file<br />must necessarily be saved with the HTM extension (characteristic of an HTML<br />page).<br />• A "JavaScript" program is nothing more than a sequence of statements, which must<br />end in a semicolon, between the tags:<br /><SCRIPT LANGUAGE="JavaScript"><br />and<br /></SCRIPT><br />• In our Prog001.htm, we have included the program in the header (HEAD) of the<br />page, but we could place it anywhere in the htm file<br />• Our first JavaScript program contains a single statement: alert(""¡Hola<br />Mundo!");<br /><br />Which "opens" a window with the message we have between quotes.<br />When clicking [OK] in the "alert" window, the JavaScript program<br />ends (the </SCRIPT> tag is found) and the HTML page continues<br />executing.<br /><br />- Using "Notepad" write the following program:<br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />// PROG002.HTM<br />var nom;<br />nom=prompt("Escribe tu nombre ","Paco");<br />alert("Mucho gusto "+ nom);<br /></SCRIPT><br /></HTML>
<br /><br />- Save it in TuCarpeta with the name Prog002.htm<br />- Run it several times, carefully observing what happens.<br />- Study of Prog002.htm<br /><br />1st) First and last line: <HTML> and </HTML><br />That is: the minimal html page we need to include a JavaScript program.<br /><br />2nd) Second and second-to-last lines: <SCRIPT LANGUAGE=.....> and </SCRIPT>, that is,<br />the JavaScript program<br /><br />3rd) First statement of the program: // PROG002.HTM<br /><br />The only line of the program that doesn't need to end with a semicolon.<br />All lines starting with // are comments for the programmer, that is, they don't<br />form part of the program; in other words: if the browser finds a line that<br />starts with //, it skips it.<br /><br />4th) var nom;<br />We define a variable named nom<br /><br />5th) nom = prompt("Escribe tu nombre","Paco");<br />A box appears with a message and a field where we can write something; the message<br />corresponds to what we wrote in the first argument of the prompt function, enclosed<br />in quotes. The second argument of prompt contains the value that appears by<br />default in the dialog box field.<br />The value of the prompt is nom, that is, whatever we write in the box will be the value<br />the variable nom takes.<br />If we don't write anything and click [OK], the prompt, that is, the variable nom,<br />will take the value Paco, because it is the default value.<br /><br />6th) alert("Mucho gusto "+nom);<br />A box appears with the message "Mucho gusto" (Nice to meet you) followed by the value of the variable<br />"nom", which will be what we wrote in the first box that appeared.<br />In short:<br /><br />- The prompt function lets us enter "values"; these values must be stored in<br />variables, which we must previously declare with the reserved word "var"<br />- The "alert" function displays messages and/or variable values.<br />- Using "Windows Notepad" write the following program:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />// PROG003.HTM<br />/*Programa que sirve para calcular<br />el área de un rectángulo */<br />var base,altura;<br />base=prompt("Escribe la base del Rectángulo","");<br />altura=prompt("Escribe la altura del Rectángulo","");<br />alert("El área del Rectángulo es = "+(base*altura));<br /></SCRIPT><br /></HTML>
<br /><br />- Save it in TuCarpeta with the name Prog003.htm<br /><br />- Run it several times. It would be good to use integers and also decimals<br />(5.72, 0.531: note that you must use the English decimal point).<br /><br />- If you have run the program once, to run it again you don't need to<br />"close" the browser, just do:<br /><br />View menu<br />Refresh<br /><br />or if you want to go faster, press the [F5] key<br /><br />- It is important that you understand this program clearly:<br /><br />• We declare two variables (var), which we need to enter the base and height<br />of the rectangle, through two "prompts":<br />base= prompt......<br />altura= prompt.....<br /><br />• Finally we need two "alerts" to show us the result of the program,<br />which is simply the product base * height<br /><br />- The only new element that appears in Prog003.htm is:<br /><br />/*Programa que sirve para calcular<br />el área de un rectángulo */<br />Everything written between /* and */ is nothing more than a comment for the<br />programmer, just like the lines starting with //<br />The difference between // and /* */ is that the latter way of including a comment<br />allows us to place it so that it spans more than one line.
Alex ·
3.- Variables
<br /><br />- Declaring variables<br />A variable can be declared in JavaScript in two ways:<br /><br />• Explicit Form: var nombre Variable;<br />• Implicit Form: var nombre Variable= valor;<br /><br />In the latter case it is not essential to write var, but it is advisable, since this way<br />we can quickly locate all the variables of the program.<br />"JavaScript" is a "Case Sensitive" programming language, that is: uppercase and lowercase<br />are not the same. In other words, for JavaScript: pepe is different from Pepe and<br />different from pEpe.<br /><br />- Write the following program:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE=''JavaScript''><br />// PROG004.HTM<br />/* Programa que utiliza una variable explícita<br />y dos implícitas */<br />var Expli;<br />var pi=3.141592;<br />var radio=7;<br />Expli=pi*radio*radio;<br />alert("Área del Círculo = "+Expli);<br /></SCRIPT><br /></HTML>
<br /><br />- Save it in TuCarpeta with the name Prog004.htm<br />- Run it
Alex ·
4.- Data Types
<br /><br />When we declare a variable, it doesn't belong to any specific data type; it is said<br />to be Undefined. It is when we assign it a value that it becomes one type or another, depending on the data<br />it holds.<br />There are 6 data types:<br />String: text strings Object: objects<br />Number: numeric values Null: null<br />Boolean: true or false Undefined: not defined.<br />We can find out the data type a variable contains by using the built-in<br />function typeof<br /><br />- Write the following program:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE=''JavaScript''><br />// PROG005.HTM<br />var Pepe;<br />var PEPE="Hola que tal ";<br />var pepE=75.47;<br />var pEpe=" ¿Como estás?";<br />Pepe=PEPE+pEpe;<br />alert("PEPE="+PEPE);<br />alert("PEPE es "+typeof(PEPE));<br />alert("pepE="+pepE);<br />alert("pepE es "+typeof(pepE));<br />alert("pEpe="+pEpe);<br />alert("pEpe es "+typeof(pEpe));<br />alert("Pepe="+Pepe);<br />alert("Pepe es "+typeof(Pepe));<br /></SCRIPT><br /></HTML>
<br /><br />- Save it in TuCarpeta with the name Prog005.htm<br />- Run it as many times as you like.
Alex ·
5.- The "String" data type:
<br /><br />In JavaScript texts are denoted by double quotes or single quotes, but not both at the<br />same time.<br /><br />Variable1 = "Pepito"<br />Variable2 = 'Paquito'<br /><br />We can include a control character in a text string if we use the so-called<br />escape character, which is: \<br /><br />The most used control characters are:<br /><br />\n line break<br />\t tab<br /><br />- Write the following program:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />// PROG006.HTM<br />var num;<br />alert("Hola que tal");<br />alert("Hola \nque tal");<br />alert("Hola\t"+"que"+"\n"+"tal");<br />alert("Hola\n que\n t\nal");<br />num=prompt("Escribe un número: ","");<br />alert("El \ndoble\n es: \n"+(num*2));<br /></SCRIPT><br /></HTML>
<br /><br />- Save it in TuCarpeta with the name Prog006.htm<br /><br />- Run it, carefully observing the effect of \n and \t<br /><br />- If we don't enter a number in the "prompt", the "alert" corresponding to double the number will show NaN, which means it is not a number.
Alex ·
6.- The "Number" data type
<br /><br />We can store in a number variable an integer, decimal, positive<br />or negative number alike.<br /><br />Examples:<br />var numNatural= 1234;<br />var numEntero = -479;<br />var numDecimal = 3.141592;<br />var numDecimal2 = -0.123;<br /><br />- Numeral Bases in JavaScript (integers)<br />By default, the numeral system is decimal.<br /><br />• Hexadecimal Base (base 16): we prepend the prefix 0X<br />• Octal Base (base 8): we prepend a zero<br /><br />Digits of the decimal system: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9<br />Digits of the hexadecimal system: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A (which corresponds to 10 in base<br />decimal), B (which corresponds to 11 in decimal), C (12), D (13), E (14), F (15)<br />Example:<br />FF32 in base 16 is 2 + 3*16 + 15*162 + 15*163 = 65330 in decimal system<br />That is: 0xFF32 (number in base 16, according to JavaScript notation) = FF3216 = 6533010<br />123458 = 5 + 4*8 + 3*82 + 2*83 + 1*84 = 534910<br />That is: 012345 (number in base 8, according to JavaScript notation) = 123458 = 534910<br /><br />- Write the following program:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE=''JavaScript''><br />// PROG007.HTM<br />var n1=57; // número en base 10<br />var n2=012345; //base 8, porque empieza por 0<br />var n3=0xFF32; //base 16, porque empieza por 0x<br />alert("número decimal= "+n1);<br />alert("el 12345 en base 8 es en decimal= "+n2);<br />alert("el FF32 en base 16 es en decimal= "+n3);<br />/* Observa que al escribir una variable numérica en un "alert"<br />siempre nos da el número en decimal,<br />aunque sea en octal o hexadecimal */<br /></SCRIPT><br /></HTML>
<br /><br />- Save it in TuCarpeta with the name Prog007.htm and run it.<br />In the previous program 3 "alerts" appear, one for each of the three numbers. There is<br />no problem including all three "alerts" in a single one....<br /><br />- Indeed, write the following program:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE=''JavaScript''><br />// PROG007b.HTM<br />var n1=57; // número en base 10<br />var n2=012345; //base 8, porque empieza por 0<br />var n3=0xFF32; //base 16, porque empieza por 0x<br />alert("número decimal= "+n1+"\n"+<br />"el 12345 en base 8 es en decimal= "+n2+"\n"+<br />"el FF32 en base 16 es en decimal= "+n3);<br /></SCRIPT><br /></HTML>
<br /><br />- Save it in TuCarpeta with the name Prog007b.htm and run it.<br />- Note that the solution to our problem is:<br /><br />• Join text (in quotes) and variables (without quotes) with the "+" sign<br />• Every time we want a line break, we include "\n"<br /><br />Let's see another way to include lots of data in an "alert" ...<br />- Write:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />// Prog007bb.htm<br />var x,y,z;<br />salida="";<br />var x1="Pepito Grillo", y1="Paquita González";<br />var num1=37, num2=3.752;<br />x=prompt("Escribe tu nombre:","");<br />y=prompt("Escribe tu primer apellido:","");<br />z=prompt("Escribe tu segundo apellido:","");<br />salida=salida+"Ahora un alert largo ";<br />salida=salida+x+y+z;<br />salida=salida+x1+" "+y1;<br />salida=salida+num1+" "+num2;<br />salida=salida+" ,ya me he cansado";<br />alert(salida);<br /></SCRIPT><br /></HTML>
<br /><br />- Save it in TuCarpeta with the name Prog007bb.htm and run it.<br />- Note how we accumulate lots of data in a single "alert" (this will be the way to<br />proceed when we need an "output" with many values):<br /><br />• we define an "empty" variable: var salida="";<br /><br />• we accumulate into the variable salida whatever we want: salida=salida+ whatever<br /><br />• "whatever" can be a string (a text) or a variable (numeric or<br />text).<br /><br />
Código: javascript
salida=salida + x1 + " " + y1;<br />salida=salida + "ya me he cansado";
<br /><br />• To finish, a single "alert": alert(salida);<br /><br />Null variables<br />When a variable doesn't contain any value, its content is null<br />Example: miVariable = "Hola";<br />miVariable= null; // we empty it so it doesn't take up memory.<br />Special values for numeric variables<br />NaN: not a number.<br />Infinity: infinity, for example 3/0<br /><br />- Write the following program:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />// PROG008.HTM<br />var var1="Pepe";<br />var var2="Paquito";<br />var var3=5/0;<br />alert("Pepe es "+var1);<br />alert("Paquito + 2 es ="+(var2+2));<br />alert("5/0 es ="+var3);<br /></SCRIPT><br /></HTML>
Alex ·
7.- Counters
<br /><br />One of the most used tools in any programming language is the so-called<br />counter<br /><br />Observe:<br /><br />var x= 10;<br />x = x+1;<br />x = x-5;<br /><br />We declare a variable "x", which is numeric and initially 10.<br />The line "x = x+1" is a counter, which we should read as: The new value of "x" equals the<br />previous value of "x" plus one unit. That is, at this moment our variable "x"<br />equals 11.<br />The next line: "x = x-5" is another counter which we should read as: the new value of "x"<br />equals the previous value of "x" minus 5 units. That is, the value of the variable "x" is<br />now 11 - 5 = 6<br /><br />- Write a program to check what we've said about counters, that is:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />// PROG009.HTM<br />var x=10;<br />alert("El valor inicial de x es "+x);<br />x=x+1;<br />alert("Después de x=x+1, x="+x);<br />x=x-5;<br />alert("Después de x=x-5, x="+x);<br /></SCRIPT><br /></HTML>
<br /><br />- Save it in TuCarpeta with the name Prog009.htm and run it.
Alex ·
8.- Conversion between data types
<br /><br />Observe:<br /><br />var var1 = "75";<br />var var2 = 25;<br />var var3, var4;<br />var3 = var1 + var2;<br />var4 = var2 + var1;<br /><br />Do the variables var3 and var4 contain numbers or texts?<br />When text strings are added to anything else, the other data types are<br />converted to text strings. But if we subtract, multiply or divide "text<br />strings", does the same happen? Let's find out in the following programs.<br /><br />- Write the following program:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />// PROG010.HTM<br />var num1="30";<br />var num2="15";<br />// Observa que definimos dos cadenas de texto<br />alert("30+15= "+(num1+num2));<br />alert("30*15= "+(num1*num2));<br /></SCRIPT><br /></HTML>
<br /><br />- Save the program in TuCarpeta with the name Prog010.htm<br />- Run it.<br />- The conclusion is clear:<br /><br />• If we add two text strings (even if they contain numbers), the<br />concatenation (joining) of the two texts occurs.<br />• If we multiply (or do any arithmetic operation other than addition)<br />two text strings that actually contain numbers, an<br />implicit conversion of the strings to numbers occurs and the arithmetic product<br />of the numbers appears.<br /><br />- What happens if we enter two numbers through the prompt function? Let's see:<br />- Write the following program:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />//PROG011.HTM<br />var num1,num2;<br />num1=prompt("Escribe un número","");<br />num2=prompt("Escribe otro número","");<br />alert("La suma es ="+(num1+num2));<br /></SCRIPT><br /></HTML>
<br /><br />- Save it in TuCarpeta, with the name Prog011.htm<br /><br />- Run it. It doesn't work as we want because the result of a prompt is always a text string.<br />The pending problem we have is: how do we add in JavaScript?<br /><br />- Explicit type conversion<br />parseFloat(cadena)<br /><br />Takes the "string" and transforms it into a floating-point number, if possible.<br />parseFloat ("123.456") = 123.456<br />parseFloat ("123ABC") = 123<br /><br />parseFloat ("ABC") = NaN<br />parseInt(cadena, número)<br />Returns integers; the second argument lets us choose the numeral<br />base (between 2 and 36)<br />parseInt ("ABC",16) = 2748 ABC16 = 274810<br />If we don't specify the second argument, by default it is 10.<br />If the string starts with 0x and there is no second argument, it is taken to be 16.<br />If the string starts with 0 and there is no second argument, it is taken to be 8<br />toString(argumento)<br />If argument = number<br />Returns a string containing the number<br />There can be an optional argument:<br />(13).toString(16) ="d" since 1310 = d16<br />(13).toString(2) = "1101" since 1310 = 11012<br /><br />- Let's make a program that adds numbers in JavaScript. Write:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />//PROG012.HTM<br />var num1,num2;<br />num1=prompt("Escribe un número","");<br />num1=parseFloat(num1);<br />num2=prompt("Escribe otro número","");<br />num2=parseFloat(num2);<br />alert("La suma es ="+(num1+num2));<br /></SCRIPT><br /></HTML>
<br /><br />- Save it in TuCarpeta with the name Prog012.htm<br />- Run it, using integers, natural numbers and decimals.<br />From now on we must be clear whether the "prompts" correspond to<br />integers, decimals or text:<br /><br />- If "x" must be an integer we will write:<br />x = parseInt(prompt("Escribe un número entero",""));<br />- If "x" must be a decimal number we will write:<br />x = parseInt(prompt("Escribe un número entero o decimal",""));<br />- If "x" must be a text string we will write:<br />x = prompt("Escribe el texto correspondiente","");<br /><br />- Write the following program:<br /><br />
Código: javascript
<br /><html><br /><SCRIPT LANGUAGE="JavaScript"><br />// Prog012b.htm<br />var x,y;<br />x=parseInt(prompt("Escribe un entero ",""));<br />y=parseInt(prompt("Escribe otro entero ",""));<br />alert("La suma de "+ x +" + " + y +" es =" + (x+y) +"\n"+<br />"El producto de "+ x +" y "+ y +" = "+(x*y)+"\n"+<br />"El promedio de "+ x +" y "+ y +" es "+ (x+y)/2);<br /></SCRIPT><br /></HTML>
<br /><br />Save it with the name Prog012b.htm, and run it.<br /><br />In exercise Prog007.htm we had seen a way to convert a number in base 8 or<br />base 16 to base 10. But we had to write those numbers implicitly, that is, in<br />the program. We would like to make a program that:<br /><br />- Asks us for a number in base 16 (prompt)<br />- Gives us as a result the previous number but in base 10<br />Let's see if we can do it:<br />- Write:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />// Prog012bb.htm<br />var m,n,x;<br />m=prompt("Escribe un número en base 16","");<br />n=parseInt(m,16);<br />alert("El número "+m+" en base 16, es igual a "+n+" en base 10");<br /></SCRIPT><br /></HTML>
<br /><br />- Save it with the name Prog012bb.htm in TuCarpeta and run it for the number "FF32", to<br />see if it really gives us "65330" as a result.<br />Observe how the program Prog012bb.htm works:<br /><br />• m = prompt("Escribe un número en base 16", "")<br />Whatever we write (a number in base 16) will be stored in the variable "m" as text<br />(since we haven't used any "parseInt" or "parseFloat").<br />• n =parseInt(m,16)<br /><br />The variable "n" will store the number in base 10<br />That is: parseInt(cadena, 16) transforms the "string", in our example a number<br />written in base 16, into the corresponding number (not string) but in decimal base.<br />Let's see if the procedure works for any other base...<br /><br />First of all let's see a few numbers in different bases:<br /><br />367 = 6 + 3.7 = 27 in base 10<br />1234 = 3 + 2.4 + 1.42 = 27 in base 10<br />51346 = 4 + 3.6 + 1.62 + 5.63 = 1138 in base 10<br /><br />- Write:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />// Prog012bbb.htm<br />var m7,n7;<br />var m4,n4;<br />var m6,n6;<br />m7=prompt("Escribe un número en base 7","");<br />n7=parseInt(m7,7);<br />m4=prompt("Escribe un número en base 4","");<br />n4=parseInt(m4,4);<br />m6=prompt("Escribe un número en base 6","");<br />n6=parseInt(m6,6);<br />alert("El número "+m7+" en base 7, es igual a "+n7+" en base 10\n"+<br />"El número "+m4+" en base 4, es igual a "+n4+" en base 10\n"+<br />"El número "+m6+" en base 6, es igual a "+n6+" en base 10");<br /></SCRIPT><br /></HTML>
<br /><br />- Save it with the name Prog012bbb.htm and run it, testing it with the previous<br />numbers.<br /><br />Let's look at the inverse problem: given a number in base 10, we want to convert it to base 7,<br />for example.<br /><br />Mathematically:<br /><br />Let 593 be a number in base 10<br /><br />59310 = 15057<br /><br />In JavaScript we should do it as follows, write:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />// Prog012bbbb.htm<br />var m,n;<br />n=parseInt(prompt("Escribe un número entero en base 10",""));<br />m=(n).toString(7);<br />alert("El número "+n+" en base 10, es igual a "+m+" en base 7");<br /></SCRIPT><br /></HTML>
<br /><br />- Save it with the name Prog012bbbb.htm and run it, testing how it works with the<br />number 593
Alex ·
Self-assessment I
<br /><br />1) Write a program named Eval1A.htm, which you must save in TuCarpeta, that serves to<br />subtract any two numbers, whether integers or reals. What happens if instead of subtracting<br />two numbers, we try to subtract two texts?<br />Write a program named Eval1Ab.htm that demonstrates the only case in which we can<br />subtract two text strings.<br /><br />2) Write a program named Eval1B.htm, which you must save in TuCarpeta, that serves to<br />divide two numbers.<br />What happens if instead of dividing two numbers, we try to divide two texts?<br />What happens if the divisor is the number 0?<br /><br />3) Write a program named Eval1C.htm, which you must save in TuCarpeta, that works<br />as follows:<br />- The program asks for our name.<br />- The program asks for our age.<br />- The program gives as a result our name followed by the days we have lived<br />so far (you'll need to multiply the age by 365).<br /><br />4) Write a program named Eval1D.htm, which you must save in TuCarpeta, that works<br />as follows:<br />- The program asks us for a number.<br />- The program shows us on a single screen (a single "alert") the double, triple and<br />quadruple of the number we entered.<br /><br />5) The following program has errors. Write it (save it with the name Eval1E.htm in<br />TuCarpeta), fix it so it works and explain what it is for:<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />/* EVAL1E.HTM<br />var a,b;<br />a=prompt("Escribe la base:")<br />b=promp("Escribe la altura:")<br />alert("Área= "+(a*b/2);<br /></SCRIP><br /></HTML>
<br /><br />6) Write a program named Eval1F.htm, which you must save in TuCarpeta, that serves to<br />calculate the circumference of a circle and the area of the corresponding circle.<br /><br />7) Write a program named Eval1G.htm, which you must save in TuCarpeta, that serves to<br />calculate a 2nd order determinant.<br /><br />8) Write a program named Eval1H.htm, which you must save in TuCarpeta, the same as<br />Eval1G, but that presents the 4 elements of the determinant tabulated in 2 rows and 2<br />columns.<br /><br />9) Write a program named Eval1I.htm, which you must save in TuCarpeta, that works<br />as follows:<br />- The program asks for our name.<br />- The program asks for our first surname.<br />- The program asks what town we live in.<br />- The program displays a screen roughly like the following:<br />==================================<br />Hello name Surname<br />Goodbye inhabitant of Town<br />==================================<br /><br />10) Write a program named Eval1J.htm, which you must save in TuCarpeta, that works<br />as follows:<br />- The program asks us for a number.<br />- It uses three counters:<br />• One counter: adds 5<br />• Another counter: adds 21<br />• Another counter: subtracts 4<br />- The program presents the 4 numbers as follows:<br />• The first line: the number entered.<br />• The second line: the three numbers, tabulated, resulting from the three counters.<br />So if we enter number 5 it should show:<br /><br />
CitarNumero introducido: 5<br />contadores: 10 31 27
<br /><br />11) Write a program named Eval1K.htm, which you must save in TuCarpeta, that works<br />as follows:<br />- The program asks us for an integer.<br />- The program gives us as a result the same number but in base 16<br />- And finally writes it in base 5<br />Test the program with the number 52. You must first calculate<br />mathematically the value of 52 in base 16 and in base 5.<br /><br />12) Write a program named Eval1L.htm, which you must save in TuCarpeta, that works<br />as follows:<br />- The program asks us for a number in base eight<br />- The program writes it in decimal base.<br />- And finally in base 2.<br />Test the program with the number 65618. You must first solve the problem<br />mathematically.<br /><br />13) Write a program named Eval1M.htm, which you must save in TuCarpeta, that works<br />as follows:<br />- The program asks us for an integer.<br />- The program asks us for the base<br />- The program writes the entered number in the desired "base".<br /><br />Test the program with the number 100, in base 2, 3 and 11. You must first solve<br />the problem mathematically.<br /><br />14) What is the WWW?<br /><br />15) Which are the best-known "browsers"?<br /><br />16) Write an HTML file (not a JavaScript program) that displays the phrase: "Hola<br />que tal" and below it your name and surnames.<br /><br />17) What does the pair of tags <BODY>, </BODY> enclose?<br /><br />18) What is the relationship between Java and JavaScript?<br /><br />19) Who created the JavaScript programming language?<br /><br />20) What are the characteristics of JavaScript?<br /><br />21) Is JavaScript a compiled or interpreted language? Which program acts as<br />compiler or interpreter?<br /><br />22) Why do we say JavaScript is a cheap programming language?<br /><br />23) What does the acronym OOP stand for?<br /><br />24) What are the two ways of defining a variable in JavaScript called and how do they work?<br /><br />25) Why is JavaScript a "Case Sensitive" language?<br /><br />26) Name all the data types that exist in JavaScript.<br /><br />27) What is the typeof function for? Make up a couple of examples.<br /><br />28) What is the escape character? What is a control character? Write two control<br />characters and indicate what they are for.<br /><br />29) What will the following program output, and why?<br /><br />
Código: javascript
<HTML><br /><SCRIPT LANGUAGE="JavaScript"><br />// EVAL1N.HTM<br />var num=0xA;<br /></HTML>
<br /><br />Save it with the name Eval1N.htm in TuCarpeta.<br /><br />30) Convert the number 9AC1, which is in base 16, to base 10, mathematically<br /><br />31) Convert the number 7640, which is in base 8, to base 10, mathematically.<br /><br />32) Use already-made programs to check the two previous exercises.<br /><br />33) What is the difference between null and NaN<br /><br />34) What problem is there when adding in JavaScript? Explain how to solve it.<br /><br />35) Indicate what the following values are equal to:<br /><br />a) parseInt("A",16)=<br />b) parseFloat("31H")=<br />c) toString(13)=<br />d) toString(4.273,49)=<br /><br />
Alex ·
II.- Programming Structures
<br /><br />
1.- Logical and Relational Operators
<br /><br />>, <, <=, >=<br />== equality<br />!= different<br />&& and<br />|| or<br />! Not
Grupo de WhatsApp