课程
本课程为JavaScript基础,包括classes, arrow functions, etc.课程链接:JavaScript Crash Course For Beginners
笔记
LOGGING OUTPUT
按F12可打开console,更多console methods:mdn console
alert('Hello World'); // Do not use for debugging.
// Stops script and only strings
console.log('Hello World');
console.error('This is an error');
console.warn('This is a warning');
Variable Assignment
var, let, const三者区别:
// VARIABLES - var, let, const
// var -> function (can be used outside the block)
// let -> block (prefered)
// const -> block (read-only, prefered)
let age = 30;
// let can be re-assigned, const can not
age = 31;
// DATA TYPES - String, Number, Boolean, null, undefined
const name = 'Brad';
const age = 37;
const rating = 3.5;
const isCool = true;
const x = null;
const y = undefined;
let z; // undefined
// Check type
console.log(typeof z);
String
// STRINGS
// Concatenation
console.log('My name is ' + name + ' and I am ' + age);
// Template literal (better)
console.log(`My name is ${name} and I am ${age}`);
// String methods & properties
const s = 'Hello World';
let val;
// Get length
val = s.length;
// Change case
val = s.toUpperCase();
val = s.toLowerCase();
// Get sub string
val = s.substring(0, 5); //output: "Hello"
// Split into array
val = s.split('');
// oupt:["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]
val = s.split(' ');
// output:["Hello", "World"]
Arrays
// ARRAYS - Store multiple values in a variable
const numbers = [1,2,3,4,5];
const fruits = ['apples', 'oranges', 'pears', 10, true];
// Get one value - Arrays start at 0
console.log(fruits[1]); //oranges
// Add value
fruits[4] = 'blueberries'; //can change values but cannot //reassign: fruits = ['apples', 'oranges']
// Add value using push()
fruits.push('strawberries'); // add to the end
// Add to beginning
fruits.unshift('mangos'); // add to the beginning
// Remove last value
fruits.pop();
// // Check if array
console.log(Array.isArray(fruits)); //true
// // Get index
console.log(fruits.indexOf('oranges')); //1
Object Literals
// OBJECT LITERALS
const person = {
name: 'John',
age: 30,
hobbies: ['music', 'movies', 'sports'],
address: {
street: '50 Main st',
city: 'Boston',
state: 'MA'
}
}
// Get single value
console.log(person.name, person.age)
// Get array value
console.log(person.hobbies[1]);
// Get embedded object
console.log(person.address.city);
// Add property
person.email = 'jdoe@gmail.com';
// pulling these out
const { name, age } = person;
console.log(name);
const { name, age, address: { city }} = person;
console.log(city);
Array of objects
// Array of objects
const todos = [
{
id: 1,
text: 'Take out trash',
isComplete: false
},
{
id: 2,
text: 'Dinner with wife',
isComplete: false
},
{
id: 3,
text: 'Meeting with boss',
isComplete: true
}
];
// Get specific object value
console.log(todos[1].text);
// Format as JSON (full stack development)
console.log(JSON.stringify(todos));
// use this method to convert
// in order to send data to the server
更多关于json format的知识:json converter
Loops
// For
for(let i = 0; i < 10; i++){
console.log(`For Loop Number: ${i}`);
} //0-9
// While
let i = 0;
while(i < 10) {
console.log(`While Loop Number: ${i}`);
i++;
} //0-9
// Loop Through Arrays
// For Loop
for(let i = 0; i < todos.length; i++){
console.log(` Todo ${i + 1}: ${todos[i].text}`);
}
// For...of Loop: easier, preferred to loop through arrays
for(let todo of todos) {
console.log(todo.text);
}
High Order Array Methods (show prototype)
// forEach() - Loops through array
todos.forEach(function(todo) {
console.log(todo.text);
});
todos.forEach(function(todo, i, myTodos) {
console.log(`${i + 1}: ${todo.text}`);
console.log(myTodos);
});
// map() - Loop through and create new array
const todoTextArray = todos.map(function(todo) {
return todo.text;
});
console.log(todoTextArray);
// filter() - Returns array based on condition
const todo1 = todos.filter(function(todo) {
// Return only todos where id is 1
return todo.id === 1;
});
// Return an array of only texts that are completed
const todoCompleted = todos.filter(function(todo) {
return todo.isCompleted === true;
}).map(function(todo) {
return todo.text;
})
Conditionals
// Simple If/Else Statement
const x = 30;
// const x = '30', then x == 30 is true but x === 30 is not
// number and string, different data types
if(x === 10) {
console.log('x is 10');
} else if(x > 10) {
console.log('x is greater than 10');
} else {
console.log('x is less than 10')
}
if(x < 5 || x > 40) {
console.log('x is less than 5 or greater than 40')
}
if(x > 5 && x < 40) {
console.log('x is greater than 5 and less than 40')
}
Switch
color = 'blue';
switch(color) {
case 'red':
console.log('color is red');
case 'blue':
console.log('color is blue');
default:
console.log('color is not red or blue')
}
// Ternary operator / Shorthand if
const z = color === 'red' ? 10 : 20;
const x = 10;
const color = x > 10 ? 'red':'blue';
// "?" represents "if...then"
// here color = 'blue'
Functions
// set the default value to 1
function addNums(num1 = 1, num2 = 1) {
return num1 + num2
}
console.log(addNums(5, 5));
// Arrow functions
const addNums(num1 = 1, num2 = 1) => num1 + num2;
console.log(addNums(5, 5));
const addNums = num1 => num1 + 5
function greet(greeting = 'Hello', name) {
if(!name) {
// console.log(greeting);
return greeting;
} else {
// console.log(`${greeting} ${name}`);
return `${greeting} ${name}`;
}
}
// ARROW FUNCTIONS
const greet = (greeting = 'Hello', name = 'There') => `${greeting} ${name}`;
console.log(greet('Hi'));
OOP
// Constructor Function
function Person(firstName, lastName, dob) {
// Set object properties
this.firstName = firstName;
this.lastName = lastName;
this.dob = new Date(dob); // Set to actual date object using Date constructor
// this.getBirthYear = function(){
// return this.dob.getFullYear();
// }
// this.getFullName = function() {
// return `${this.firstName} ${this.lastName}`
// }
}
// Get Birth Year, put in the prototype
Person.prototype.getBirthYear = function () {
return this.dob.getFullYear();
}
// Get Full Name
Person.prototype.getFullName = function() {
return `${this.firstName} ${this.lastName}`
}
// Instantiate an object from the class
const person1 = new Person('John', 'Doe', '7-8-80');
const person2 = new Person('Steve', 'Smith', '8-2-90');
console.log(person2); // return like an object literal
// but prefixed with the object name
// console.log(person1.getBirthYear());
// console.log(person1.getFullName());
// Built in constructors
const name = new String('Kevin');
console.log(typeof name); // Shows 'Object'
const num = new Number(5);
console.log(typeof num); // Shows 'Object'
ES6 Classes
We call them syntactic sugar, which function the same but more easier to write.
class Person {
constructor(firstName, lastName, dob) {
this.firstName = firstName;
this.lastName = lastName;
this.dob = new Date(dob);
}
// Get Birth Year
getBirthYear() {
return this.dob.getFullYear();
}
// Get Full Name
getFullName() {
return `${this.firstName} ${this.lastName}`
}
}
const person1 = new Person('John', 'Doe', '7-8-80');
console.log(person1.getBirthYear());
Element selectors
// the whole window is also an object
console.log(window)
window.alert(1) // equal to alert(1)
// Single Element Selectors
const form = document.getElementById('my-form');
console.log(document.querySelector('.container'));
// acts like JQuery, can select anything: tag, class, id
//but if there are many, only select the first one
// Multiple Element Selectors
console.log(document.querySelectorAll('.item'));
// can get an array and do for loops
// The following not used often: (only get HTML collection)
console.log(document.getElementsByTagName('li'));
console.log(document.getElementsByClassName('item'));
const items = document.querySelectorAll('.item');
items.forEach((item) => console.log(item));
Manipulating the DOM (HTML elements)
const ul = document.querySelector('.items');
// ul.remove();
// ul.lastElementChild.remove(); // remove the last item (li) in ul
// change the first li to 'Hello'
ul.firstElementChild.textContent = 'Hello';
// change the second li to 'Brad'
ul.children[1].innerText = 'Brad';
// change the last li, add html
ul.lastElementChild.innerHTML = '<h1>Hello</h1>';
// change the style
const btn = document.querySelector('.btn');
btn.style.background = 'red';
Events
You can refer to the MDN documentation:MDN Event
// Mouse Event
btn.addEventListener('click', e => {
e.preventDefault();
console.log(e.target.className); //btn; get attribute of the event
document.getElementById('my-form').style.background = '#ccc';
document.querySelector('body').classList.add('bg-dark');
ul.lastElementChild.innerHTML = '<h1>Changed</h1>';
});
// Keyboard Event
const nameInput = document.querySelector('#name');
nameInput.addEventListener('input', e => {
document.querySelector('.container').append(nameInput.value);
});
Example: User Form Script
Show the input as a list, but not saved in database.
// Put DOM elements into variables
const myForm = document.querySelector('#my-form');
const nameInput = document.querySelector('#name');
const emailInput = document.querySelector('#email');
const msg = document.querySelector('.msg');
const userList = document.querySelector('#users');
// Listen for form submit
myForm.addEventListener('submit', onSubmit);
function onSubmit(e) {
e.preventDefault();
if(nameInput.value === '' || emailInput.value === '') {
// alert('Please enter all fields');
msg.classList.add('error');
msg.innerHTML = 'Please enter all fields';
// Remove error after 3 seconds
setTimeout(() => msg.remove(), 3000);
} else {
// Create new list item with user
const li = document.createElement('li');
// Add text node with input values
li.appendChild(document.createTextNode(`${nameInput.value}: ${emailInput.value}`));
// Add HTML
// li.innerHTML = `<strong>${nameInput.value}</strong>e: ${emailInput.value}`;
// Append to ul
userList.appendChild(li);
// Clear fields
nameInput.value = '';
emailInput.value = '';
}
}