Sie sind auf Seite 1von 38

JavaScript

JavaScript
<!doctype html>
<html>

<head>
<title>Code inside an HTML document</title>
<script>
alert("Hello, world!");
</script>
</head>

<body>
</body>

</html>
JavaScript
<!doctype html>
<html>

<head>
<title>Code inside an HTML document</title>
<script src="hello.js"></script>
</head>

<body>
</body>

</html>
JavaScript - DOM
El navegador convierte las etiquetas HTML, en una representación interna
llamada DOM Modelo de Objetos de Documento.

JavaScript interactúa con su HTML a través de la manipulación del DOM.

Si se accede al DOM antes de que el navegador haya terminado de construirlo,


se generará error.

Al incluir <script> al inicio ejecuta el código inmediatamente, incluso si el DOM no


se ha construido. Cualquier referencia al DOM en ese momento producirá error.
JavaScript - DOM
Solución:

función onload()

Incluir la etiqueta al final del documento. Después de </body>. Éste es el método


preferido ya que con onload hay que esperar a que se hayan descargado todos
los recursos de la página para poder ejecutarse.
JavaScript
<!doctype html>
<html>
<head>
<title>Code inside an HTML document</title>
<script>
window.onload = function () {
alert("Hello, world!");
};
</script>
</head>
<body>
<h1>An example</h1>
<p>Here's an example document with loads of images.</p>
<ul>
<li><img src="pic1.jpg" /></li>
<li><img src="pic2.jpg" /></li>
<li><img src="pic3.jpg" /></li>
<!-- lots more -->
</ul>
<script src="hello.js"></script>
<script src="another.js"></script>
<script src="and-another.js"></script>
</body>
</html>
JavaScript - Variables
var task = "Write the first chapter.";

var task = "Write the first chapter.",


complete = true;

Case Sensitive

Se recomienda definir y después inicializar las variables.

var task, complete;


// initialization
task = "Write the first chapter.";
complete = true;
JavaScript - Type
No es necesario definir el tipo (lenguaje no fuertemente tipado).
Se puede cambiar el tipo de la variable en la ejecución.

Tipos:

1. number
2. string
3. Boolean
4. null
5. undefined
6. object

El valor NaN es un valor que se obtiene cuando funciones matemáticas fallan:


Math.abs("foo")

Se usa la función isNaN para verificar el valor NaN


JavaScript - Variables
Undefined
Representa el estado de una variable que ha sido creada, pero que no se le ha
asignado un valor.

Null
Se usa cuando se define una variable y se define que no va tener ningún valor

Object
Colección de propiedades. Las propiedades pueden ser de tipo cualquiera de los
vistos anteriormente.
JavaScript - Operaciones
Concatenar
var fname, lname, fullName;
fname = "John";
lname = "Doe";
fullName = fname + " " + lname; // fullName is "John Doe"

Operaciones matemáticas ( +, -, *, / )
var widgets, gizmos, inventory;
widgets = 1043;
gizmos = 2279;
inventory = widgets + gizmos; // inventory is 3322
JavaScript - Operaciones
Operaciones matemáticas ( +, -, *, /, % )
var provincial, federal, subtotal, total;
provincial = 0.095;
federal = 0.05;
subtotal = 10;
total = subtotal + (subtotal * provincial) + (subtotal * federal); // total is 11.45

Importante
var johnTaskCount = 11,
janeTaskCount = "42",
totalTaskCount = johnTaskCount + janeTaskCount;
JavaScript - Comparaciones
Equal (==)
1 == 1 // returns true
"1" == 1 // returns true ("1" converts to 1)
1 == true // returns true
0 == false // returns true
"" == 0 // returns true ("" converts to 0)
" " == 0 // returns true (" " converts to 0)
0 == 1 // returns false
1 == false // returns false
0 == true // returns false
var x, y; // declare x and y
x = {}; // create an object and assign it to x
y = x; // point y to x
x == y; // returns true (refers to same object in memory)
x == {}; // returns false (not the same object)
JavaScript - Comparaciones
Not Equal (!=)

1 != 1 // returns false
"1" != 1 // returns false ("1" converts to 1)
1 != true // returns false
0 != false // returns false
"" != 0 // returns false ("" converts to 0)
" " != 0 // returns false (" " converts to 0)
0 != 1 // returns true
1 != false // returns true
0 != true // returns true
var x, y; // declare x and y
x = {}; // create an object and assign it to x
y = x; // point y to x
x != y; // returns false (refers to same object in memory)
x != {}; // returns true (not the same object)
JavaScript - Comparaciones
Strict Equal (===)

1 === 1 // returns true


"1" === 1 // returns false ("1" is not converted)
1 === true // returns false
0 === false // returns false
"" === 0 // returns false ("" is not converted)
" " === 0 // returns false (" " is not converted)
0 === 1 // returns false
1 === false // returns false
0 === true // returns false
var x, y; // declare x and y
x = {}; // create an object and assign it to x
y = x; // point y to x
x === y; // returns true (refers to same object
JavaScript - Comparaciones
Strict Not Equal (!==)

1 !== 1 // returns false


"1" !== 1 // returns true ("1" is not converted)
1 !== true // returns true
0 !== false // returns true
"" !== 0 // returns true ("" is not converted)
" " !== 0 // returns true (" " is not converted)
0 !== 1 // returns true
1 !== false // returns true
0 !== true // returns true
var x, y; // declare x and y
x = {}; // create an object and assign it to x
y = x; // point y to x
x !== y; // returns false (refers to same object in memory)
x !== {}; // returns true (not the same object)
JavaScript - Comparaciones
Greater than (>)

Greater than or Equal to (>=)

Less than (<)

Less than or Equal to (<=)


JavaScript - Array
var myArray = new Array();

var myArray = []; // Recomendado

var myArray = [4, 8, 15, 16, 23, 42];

var fruit = ["apple", "orange", "pear", "grapes"];

var stuff = [1, "apple", undefined, 42, "tanks", null, []];


JavaScript - Array - Add Data
var myArray = [];
myArray[0] = "Hello";
myArray[1] = "World";

var myArray = [];


myArray["fruit"] = "apple";
myArray["vehicle"] = "tank"; // No recomendado

myArray.push("hello");
JavaScript - Array - Read Data
var myValue,
myArray = ["Hello", "World", "I", "am", "an", "array"];

myValue = myArray[4]; // returns "an"


JavaScript - Array - Métodos
pop()
Elimina el último elemento del array y lo retorna.

var tasks = [
"Pay phone bill",
"Write best-selling novel",
"Walk the dog"
];
tasks.pop(); // returns "Walk the dog"
JavaScript - Array - Métodos
push()
Agrega un nuevo elemento al final del array y retorna la nueva longitud

var tasks = [
"Pay phone bill",
"Write best-selling novel",
"Walk the dog"
];
tasks.push("Feed the cat"); // returns 4
// tasks is now:
// ["Pay phone bill",
// "Write best-selling novel",
// "Walk the dog",
// "Feed the cat"]
JavaScript - Array - Métodos
reverse()
Invierte el orden de los elementos en el array

var tasks = [
"Pay phone bill",
"Write best-selling novel",
"Walk the dog"
];
tasks.reverse();
// tasks is now:
// ["Walk the dog",
// "Write best-selling novel",
// "Pay phone bill"]
JavaScript - Array - Métodos
shift()
Elimina el primer elemento del array y lo retorna

var tasks = [
"Pay phone bill",
"Write best-selling novel",
"Walk the dog"
];
tasks.shift(); // returns "Pay phone bill"
// tasks is now:
// ["Write best-selling novel",
// "Walk the dog"]
JavaScript - Array - Métodos
sort()
Ordena los elementos en orden ascendente. Todo se convierte en String y luego
se compara. Si el array es [3, 10, 1, 2], lo ordena [1, 10, 2, 3].

var tasks = ["Pay phone bill", "Write best-selling novel", "Walk the dog"];
tasks.sort(); // sorts array in ascending order
// tasks is now:
// ["Pay phone bill", "Walk the dog", "Write best-selling novel"]

Podemos pasar como comparar los elementos (función).

array.sort([compare]);
JavaScript - Array - Métodos
splice()
Permite agregar y eliminar simultáneamente elementos a un array. Retorna los
elementos que elimina.

var tasks = [
"Pay phone bill",
"Write best-selling novel",
"Walk the dog"
];
tasks.splice(1, 1, "World domination");
// tasks is now:
// ["Pay phone bill",
// "World domination",
// "Walk the dog"]
JavaScript - Array - Métodos
splice()
var tasks = [
"Pay phone bill",
"Write best-selling novel",
"Walk the dog"
];
tasks.splice(1, 1, "World domination", "Rotate tires",
➥"Hire hit squad");
// tasks is now:
// ["Pay phone bill",
// "World domination",
// "Rotate tires",
// "Hire hit squad",
// "Walk the dog"]
JavaScript - Array - Métodos
unshift()
Agregar uno o más elementos al inicio del array, y retorna la nueva longitud.

var tasks, len;


tasks = [
"Pay phone bill",
"Write best-selling novel",
"Walk the dog"
];
len = tasks.unshift("Defeat nemesis", "Pick up dry cleaning");
alert("You now have " + len + " tasks to complete: " + tasks.join(", "));
JavaScript - Array - Métodos de acceso
join()
Muestra los elementos del array con el separador que asignado como parámetro.

var nums;
nums = [4, 8, 15, 16, 23, 42];
alert("The winning lottery numbers are: " + nums.join(", "));
JavaScript - Array - Métodos de acceso
slice()
Copia o extrae una parte de una array. Se indica el inicio y opcionalmente el final a
extraer.

var tasks, todo, cleanup, noCleaning;


tasks = [
"Fly a kite",
"Save the world",
[ "Clean bathroom", "Clean garage", "Clean up act" ]
];
todo = tasks.slice(0); // makes a copy of tasks
cleanup = tasks.slice(-1); // copies only the nested array
noCleaning = tasks.slice(0, 2); // copies only the first two items
JavaScript - Array - Métodos de acceso
toString()
Retorna un string representando el array y sus elementos.

var arr = ["These", "words", "are",


"separated", "by", "commas"];

arr.toString(); // returns "These,words,are,separated,by,commas"


JavaScript - Array - Métodos de acceso
indexOf()
Retorna el índice del primer elemento encontrado, pasado como parámetro.

var alphabet;
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

alert("The letter ’m’ is at index: " + alphabet.indexOf("m"));

//Retorna 12
JavaScript - Array - Iteration Methods
forEach()

var arr, i, num, total;


arr = [4, 8, 15, 16, 23, 42];
total = 0;

for (i = 0; i < arr.length; i = i + 1) {


num = arr[i];
total = total + num;
}

alert("The total is: " + total);


JavaScript - Array - Iteration Methods
forEach()

var arr, total;


arr = [4, 8, 15, 16, 23, 42];
total = 0;

arr.forEach(function(num) {
total = total + num;
});

alert("The total is: " + total);


JavaScript - Objects
var myObject = new Object();

var myObject = {}; // Ésta forma es más preferible, sencillo y más seguro

Utilizan sistema clave - valor para acceder a los valores y propiedades

var lotteryNumbers, profile;

lotteryNumbers = [4, 8, 15, 16, 23, 42];

profile = {
firstName: "Hugo",
lastName: "Reyes",
flight: "Oceanic 815",
car: "Camaro"
};
JavaScript - Objects
var obj = {};
obj["firstName"] = "Hugo";
obj["lastName"] = "Reyes";

var obj = {};


obj.firstName = "Hugo";
obj.lastName = "Reyes";

La selección de la notación puede depender de algunas necesidades. Por ejemplo, los [] pueden contener
variables o espacios.

alert("Hello, my name is " + obj.firstName + " " + obj.lastName + ".");


JavaScript
DOM
JavaScript - Document Object Model
API para manipular documentos HTML y XHTML.
Árbol jerárquico de objetos que representa un documento.
Se exponen métodos y propiedades.

alert("Hello, my name is " + obj.firstName + " " + obj.lastName + ".");


Referencias
Jump Start JavaScript

Das könnte Ihnen auch gefallen