Last active
December 11, 2015 01:38
-
-
Save marioplumbarius/4524649 to your computer and use it in GitHub Desktop.
Linhas de código que estou armazenando com alguns exemplos da sintaxe enquanto aprendo javaScript. Aqui você encontra como instanciar um objeto, como criar uma função, estruturas de repetição/seleção e algumas outras coisas básicas.
This file contains hidden or 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 characters
/* objetos */ | |
// literal notation | |
var calendar = { | |
name: "PHP Event", | |
year: 2012 | |
}; | |
// constructor | |
var pets = {}; | |
// OU | |
var dogs = new Object(); | |
// adicionando métodos e propriedades ao objeto vazio | |
pets.name = "marcela"; | |
pets["age"] = 7; | |
pets.printPets = function(){ | |
return this.name + ' ' + this.age; | |
}; | |
/* classes */ | |
function Pet(name, age){ | |
this.name = name; | |
this.age = age; | |
this.printPet = function(){ | |
return this.name + " " + this.age; | |
} | |
} | |
function Dog(name, age){ | |
this.name = name; | |
this.age = age; /* este é um atributo público */ | |
var breed = breed; /* este é um atributo privado */ | |
// função para acessar o atributo privado fora desta classe | |
this.getBreed = function(){ | |
return breed; | |
} | |
} | |
function Cat(name){ | |
this.name = name; | |
this.age = 7; | |
} | |
/* herança */ | |
/* prototype */ | |
// fazendo as classes JÁ CRIADAS Dog e Cat herdarem os atributos e métodos da classe Pet | |
Dog.prototype = new Pet(); | |
Cat.prototype = new Pet(); | |
var newDog = new Dog("andre", 9); | |
var newCat = new Cat("lucy", 9); | |
newCat.age; | |
newDog.printPet(); | |
function Pets(name, age){ | |
this.age = age; | |
} | |
Pets.prototype.printPets = function(){ | |
return this.name + ' ' + this.age; | |
}; | |
var newPet = new Pets(5); | |
newPet.printPets; | |
/* funcoes */ | |
// funções são objetos. possuem atributos e métodos | |
var sum = function(a,b){ | |
return a + b; | |
}; | |
console.log(sum.length); // número de parâmetros na função | |
var divideByThree = function(number){ | |
var result = number / 3; | |
console.log(result); | |
}; | |
divideByThree(12); | |
var isEven = function(number){ | |
console.log(number % 2 === 0); | |
}; | |
isEven(2); | |
/* funções anônimas */ | |
(function(){ | |
var a = 1, | |
b = 2; | |
alert(a + b); | |
}()); | |
/* estruturas de dados */ | |
/* arrays */ | |
var dudes = ['mario', 'carlos', 'joao']; | |
var mix = ['mario', 22, 'male', 15]; | |
var dudes = new Array('mario', 'carlos', 'joao'); | |
alert(dudes[2]); | |
alert(dudes.length); | |
//jagged arrays = quando as 'colunas' dos arrays contém outros arrays dentro, com dimensões diferentes | |
var jagged = [[1, 2], ['a', 'b', 'c'], 'string']; | |
// métodos: push, pop, toString | |
dudes.pop(); | |
dudes.toString(); | |
dudes.push('cleiton'); | |
// join, split | |
var a = '1,2,3'; | |
var a = a.split(','); | |
var a = a.join(', then '); | |
alert(a); | |
/* strings */ | |
// primitive string | |
var animal = 'aligator'; | |
typeof animal; // diz qual o tipo | |
// string object | |
var animal = new String('crocodile'); | |
typeof animal; | |
// funções com strings | |
var nomeLongo = "Meu nome é Mário Luan"; | |
nomeLongo.substring(11); // prints "Mário Luan" | |
nomeLongo.replace('á', 'a'); | |
nomeLongo.replace('o', 'ó').substring(0,8); | |
/* callbacks */ | |
var a = [2, 1, 30, 15]; | |
a.sort(); // ordena como strings =-( | |
// passando uma função callback para ordenar da forma correta | |
// utilizando uma função anônima | |
var a = [2, 1, 30, 15]; | |
a.sort(function (a, b){ | |
return (a > b) ? 1 : -1; | |
}); | |
// OU | |
// utilizando uma função existente | |
function numsort(a, b){ | |
return (a > b) ? 1 : -1; | |
} | |
a.sort(numsort); | |
/* confirm */ | |
// usado para confirmar ações feitas pelo usuário. ex: deletar, sair sem salvar | |
confirm("Quer mesmo deletar estes dados?"); | |
/* prompt */ | |
// usado para receber uma entrada de dados | |
var country = prompt("Where are you from?"); | |
/* console.log */ | |
// dá um print para o argumento passado | |
console.log("mario"); | |
console.log("mario".length > 3); | |
console.log(8 * 3); | |
/* comparisons */ | |
//> | |
//< | |
//<= | |
//>= | |
// === | |
/* estruturas de decisão */ | |
// similar ao Java | |
if("mario".length > 2){ | |
alert("Condição verdadeira!"); | |
}else if("luan". length > 20){ | |
alert("Condição falsa!"); | |
}else{ | |
alert("Mensagem defaut"); | |
} | |
/* substring */ | |
// similar ao String slice do Python | |
console.log("mario luan".substring(0,5)); // pega do índice 0 ao 4 | |
console.log("mario luan".substring(5)); // pega do índice 5 ao último | |
/* estruturas de repetição */ | |
// todas estruturas são similares ao Java | |
// for | |
for (var i = 5; i < 11; i++){ | |
console.log(i); | |
} | |
// while | |
var i = 0; | |
while(i < 10){ | |
console.log(i); | |
i++; | |
} | |
//do...while | |
var i = 0 | |
do{ | |
console.log(i); | |
i++; | |
}while(i < 10); | |
//switch | |
var name = prompt('digite seu nome'); | |
switch(name){ | |
case 'mario': | |
console.log('Ola ' + name); | |
break; | |
case 'luan': | |
console.log('Você não é o Mário! É o luan.'); | |
break; | |
default: | |
console.log('Você nunca veio aqui!'); | |
break; | |
} | |
/* Função recursiva */ | |
// Utilizando um loop | |
var power = function(base, exponent){ | |
var result = 1; | |
for(var i = 0; i < exponent; i++){ | |
result *= base; | |
} | |
return result | |
}; | |
// Utilizando a função recursiva | |
var power = function(base, exponent){ | |
// qualquer numero elevado a zero é 1 | |
if(exponent === 0){ | |
return 1; | |
} else{ | |
return base * power(base, exponent - 1); | |
} | |
}; | |
//logical operators | |
/* | |
|| = or | |
&& = and | |
! = not | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment