Last active
April 28, 2020 02:28
Revisions
-
lavesan revised this gist
Apr 28, 2020 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,4 @@ ### Desconstruct ```javascript const res = data { situacao: 'alguma', -
lavesan revised this gist
Dec 27, 2019 . 1 changed file with 1 addition and 0 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -20,6 +20,7 @@ const obj = { name: 'algum nome', idade: 23 } Object.keys(obj) // ['name', 'idade'] Object.values(obj) // ['algum nome', 23] Object.entries(obj) // [['name', 'algum nome'], ['idade', 23]] // Já que é um array, só usar algum método 'for' agora ``` -
lavesan revised this gist
Oct 21, 2019 . 1 changed file with 5 additions and 0 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -29,4 +29,9 @@ a(); // Deixando o '$' com o jQuery (function($) {})(jQuery) // Ou só chamo ela (() => { })() // ou (function(){}.bind(this))() ``` -
lavesan revised this gist
Sep 9, 2019 . 1 changed file with 35 additions and 0 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,35 @@ ### Modularizando algo > arquivo.js ```javascript const modulo = require('./modulo.js') console.log('variavel: ', modulo.variavel) modulo.funcao('te chamei mizera') ``` > modulo.js ```javascript const variavel = 'não sei' const funcao = function(parametro) { console.log('parametro: ', parametro) } module.exports = { variavel, funcao } ``` ### Chamando função, objeto ou sei lá do arquivo que importou o módulo > arquivo.js ```javascript const variavel = 'sei lá' require('/modulo.js)() ``` > modulo.js ```javascript module.exports = () => { console.log(variavel) } ``` -
lavesan revised this gist
Sep 1, 2019 . 1 changed file with 18 additions and 1 deletion.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -12,4 +12,21 @@ funcao.name // 'funcao' funcao.bind(this) // Assim não importa onde ela for chamada, o 'this' vai ser o mesmo daonde isso foi colocado funcao.bind([1, 2, 3]) // Assim o 'this' vai ser este array sempre que for chamado (só um exemplo) ``` https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype ### Função auto-invocada Uma função que se autoinvoca ```javascript // Ao invés de const a = function() {} a(); // Faço (function(parametro) { // Corpo da função })('contexto') // Deixando o '$' com o jQuery (function($) {})(jQuery) ``` -
lavesan revised this gist
Jul 9, 2019 . 1 changed file with 2 additions and 1 deletion.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -18,7 +18,8 @@ Math.LOG10E // logaritmo de 10 na base E ```javascript Math.ceil(4.3) // 5 -> Inteiro maior mais perto Math.floor(4.7) // 4 -> Inteiro menor mais perto Math.round(4.4) // 4 -> Inteiro mais perto Math.round(4.6) // 5 -> Inteiro mais perto ``` ### <a id="operacao"></a>Operações ```javascript -
lavesan revised this gist
Jun 16, 2019 . 1 changed file with 0 additions and 78 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,78 +0,0 @@ -
lavesan revised this gist
Jun 16, 2019 . 1 changed file with 34 additions and 2 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -25,16 +25,22 @@ document.getElementById('id').classList.add('classe') // Remove uma classe document.getElementById('id').classList.remove('classe') // Se existe remove, se não existe adiciona document.getElementById('id').classList.toggle('classe') ``` ## Acessando atributos de uma tag ```javascript const elemento = document.getElementById('id'); elemento.getAttribute('href') // pega o href de um link elemento.getAttribute('name') // pega o atributo name elemento.getAttribute('value') // pega o atributo value e por ai vai... // Alguns atributor posso pegar de maneira direta elemento.href // o href // Verifica se o atributo existe (é um boolean) element.hasAttribute('href'); ``` ## Saber se algo é um elemento, atributo ou seja o que for... ```javascript @@ -43,4 +49,30 @@ element.nodeType * Retorna um número que avisa qual o tipo de elemento aquilo é * 1 é um element HTML, 2 é um atributo... * Link com o que é cada número: * https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType ## Adicionando elementos 1. Primeiro crio um elemento ```javascript const div = document.createElement('div'); // Posso copiar o elemento const div2 = document.copyElement(div, true); ``` 2. Adiciono o elemento ```javascript const elemento = getElementById('id'); // Adiciona após o elemento elemento.appendChild(div); elemento.insertAdjacentHTML('afterbegin', '<p>Elemento adicionado</p>'); // Adiciona como ultimo filho elemento.insertAdjacentHTML('beforeend', '<p>Elemento adicionado</p>'); // Adiciona um nível acima do elemento ANTES deste elemento elemento.insertAdjacentHTML('beforebegin', '<p>Elemento adicionado</p>'); // Adiciona um nível acima do elemento DEPOIS deste elemento elemento.insertAdjacentHTML('afterend', '<p>Elemento adicionado</p>'); ``` -
lavesan revised this gist
Jun 16, 2019 . 1 changed file with 25 additions and 4 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,25 +1,46 @@ ## Coleta elementos da DOM ```javascript // Pega 1 elemento pelo id document.getElementById('id'); // Pega TODOS os elementos com esta classe document.getElementsByClassName('classe'); // Pega um elemento ou TODOS com algum nome document.getElementsByName('algumNome'); // Pega TODOS os elementos com esta tag document.getElementsByTagName('div'); // Pega 1 o primeiro elemento que achar com esta regra que eu colocar document.querySelector('div #id .classe'); // Pega TODOS os elements que eu achar com esta regra que eu colocar document.querySelectorAll('div #id .classe *'); // o *, quer dizer todos os elementos ``` ## Posso adicionar ou remover elementos classes apartir do javascript ```javascript // Adiciona uma class document.getElementById('id').classList.add('classe') // Remove uma classe document.getElementById('id').classList.remove('classe') ``` ## Acessando atributos de uma tag ```javascript elemento = document.getElementById('id'); elemento.getAttribute('href') // pega o href de um link elemento.getAttribute('name') // pega o atributo name elemento.getAttribute('value') // pega o atributo value e por ai vai... // Alguns atributor posso pegar de maneira direta elemento.href // o href ``` ## Saber se algo é um elemento, atributo ou seja o que for... ```javascript element.nodeType ``` * Retorna um número que avisa qual o tipo de elemento aquilo é * 1 é um element HTML, 2 é um atributo... * Link com o que é cada número: * https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType -
lavesan revised this gist
Jun 16, 2019 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -13,7 +13,7 @@ document.getElementsByTag('div'); document.querySelector('div #id .classe'); // Pega TODOS os elements que eu achar com esta regra que eu colocar document.querySelectorAll('div #id .classe *'); // o *, quer dizer todos os elementos ``` Posso adicionar ou remover elementos classes apartir do javascript ```javascript -
lavesan revised this gist
Jun 16, 2019 . 1 changed file with 8 additions and 0 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -14,4 +14,12 @@ document.querySelector('div #id .classe'); // Pega TODOS os elements que eu achar com esta regra que eu colocar document.querySelectorAll('div #id .classe'); ``` Posso adicionar ou remover elementos classes apartir do javascript ```javascript // Adiciona uma class document.getElementById('id').classList.add('classe') // Remove uma classe document.getElementById('id').classList.remove('classe') ``` -
lavesan revised this gist
Jun 16, 2019 . 1 changed file with 17 additions and 0 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,17 @@ Coleta elementos da DOM ```javascript // Pega 1 elemento pelo id document.getElementById('id'); // Pega TODOS os elementos com esta classe document.getElementsByClassName('classe'); // Pega TODOS os elementos com esta tag document.getElementsByTag('div'); // Pega 1 o primeiro elemento que achar com esta regra que eu colocar document.querySelector('div #id .classe'); // Pega TODOS os elements que eu achar com esta regra que eu colocar document.querySelectorAll('div #id .classe'); ``` -
lavesan revised this gist
Jun 5, 2019 . 1 changed file with 23 additions and 0 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,23 @@ ## Uso básico mas eficiente: ```javascript const func1 = function() { return new Promise((resolve, rejected) => { if (true) { rejected() // retorna um erro no catch } resolve() // Retorna acerto }) } const func2 = function() { func1() // No acerto, vem para o then .then(() => { console.log('não deu pau!'); }) // No erro, vem para o catch .catch(() => { console.log('deu pau :('); }) } ``` -
lavesan revised this gist
Apr 23, 2019 . 1 changed file with 5 additions and 5 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -3,7 +3,7 @@ * [Operações](#operacao) * [Converção de valor](#converter) * [Random](#random) ### <a id="variaveis"></a>Variáveis ```javascript Math.PI // Valor de pi 3,141592653589793... Math.E // Número de euler @@ -14,13 +14,13 @@ Math.LN10 // logaritmo natural de 10 Math.LOG2E // logaritmo de 2 na base E Math.LOG10E // logaritmo de 10 na base E ``` ### <a id="aproximacao"></a>Float -> inteiro ```javascript Math.ceil(4.3) // 5 -> Inteiro maior mais perto Math.floor(4.7) // 4 -> Inteiro menor mais perto Math.round(4.4) // 4 -> Inteiro mais perto ``` ### <a id="operacao"></a>Operações ```javascript Math.pow(8, 2) // 64 -> Primeiro elevado ao segundo Math.sqrt(64) // 8 -> Raiz quadrada do número @@ -41,11 +41,11 @@ Number((4.6 - Math.trunc(4.6)) .replace('.', '')) // 6 -> Parte decimal do número como um inteiro ``` ### <a id="converter"></a>Convertendo número ```javascript Math.abs(-4.5) // 4.5 -> De negativo para positivo ``` ## <a id="random"></a>Valor random ```javascript Math.random() // Valor random de 0 a 1 Matn.random() * 10 // Valor random de 0 a 10 -
lavesan revised this gist
Apr 2, 2019 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -39,7 +39,7 @@ array.reverse() // [4, 3, 2, 1] // Ordena os elementos de acordo com o UNICODE // Se eu não achar legal posso passar uma função que faz o sort; array.sort(funcaoCriada(elem1, elem2)) // Altera dados dentro de um array e retorna os elementos removidos // índice de começo; quantidade de elementos removidos; elemento que entrará no meio -
lavesan revised this gist
Mar 3, 2019 . 1 changed file with 1 addition and 2 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -39,8 +39,7 @@ Math.trunc(4.6) // 4 -> Parte inteiro de um número float 4.6 - Math.trunc(4.6) // 0.6 -> Parte decimal do número Number((4.6 - Math.trunc(4.6)) .replace('.', '')) // 6 -> Parte decimal do número como um inteiro ``` ### <a name="converter"></a>Convertendo número ```javascript -
lavesan revised this gist
Mar 3, 2019 . 1 changed file with 2 additions and 2 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -38,9 +38,9 @@ Math.tanh(x) // tangente hiperbólica de um número Math.trunc(4.6) // 4 -> Parte inteiro de um número float 4.6 - Math.trunc(4.6) // 0.6 -> Parte decimal do número Number((4.6 - Math.trunc(4.6)) .replace('.', '') .replace(',', '')) // 6 -> Parte decimal do número como um inteiro ``` ### <a name="converter"></a>Convertendo número ```javascript -
lavesan revised this gist
Mar 3, 2019 . 1 changed file with 2 additions and 2 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -37,10 +37,10 @@ Math.atan2(y, x) // Arcotangete do quociente dos parâmetros Math.tanh(x) // tangente hiperbólica de um número Math.trunc(4.6) // 4 -> Parte inteiro de um número float 4.6 - Math.trunc(4.6) // 0.6 -> Parte decimal do número Number((4.6 - Math.trunc(4.6) .replace('.', '') .replace(',', ''))) // 6 -> Parte decimal do número como um inteiro ``` ### <a name="converter"></a>Convertendo número ```javascript -
lavesan revised this gist
Mar 3, 2019 . 1 changed file with 19 additions and 1 deletion.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -25,4 +25,22 @@ Object.values(obj) // ['algum nome', 23] ``` ### utilidades ```javascript // Assim adiciono uma função ou o que quer que seja à todo filho dele Object.prototype.algumaCoisaCompartilhada Object.keys(obj) // ['name', 'idade'] Object.values(obj) // ['algum nome', 23] // Criação de um objeto Object.create(AlgumaClasse)) // Vê se um objeto é protótipo de outro Object.isPrototypeOf(OutroObjeto) // true ou false // Vê se um objeto tem tal propriedade Object.hasOwnProperty(propriedade) // true ou false // Transforma um objeto em string (JSON) Object.toString() ``` https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype -
lavesan revised this gist
Mar 1, 2019 . 1 changed file with 14 additions and 8 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -16,9 +16,9 @@ Math.LOG10E // logaritmo de 10 na base E ``` ### <a name="aproximacao"></a>Float -> inteiro ```javascript Math.ceil(4.3) // 5 -> Inteiro maior mais perto Math.floor(4.7) // 4 -> Inteiro menor mais perto Math.round(4.4) // 4 -> Inteiro mais perto ``` ### <a name="operacao"></a>Operações ```javascript @@ -34,16 +34,22 @@ Math.acos(x) // Arcocoseno de x em radianos Math.asin(x) // Arcoseno de x em radianos Math.atan(x) // Arcotangente de x de -PI/2 à PI/2 Math.atan2(y, x) // Arcotangete do quociente dos parâmetros Math.tanh(x) // tangente hiperbólica de um número Math.trunc(4.6) // 4 -> Parte inteiro de um número float 4.6 - Math.trunc(4.6) // 0.6 -> Parte decimal do número Number(4.6 - Math.trunc(4.6) .replace('.', '') .replace(',', '')) // 6 -> Parte decimal do número como um inteiro ``` ### <a name="converter"></a>Convertendo número ```javascript Math.abs(-4.5) // 4.5 -> De negativo para positivo ``` ## <a name="random"></a>Valor random ```javascript Math.random() // Valor random de 0 a 1 Matn.random() * 10 // Valor random de 0 a 10 Math.floor(Math.random() * 10) // Valor inteiro random e 1 a 9 Math.floor(Math.random() * 10) + 1 // Valor inteiro random de 1 a 10 ``` -
lavesan revised this gist
Mar 1, 2019 . 1 changed file with 2 additions and 0 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -34,6 +34,8 @@ Math.acos(x) // Arcocoseno de x em radianos Math.asin(x) // Arcoseno de x em radianos Math.atan(x) // Arcotangente de x de -PI/2 à PI/2 Math.atan2(y, x) // Arcotangete do quociente dos parâmetros tanh(x) // Returns the hyperbolic tangent of a number trunc(4.6) // 4 -> Parte inteiro de um número float ``` ### <a name="converter"></a>Convertendo número ```javascript -
lavesan revised this gist
Mar 1, 2019 . 1 changed file with 11 additions and 6 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,9 @@ * [Variáveis](#variaveis) * [Aproximação de float](#aproximacao) * [Operações](#operacao) * [Converção de valor](#converter) * [Random](#random) ### <a name="variaveis"></a>Variáveis ```javascript Math.PI // Valor de pi 3,141592653589793... Math.E // Número de euler @@ -9,13 +14,13 @@ Math.LN10 // logaritmo natural de 10 Math.LOG2E // logaritmo de 2 na base E Math.LOG10E // logaritmo de 10 na base E ``` ### <a name="aproximacao"></a>Float -> inteiro ```javascript Math.ceil(4.3) // 5 -> Inteiro maior mais perto Math.floor(4.7) // 4 -> Inteiro menor mais perto Math.round(4.4) // 4 -> Inteiro mais perto ``` ### <a name="operacao"></a>Operações ```javascript Math.pow(8, 2) // 64 -> Primeiro elevado ao segundo Math.sqrt(64) // 8 -> Raiz quadrada do número @@ -30,13 +35,13 @@ Math.asin(x) // Arcoseno de x em radianos Math.atan(x) // Arcotangente de x de -PI/2 à PI/2 Math.atan2(y, x) // Arcotangete do quociente dos parâmetros ``` ### <a name="converter"></a>Convertendo número ```javascript Math.abs(-4.5) // 4.5 -> De negativo para positivo ``` ## <a name="random"></a>Valor random ```javascript Math.random() // Valor random de 0 a 1 Matn.random() * 10 // Valor random de 0 a 10 Math.floor(Math.random() * 10) // Valor inteiro random e 0 a 9 ``` -
lavesan revised this gist
Mar 1, 2019 . 1 changed file with 24 additions and 5 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,6 +1,13 @@ ### Variáveis ```javascript Math.PI // Valor de pi 3,141592653589793... Math.E // Número de euler Math.SQRT2 // raiz de 2 Math.SQRT1_2 // raiz de 1/2 Math.LN2 // logaritmo natural de 2 Math.LN10 // logaritmo natural de 10 Math.LOG2E // logaritmo de 2 na base E Math.LOG10E // logaritmo de 10 na base E ``` ### Float -> inteiro ```javascript @@ -10,14 +17,26 @@ Math.round(4.4) // 4 -> Inteiro mais perto ``` ### Operações ```javascript Math.pow(8, 2) // 64 -> Primeiro elevado ao segundo Math.sqrt(64) // 8 -> Raiz quadrada do número Math.exp(1) // E -> valor de E^1 Math.log(1) // 0 -> Logaritmo de 1 na base E(número de euler) Math.min(4, 5, 9, -10) // -10 -> Valor mínimo Math.max(4, 5, 9, -10) // 9 -> Valor máximo Math.sin(90) // 1 -> Seno Math.cos(180) // -1 -> Cosseno Math.acos(x) // Arcocoseno de x em radianos Math.asin(x) // Arcoseno de x em radianos Math.atan(x) // Arcotangente de x de -PI/2 à PI/2 Math.atan2(y, x) // Arcotangete do quociente dos parâmetros ``` ### Convertendo número ```javascript Math.abs(-4.5) // 4.5 -> De negativo para positivo ``` ## Valor random ```javascript Math.random() // Valor random de 0 a 1 Matn.random() * 10 // Valor random de 0 a 10 Math.floor(Math.random() * 10) // Valor inteiro random e 0 a 10 ``` -
lavesan revised this gist
Mar 1, 2019 . 1 changed file with 23 additions and 0 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,23 @@ ### Variáveis ```javascript Math.PI // Valor de pi 3,141592653589793... ``` ### Float -> inteiro ```javascript Math.ceil(4.3) // 5 -> Inteiro maior mais perto Math.floor(4.7) // 4 -> Inteiro menor mais perto Math.round(4.4) // 4 -> Inteiro mais perto ``` ### Operações ```javascript Math.pow(8, 2) // 64 -> Primeiro elevado ao segundo Math.sqrt(64) // 8 -> Raiz quadrada do número Math.sin(90) // 1 -> Seno Math.cos(180) // -1 -> Cosseno Math.min(4, 5, 9, -10) // -10 -> Valor mínimo Math.max(4, 5, 9, -10) // 9 -> Valor máximo ``` ### Convertendo número ```javascript Math.abs(-4.5) // 4.5 -> De negativo para positivo ``` -
lavesan revised this gist
Mar 1, 2019 . 1 changed file with 15 additions and 0 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,15 @@ ```javascript let funcao = function(num1, let2, algo) { } // Retorna numero de parâmetros na função funcao.length // 3 // Retorno o nome da função funcao.name // 'funcao' // Colocando o this de uma função em um contexto que eu quiser funcao.bind(this) // Assim não importa onde ela for chamada, o 'this' vai ser o mesmo daonde isso foi colocado funcao.bind([1, 2, 3]) // Assim o 'this' vai ser este array sempre que for chamado (só um exemplo) ``` https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype -
lavesan revised this gist
Mar 1, 2019 . 1 changed file with 17 additions and 4 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -99,8 +99,20 @@ let teste // Loop normal // elemento(opcional); índice(opcional); array(opcional) // ^ Praticamente todos seguem esse fluxo dai de cima ^ array.forEach((elem, i, arrayIn) => {}) // Retorna um novo array de acordo com como eu mudar os elementos teste = array.map(elem => {return elem * 2}) // [2, 4, 6, 8, 10] // Executa uma função feita por mim // Elemento atual; Próximo elemento; index; array teste = array.reduce((elem, proxElem) => elem + proxElem) // 15 // Executa uma função feita por mim de trás para frente // Elemento atual; Elemento anterior; index; array teste = array.reduceRight((elem, elemAnterior) => elem + elemAnterior) // 15 // Retorna um array de arrays com chave(index) e valor(valor dele) teste = array.entries() // [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]] @@ -126,8 +138,9 @@ teste = array.keys() // [0, 1, 2, 3, 4] // Retorna array com valores teste = array.values() // [1, 2, 3, 4, 5] // Retorna um ArrayIterator teste = array[Symbol.Iterator]() teste.next().value // 1 teste.next().value // 2 ... ``` -
lavesan revised this gist
Mar 1, 2019 . 1 changed file with 12 additions and 0 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -108,11 +108,23 @@ teste = array.entries() // [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]] // Elemento atual; índice(opcional); array(pocional) teste = array.every(elem => {return elem >= 2}) // false // Testa para ver se existe um elemento de um array com a condicional e retorna um boolean teste = array.some(elem => {return elem >= 2}) // true // Retorna um novo array com todos elementos que passam na condiciona, em caso de erro retorna -1 teste = array.filter(elem => {return elem >= 2}) // [2, 3, 4, 5] // Retorna valor do primeiro elemento que satisfizer a condicional, em caso de erro retorna -1 teste = array.find(elem => {return elem >= 2}) // 2 // Retorna o índice do primeiro elemento que satisfizer a condicional, em caso de erro retorna -1 teste = array.findIndex(elem => {return elem >= 2}) // 1 // Retorna array de objetos com chave(index) teste = array.keys() // [0, 1, 2, 3, 4] // Retorna array com valores teste = array.values() // [1, 2, 3, 4, 5] -
lavesan revised this gist
Mar 1, 2019 . 1 changed file with 18 additions and 9 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,9 @@ * [loop](#loop) * [Funções úteis](#uteis) * [Alterando um array](#alterar) * [Consulta num array](#consulta) * [Procura no array](#procura) ### <a name="loop"></a>loop ```javascript const array = ['dado1', 34, true, 'dado4'] @@ -16,9 +21,9 @@ array.forEach((elem, i, array) => { console.log(elem) }) ``` ### <a name="uteis"></a>Funções úteis *explicação dos parâmetros seguidos por ';'* #### <a name="alterar"></a>Alterando array ```javascript let array = [1, 2, 3, 4] @@ -52,7 +57,7 @@ array.shift() // [2, 3, 4] // Remove e retorna o último elemento array.pop() // [1, 2, 3] ``` #### <a name="consulta"></a>Consultas no array ```javascript let array = [1, 2, 3, 4] let array2 = [4, 5] @@ -87,17 +92,21 @@ array3 = [1, 2, 3, 4, 4, 5].indexOf(4, 0) // 3 // Elemento procurado; Começo da procura(opcional) array3 = [1, 2, 3, 4, 4, 5].lastIndexOf(2, 3) // 4 ``` #### <a name="procura"></a> Procura com loops ```javascript let array = [1, 2, 3, 4, 5] let teste // Loop normal // elemento(opcional); índice(opcional); array(opcional) array.forEach((elem, i, arrayIn) => {}) // Retorna um array de arrays com chave(index) e valor(valor dele) teste = array.entries() // [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]] // Testa todos elementos de um array e retorna um booleano // Elemento atual; índice(opcional); array(pocional) teste = array.every(elem => {return elem >= 2}) // false -
lavesan revised this gist
Mar 1, 2019 . 1 changed file with 55 additions and 3 deletions.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -16,12 +16,11 @@ array.forEach((elem, i, array) => { console.log(elem) }) ``` ### Funções úteis *explicação dos parâmetros seguidos por ';'* #### Alterando array ```javascript let array = [1, 2, 3, 4] // Copia elementos dentro de um array para ele mesmo sem alterar o índice // indíce para onde os elementos vão ser copiados; índice de começo; índice de término (senão copiará tudo) @@ -37,6 +36,10 @@ array.reverse() // [4, 3, 2, 1] // Se eu não achar legal posso passar uma função que faz o sort; array.sort(funcaoCriada(elem1, 2elem1)) // Altera dados dentro de um array e retorna os elementos removidos // índice de começo; quantidade de elementos removidos; elemento que entrará no meio array.splice(1, 0, 43) // [1, 43, 2, 3, 4] // Adiciona um ou mais elementos no fim do array e retorna novo length array.push(5, 6) // [1, 2, 3, 4, 5, 6] @@ -48,6 +51,55 @@ array.shift() // [2, 3, 4] // Remove e retorna o último elemento array.pop() // [1, 2, 3] ``` #### Consultas no array ```javascript let array = [1, 2, 3, 4] let array2 = [4, 5] let array3 // Concatena elementos dentro do array ou até arrays com arrays array3 = array.concat(array2, 65) // [1, 2, 3, 4, 4, 5, 65] // Verifica se existe alguma ocorrência dentro do array let booleano = array.includes(3) // true // Adiciona uma string no meio dos elementos de um array e retorna uma string disso array3 = array.join() // '1,2,3,4' array3 = array.join('A') // '1A2A3A4' // Retorna uma cópia do array // começo, fim(opcional) array3 = array.slice(1, 2) // [2, 3] // Converte algo para string array3 = array.toString() // '1,2,3,4' array3 = 43.toString() // '43' // Converte algo para string (datas e pa) utilizando seus respectivos métodos array3 = array.toLocaleString() // '1,2,3,4' // Retorna primeiro índice da ocorrência e -1 em caso de erro // Elemento procurado; Começo da procura(opcional) array3 = [1, 2, 3, 4, 4, 5].indexOf(4, 0) // 3 // Retorna último índice da ocorrência e -1 em caso de erro. A procura começa de trás para frente // Elemento procurado; Começo da procura(opcional) array3 = [1, 2, 3, 4, 4, 5].lastIndexOf(2, 3) // 4 ``` #### Procura com loops ```javascript let array = [1, 2, 3, 4, 4, 5] // loop normal // elemento(opcional); índice(opcional); array(opcional) array.forEach((elem, i, arrayIn) => {}) -
lavesan revised this gist
Mar 1, 2019 . 2 changed files with 46 additions and 1 deletion.There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -8,11 +8,53 @@ for(let i = 0; i < array.length; i++) { for(const i in array) { console.log(array[i]) } for(let i of array) { console.log(array[i]) } // loop com elemento, índice e array completo array.forEach((elem, i, array) => { console.log(elem) }) ``` ### funções úteis *explicação dos parâmetros seguidos por ';'* ```javascript let array = [1, 2, 3, 4] let array2 = [] let array3 = [{name: 'sei la', value: 2}, {name: 'tanto faz', value: 4}] // Copia elementos dentro de um array para ele mesmo sem alterar o índice // indíce para onde os elementos vão ser copiados; índice de começo; índice de término (senão copiará tudo) array.copyWithin(0, 2, 3) // [3, 4, 3, 4] // Adicionar elemento em um array de um índice à outro array.fill(5, 1, 3) // [3, 5, 5, 5] // Reverte a ordem dos elementos array.reverse() // [4, 3, 2, 1] // Ordena os elementos de acordo com o UNICODE // Se eu não achar legal posso passar uma função que faz o sort; array.sort(funcaoCriada(elem1, 2elem1)) // Adiciona um ou mais elementos no fim do array e retorna novo length array.push(5, 6) // [1, 2, 3, 4, 5, 6] // Adiciona um ou mais elementos no começo do array e retorna novo length array.unshift(5, 6) // [5, 6, 1, 2, 3, 4] // Remove e retorna o primeiro elemento array.shift() // [2, 3, 4] // Remove e retorna o último elemento array.pop() // [1, 2, 3] ``` This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -22,4 +22,7 @@ Object.keys(obj) // ['name', 'idade'] Object.values(obj) // ['algum nome', 23] // Já que é um array, só usar algum método 'for' agora ``` ### utilidades ```javascript ```
NewerOlder