commit
ff3d69bc82
@ -0,0 +1,682 @@
|
||||
# 30 Dias de JavaScript
|
||||
|
||||
| # Dia | Tópicos |
|
||||
| ----- | :-------------------------------------------------------------------------------------------------------------------------------------------------: |
|
||||
| 01 | [Introdução](./readMe.md) |
|
||||
| 02 | [Tipos de Dados](./02_Day_Data_types/02_day_data_types.md) |
|
||||
| 03 | [Booleanos, Operadores, Data](./03_Day_Booleans_operators_date/03_booleans_operators_date.md) |
|
||||
| 04 | [Condicionais](./04_Day_Conditionals/04_day_conditionals.md) |
|
||||
| 05 | [Arrays](./05_Day_Arrays/05_day_arrays.md) |
|
||||
| 06 | [Loops](./06_Day_Loops/06_day_loops.md) |
|
||||
| 07 | [Funções](./07_Day_Functions/07_day_functions.md) |
|
||||
| 08 | [Objetos](./08_Day_Objects/08_day_objects.md) |
|
||||
| 09 | [Higher Order Functions](./09_Day_Higher_order_functions/09_day_higher_order_functions.md) |
|
||||
| 10 | [Sets and Maps](./10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) |
|
||||
| 11 | [Destructuring and Spreading](./11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) |
|
||||
| 12 | [Expressões Regulares](./12_Day_Regular_expressions/12_day_regular_expressions.md) |
|
||||
| 13 | [Método Console Objeto](./13_Day_Console_object_methods/13_day_console_object_methods.md) |
|
||||
| 14 | [Tratamento de Erros](./14_Day_Error_handling/14_day_error_handling.md) |
|
||||
| 15 | [Classes](./15_Day_Classes/15_day_classes.md) |
|
||||
| 16 | [JSON](./16_Day_JSON/16_day_json.md) |
|
||||
| 17 | [Armazenamento na Web](./17_Day_Web_storages/17_day_web_storages.md) |
|
||||
| 18 | [Promises](./18_Day_Promises/18_day_promises.md) |
|
||||
| 19 | [Closure](./19_Day_Closures/19_day_closures.md) |
|
||||
| 20 | [Escrevendo Código Limpo](./20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) |
|
||||
| 21 | [DOM](./21_Day_DOM/21_day_dom.md) |
|
||||
| 22 | [Manipulando DOM Objetos](./22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) |
|
||||
| 23 | [Event Listeners](./23_Day_Event_listeners/23_day_event_listeners.md) |
|
||||
| 24 | [Mini Projeto: Sistema Solar](./24_Day_Project_solar_system/24_day_project_solar_system.md) |
|
||||
| 25 | [Mini Projeto: Visualização de Dados de Paises do mundo](./25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) |
|
||||
| 26 | [Mini Projeto: Visualização de Dados de Paises do mundo 2](./26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) |
|
||||
| 27 | [Mini Projeto: Portfólio](./27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) |
|
||||
| 28 | [Mini Projeto: Leaderboard](./28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) |
|
||||
| 29 | [Mini Projeto: Caracteres Animados](./29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md) |
|
||||
| 30 | [Projetos Finais](./30_Day_Mini_project_final/30_day_mini_project_final.md) |
|
||||
|
||||
🧡🧡🧡 HAPPY CODING 🧡🧡🧡
|
||||
|
||||
<div>
|
||||
<small>Dê suporte ao <strong>Autor</strong> para criar mais materiais educacionais</small> <br />
|
||||
<a href = "https://www.paypal.me/asabeneh"><img src='/images/paypal_lg.png' alt='Paypal Logo' style="width:10%"/></a>
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<h1> 30 Dias de JavaScript: Introdução</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Janeiro, 2020</small>
|
||||
</sub>
|
||||
|
||||
<div>
|
||||
|
||||
🇬🇧 [English](./readMe.md)
|
||||
🇪🇸 [Spanish](./Spanish/readme.md)
|
||||
🇮🇹 [Italian](./Italian/readMe.md)
|
||||
🇷🇺 [Russian](./RU/README.md)
|
||||
🇹🇷 [Turkish](./Turkish/readMe.md)
|
||||
🇦🇿 [Azerbaijan](./Azerbaijani/readMe.md)
|
||||
🇰🇷 [Korean](./Korea/README.md)
|
||||
🇻🇳 [Vietnamese](./Vietnamese/README.md)
|
||||
🇵🇱 [Polish](./Polish/readMe.md)
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
[Dia 2 >>](./02_Day_Data_types/02_day_data_types.md)
|
||||
|
||||

|
||||
|
||||
- [30 dias de JavaScript](#30-days-of-javascript)
|
||||
- [📔 Dia 1](#-day-1)
|
||||
- [Introdução](#introduction)
|
||||
- [Requisitos](#requirements)
|
||||
- [Setup](#setup)
|
||||
- [Instalação Node.js](#install-nodejs)
|
||||
- [Navegador](#browser)
|
||||
- [Instalando Google Chrome](#installing-google-chrome)
|
||||
- [Abrindo Google Chrome Console](#opening-google-chrome-console)
|
||||
- [Escrevendo Código no Browser Console](#writing-code-on-browser-console)
|
||||
- [Console.log](#consolelog)
|
||||
- [Console.log com Múltiplos Argumentos](#consolelog-with-multiple-arguments)
|
||||
- [Comentários](#comments)
|
||||
- [Sintaxe](#syntax)
|
||||
- [Aritimética](#arithmetics)
|
||||
- [Editor de Código](#code-editor)
|
||||
- [Instalando Visual Studio Code](#installing-visual-studio-code)
|
||||
- [Como usar o Visual Studio Code](#how-to-use-visual-studio-code)
|
||||
- [Adicionando JavaScript na Web Page](#adding-javascript-to-a-web-page)
|
||||
- [Script em Linha](#inline-script)
|
||||
- [Script Interno](#internal-script)
|
||||
- [Script Externo](#external-script)
|
||||
- [Multiplo Scripts Externos](#multiple-external-scripts)
|
||||
- [Introdução Tipo de Dados](#introduction-to-data-types)
|
||||
- [Números](#numbers)
|
||||
- [Strings](#strings)
|
||||
- [Booleanos](#booleans)
|
||||
- [Undefined](#undefined)
|
||||
- [Null](#null)
|
||||
- [Verificando Tipo de Dados](#checking-data-types)
|
||||
- [Novamente Comentarios](#comments-again)
|
||||
- [Variáveis](#variables)
|
||||
- [💻 Dia 1: Exercícios](#-day-1-exercises)
|
||||
|
||||
# 📔 Dia 1
|
||||
|
||||
## Introdução
|
||||
|
||||
**Parabéns** Em decidir participar dos 30 dias de JavaScript desafio. Neste desafio você aprenderá tudo que precisa para ser um JavaScript programador, e em general, todo o conceito de programaçao. No fim do desafio voce estará adquirindo o Certificado de conclusão dos 30DiasdeJavaScript desafio. Em caso de precisar de ajuda ou se preferir ajudar outros você pode entrar no [Grupo Telegram](https://t.me/ThirtyDaysOfJavaScript).
|
||||
|
||||
**30DiasDeJavaScript** desafio é um guia tanto para iniciantes e Avançados JavaScript Desenvolvedores, Bem vindo ao JavaScript. JavaScript é a linguagem da internet. Eu me divirto em usar e ensinar JavaScript e eu acredito que voce fará tambem.
|
||||
|
||||
Neste passo a passo do JavaScript Desafio, você aprenderá JavaScript, a mais popular linguagem de programação da história da humanindade.
|
||||
JavaScript é usado **_para adicionar interatividade aos websites, desenvolvimento de mobile apps, desktop aplicações, jogos_** e nos dias de hoje JavaScript pode ser usado para **_machine learning_** e **_AI_**.
|
||||
**_JavaScript (JS)_** Teve um aumento na popularidade nos últimos anos e segue como a linguagem de programação líder por seis anos consecutivos e é a linguagem de programação mais usada no GitHub
|
||||
|
||||
## Requisitos
|
||||
|
||||
Sem conhecimentos prévios de programação é exigido para seguir este desafio. Precisará apenas:
|
||||
1. Motivação
|
||||
2. Um computador
|
||||
3. Internet
|
||||
4. Um navegador
|
||||
5. Um editor de Código
|
||||
|
||||
## Setup
|
||||
|
||||
Eu acredito que voce tem a motivação e o forte desejo de ser um desenvolvedor, um computador e internet. Se voce tem isso, então você tem tudo para iniciar.
|
||||
|
||||
## Instalando Node.js
|
||||
|
||||
Você pode não precisar do Node.js agora mas você precisará mais tarde. Instalação do [node.js](https://nodejs.org/en/).
|
||||
|
||||

|
||||
|
||||
Depois do download click duplo e intalar
|
||||
|
||||

|
||||
|
||||
Nós podemos verificar se o Node está instalador na nossa máquina local abrindo nosso terminal do dispositivo ou prompt de comando.
|
||||
|
||||
```sh
|
||||
asabeneh $ node -v
|
||||
v12.14.0
|
||||
```
|
||||
|
||||
Enquanto fazia este tutorial eu estava usando a versão 12.14.0 do Node, mas agora a recomendada versão do Node.js para dowload é v14.17.6, pelo tempo que você usar este material pode haver versão mais atual do Node.js.
|
||||
|
||||
### Navegador
|
||||
|
||||
Existe muitos navegadores por ai, Entento, Eu fortemente recomento o Google Chrome.
|
||||
|
||||
#### Instalando Google Chrome
|
||||
|
||||
Instalar o [Google Chrome](https://www.google.com.br/chrome/) se você não tem um ainda. Nós podemos escrever um pequeno código de JavaScript no console do browser, mas nós não usamos o console do navegador para desenvolver aplicações.
|
||||
|
||||

|
||||
|
||||
#### Abrindo o Google Chrome Console
|
||||
|
||||
Você pode abrir o Google Chrome console por um ou outro clicando nos 3 pontos no topo do lado direito do navegador, selecionando _Mais ferramentas -> Ferramenta para desenvolvedores ou usando o atalho do teclado. Eu prefiro os atalhos.
|
||||
|
||||

|
||||
|
||||
Para abrir o console do Chrome usando o atalho do teclado.
|
||||
|
||||
```sh
|
||||
Mac
|
||||
Command+Option+J
|
||||
|
||||
Windows/Linux:
|
||||
Ctl+Shift+J
|
||||
```
|
||||
|
||||

|
||||
|
||||
Depois de você abrir o console do Google Chrome, tente explorar os botões marcados. Nós vamos passar a maior parte do tempo no Console. O Console é o lugar onde vai seu código de JavaScript. O Console do Google Chrome V8 engine muda seu codigo de JavaScript para código de máquina.
|
||||
Vamos escrever códigos de JavaScript no Google Chome console:
|
||||
|
||||

|
||||
|
||||
#### Escrevendo Código no console do Navegador
|
||||
|
||||
Nós podemos escrever qualquer código de JavaScript no console do Google Chrome ou qualquer outro console de navegador, para este desafio, nós vamos focar no Console do Google Chrome. Abra o Console usando:
|
||||
|
||||
```sh
|
||||
Mac
|
||||
Command+Option+I
|
||||
|
||||
Windows:
|
||||
Ctl+Shift+I
|
||||
```
|
||||
|
||||
##### Console.log
|
||||
|
||||
Para escrever nosso primeiro código em JavaScript, vamos usar uma função já construída chamada **console.log()**. Nós passamos um argumento como dados de input, e a função mostra o output. Nós passamos `'Olá, Mundo!'` como dados de input ou argumento na função console.log().
|
||||
|
||||
```js
|
||||
console.log('Olá, Mundo!')
|
||||
```
|
||||
|
||||
##### Console.log com Múltiplos Argumentos
|
||||
|
||||
A funçao **`console.log()`** pode receber múltiplos parâmetros separados por vírgulas. A sintaxe é similar ao seguinte modo:**`console.log(param1, param2, param3)`**
|
||||
|
||||

|
||||
|
||||
```js
|
||||
console.log('Olá', 'Mundo', '!')
|
||||
console.log('Feliz', 'Ano', 'Novo', 2020)
|
||||
console.log('Bem vindo', 'aos', 30, 'Dias', 'de', 'JavaScript')
|
||||
```
|
||||
|
||||
Como você pode ver pelo trecho de código acima, _`console.log()`_ pode receber múltiplos argumentos.
|
||||
|
||||
Parabéns! Você escreveu seu primeiro código de JavaScript usando _`console.log()`_.
|
||||
|
||||
##### Comentários
|
||||
|
||||
Nós podemos adicionar comentários para nosso código. Comentários sao importantes para fazer o codigo ser fácil de ler e deixar observações no nosso código. JavaScript nao executa o partes com comentário no nosso código. No JavaScript, qualquer linha de texto começando com // em JavaScript é um comentário, e q
|
||||
|
||||
|
||||
|
||||
|
||||
##### Comments
|
||||
|
||||
We can add comments to our code. Comments are very important to make code more readable and to leave remarks in our code. JavaScript does not execute the comment part of our code. In JavaScript, any text line starting with // in JavaScript is a comment, and anything enclosed like this `//` is also a comment.
|
||||
|
||||
**Example: Single Line Comment**
|
||||
|
||||
```js
|
||||
// This is the first comment
|
||||
// This is the second comment
|
||||
// I am a single line comment
|
||||
```
|
||||
|
||||
**Example: Multiline Comment**
|
||||
|
||||
```js
|
||||
/*
|
||||
This is a multiline comment
|
||||
Multiline comments can take multiple lines
|
||||
JavaScript is the language of the web
|
||||
*/
|
||||
```
|
||||
|
||||
##### Syntax
|
||||
|
||||
Programming languages are similar to human languages. English or many other language uses words, phrases, sentences, compound sentences and other more to convey a meaningful message. The English meaning of syntax is _the arrangement of words and phrases to create well-formed sentences in a language_. The technical definition of syntax is the structure of statements in a computer language. Programming languages have syntax. JavaScript is a programming language and like other programming languages it has its own syntax. If we do not write a syntax that JavaScript understands, it will raise different types of errors. We will explore different kinds of JavaScript errors later. For now, let us see syntax errors.
|
||||
|
||||

|
||||
|
||||
I made a deliberate mistake. As a result, the console raises syntax errors. Actually, the syntax is very informative. It informs what type of mistake was made. By reading the error feedback guideline, we can correct the syntax and fix the problem. The process of identifying and removing errors from a program is called debugging. Let us fix the errors:
|
||||
|
||||
```js
|
||||
console.log('Hello, World!')
|
||||
console.log('Hello, World!')
|
||||
```
|
||||
|
||||
So far, we saw how to display text using the _`console.log()`_. If we are printing text or string using _`console.log()`_, the text has to be inside the single quotes, double quotes, or a backtick.
|
||||
**Example:**
|
||||
|
||||
```js
|
||||
console.log('Hello, World!')
|
||||
console.log("Hello, World!")
|
||||
console.log(`Hello, World!`)
|
||||
```
|
||||
|
||||
#### Arithmetics
|
||||
|
||||
Now, let us practice more writing JavaScript codes using _`console.log()`_ on Google Chrome console for number data types.
|
||||
In addition to the text, we can also do mathematical calculations using JavaScript. Let us do the following simple calculations.
|
||||
It is possible to write JavaScript code on Google Chrome console can directly without the **_`console.log()`_** function. However, it is included in this introduction because most of this challenge would be taking place in a text editor where the usage of the function would be mandatory. You can play around directly with instructions on the console.
|
||||
|
||||

|
||||
|
||||
```js
|
||||
console.log(2 + 3) // Addition
|
||||
console.log(3 - 2) // Subtraction
|
||||
console.log(2 * 3) // Multiplication
|
||||
console.log(3 / 2) // Division
|
||||
console.log(3 % 2) // Modulus - finding remainder
|
||||
console.log(3 ** 2) // Exponentiation 3 ** 2 == 3 * 3
|
||||
```
|
||||
|
||||
### Code Editor
|
||||
|
||||
We can write our codes on the browser console, but it won't be for bigger projects. In a real working environment, developers use different code editors to write their codes. In this 30 dias de JavaScript challenge, we will be using Visual Studio Code.
|
||||
|
||||
#### Installing Visual Studio Code
|
||||
|
||||
Visual Studio Code is a very popular open-source text editor. I would recommend to [download Visual Studio Code](https://code.visualstudio.com/), but if you are in favor of other editors, feel free to follow with what you have.
|
||||
|
||||

|
||||
|
||||
If you installed Visual Studio Code, let us start using it.
|
||||
|
||||
#### How to Use Visual Studio Code
|
||||
|
||||
Open the Visual Studio Code by double-clicking its icon. When you open it, you will get this kind of interface. Try to interact with the labeled icons.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## Adding JavaScript to a Web Page
|
||||
|
||||
JavaScript can be added to a web page in three different ways:
|
||||
|
||||
- **_Inline script_**
|
||||
- **_Internal script_**
|
||||
- **_External script_**
|
||||
- **_Multiple External scripts_**
|
||||
|
||||
The following sections show different ways of adding JavaScript code to your web page.
|
||||
|
||||
### Inline Script
|
||||
|
||||
Create a project folder on your desktop or in any location, name it 30DaysOfJS and create an **_`index.html`_** file in the project folder. Then paste the following code and open it in a browser, for example [Chrome](https://www.google.com/chrome/).
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>30DaysOfScript:Inline Script</title>
|
||||
</head>
|
||||
<body>
|
||||
<button onclick="alert('Welcome to 30DiasDeJavaScript!')">Click Me</button>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Now, you just wrote your first inline script. We can create a pop up alert message using the _`alert()`_ built-in function.
|
||||
|
||||
### Internal Script
|
||||
|
||||
The internal script can be written in the _`head`_ or the _`body`_, but it is preferred to put it on the body of the HTML document.
|
||||
First, let us write on the head part of the page.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>30DaysOfScript:Internal Script</title>
|
||||
<script>
|
||||
console.log('Welcome to 30DiasDeJavaScript')
|
||||
</script>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
```
|
||||
|
||||
This is how we write an internal script most of the time. Writing the JavaScript code in the body section is the most preferred option. Open the browser console to see the output from the `console.log()`.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>30DaysOfScript:Internal Script</title>
|
||||
</head>
|
||||
<body>
|
||||
<button onclick="alert('Welcome to 30DiasDeJavaScript!');">Click Me</button>
|
||||
<script>
|
||||
console.log('Welcome to 30DiasDeJavaScript')
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Open the browser console to see the output from the `console.log()`.
|
||||
|
||||

|
||||
|
||||
### External Script
|
||||
|
||||
Similar to the internal script, the external script link can be on the header or body, but it is preferred to put it in the body.
|
||||
First, we should create an external JavaScript file with .js extension. All files ending with .js extension are JavaScript files. Create a file named introduction.js inside your project directory and write the following code and link this .js file at the bottom of the body.
|
||||
|
||||
```js
|
||||
console.log('Welcome to 30DiasDeJavaScript')
|
||||
```
|
||||
|
||||
External scripts in the _head_:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>30DiasDeJavaScript:External script</title>
|
||||
<script src="introduction.js"></script>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
```
|
||||
|
||||
External scripts in the _body_:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>30DiasDeJavaScript:External script</title>
|
||||
</head>
|
||||
<body>
|
||||
<!-- JavaScript external link could be in the header or in the body -->
|
||||
<!-- Before the closing tag of the body is the recommended place to put the external JavaScript script -->
|
||||
<script src="introduction.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Open the browser console to see the output of the `console.log()`.
|
||||
|
||||
### Multiple External Scripts
|
||||
|
||||
We can also link multiple external JavaScript files to a web page.
|
||||
Create a `helloworld.js` file inside the 30DaysOfJS folder and write the following code.
|
||||
|
||||
```js
|
||||
console.log('Hello, World!')
|
||||
```
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Multiple External Scripts</title>
|
||||
</head>
|
||||
<body>
|
||||
<script src="./helloworld.js"></script>
|
||||
<script src="./introduction.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
_Your main.js file should be below all other scripts_. It is very important to remember this.
|
||||
|
||||

|
||||
|
||||
## Introduction to Data types
|
||||
|
||||
In JavaScript and also other programming languages, there are different types of data types. The following are JavaScript primitive data types: _String, Number, Boolean, undefined, Null_, and _Symbol_.
|
||||
|
||||
### Numbers
|
||||
|
||||
- Integers: Integer (negative, zero and positive) numbers
|
||||
Example:
|
||||
... -3, -2, -1, 0, 1, 2, 3 ...
|
||||
- Float-point numbers: Decimal number
|
||||
Example
|
||||
... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...
|
||||
|
||||
### Strings
|
||||
|
||||
A collection of one or more characters between two single quotes, double quotes, or backticks.
|
||||
|
||||
**Example:**
|
||||
|
||||
```js
|
||||
'a'
|
||||
'Asabeneh'
|
||||
"Asabeneh"
|
||||
'Finland'
|
||||
'JavaScript is a beautiful programming language'
|
||||
'I love teaching'
|
||||
'I hope you are enjoying the first day'
|
||||
`We can also create a string using a backtick`
|
||||
'A string could be just as small as one character or as big as many pages'
|
||||
'Any data type under a single quote, double quote or backtick is a string'
|
||||
```
|
||||
|
||||
### Booleans
|
||||
|
||||
A boolean value is either True or False. Any comparisons returns a boolean value, which is either true or false.
|
||||
|
||||
A boolean data type is either a true or false value.
|
||||
|
||||
**Example:**
|
||||
|
||||
```js
|
||||
true // if the light is on, the value is true
|
||||
false // if the light is off, the value is false
|
||||
```
|
||||
|
||||
### Undefined
|
||||
|
||||
In JavaScript, if we don't assign a value to a variable, the value is undefined. In addition to that, if a function is not returning anything, it returns undefined.
|
||||
|
||||
```js
|
||||
let firstName
|
||||
console.log(firstName) // undefined, because it is not assigned to a value yet
|
||||
```
|
||||
|
||||
### Null
|
||||
|
||||
Null in JavaScript means an empty value.
|
||||
|
||||
```js
|
||||
let emptyValue = null
|
||||
```
|
||||
|
||||
## Checking Data Types
|
||||
|
||||
To check the data type of a certain variable, we use the **typeof** operator. See the following example.
|
||||
|
||||
```js
|
||||
console.log(typeof 'Asabeneh') // string
|
||||
console.log(typeof 5) // number
|
||||
console.log(typeof true) // boolean
|
||||
console.log(typeof null) // object type
|
||||
console.log(typeof undefined) // undefined
|
||||
```
|
||||
|
||||
## Comments Again
|
||||
|
||||
Remember that commenting in JavaScript is similar to other programming languages. Comments are important in making your code more readable.
|
||||
There are two ways of commenting:
|
||||
|
||||
- _Single line commenting_
|
||||
- _Multiline commenting_
|
||||
|
||||
```js
|
||||
// commenting the code itself with a single comment
|
||||
// let firstName = 'Asabeneh'; single line comment
|
||||
// let lastName = 'Yetayeh'; single line comment
|
||||
```
|
||||
|
||||
Multiline commenting:
|
||||
|
||||
```js
|
||||
/*
|
||||
let location = 'Helsinki';
|
||||
let age = 100;
|
||||
let isMarried = true;
|
||||
This is a Multiple line comment
|
||||
*/
|
||||
```
|
||||
|
||||
## Variables
|
||||
|
||||
Variables are _containers_ of data. Variables are used to _store_ data in a memory location. When a variable is declared, a memory location is reserved. When a variable is assigned to a value (data), the memory space will be filled with that data. To declare a variable, we use _var_, _let_, or _const_ keywords.
|
||||
|
||||
For a variable that changes at a different time, we use _let_. If the data does not change at all, we use _const_. For example, PI, country name, gravity do not change, and we can use _const_. We will not use var in this challenge and I don't recommend you to use it. It is error prone way of declaring variable it has lots of leak. We will talk more about var, let, and const in detail in other sections (scope). For now, the above explanation is enough.
|
||||
|
||||
A valid JavaScript variable name must follow the following rules:
|
||||
|
||||
- A JavaScript variable name should not begin with a number.
|
||||
- A JavaScript variable name does not allow special characters except dollar sign and underscore.
|
||||
- A JavaScript variable name follows a camelCase convention.
|
||||
- A JavaScript variable name should not have space between words.
|
||||
|
||||
The following are examples of valid JavaScript variables.
|
||||
|
||||
```js
|
||||
firstName
|
||||
lastName
|
||||
country
|
||||
city
|
||||
capitalCity
|
||||
age
|
||||
isMarried
|
||||
|
||||
first_name
|
||||
last_name
|
||||
is_married
|
||||
capital_city
|
||||
|
||||
num1
|
||||
num_1
|
||||
_num_1
|
||||
$num1
|
||||
year2020
|
||||
year_2020
|
||||
```
|
||||
|
||||
The first and second variables on the list follows the camelCase convention of declaring in JavaScript. In this material, we will use camelCase variables(camelWithOneHump). We use CamelCase(CamelWithTwoHump) to declare classes, we will discuss about classes and objects in other section.
|
||||
|
||||
Example of invalid variables:
|
||||
|
||||
```js
|
||||
first-name
|
||||
1_num
|
||||
num_#_1
|
||||
```
|
||||
|
||||
Let us declare variables with different data types. To declare a variable, we need to use _let_ or _const_ keyword before the variable name. Following the variable name, we write an equal sign (assignment operator), and a value(assigned data).
|
||||
|
||||
```js
|
||||
// Syntax
|
||||
let nameOfVariable = value
|
||||
```
|
||||
|
||||
The nameOfVriable is the name that stores different data of value. See below for detail examples.
|
||||
|
||||
**Examples of declared variables**
|
||||
|
||||
```js
|
||||
// Declaring different variables of different data types
|
||||
let firstName = 'Asabeneh' // first name of a person
|
||||
let lastName = 'Yetayeh' // last name of a person
|
||||
let country = 'Finland' // country
|
||||
let city = 'Helsinki' // capital city
|
||||
let age = 100 // age in years
|
||||
let isMarried = true
|
||||
|
||||
console.log(firstName, lastName, country, city, age, isMarried)
|
||||
```
|
||||
|
||||
```sh
|
||||
Asabeneh Yetayeh Finland Helsinki 100 true
|
||||
```
|
||||
|
||||
```js
|
||||
// Declaring variables with number values
|
||||
let age = 100 // age in years
|
||||
const gravity = 9.81 // earth gravity in m/s2
|
||||
const boilingPoint = 100 // water boiling point, temperature in °C
|
||||
const PI = 3.14 // geometrical constant
|
||||
console.log(gravity, boilingPoint, PI)
|
||||
```
|
||||
|
||||
```sh
|
||||
9.81 100 3.14
|
||||
```
|
||||
|
||||
```js
|
||||
// Variables can also be declaring in one line separated by comma, however I recommend to use a seperate line to make code more readble
|
||||
let name = 'Asabeneh', job = 'teacher', live = 'Finland'
|
||||
console.log(name, job, live)
|
||||
```
|
||||
|
||||
```sh
|
||||
Asabeneh teacher Finland
|
||||
```
|
||||
|
||||
When you run _index.html_ file in the 01-Day folder you should get this:
|
||||
|
||||

|
||||
|
||||
🌕 You are amazing! You have just completed day 1 challenge and you are on your way to greatness. Now do some exercises for your brain and muscle.
|
||||
|
||||
# 💻 Day 1: Exercises
|
||||
|
||||
1. Write a single line comment which says, _comments can make code readable_
|
||||
2. Write another single comment which says, _Welcome to 30DiasDeJavaScript_
|
||||
3. Write a multiline comment which says, _comments can make code readable, easy to reuse_
|
||||
_and informative_
|
||||
|
||||
4. Create a variable.js file and declare variables and assign string, boolean, undefined and null data types
|
||||
5. Create datatypes.js file and use the JavaScript **_typeof_** operator to check different data types. Check the data type of each variable
|
||||
6. Declare four variables without assigning values
|
||||
7. Declare four variables with assigned values
|
||||
8. Declare variables to store your first name, last name, marital status, country and age in multiple lines
|
||||
9. Declare variables to store your first name, last name, marital status, country and age in a single line
|
||||
10. Declare two variables _myAge_ and _yourAge_ and assign them initial values and log to the browser console.
|
||||
|
||||
```sh
|
||||
I am 25 years old.
|
||||
You are 30 years old.
|
||||
```
|
||||
|
||||
🎉 CONGRATULATIONS ! 🎉
|
||||
|
||||
[Day 2 >>](./02_Day_Data_types/02_day_data_types.md)
|
@ -0,0 +1,602 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: JSON</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 15](../dia_15_Clases/dia_15_clases.md) | [Día 17 >>](../dia_17_Web_storages/dia_17_web_storages.md)
|
||||
|
||||

|
||||
|
||||
- [Día 16](#día-16)
|
||||
- [JSON](#json)
|
||||
- [Convertir JSON en objeto JavaScript](#convertir-json-en-objeto-javascript)
|
||||
- [JSON.parse()](#jsonparse)
|
||||
- [Uso de una función de recuperación con JSON.parse()](#uso-de-una-función-de-recuperación-con-jsonparse)
|
||||
- [Conversión de objetos a JSON](#conversión-de-objetos-a-json)
|
||||
- [Usando un filtro de array con JSON.stringify](#usando-un-filtro-de-array-con-jsonstringify)
|
||||
- [Ejercicios](#ejercicios)
|
||||
- [Ejercicios Nivel 1](#ejercicios-nivel-1)
|
||||
- [Ejercicios Nivel 2](#ejercicios-nivel-2)
|
||||
- [Ejercicios Nivel 3](#ejercicios-nivel-3)
|
||||
|
||||
# Día 16
|
||||
|
||||
## JSON
|
||||
|
||||
JSON son las siglas de JavaScript Object Notation (Notación de objetos de JavaScript). La sintaxis JSON se deriva de la sintaxis de notación de objetos de JavaScript, pero el formato JSON es sólo de texto o cadena. JSON es un formato de datos ligero para almacenar y transportar. JSON se utiliza sobre todo cuando se envían datos de un servidor a un cliente. JSON es una alternativa más fácil de usar que XML.
|
||||
|
||||
**Ejemplo:**
|
||||
|
||||
```js
|
||||
{
|
||||
"users":[
|
||||
{
|
||||
"firstName":"Asabeneh",
|
||||
"lastName":"Yetayeh",
|
||||
"age":250,
|
||||
"email":"asab@asb.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Alex",
|
||||
"lastName":"James",
|
||||
"age":25,
|
||||
"email":"alex@alex.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Lidiya",
|
||||
"lastName":"Tekle",
|
||||
"age":28,
|
||||
"email":"lidiya@lidiya.com"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
El ejemplo JSON anterior no es muy diferente de un objeto normal. Entonces, ¿cuál es la diferencia? La diferencia es que la clave de un objeto JSON debe ir con comillas dobles o debe ser una cadena. JavaScript Object y JSON son muy similares por lo que podemos cambiar JSON a Object y Object a JSON.
|
||||
|
||||
Veamos el ejemplo anterior con más detalle, comienza con una llave. Dentro de la corchete, hay una clave "usuarios" que tiene una matriz de valores. Dentro del array tenemos diferentes objetos y cada objeto tiene claves, cada clave tiene que tener comillas dobles. Por ejemplo, utilizamos "firstNaMe" en lugar de sólo firstName, sin embargo en el objeto utilizamos claves sin comillas dobles. Esta es la mayor diferencia entre un objeto y un JSON. Veamos más ejemplos sobre JSON.
|
||||
|
||||
**Ejemplo:**
|
||||
|
||||
```js
|
||||
{
|
||||
"Alex": {
|
||||
"email": "alex@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 30
|
||||
},
|
||||
"Asab": {
|
||||
"email": "asab@asab.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Redux",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 25,
|
||||
"isLoggedIn": false,
|
||||
"points": 50
|
||||
},
|
||||
"Brook": {
|
||||
"email": "daniel@daniel.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux"
|
||||
],
|
||||
"age": 30,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Daniel": {
|
||||
"email": "daniel@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Python"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"John": {
|
||||
"email": "john@john.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux",
|
||||
"Node.js"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Thomas": {
|
||||
"email": "thomas@thomas.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"Paul": {
|
||||
"email": "paul@paul.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Convertir JSON en objeto JavaScript
|
||||
|
||||
La mayoría de las veces obtenemos los datos JSON de la respuesta HTTP o de un archivo, pero podemos almacenar el JSON como una cadena y podemos cambiarlo por un objeto para la demostración. En JavaScript la palabra clave _JSON_ tiene los métodos _parse()_ y _stringify()_. Cuando queremos cambiar el JSON a un objeto, parseamos el JSON usando _JSON.parse()_. Cuando queremos pasar el objeto a JSON utilizamos _JSON.stringify()_.
|
||||
|
||||
#### JSON.parse()
|
||||
|
||||
```js
|
||||
JSON.parse(json[, reviver])
|
||||
// json or text , los datos
|
||||
//reviver es una función opcional de callback
|
||||
/* JSON.parse(json, (key, value) => {
|
||||
|
||||
})
|
||||
*/
|
||||
```
|
||||
|
||||
```js
|
||||
const usersText = `{
|
||||
"users":[
|
||||
{
|
||||
"firstName":"Asabeneh",
|
||||
"lastName":"Yetayeh",
|
||||
"age":250,
|
||||
"email":"asab@asb.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Alex",
|
||||
"lastName":"James",
|
||||
"age":25,
|
||||
"email":"alex@alex.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Lidiya",
|
||||
"lastName":"Tekle",
|
||||
"age":28,
|
||||
"email":"lidiya@lidiya.com"
|
||||
}
|
||||
]
|
||||
}`;
|
||||
|
||||
const usersObj = JSON.parse(usersText, undefined, 4);
|
||||
console.log(usersObj);
|
||||
```
|
||||
|
||||
### Uso de una función de recuperación con JSON.parse()
|
||||
|
||||
Para utilizar la función reviver como formateador, ponemos las claves que queremos para formatear el valor del nombre y del apellido. Digamos que estamos interesados en formatear el nombre y el apellido de los datos JSON.
|
||||
|
||||
```js
|
||||
const usersText = `{
|
||||
"users":[
|
||||
{
|
||||
"firstName":"Asabeneh",
|
||||
"lastName":"Yetayeh",
|
||||
"age":250,
|
||||
"email":"asab@asb.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Alex",
|
||||
"lastName":"James",
|
||||
"age":25,
|
||||
"email":"alex@alex.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Lidiya",
|
||||
"lastName":"Tekle",
|
||||
"age":28,
|
||||
"email":"lidiya@lidiya.com"
|
||||
}
|
||||
]
|
||||
}`;
|
||||
|
||||
const usersObj = JSON.parse(usersText, (key, value) => {
|
||||
let newValue =
|
||||
typeof value == "string" && key != "email" ? value.toUpperCase() : value;
|
||||
return newValue;
|
||||
});
|
||||
console.log(usersObj);
|
||||
```
|
||||
|
||||
El _JSON.parse()_ es muy práctico de usar. No tienes que pasar el parámetro opcional, puedes simplemente usarlo con el parámetro requerido y lograrás bastante.
|
||||
|
||||
### Conversión de objetos a JSON
|
||||
|
||||
Cuando queremos pasar el objeto a JSON utilizamos _JSON.stringify()_. El método stringify toma un parámetro obligatorio y dos opcionales. _Replacer_ se utiliza como filtro y _space_ es una indentación. Si no queremos filtrar ninguna de las claves del objeto podemos pasar simplemente undefined.
|
||||
|
||||
```js
|
||||
JSON.stringify(obj, replacer, space);
|
||||
// json or text , los datos
|
||||
// reviver es una función opcional de callback
|
||||
```
|
||||
|
||||
Convirtamos el siguiente objeto en una cadena. Primero mantengamos todas las claves y también tengamos una indentación de 4 espacios.
|
||||
|
||||
```js
|
||||
const users = {
|
||||
Alex: {
|
||||
email: "alex@alex.com",
|
||||
skills: ["HTML", "CSS", "JavaScript"],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 30,
|
||||
},
|
||||
Asab: {
|
||||
email: "asab@asab.com",
|
||||
skills: [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Redux",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node",
|
||||
],
|
||||
age: 25,
|
||||
isLoggedIn: false,
|
||||
points: 50,
|
||||
},
|
||||
Brook: {
|
||||
email: "daniel@daniel.com",
|
||||
skills: ["HTML", "CSS", "JavaScript", "React", "Redux"],
|
||||
age: 30,
|
||||
isLoggedIn: true,
|
||||
points: 50,
|
||||
},
|
||||
Daniel: {
|
||||
email: "daniel@alex.com",
|
||||
skills: ["HTML", "CSS", "JavaScript", "Python"],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40,
|
||||
},
|
||||
John: {
|
||||
email: "john@john.com",
|
||||
skills: ["HTML", "CSS", "JavaScript", "React", "Redux", "Node.js"],
|
||||
age: 20,
|
||||
isLoggedIn: true,
|
||||
points: 50,
|
||||
},
|
||||
Thomas: {
|
||||
email: "thomas@thomas.com",
|
||||
skills: ["HTML", "CSS", "JavaScript", "React"],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40,
|
||||
},
|
||||
Paul: {
|
||||
email: "paul@paul.com",
|
||||
skills: [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node",
|
||||
],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40,
|
||||
},
|
||||
};
|
||||
|
||||
const txt = JSON.stringify(users, undefined, 4);
|
||||
console.log(txt); // text significa JSON- porque json es una forma de cadena de un objeto.
|
||||
```
|
||||
|
||||
```sh
|
||||
{
|
||||
"Alex": {
|
||||
"email": "alex@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 30
|
||||
},
|
||||
"Asab": {
|
||||
"email": "asab@asab.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Redux",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 25,
|
||||
"isLoggedIn": false,
|
||||
"points": 50
|
||||
},
|
||||
"Brook": {
|
||||
"email": "daniel@daniel.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux"
|
||||
],
|
||||
"age": 30,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Daniel": {
|
||||
"email": "daniel@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Python"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"John": {
|
||||
"email": "john@john.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux",
|
||||
"Node.js"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Thomas": {
|
||||
"email": "thomas@thomas.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"Paul": {
|
||||
"email": "paul@paul.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Usando un filtro de array con JSON.stringify
|
||||
|
||||
Ahora, vamos a utilizar replacer como un filtro. El objeto usuario tiene una larga lista de claves, pero sólo nos interesan algunas de ellas. Ponemos las claves que queremos conservar en un array como se muestra en el ejemplo y lo utilizamos en lugar del replacer.
|
||||
|
||||
```js
|
||||
const user = {
|
||||
firstName: "Asabeneh",
|
||||
lastName: "Yetayeh",
|
||||
country: "Finland",
|
||||
city: "Helsinki",
|
||||
email: "alex@alex.com",
|
||||
skills: ["HTML", "CSS", "JavaScript", "React", "Python"],
|
||||
age: 250,
|
||||
isLoggedIn: false,
|
||||
points: 30,
|
||||
};
|
||||
|
||||
const txt = JSON.stringify(
|
||||
user,
|
||||
["firstName", "lastName", "country", "city", "age"],
|
||||
4
|
||||
);
|
||||
console.log(txt);
|
||||
```
|
||||
|
||||
```sh
|
||||
{
|
||||
"firstName": "Asabeneh",
|
||||
"lastName": "Yetayeh",
|
||||
"country": "Finland",
|
||||
"city": "Helsinki",
|
||||
"age": 250
|
||||
}
|
||||
```
|
||||
|
||||
🌕 Eres extraordinario. Ahora, ya conoces un formato de datos ligero que puedes utilizar para almacenar datos o para enviarlos a un servidor HTTP. Llevas 16 pasos de ventaja en tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y para tus músculos.
|
||||
|
||||
## Ejercicios
|
||||
|
||||
```js
|
||||
const skills = ["HTML", "CSS", "JS", "React", "Node", "Python"];
|
||||
let age = 250;
|
||||
let isMarried = true;
|
||||
const student = {
|
||||
firstName: "Asabeneh",
|
||||
lastName: "Yetayehe",
|
||||
age: 250,
|
||||
isMarried: true,
|
||||
skills: ["HTML", "CSS", "JS", "React", "Node", "Python"],
|
||||
};
|
||||
const txt = `{
|
||||
"Alex": {
|
||||
"email": "alex@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 30
|
||||
},
|
||||
"Asab": {
|
||||
"email": "asab@asab.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Redux",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 25,
|
||||
"isLoggedIn": false,
|
||||
"points": 50
|
||||
},
|
||||
"Brook": {
|
||||
"email": "daniel@daniel.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux"
|
||||
],
|
||||
"age": 30,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Daniel": {
|
||||
"email": "daniel@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Python"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"John": {
|
||||
"email": "john@john.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux",
|
||||
"Node.js"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Thomas": {
|
||||
"email": "thomas@thomas.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"Paul": {
|
||||
"email": "paul@paul.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
}
|
||||
}
|
||||
`;
|
||||
```
|
||||
|
||||
### Ejercicios Nivel 1
|
||||
|
||||
1. Cambiar el array de habilidades a JSON usando JSON.stringify()
|
||||
1. Stringify la variable de la edad
|
||||
1. Stringify la variable isMarried
|
||||
1. Stringify el objeto estudiante
|
||||
|
||||
### Ejercicios Nivel 2
|
||||
|
||||
1. Stringify el objeto estudiantes con sólo las propiedades firstName, lastName y skills
|
||||
|
||||
### Ejercicios Nivel 3
|
||||
|
||||
1. Parsear el _txt_ JSON a objeto.
|
||||
2. Encuentra el usuario que tiene muchas habilidades de la variable almacenada en _txt_.
|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 15](../dia_15_Clases/dia_15_clases.md) | [Día 17 >>](../dia_17_Web_storages/dia_17_web_storages.md)
|
@ -0,0 +1,105 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Closures</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 18](../dia_18_Promesas/dia_18_Promesas.md) | [Día 20 >>](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md)
|
||||
|
||||

|
||||
|
||||
- [Día 19](#día-19)
|
||||
- [Closure](#closure)
|
||||
- [Ejercicios](#exercises)
|
||||
- [Ejercicios: Nivel 1](#exercises-level-1)
|
||||
- [Ejercicios: Nivel 2](#exercises-level-2)
|
||||
- [Ejercicios: Nivel 3](#exercises-level-3)
|
||||
|
||||
# Día 19
|
||||
|
||||
## Closure
|
||||
|
||||
JavaScript permite escribir una función dentro de una función externa. Podemos escribir tantas funciones internas como queramos. Si la función interna accede a las variables de la función externa entonces se llama closure (clausura).
|
||||
|
||||
```js
|
||||
function outerFunction() {
|
||||
let count = 0;
|
||||
function innerFunction() {
|
||||
count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
return innerFunction;
|
||||
}
|
||||
const innerFunc = outerFunction();
|
||||
|
||||
console.log(innerFunc());
|
||||
console.log(innerFunc());
|
||||
console.log(innerFunc());
|
||||
```
|
||||
|
||||
```sh
|
||||
1
|
||||
2
|
||||
3
|
||||
```
|
||||
|
||||
Veamos más ejemplos de funciones internas
|
||||
|
||||
```js
|
||||
function outerFunction() {
|
||||
let count = 0;
|
||||
function plusOne() {
|
||||
count++;
|
||||
return count;
|
||||
}
|
||||
function minusOne() {
|
||||
count--;
|
||||
return count;
|
||||
}
|
||||
|
||||
return {
|
||||
plusOne: plusOne(),
|
||||
minusOne: minusOne(),
|
||||
};
|
||||
}
|
||||
const innerFuncs = outerFunction();
|
||||
|
||||
console.log(innerFuncs.plusOne);
|
||||
console.log(innerFuncs.minusOne);
|
||||
```
|
||||
|
||||
```sh
|
||||
1
|
||||
0
|
||||
```
|
||||
|
||||
🌕 Estás haciendo progresos. Mantén tu ritmo, sigue con el buen trabajo. Ahora haz algunos ejercicios para tu cerebro y para tus músculos.
|
||||
|
||||
## Ejercicios
|
||||
|
||||
### Ejercicios: Nivel 1
|
||||
|
||||
1. Crear una closure que tenga una función interna
|
||||
|
||||
### Ejercicios: Nivel 2
|
||||
|
||||
1. Crear una closure que tenga tres funciones internas
|
||||
|
||||
### Ejercicios: Nivel 3
|
||||
|
||||
1. Crear una función de salida de personAccount. Tiene variables internas de nombre, apellido, ingresos y gastos. Tiene las funciones internas totalIncome, totalExpense, accountInfo,addIncome, addExpense y accountBalance. Los ingresos son un conjunto de ingresos y su descripción y los gastos son también un conjunto de gastos con su descripción.
|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 18](../dia_18_Promesas/dia_18_Promesas.md) | [Día 20 >>](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md)
|
@ -0,0 +1,376 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Escribiendo Códigos Limpios</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 19](../dia_19_Closures/dia_19_closures.md) | [Día 21 >>](../dia_21_DOM/dia_21_dom.md)
|
||||
|
||||

|
||||
|
||||
- [Día 20](#día-20)
|
||||
- [Escribiendo código limpio](#escribiendo-código-limpio)
|
||||
- [Guía de estilo JavaScript](#guía-de-estilo-javascript)
|
||||
- [¿Por qué necesitamos una guía de estilo?](#¿por-qué-necesitamos-una-guía-de-estilo)
|
||||
- [Guía de estilo JavaScript de Airbnb](#guía-de-estilo-javascript-de-airbnb)
|
||||
- [Guía de estilo estándar de JavaScript](#guía-de-estilo-estándar-de-javascript)
|
||||
- [Guía de estilo JavaScript de Google](#guía-de-estilo-javascript-de-google)
|
||||
- [Convenciones de codificación en JavaScript](#convenciones-de-codificación-en-javascript)
|
||||
- [Convenciones usadas en 30DíasDeJavaScript](#convenciones-usadas-en-30díasdejavascript)
|
||||
- [Variables](#variables)
|
||||
- [Arrays](#arrays)
|
||||
- [Funciones](#funciones)
|
||||
- [Bucles](#bucles)
|
||||
- [Objetos](#objetos)
|
||||
- [Condicional](#condicional)
|
||||
- [Clases](#clases)
|
||||
|
||||
# Día 20
|
||||
|
||||
## Escribiendo código limpio
|
||||
|
||||
### Guía de estilo JavaScript
|
||||
|
||||
Una guía de estilo de JavaScript es un conjunto de normas que indica cómo debe escribirse y organizarse el código de JavaScript. En esta sección, hablaremos de las guías de JavaScript y de cómo escribir un código limpio.
|
||||
|
||||
JavaScript es un lenguaje de programación, como el lenguaje humano, tiene una sintaxis. La sintaxis de JavaScript debe escribirse siguiendo una determinada pauta de estilo para convencer y simplificar.
|
||||
|
||||
### ¿Por qué necesitamos una guía de estilo?
|
||||
|
||||
Has estado codificando solo durante mucho tiempo, pero ahora parece que trabajas en equipo. No importa de qué manera escribas tu código, siempre y cuando funcione, sin embargo, cuando trabajas en un equipo de 10, 20 o más desarrolladores en un proyecto y en la misma base de código, el código será desordenado y difícil de manejar si no hay ninguna guía a seguir.
|
||||
|
||||
Puede desarrollar sus propias directrices y convenciones o también puede adaptar directrices bien desarrolladas. Conozcamos las guías más comunes.
|
||||
|
||||
Guías de estilo de JavaScript más comunes
|
||||
|
||||
- Guía de estilo JavaScript de Airbnb
|
||||
- Guía de estilo estándar de JavaScript
|
||||
- Guía de estilo JavaScript de Google
|
||||
|
||||
#### Guía de estilo JavaScript de Airbnb
|
||||
|
||||
Airbnb tiene una de las guías de estilo JavaScript más populares de Internet. También cubre casi todos los aspectos de JavaScript y es adoptado por muchos desarrolladores y empresas. Puede consultar la [Guía de estilo de Airbnb](https://github.com/airbnb/javascript). Yo también recomendaría probarlo. Su estilo es muy fácil de usar y sencillo de entender.
|
||||
|
||||
#### Guía de estilo estándar de JavaScript
|
||||
|
||||
Esta guía no es tan popular como la de Airbnb, pero merece la pena echarle un vistazo. Han eliminado el punto y coma en su [guía de estilo](https://standardjs.com/).
|
||||
|
||||
#### Guía de estilo JavaScript de Google
|
||||
|
||||
No diré mucho sobre la guía de Google. No las he usado, más bien te sugiero que eches un vistazo desde este [link](https://google.github.io/styleguide/jsguide.html).
|
||||
|
||||
### Convenciones de codificación en JavaScript
|
||||
|
||||
En este desafío también utilizamos las convenciones y guías generales de codificación de JavaScript. Las convenciones de codificación son pautas de estilo de programación desarrolladas por un individuo, un equipo o una empresa.
|
||||
|
||||
Las convenciones de codificación ayudan:
|
||||
|
||||
- para escribir un código limpio
|
||||
- para mejorar la legibilidad del código
|
||||
- para mejorar la reutilización y el mantenimiento del código
|
||||
|
||||
Las convenciones de codificación incluyen
|
||||
|
||||
- Reglas de declaración y denominación de las variables
|
||||
- Reglas de declaración y denominación de las funciones
|
||||
- Reglas para el uso de espacios en blanco, sangría y comentarios
|
||||
- Prácticas y principios de programación
|
||||
|
||||
#### Convenciones usadas en 30DíasDeJavaScript
|
||||
|
||||
En este reto seguimos la convención habitual de JavaScript pero he añadido también mi preferencia de escritura.
|
||||
|
||||
- Utilizamos camelCase para las variables y las funciones.
|
||||
- Todos los nombres de las variables comienzan con una letra.
|
||||
- Hemos optado por utilizar _const_ para las constantes, los arrays, los objetos y las funciones. En lugar de las comillas dobles, hemos optado por utilizar las comillas simples o backtick. Las comillas simples se están poniendo de moda.
|
||||
- También hemos eliminado el punto y coma de nuestro código, pero es una cuestión de preferencia personal.
|
||||
- Espacio alrededor de los operadores aritméticos, operadores de asignación y después de la coma
|
||||
- Función de flecha en lugar de declaración de función
|
||||
- Retorno explícito en lugar de implícito si la función es de una línea
|
||||
- No hay coma final en el último valor de un objeto
|
||||
- Preferimos este +=, -=, \*= /=, \*\*= en lugar de la versión más larga
|
||||
- Cuando usamos console.log() es bueno imprimir con una cadena de etiquetas para identificar de dónde viene la consola
|
||||
|
||||
#### Variables
|
||||
|
||||
```js
|
||||
let firstName = "Asabeneh";
|
||||
let lastName = "Yetayeh";
|
||||
let country = "Finland";
|
||||
let city = "Helsinki";
|
||||
|
||||
const PI = Math.PI;
|
||||
const gravity = 9.81;
|
||||
```
|
||||
|
||||
#### Arrays
|
||||
|
||||
Hemos optado por hacer que los nombres de los arrays sean plurales
|
||||
|
||||
- names
|
||||
- numbers
|
||||
- countries
|
||||
- languages
|
||||
- skills
|
||||
- fruits
|
||||
- vegetables
|
||||
|
||||
```js
|
||||
// arrays
|
||||
const names = ["Asabeneh", "Mathias", "Elias", "Brook"];
|
||||
const numbers = [0, 3.14, 9.81, 37, 98.6, 100];
|
||||
const countries = ["Finland", "Denmark", "Sweden", "Norway", "Iceland"];
|
||||
const languages = ["Amharic", "Arabic", "English", "French", "Spanish"];
|
||||
const skills = ["HTML", "CSS", "JavaScript", "React", "Python"];
|
||||
const fruits = ["banana", "orange", "mango", "lemon"];
|
||||
const vegetables = ["Tomato", "Potato", "Cabbage", "Onion", "Carrot"];
|
||||
```
|
||||
|
||||
#### Funciones
|
||||
|
||||
A estas alturas ya estás muy familiarizado con la declaración de funciones, la función de expresión, la función de flecha y la función anónima. En este reto tendemos a utilizar la función de flecha en lugar de otras funciones. La función flecha no sustituye a otras funciones. Además, las funciones de flecha y las declaraciones de función no son exactamente iguales. Por lo tanto, debes saber cuándo usarla y cuándo no. En otras secciones trataré la diferencia en detalle. Utilizaremos el retorno explícito en lugar del implícito si la función es de una sola línea.
|
||||
|
||||
```js
|
||||
// función que devuelve el nombre completo de una persona
|
||||
const printFullName = (firstName, lastName) => firstName + " " + lastName;
|
||||
|
||||
// función que calcula el cuadrado de un número
|
||||
const square = (n) => n * n;
|
||||
|
||||
// una función que genera colores hexa al azar
|
||||
const hexaColor = () => {
|
||||
const str = "0123456789abcdef";
|
||||
let hexa = "#";
|
||||
let index;
|
||||
for (let i = 0; i < 6; i++) {
|
||||
index = Math.floor(Math.random() * str.length);
|
||||
hexa += str[index];
|
||||
}
|
||||
return hexa;
|
||||
};
|
||||
|
||||
// una función que muestra la fecha y la hora
|
||||
const showDateTime = () => {
|
||||
const now = new Date();
|
||||
const year = now.getFullYear();
|
||||
const month = now.getMonth() + 1;
|
||||
const date = now.getDate();
|
||||
let hours = now.getHours();
|
||||
let minutes = now.getMinutes();
|
||||
if (hours < 10) {
|
||||
hours = "0" + hours;
|
||||
}
|
||||
if (minutes < 10) {
|
||||
minutes = "0" + minutes;
|
||||
}
|
||||
|
||||
const dateMonthYear = date + "." + month + "." + year;
|
||||
const time = hours + ":" + minutes;
|
||||
const fullTime = dateMonthYear + " " + time;
|
||||
return fullTime;
|
||||
};
|
||||
```
|
||||
|
||||
La función `new Dat().toLocaleString()` también puede utilizarse para mostrar la fecha y hora actuales. Los métodos `toLocaleString()` toman diferentes argumentos. Puede aprender más sobre la fecha y la hora en este [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString).
|
||||
|
||||
#### Bucles
|
||||
|
||||
En estos retos cubrimos muchos tipos de bucles. El bucle regular for, el bucle while, el bucle do while, el bucle for of, el bucle forEach y el bucle for in.
|
||||
|
||||
Veamos cómo los utilizamos:
|
||||
|
||||
```js
|
||||
for (let i = 0; i < n; i++) {
|
||||
console.log();
|
||||
}
|
||||
|
||||
// declaración de una variable array
|
||||
const names = ["Asabeneh", "Mathias", "Elias", "Brook"];
|
||||
|
||||
// iteración de un array mediante un bucle for regular
|
||||
let len = names.length;
|
||||
for (let i = 0; i < len; i++) {
|
||||
console.log(names[i].toUpperCase());
|
||||
}
|
||||
|
||||
// iteración de un array mediante for of
|
||||
for (const name of names) {
|
||||
console.log(name.toUpperCase());
|
||||
}
|
||||
|
||||
// iteración de un array mediante forEach
|
||||
names.forEach((name) => name.toUpperCase());
|
||||
|
||||
const person = {
|
||||
firstName: "Asabeneh",
|
||||
lastName: "Yetayeh",
|
||||
age: 250,
|
||||
country: "Finland",
|
||||
city: "Helsinki",
|
||||
skills: [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Node",
|
||||
"MongoDB",
|
||||
"Python",
|
||||
"D3.js",
|
||||
],
|
||||
isMarried: true,
|
||||
};
|
||||
for (const key in person) {
|
||||
console.log(key);
|
||||
}
|
||||
```
|
||||
|
||||
#### Objetos
|
||||
|
||||
Declaramos el objeto literal con _const_.
|
||||
|
||||
```js
|
||||
// declarando el objeto literal
|
||||
const person = {
|
||||
firstName: "Asabeneh",
|
||||
lastName: "Yetayeh",
|
||||
age: 250,
|
||||
country: "Finland",
|
||||
city: "Helsinki",
|
||||
skills: [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"TypeScript",
|
||||
"React",
|
||||
"Node",
|
||||
"MongoDB",
|
||||
"Python",
|
||||
"D3.js",
|
||||
],
|
||||
isMarried: true,
|
||||
};
|
||||
// iterar a través de las claves del objeto
|
||||
for (const key in person) {
|
||||
console.log(key, person[key]);
|
||||
}
|
||||
```
|
||||
|
||||
#### Condicional
|
||||
|
||||
Hemos dicho if, if else, else, switch y operadores ternarios en los retos anteriores.
|
||||
|
||||
```js
|
||||
// sintaxis
|
||||
if (condition) {
|
||||
// esta parte del código se ejecuta para la condición de verdad
|
||||
} else {
|
||||
// esta parte del código se ejecuta para una condición falsa
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
// if else
|
||||
let num = 3;
|
||||
if (num > 0) {
|
||||
console.log(`${num} is a positive number`);
|
||||
} else {
|
||||
console.log(`${num} is a negative number`);
|
||||
}
|
||||
// 3 is a positive number
|
||||
```
|
||||
|
||||
```js
|
||||
// if else if else if else
|
||||
|
||||
let a = 0;
|
||||
if (a > 0) {
|
||||
console.log(`${a} is a positive number`);
|
||||
} else if (a < 0) {
|
||||
console.log(`${a} is a negative number`);
|
||||
} else if (a == 0) {
|
||||
console.log(`${a} is zero`);
|
||||
} else {
|
||||
console.log(`${a} is not a number`);
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
// Switch Más Ejemplos
|
||||
let dayUserInput = prompt("What day is today ?");
|
||||
let day = dayUserInput.toLowerCase();
|
||||
|
||||
switch (day) {
|
||||
case "monday":
|
||||
console.log("Today is Monday");
|
||||
break;
|
||||
case "tuesday":
|
||||
console.log("Today is Tuesday");
|
||||
break;
|
||||
case "wednesday":
|
||||
console.log("Today is Wednesday");
|
||||
break;
|
||||
case "thursday":
|
||||
console.log("Today is Thursday");
|
||||
break;
|
||||
case "friday":
|
||||
console.log("Today is Friday");
|
||||
break;
|
||||
case "saturday":
|
||||
console.log("Today is Saturday");
|
||||
break;
|
||||
case "sunday":
|
||||
console.log("Today is Sunday");
|
||||
break;
|
||||
default:
|
||||
console.log("It is not a week day.");
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
// ternario
|
||||
|
||||
let isRaining = true;
|
||||
isRaining
|
||||
? console.log("You need a rain coat.")
|
||||
: console.log("No need for a rain coat.");
|
||||
```
|
||||
|
||||
#### Clases
|
||||
|
||||
Declaramos la clase con CamelCase que empieza con mayúscula.
|
||||
|
||||
```js
|
||||
// sintaxis
|
||||
class ClassName {
|
||||
// el código va aquí
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
// definir la clase
|
||||
class Person {
|
||||
constructor(firstName, lastName) {
|
||||
console.log(this); // Compruebe el resultado desde aquí
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Sea cual sea la guía de estilo que sigas, sé coherente. Sigue algunos paradigmas de programación y patrones de diseño. Recuerda que si no escribes tu código en cierto orden o forma, será difícil leerlo. Así que hazte un favor a ti mismo o a alguien que vaya a leer tu código escribiendo código legible.
|
||||
|
||||
🌕 Eres ordenado. Ahora, has aprendido a escribir un código limpio, para que cualquiera que conozca el idioma inglés pueda entender tu código.Siempre estás progresando y llevas 20 pasos en tu camino hacia la grandeza.
|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 19](../dia_19_Closures/dia_19_closures.md) | [Día 21 >>](../dia_21_DOM/dia_21_dom.md)
|
@ -0,0 +1,407 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Document Object Model(DOM)</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 20](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md) | [Día 22 >>](../dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md)
|
||||
|
||||

|
||||
|
||||
- [Día 21](#día-21)
|
||||
- [Document Object Model (DOM) - Día 1](#document-object-model-dom---día-1)
|
||||
- [Obtención del elemento](#obtención-del-elemento)
|
||||
- [Obtener elementos por nombre de etiqueta](#obtener-elementos-por-nombre-de-etiqueta)
|
||||
- [Obtener elementos por el nombre de la clase](#obtener-elementos-por-el-nombre-de-la-clase)
|
||||
- [Obtener un elemento por id](#obtener-un-elemento-por-id)
|
||||
- [Obtener elementos mediante métodos querySelector](#obtener-elementos-mediante-métodos-queryselector)
|
||||
- [Añadir atributo](#añadir-atributo)
|
||||
- [Añadir un atributo con setAttribute](#añadir-un-atributo-con-setattribute)
|
||||
- [Añadir atributo sin setAttribute](#añadir-atributo-sin-setattribute)
|
||||
- [Añadir una clase mediante classList](#añadir-una-clase-mediante-classlist)
|
||||
- [Eliminación de la clase mediante remove](#eliminación-de-la-clase-mediante-remove)
|
||||
- [Añadir texto a un elemento HTML](#añadir-texto-a-un-elemento-html)
|
||||
- [Añadir contenido de texto usando textContent](#añadir-contenido-de-texto-usando-textcontent)
|
||||
- [Añadir contenido de texto usando innerHTML](#añadir-contenido-de-texto-usando-innerhtml)
|
||||
- [textContent](#textcontent)
|
||||
- [innerHTML](#innerhtml)
|
||||
- [Añadir estilo](#añadir-estilo)
|
||||
- [Añadir estilo color](#añadir-estilo-color)
|
||||
- [Añadir estilo Background Color](#añadir-estilo-background-color)
|
||||
- [Añadir estilo Font Size](#añadir-estilo-font-size)
|
||||
- [Ejercicios](#ejercicios)
|
||||
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
|
||||
- [Ejercicios: Nivel 2](#ejercicios-nivel-2)
|
||||
- [Ejercicios: Nivel 3](#ejercicios-nivel-3)
|
||||
- [DOM: Mini proyecto 1](#dom-mini-proyecto-1)
|
||||
|
||||
# Día 21
|
||||
|
||||
## Document Object Model (DOM) - Día 1
|
||||
|
||||
El documento HTML está estructurado como un objeto JavaScript. Cada elemento HTML tiene diferentes propiedades que pueden ayudar a manipularlo. Es posible obtener, crear, añadir o eliminar elementos HTML mediante JavaScript. Compruebe los ejemplos siguientes. La selección de elementos HTML mediante JavaScript es similar a la selección mediante CSS. Para seleccionar un elemento HTML, utilizamos el nombre de la etiqueta, el id, el nombre de la clase u otros atributos.
|
||||
|
||||
### Obtención del elemento
|
||||
|
||||
Podemos acceder al elemento o elementos ya creados mediante JavaScript. Para acceder u obtener elementos utilizamos diferentes métodos. El código siguiente tiene cuatro elementos _h1_. Veamos los diferentes métodos para acceder a los elementos _h1_.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Document Object Model - (Modelo de objeto de documento)</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1 class="title" id="first-title">First Title</h1>
|
||||
<h1 class="title" id="second-title">Second Title</h1>
|
||||
<h1 class="title" id="third-title">Third Title</h1>
|
||||
<h1></h1>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
#### Obtener elementos por nombre de etiqueta
|
||||
|
||||
**_getElementsByTagName()_**:toma un nombre de etiqueta como parámetro de cadena y este método devuelve un objeto HTMLCollection. Una HTMLCollection es un objeto tipo array de elementos HTML. La propiedad length proporciona el tamaño de la colección. Siempre que usamos este método accedemos a los elementos individuales usando el índice o después de hacer un bucle a través de cada elemento individual. Un HTMLCollection no soporta todos los métodos de los arrays, por lo que deberíamos utilizar un bucle for normal en lugar de forEach.
|
||||
|
||||
```js
|
||||
// sintaxis
|
||||
document.getElementsByTagName("tagname");
|
||||
```
|
||||
|
||||
```js
|
||||
const allTitles = document.getElementsByTagName("h1");
|
||||
|
||||
console.log(allTitles); //HTMLCollections
|
||||
console.log(allTitles.length); // 4
|
||||
|
||||
for (let i = 0; i < allTitles.length; i++) {
|
||||
console.log(allTitles[i]); // imprime cada uno de los elementos de la HTMLCollection
|
||||
}
|
||||
```
|
||||
|
||||
#### Obtener elementos por el nombre de la clase
|
||||
|
||||
El método **_getElementsByClassName()_** devuelve un objeto HTMLCollection. Una HTMLCollection es una lista tipo array de elementos HTML. La propiedad length proporciona el tamaño de la colección. Es posible realizar un bucle a través de todos los elementos de HTMLCollection. Vea el siguiente ejemplo
|
||||
|
||||
```js
|
||||
//sintaxis
|
||||
document.getElementsByClassName("classname");
|
||||
```
|
||||
|
||||
```js
|
||||
const allTitles = document.getElementsByClassName("title");
|
||||
|
||||
console.log(allTitles); //HTMLCollections
|
||||
console.log(allTitles.length); // 4
|
||||
|
||||
for (let i = 0; i < allTitles.length; i++) {
|
||||
console.log(allTitles[i]); // imprime cada uno de los elementos de la HTMLCollection
|
||||
}
|
||||
```
|
||||
|
||||
#### Obtener un elemento por id
|
||||
|
||||
**_getElementsById()_** tiene como objetivo un único elemento HTML. Pasamos el id sin # como argumento.
|
||||
|
||||
```js
|
||||
//sintaxis
|
||||
document.getElementById("id");
|
||||
```
|
||||
|
||||
```js
|
||||
let firstTitle = document.getElementById("first-title");
|
||||
console.log(firstTitle); // <h1>First Title</h1>
|
||||
```
|
||||
|
||||
#### Obtener elementos mediante métodos querySelector
|
||||
|
||||
El método _document.querySelector_ puede seleccionar un HTML o elementos HTML por nombre de etiqueta, por id o por nombre de clase.
|
||||
|
||||
**_querySelector_**: se puede utilizar para seleccionar elementos HTML por su nombre de etiqueta, id o clase. Si se utiliza el nombre de la etiqueta, sólo se selecciona el primer elemento.
|
||||
|
||||
```js
|
||||
let firstTitle = document.querySelector("h1"); // seleccionar el primer elemento h1 disponible
|
||||
let firstTitle = document.querySelector("#first-title"); // selecciona el id con first-title
|
||||
let firstTitle = document.querySelector(".title"); // seleccionar el primer elemento disponible con clase title
|
||||
```
|
||||
|
||||
**_querySelectorAll_**: se puede utilizar para seleccionar elementos html por su nombre de etiqueta o clase. Devuelve un nodeList que es un objeto tipo array que soporta métodos de array. Podemos utilizar **_bucle for_** o **_forEach_** para recorrer cada elemento de nodeList.
|
||||
|
||||
```js
|
||||
const allTitles = document.querySelectorAll('h1') # selects all the available h1 elements in the page
|
||||
|
||||
console.log(allTitles.length) // 4
|
||||
for (let i = 0; i < allTitles.length; i++) {
|
||||
console.log(allTitles[i])
|
||||
}
|
||||
|
||||
allTitles.forEach(title => console.log(title))
|
||||
const allTitles = document.querySelectorAll('.title') // lo mismo ocurre con la selección mediante la clase
|
||||
```
|
||||
|
||||
### Añadir atributo
|
||||
|
||||
En la etiqueta de apertura de HTML se añade un atributo que proporciona información adicional sobre el elemento. Atributos HTML comunes: id, class, src, style, href, disabled, title, alt. Añadamos id y class para el cuarto título.
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll("h1");
|
||||
titles[3].className = "title";
|
||||
titles[3].id = "fourth-title";
|
||||
```
|
||||
|
||||
#### Añadir un atributo con setAttribute
|
||||
|
||||
El método **_setAttribute()_** establece cualquier atributo html. Toma dos parámetros: el tipo de atributo y el nombre del atributo.
|
||||
Agreguemos la clase y el atributo id para el cuarto título.
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll("h1");
|
||||
titles[3].setAttribute("class", "title");
|
||||
titles[3].setAttribute("id", "fourth-title");
|
||||
```
|
||||
|
||||
#### Añadir atributo sin setAttribute
|
||||
|
||||
Podemos utilizar el método normal de configuración de objetos para establecer un atributo, pero esto no puede funcionar para todos los elementos. Algunos atributos son propiedades de los objetos del DOM y se pueden establecer directamente. Por ejemplo, id y class
|
||||
|
||||
```js
|
||||
//otra forma de establecer un atributo
|
||||
titles[3].className = "title";
|
||||
titles[3].id = "fourth-title";
|
||||
```
|
||||
|
||||
#### Añadir una clase mediante classList
|
||||
|
||||
El método classList es un buen método para añadir clases adicionales. No anula la clase original si existe una clase, sino que añade una clase adicional para el elemento.
|
||||
|
||||
```js
|
||||
//otra forma de establecer un atributo: anexar la clase, no se sobrepone a
|
||||
titles[3].classList.add("title", "header-title");
|
||||
```
|
||||
|
||||
#### Eliminación de la clase mediante remove
|
||||
|
||||
De forma similar a la adición, también podemos eliminar la clase de un elemento. Podemos eliminar una clase específica de un elemento.
|
||||
|
||||
```js
|
||||
//otra forma de establecer un atributo: anexar la clase, no se sobrepone a
|
||||
titles[3].classList.remove("title", "header-title");
|
||||
```
|
||||
|
||||
### Añadir texto a un elemento HTML
|
||||
|
||||
Un HTML es un bloque compuesto por una etiqueta de apertura, una etiqueta de cierre y un contenido de texto. Podemos añadir un contenido de texto utilizando la propiedad _textContent_ o \*innerHTML.
|
||||
|
||||
#### Añadir contenido de texto usando textContent
|
||||
|
||||
La propiedad _textContent_ se utiliza para añadir texto a un elemento HTML.
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll("h1");
|
||||
titles[3].textContent = "Fourth Title";
|
||||
```
|
||||
|
||||
#### Añadir contenido de texto usando innerHTML
|
||||
|
||||
La mayoría de la gente se confunde entre _textContent_ y _innerHTML_. _textContent_ está pensado para añadir texto a un elemento HTML, sin embargo innerHTML puede añadir un elemento o elementos de texto o HTML como hijo.
|
||||
|
||||
##### textContent
|
||||
|
||||
Asignamos la propiedad del objeto HTML _textContent_ a un texto
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll("h1");
|
||||
titles[3].textContent = "Fourth Title";
|
||||
```
|
||||
|
||||
##### innerHTML
|
||||
|
||||
Usamos la propiedad innerHTML cuando queremos reemplazar o un contenido hijo completamente nuevo a un elemento padre.
|
||||
El valor que asignemos será una cadena de elementos HTML.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>JavaScript para todos:DOM</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrapper">
|
||||
<h1>Asabeneh Yetayeh desafíos en 2020</h1>
|
||||
<h2>Reto 30DaysOfJavaScript</h2>
|
||||
<ul></ul>
|
||||
</div>
|
||||
<script>
|
||||
const lists = `
|
||||
<li>30DaysOfPython Challenge Done</li>
|
||||
<li>30DaysOfJavaScript Challenge Ongoing</li>
|
||||
<li>30DaysOfReact Challenge Coming</li>
|
||||
<li>30DaysOfFullStack Challenge Coming</li>
|
||||
<li>30DaysOfDataAnalysis Challenge Coming</li>
|
||||
<li>30DaysOfReactNative Challenge Coming</li>
|
||||
<li>30DaysOfMachineLearning Challenge Coming</li>`;
|
||||
const ul = document.querySelector("ul");
|
||||
ul.innerHTML = lists;
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
La propiedad innerHTML puede permitirnos también eliminar todos los hijos de un elemento padre. En lugar de utilizar removeChild() yo recomendaría el siguiente método.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>JavaScript for Everyone:DOM</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrapper">
|
||||
<h1>Asabeneh Yetayeh challenges in 2020</h1>
|
||||
<h2>30DaysOfJavaScript Challenge</h2>
|
||||
<ul>
|
||||
<li>30DaysOfPython Challenge Done</li>
|
||||
<li>30DaysOfJavaScript Challenge Ongoing</li>
|
||||
<li>30DaysOfReact Challenge Coming</li>
|
||||
<li>30DaysOfFullStack Challenge Coming</li>
|
||||
<li>30DaysOfDataAnalysis Challenge Coming</li>
|
||||
<li>30DaysOfReactNative Challenge Coming</li>
|
||||
<li>30DaysOfMachineLearning Challenge Coming</li>
|
||||
</ul>
|
||||
</div>
|
||||
<script>
|
||||
const ul = document.querySelector("ul");
|
||||
ul.innerHTML = "";
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Añadir estilo
|
||||
|
||||
#### Añadir estilo Color
|
||||
|
||||
Añadamos un poco de estilo a nuestros títulos. Si el elemento tiene índice par le damos color verde sino rojo.
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll("h1");
|
||||
titles.forEach((title, i) => {
|
||||
title.style.fontSize = "24px"; // todos los títulos tendrán un tamaño de letra de 24px
|
||||
if (i % 2 === 0) {
|
||||
title.style.color = "green";
|
||||
} else {
|
||||
title.style.color = "red";
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
#### Añadir estilo Background Color
|
||||
|
||||
Añadamos un poco de estilo a nuestros títulos. Si el elemento tiene índice par le damos color verde sino rojo.
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll("h1");
|
||||
titles.forEach((title, i) => {
|
||||
title.style.fontSize = "24px"; // todos los títulos tendrán un tamaño de letra de 24px
|
||||
if (i % 2 === 0) {
|
||||
title.style.backgroundColor = "green";
|
||||
} else {
|
||||
title.style.backgroundColor = "red";
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
#### Añadir estilo Font Size
|
||||
|
||||
Añadamos algo de estilo a nuestros títulos. Si el elemento tiene índice par le damos 20px sino 30px
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll("h1");
|
||||
titles.forEach((title, i) => {
|
||||
title.style.fontSize = "24px"; // todos los títulos tendrán un tamaño de letra de 24px
|
||||
if (i % 2 === 0) {
|
||||
title.style.fontSize = "20px";
|
||||
} else {
|
||||
title.style.fontSize = "30px";
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
Como has notado, las propiedades de css cuando lo usamos en JavaScript va a ser un camelCase. Las siguientes propiedades CSS cambian de background-color a backgroundColor, font-size a fontSize, font-family a fontFamily, margin-bottom a marginBottom.
|
||||
|
||||
---
|
||||
|
||||
🌕 Ahora, estás completamente dotado de un súper poder, has completado la parte más importante y desafiante del desafío y en general de JavaScript. Has aprendido DOM y ahora tienes la capacidad de construir y desarrollar aplicaciones. Ahora haz algunos ejercicios para tu cerebro y para tus músculos.
|
||||
|
||||
## Ejercicios
|
||||
|
||||
### Ejercicios: Nivel 1
|
||||
|
||||
1. Crear un archivo index.html y poner cuatro elementos p: Obtenga el primer párrafo utilizando **_document.querySelector(tagname)_** y el nombre de la etiqueta
|
||||
2. Obtener cada uno de los párrafos usando **_document.querySelector('#id')_** mediante su id
|
||||
3. Obtener todos los p como nodeList usando **_document.querySelectorAll(tagname)_** por su nombre de etiqueta
|
||||
4. Recorrer nodeList y obtener el contenido del texto de cada párrafo
|
||||
5. Establecer un textContent para el párrafo del cuarto párrafo,**_Fourth Paragraph_**
|
||||
6. Establezca los atributos id y class para todos los párrafos utilizando diferentes métodos de establecimiento de atributos
|
||||
|
||||
### Ejercicios: Nivel 2
|
||||
|
||||
1. Cambiar el estilo de cada párrafo mediante JavaScript (ej, color, fondo, borde, tamaño de la fuente, familia de la fuente)
|
||||
1. Seleccione todos los párrafos y haga un bucle a través de cada uno de los elementos y dé al primer y tercer párrafo un color verde, y al segundo y cuarto párrafo un color rojo
|
||||
1. Establecer textContent, id y class a cada párrafo
|
||||
|
||||
### Ejercicios: Nivel 3
|
||||
|
||||
#### DOM: Mini proyecto 1
|
||||
|
||||
1. Desarrolle la siguiente aplicación, utilice los siguientes elementos HTML para empezar. Obtendrá el mismo código en la carpeta de inicio. Aplique todos los estilos y la funcionalidad utilizando sólo JavaScript.
|
||||
|
||||
- El color del año cambia cada 1 segundo
|
||||
- El color de fondo de la fecha y la hora cambia cada dos segundos
|
||||
- El reto completado tiene fondo verde
|
||||
- El desafío en curso tiene fondo amarillo
|
||||
- Los próximos retos tienen fondo rojo
|
||||
|
||||
```html
|
||||
<!-- index.html -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>JavaScript para todos: DOM</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrapper">
|
||||
<h1>Asabeneh Yetayeh retos en 2020</h1>
|
||||
<h2>Reto 30DaysOfJavaScript</h2>
|
||||
<ul>
|
||||
<li>Reto 30DaysOfPython Realizado</li>
|
||||
<li>Reto 30DaysOfJavaScript en curso</li>
|
||||
<li>Reto 30DaysOfReact próximamente</li>
|
||||
<li>Reto 30DaysOfFullStack próximamente</li>
|
||||
<li>Reto 30DaysOfDataAnalysis próximamente</li>
|
||||
<li>Reto 30DaysOfReactNative próximamente</li>
|
||||
<li>Reto 30DaysOfMachineLearning próximamente</li>
|
||||
</ul>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 20](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md) | [Día 22 >>](../dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md)
|
@ -0,0 +1,224 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Manipulación del Objeto DOM </h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 21](../dia_21_DOM/dia_21_dom.md) | [Día 23 >>](../dia_23_Event_Listeners/dia_23_event_listeners.md)
|
||||
|
||||

|
||||
|
||||
- [Día 22](#día-22)
|
||||
- [DOM(Document Object Model)-Día 2](#domdocument-object-model-día-2)
|
||||
- [Creando un elemento](#creando-un-elemento)
|
||||
- [Creación de elementos](#creación-de-elementos)
|
||||
- [Añadir un hijo a un elemento padre](#añadir-un-hijo-a-un-elemento-padre)
|
||||
- [Eliminar un elemento hijo de un nodo padre](#eliminar-un-elemento-hijo-de-un-nodo-padre)
|
||||
- [Ejercicios](#ejercicios)
|
||||
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
|
||||
- [Ejercicios: Nivel 2](#ejercicios-nivel-2)
|
||||
- [Ejercicios: Nivel 3](#ejercicios-nivel-3)
|
||||
|
||||
# Día 22
|
||||
|
||||
## DOM(Document Object Model)-Día 2
|
||||
|
||||
### Creando un elemento
|
||||
|
||||
Para crear un elemento HTML utilizamos el nombre de la etiqueta. La creación de un elemento HTML mediante JavaScript es muy sencilla y directa. Utilizamos el método _document.createElement()_. El método toma un nombre de etiqueta de elemento HTML como parámetro de cadena.
|
||||
|
||||
```js
|
||||
// sintaxus
|
||||
document.createElement("tagname");
|
||||
```
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<script>
|
||||
let title = document.createElement("h1");
|
||||
title.className = "title";
|
||||
title.style.fontSize = "24px";
|
||||
title.textContent = "Creating HTML element DOM Day 2";
|
||||
|
||||
console.log(title);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Creación de elementos
|
||||
|
||||
Para crear múltiples elementos debemos utilizar el bucle. Usando el bucle podemos crear tantos elementos HTML como queramos.
|
||||
Después de crear el elemento podemos asignar valor a las diferentes propiedades del objeto HTML.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<script>
|
||||
let title;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
title = document.createElement("h1");
|
||||
title.className = "title";
|
||||
title.style.fontSize = "24px";
|
||||
title.textContent = i;
|
||||
console.log(title);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Añadir un hijo a un elemento padre
|
||||
|
||||
Para ver un elemento creado en el documento HTML debemos añadirlo al padre como elemento hijo. Podemos acceder al cuerpo del documento HTML utilizando _document.body_. El _document.body_ soporta el método _appendChild()_. Vea el ejemplo siguiente.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<script>
|
||||
// creación de múltiples elementos y anexión al elemento padre
|
||||
let title;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
title = document.createElement("h1");
|
||||
title.className = "title";
|
||||
title.style.fontSize = "24px";
|
||||
title.textContent = i;
|
||||
document.body.appendChild(title);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Eliminar un elemento hijo de un nodo padre
|
||||
|
||||
Después de crear un HTML, es posible que queramos eliminar uno o varios elementos y podemos utilizar el método _removeChild()_.
|
||||
|
||||
**Ejemplo:**
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Removing child Node</h1>
|
||||
<h2>Asabeneh Yetayeh challenges in 2020</h1>
|
||||
<ul>
|
||||
<li>30DaysOfPython Challenge Done</li>
|
||||
<li>30DaysOfJavaScript Challenge Done</li>
|
||||
<li>30DaysOfReact Challenge Coming</li>
|
||||
<li>30DaysOfFullStack Challenge Coming</li>
|
||||
<li>30DaysOfDataAnalysis Challenge Coming</li>
|
||||
<li>30DaysOfReactNative Challenge Coming</li>
|
||||
<li>30DaysOfMachineLearning Challenge Coming</li>
|
||||
</ul>
|
||||
|
||||
<script>
|
||||
const ul = document.querySelector('ul')
|
||||
const lists = document.querySelectorAll('li')
|
||||
for (const list of lists) {
|
||||
ul.removeChild(list)
|
||||
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
```
|
||||
|
||||
Como hemos visto en la sección anterior hay una forma mejor de eliminar todos los elementos HTML internos o hijos de un elemento padre utilizando el método _innerHTML_ propiedades.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Removing child Node</h1>
|
||||
<h2>Asabeneh Yetayeh challenges in 2020</h1>
|
||||
<ul>
|
||||
<li>30DaysOfPython Challenge Done</li>
|
||||
<li>30DaysOfJavaScript Challenge Done</li>
|
||||
<li>30DaysOfReact Challenge Coming</li>
|
||||
<li>30DaysOfFullStack Challenge Coming</li>
|
||||
<li>30DaysOfDataAnalysis Challenge Coming</li>
|
||||
<li>30DaysOfReactNative Challenge Coming</li>
|
||||
<li>30DaysOfMachineLearning Challenge Coming</li>
|
||||
</ul>
|
||||
|
||||
<script>
|
||||
const ul = document.querySelector('ul')
|
||||
ul.innerHTML = ''
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
```
|
||||
|
||||
El fragmento de código anterior borró todos los elementos hijos.
|
||||
|
||||
---
|
||||
|
||||
🌕 Eres muy especial, estás progresando cada día. Ahora, sabes cómo destruir un elemento DOM creado cuando es necesario. Aprendiste DOM y ahora tienes la capacidad de construir y desarrollar aplicaciones. Te quedan sólo ocho días para tu camino a la grandeza. Ahora haz algunos ejercicios para tu cerebro y para tus músculos.
|
||||
|
||||
## Ejercicios
|
||||
|
||||
### Ejercicios: Nivel 1
|
||||
|
||||
1. Crear un div contenedor en el documento HTML y crear 100 a 100 números dinámicamente y anexar al div contenedor.
|
||||
- El fondo de los números pares es verde
|
||||
- El fondo de los números impares es amarillo
|
||||
- El fondo de los números primos es rojo
|
||||
|
||||

|
||||
|
||||
### Ejercicios: Nivel 2
|
||||
|
||||
1. Utilice el array de países para mostrar todos los países. Vea el diseño
|
||||
|
||||

|
||||
|
||||
### Ejercicios: Nivel 3
|
||||
|
||||
Compruebe los requisitos de este proyecto a partir de ambas imágenes (jpg y gif). Todos los datos y el CSS se han implementado utilizando únicamente JavaScript. Los datos se encuentran en la carpeta de inicio del proyecto\*3. El botón desplegable se ha creado utilizando el [details\*](https://www.w3schools.com/tags/tag_details.asp) elemento HTML.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 21](../dia_21_DOM/dia_21_dom.md) | [Día 23 >>](../dia_23_Event_Listeners/dia_23_event_listeners.md)
|
@ -0,0 +1,334 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Event Listeners</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 22](../dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md) | [Día 24 >>](../dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md)
|
||||
|
||||

|
||||
|
||||
- [Día 23](#día-23)
|
||||
- [DOM(Document Object Model)-Día 3](#domdocument-object-model-día-3)
|
||||
- [Event Listeners](#event-listeners)
|
||||
- [Click](#click)
|
||||
- [Doble Click](#doble-click)
|
||||
- [Mouse enter](#mouse-enter)
|
||||
- [Obtener el valor de un elemento input](#obtener-el-valor-de-un-elemento-input)
|
||||
- [valor de entrada](#valor-de-entrada)
|
||||
- [evento de entrada y cambio](#evento-de-entrada-y-cambio)
|
||||
- [evento de desenfoque](#evento-de-desenfoque)
|
||||
- [keypress, keydow y keyup](#keypress-keydow-y-keyup)
|
||||
- [Ejercicios](#ejercicios)
|
||||
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
|
||||
|
||||
# Día 23
|
||||
|
||||
## DOM(Document Object Model)-Día 3
|
||||
|
||||
### Event Listeners
|
||||
|
||||
Eventos HTML comunes: onclick, onchange, onmouseover, onmouseout, onkeydown, onkeyup, onload.
|
||||
Podemos añadir el método **event_listener** (escuchador de eventos) a cualquier objeto DOM. Utilizamos el método **_addEventListener()_** para escuchar diferentes tipos de eventos en los elementos HTML. El método _addEventListener()_ toma dos argumentos, un event listener y una función callback.
|
||||
|
||||
```js
|
||||
selectedElement.addEventListener("eventlistner", function (e) {
|
||||
// la actividad que quieres que ocurra después del evento estará aquí
|
||||
});
|
||||
// or
|
||||
|
||||
selectedElement.addEventListener("eventlistner", (e) => {
|
||||
// la actividad que quieres que ocurra después del evento estará aquí
|
||||
});
|
||||
```
|
||||
|
||||
#### Click
|
||||
|
||||
Para adjuntar un event listener a un elemento, primero seleccionamos el elemento y luego adjuntamos el método addEventListener. El event listener toma como argumento el tipo de evento y las funciones de callback.
|
||||
|
||||
El siguiente es un ejemplo de evento de tipo click.
|
||||
|
||||
**Ejemplo: click**
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<button>Click Me</button>
|
||||
|
||||
<script>
|
||||
const button = document.querySelector("button");
|
||||
button.addEventListener("click", (e) => {
|
||||
console.log("e gives the event listener object:", e);
|
||||
console.log("e.target gives the selected element: ", e.target);
|
||||
console.log(
|
||||
"e.target.textContent gives content of selected element: ",
|
||||
e.target.textContent
|
||||
);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
También se puede adjuntar un evento directamente al elemento HTML como script en línea.
|
||||
|
||||
**Ejemplo: onclick**
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<button onclick="clickMe()">Click Me</button>
|
||||
<script>
|
||||
const clickMe = () => {
|
||||
alert("We can attach event on HTML element");
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
#### Doble Click
|
||||
|
||||
Para adjuntar un event listener a un elemento, primero seleccionamos el elemento y luego adjuntamos el método addEventListener. El event listener toma como argumento el tipo de evento y las funciones de callback.
|
||||
|
||||
El siguiente es un ejemplo de evento de tipo click.
|
||||
|
||||
**Ejemplo: dblclick**
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<button>Click Me</button>
|
||||
<script>
|
||||
const button = document.querySelector("button");
|
||||
button.addEventListener("dblclick", (e) => {
|
||||
console.log("e gives the event listener object:", e);
|
||||
console.log("e.target gives the selected element: ", e.target);
|
||||
console.log(
|
||||
"e.target.textContent gives content of selected element: ",
|
||||
e.target.textContent
|
||||
);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
#### Mouse enter
|
||||
|
||||
Para adjuntar un event listener a un elemento, primero seleccionamos el elemento y luego adjuntamos el método addEventListener. El event listener toma como argumento el tipo de evento y las funciones de callback.
|
||||
|
||||
El siguiente es un ejemplo de evento de tipo click.
|
||||
|
||||
**Ejemplo: mouseenter**
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<button>Click Me</button>
|
||||
<script>
|
||||
const button = document.querySelector("button");
|
||||
button.addEventListener("mouseenter", (e) => {
|
||||
console.log("e gives the event listener object:", e);
|
||||
console.log("e.target gives the selected element: ", e.target);
|
||||
console.log(
|
||||
"e.target.textContent gives content of selected element: ",
|
||||
e.target.textContent
|
||||
);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
A estas alturas ya estás familiarizado con el método addEventListen y cómo añadir un event listener. Hay muchos tipos de event listeners. Pero en este reto nos centraremos en los eventos importantes más comunes.
|
||||
|
||||
Lista de eventos:
|
||||
|
||||
- click - cuando se hace click en el elemento
|
||||
- dblclick - cuando se hace doble click en el elemento
|
||||
- mouseenter - cuando el punto del mouse ingresa al elemento
|
||||
- mouseleave - cuando el puntero del mouse abandona el elemento
|
||||
- mousemove - cuando el puntero del mouse se mueve sobre el elemento
|
||||
- mouseover - cuando el puntero del mouse se mueve sobre el elemento
|
||||
- mouseout - cuando el puntero del mouse sale del elemento
|
||||
- input - cuando el valor entra en el input de entrada
|
||||
- change - cuando el valor cambia en el input de entrada
|
||||
- blur - cuando el elemento no está enfocado
|
||||
- keydown - cuando una tecla está pulsada
|
||||
- keyup - cuando una tecla está levantada
|
||||
- keypress - cuando pulsamos cualquier tecla
|
||||
- onload - cuando el navegador ha terminado de cargar una página
|
||||
|
||||
Pruebe los tipos de eventos anteriores sustituyendo el tipo de evento en el fragmento de código anterior.
|
||||
|
||||
### Obtener el valor de un elemento input
|
||||
|
||||
Normalmente rellenamos formularios y los formularios aceptan datos. Los campos de los formularios se crean utilizando el elemento HTML input. Vamos a construir una pequeña aplicación que nos permita calcular el índice de masa corporal de una persona utilizando dos campos de entrada, un botón y una etiqueta p.
|
||||
|
||||
### valor de entrada
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Body Mass Index Calculator</h1>
|
||||
|
||||
<input type="text" id="mass" placeholder="Mass in Kilogram" />
|
||||
<input type="text" id="height" placeholder="Height in meters" />
|
||||
<button>Calculate BMI</button>
|
||||
|
||||
<script>
|
||||
const mass = document.querySelector("#mass");
|
||||
const height = document.querySelector("#height");
|
||||
const button = document.querySelector("button");
|
||||
|
||||
let bmi;
|
||||
button.addEventListener("click", () => {
|
||||
bmi = mass.value / height.value ** 2;
|
||||
alert(`your bmi is ${bmi.toFixed(2)}`);
|
||||
console.log(bmi);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
#### evento de entrada y cambio
|
||||
|
||||
En el ejemplo anterior, hemos conseguido obtener los valores de entrada de dos campos de entrada haciendo click en el botón. Qué tal si queremos obtener el valor sin hacer click en el botón. Podemos utilizar el tipo de evento _change_ o _input_ para obtener los datos inmediatamente del campo de entrada cuando el campo está en el foco. Veamos cómo lo haremos.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Data Binding using input or change event</h1>
|
||||
|
||||
<input type="text" placeholder="say something" />
|
||||
<p></p>
|
||||
|
||||
<script>
|
||||
const input = document.querySelector("input");
|
||||
const p = document.querySelector("p");
|
||||
|
||||
input.addEventListener("input", (e) => {
|
||||
p.textContent = e.target.value;
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
#### evento de desenfoque
|
||||
|
||||
A diferencia de _input_ o _change_, el evento _blur_ se produce cuando el campo de entrada no está enfocado.
|
||||
|
||||
```js
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Giving feedback using blur event</h1>
|
||||
|
||||
<input type="text" id="mass" placeholder="say something" />
|
||||
<p></p>
|
||||
|
||||
<script>
|
||||
const input = document.querySelector('input')
|
||||
const p = document.querySelector('p')
|
||||
|
||||
input.addEventListener('blur', (e) => {
|
||||
p.textContent = 'Field is required'
|
||||
p.style.color = 'red'
|
||||
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
```
|
||||
|
||||
#### keypress, keydow y keyup
|
||||
|
||||
Podemos acceder a todos los números de teclas del teclado utilizando diferentes tipos de event listener. Usemos keypress y obtengamos el keyCode de cada tecla del teclado.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Key events: Press any key</h1>
|
||||
|
||||
<script>
|
||||
document.body.addEventListener("keypress", (e) => {
|
||||
alert(e.keyCode);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
🌕 Eres muy especial, estás progresando cada día. Ahora, sabes cómo manejar cualquier tipo de eventos DOM. . Te quedan sólo siete días para tu camino a la grandeza. Ahora haz algunos ejercicios para tu cerebro y para tus músculos.
|
||||
|
||||
## Ejercicios
|
||||
|
||||
### Ejercicios: Nivel 1
|
||||
|
||||
1. Generar números y marcar pares, impares y primos con tres colores diferentes. Vea la imagen de abajo.
|
||||
|
||||

|
||||
|
||||
1. Generando el código del teclado usando even listener. La imagen de abajo.
|
||||
|
||||

|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 22](../dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md) | [Día 24 >>](../dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md)
|
@ -0,0 +1,37 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Mini Proyecto Sistema Solar</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 23](../dia_23_Event_Listeners/dia_23_event_listeners.md) | [Día 25 >>](../dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md)
|
||||
|
||||

|
||||
|
||||
- [Día 24](#día-24)
|
||||
- [Ejercicios](#ejercicios)
|
||||
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
|
||||
|
||||
# Día 24
|
||||
|
||||
## Ejercicios
|
||||
|
||||
### Ejercicios: Nivel 1
|
||||
|
||||
1. Desarrollar una pequeña aplicación que calcule el peso de un objeto en un determinado planeta. La imagen gif no está completa revisa el video en el archivo de inicio.
|
||||
|
||||

|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 23](../dia_23_Event_Listeners/dia_23_event_listeners.md) | [Día 25 >>](../dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md)
|
@ -0,0 +1,39 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Visualización de Datos de los Países del Mundo</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 24](../dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md) | [Día 26 >>](../dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md)
|
||||
|
||||

|
||||
|
||||
- [Día 25](#día-25)
|
||||
- [Ejercicios](#ejercicios)
|
||||
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
|
||||
|
||||
# Día 25
|
||||
|
||||
## Ejercicios
|
||||
|
||||
### Ejercicios: Nivel 1
|
||||
|
||||
1. Visualiza los diez países más poblados y los diez idiomas más hablados del mundo usando DOM(HTML, CSS, JS)
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 24](../dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md) | [Día 26 >>](../dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md)
|
@ -0,0 +1,37 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Visualización de Datos de los Países del Mundo 2 </h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 25](../dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md) | [Día 27 >>](../dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md)
|
||||
|
||||

|
||||
|
||||
- [Día 26](#día-26)
|
||||
- [Ejercicios](#ejercicios)
|
||||
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
|
||||
|
||||
# Día 26
|
||||
|
||||
## Ejercicios
|
||||
|
||||
### Ejercicios: Nivel 1
|
||||
|
||||
1. Visualice el array de países de la siguiente manera
|
||||
|
||||

|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 25](../dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md) | [Día 27 >>](../dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md)
|
@ -0,0 +1,37 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Portafolio</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 26](../dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md) | [Día 28 >>](../dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md)
|
||||
|
||||

|
||||
|
||||
- [Día 27](#día-27)
|
||||
- [Ejercicios](#ejercicios)
|
||||
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
|
||||
|
||||
# Día 27
|
||||
|
||||
## Ejercicios
|
||||
|
||||
### Ejercicios: Nivel 1
|
||||
|
||||
1. Crea lo siguiente usando HTML, CSS y JavaScript
|
||||
|
||||

|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 26](../dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md) | [Día 28 >>](../dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md)
|
@ -0,0 +1,37 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Tabla de Posiciones</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 27](../dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md) | [Día 29>>](../dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md)
|
||||
|
||||

|
||||
|
||||
- [Día 28](#día-28)
|
||||
- [Ejercicio](#ejercicio)
|
||||
- [Ejercicio: Nivel 1](#ejercicio-nivel-1)
|
||||
|
||||
# Día 28
|
||||
|
||||
## Ejercicio
|
||||
|
||||
### Ejercicio: Nivel 1
|
||||
|
||||
1. Crea lo siguiente usando HTML, CSS y JavaScript
|
||||
|
||||

|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 27](../dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md) | [Día 29>>](../dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md)
|
@ -0,0 +1,37 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Animación de Caracteres</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Día 28](../dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md) | [Día 30>>](../dia_30_Mini_Proyecto_Final/dia_30_mini_proyecto_final.md)
|
||||
|
||||

|
||||
|
||||
- [Día 29](#día-29)
|
||||
- [Ejercicios](#ejercicios)
|
||||
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
|
||||
|
||||
# Día 29
|
||||
|
||||
## Ejercicios
|
||||
|
||||
### Ejercicios: Nivel 1
|
||||
|
||||
1. Crea la siguiente animación utilizando (HTML, CSS, JS)
|
||||
|
||||

|
||||
|
||||
🎉 ¡FELICITACIONES! 🎉
|
||||
|
||||
[<< Día 28](../dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md) | [Día 30>>](../dia_30_Mini_Proyecto_Final/dia_30_mini_proyecto_final.md)
|
@ -0,0 +1,67 @@
|
||||
<div align="center">
|
||||
<h1> 30 Días de JavaScript: Proyecto Final</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Autor:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Enero, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<small>Apoya al <strong>autor</strong> para que cree más material educativo</small> <br />
|
||||
<a href = "https://www.paypal.me/asabeneh"><img src='../../images/paypal_lg.png' alt='Paypal Logo' style="width:10%"/></a>
|
||||
</div>
|
||||
|
||||
[<< Día 29](../dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md)
|
||||
|
||||

|
||||
|
||||
- [Día 30](#día-30)
|
||||
- [Ejercicios](#ejercicios)
|
||||
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
|
||||
- [Testimonio](#testimonio)
|
||||
- [Apoyo](#apoyo)
|
||||
|
||||
# Día 30
|
||||
|
||||
## Ejercicios
|
||||
|
||||
### Ejercicios: Nivel 1
|
||||
|
||||
1. Crea la siguiente animación utilizando (HTML, CSS, JS)
|
||||
|
||||

|
||||
|
||||
2. Valide el siguiente formulario utilizando regex.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
🌕 Tu viaje a la grandeza se ha completado con éxito. Has alcanzado un alto nivel de genialidad. Ahora, eres mucho más brillante que antes. Yo sabía lo que se necesita para llegar a este nivel y tú llegaste a este punto. Eres un verdadero héroe. Ahora, es el momento de celebrar tu éxito con un amigo o con la familia. Estoy deseando verte en otro reto.
|
||||
|
||||
## Testimonio
|
||||
|
||||
Ahora es el momento de apoyar al autor y expresar su opinión sobre el autor y 30DaysOfJavaScript. Puedes dejar tu testimonio en este [link](https://testimonify.herokuapp.com/)
|
||||
|
||||
## Apoyo
|
||||
|
||||
Puedes apoyar al autor para que produzca más material educativo
|
||||
|
||||
[](https://www.paypal.me/asabeneh)
|
||||
|
||||

|
||||
|
||||
[<< Día 29](../dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md)
|
Loading…
Reference in new issue