javascript JavaScript语言基础知识
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript JavaScript语言基础知识相关的知识,希望对你有一定的参考价值。
// Function Declarations
function sayIt(firstName, middleName,lastName){
return 'Wassup ' + firstName + ' ' + middleName + ' ' + lastName +'!';
}
sayIt('Ken','Van','Truong');
//------------------------------------
// ES5
function sayIt(firstName, middleName,lastName){
if(typeof firstName === 'undefined'){firstName = 'John'};
if(typeof middleName === 'undefined'){middleName = 'Cong'};
if(typeof lastName === 'undefined'){lastName = 'Doe'};
return 'Wassup ' + firstName + ' ' + middleName + ' ' + lastName +'!';
}
sayIt('Ken','Van','Truong');
//------------------------------------
// ES6
function sayIt(firstName = 'John', middleName = 'Cong',lastName = 'Doe'){
return 'Wassup ' + firstName + ' ' + middleName + ' ' + lastName +'!';
}
sayIt('Ken');
//------ Function Expressions ---------
const hello = function(x){
return x * x;
};
console.log(hello(1234));
// Immidiatley Invokable Function Expressions - Iiefs
(function(){
console.log('Iife Ran..');
})();
(function(name){
console.log('Hello ' + name);
})('Brad');
// Property Methods
const crypto = {
add: function(e){
console.log(`wassup ${e}`);
},
edit: function(e){
console.log(`LETS GOO ${e}!!!!!!`);
},
}
crypto.add('Sparkster');
// Windows Methods / Objects / Properties
window.console.log(123);
// Alert
alert('Hello World');
// Prompt
prompt('How old are you?');
// Confirm
confirm('confirm it');
if(confirm('Are you sure?')){
console.log('Deleted');
} else {
console.log('Cancelled');
}
//-------
const input = prompt('How old are you?');
alert(`So you are only ${input}?`);
// Windows Methods / Objects / Properties
let val;
// Outter height and width
val = window.outerHeight;
val = window.outerWidth;
// Inner height and width
val = window.innerHeight;
val = window.innerWidth;
// Scroll Points
val = window.scrollY;
val = window.scrollX;
// Location Object
val = window.location;
val = window.location.hostname;
val = window.location.port;
val = window.location.href;
val = window.location.search;
// Redirect
window.location.href = 'http://kenvantruong.com';
// Reload
window.location.reload();
// History Object
window.history.go(-1);
val = window.history.length;
// Navigator Object
val = window.navigator;
val = window.navigator.appName;
val = window.navigator.appVersion;
val = window.navigator.userAgent;
val = window.navigator.platform;
val = window.navigator.vendor;
val = window.navigator.language;
console.log(val);
const color = prompt('Are you repping blue or red?');
switch(color){
case 'red':
console.log('I\'m Piru Blood Gang. Suuwoop!');
break;
case 'blue':
console.log('I\'m Eastside Crip. WAZZZZUH CUHHH!');
default:
console.log('You ain\'t from around here Cuh GTFO!');
break;
}
let day;
switch(new Date().getDay()){
case 0:
day = 'Sunday';
break;
case 0:
day = 'Monday';
break;
case 0:
day = 'Tuesday';
break;
case 0:
day = 'Wednesday';
break;
case 0:
day = 'Thursday';
break;
case 0:
day = 'Friday';
break;
case 0:
day = 'Saturday';
break;
}
console.log(`Today is ${day}`);
const person = {
firstName: 'Steve',
lastName: 'Hoang',
age: 28,
email: 'steveHoang@aol.com',
hobbies: ['music', 'sports', 'gambling', 'drinks'],
address: {
city: 'San Francisco',
state: 'CA'
},
getBirthYear: function() {
return 1990;
}
}
let val;
val = person;
// Get specific value
val = person. firstName;
val = person['lastName'];
val = person.age;
val = person.hobbies;
console.log(val);
const people = [
{name: 'Tuan', age: 29},
{name: 'Mike', age: 21},
{name: 'Lucy', age: 25}
];
for(let i = 0; i < people.length; i++){
console.log(people[i].name);
}
if(something is something){
do something
} else {
do something else
}
const id = 100;
// Equal to
if(id == 100){
console.log('CORRECT');
} else {
console.log('INCORRECT');
}
// Not Equal to
if(id != 101){
console.log('CORRECT');
} else {
console.log('INCORRECT');
}
// Equal to Value & Type
if(id === 100){
console.log('CORRECT');
} else {
console.log('INCORRECT');
}
//Rest if undefined
const id = 100;
if(typeof id !== 'undefined'){
console.log(`The ID is ${id}`);
} else {
console.log(`NO ID`);
}
//Greater Or Less Than
if(id <= 100){
console.log('Correct');
} else {
console.log('Incorrect');
}
// IF ELSE
const color = 'yellow';
if(color === 'red'){
console.log('Color is red');
} else if (color === 'blue'){
console.log('Color is blue');
} else {
console.log('Color is not red or blue');
}
// Logical Operators
const name = 'Steve';
const age = 4;
// And &&
if(age > 0 && age <= 12){
console.log(`${name} is a child`);
} else if (age >= 13 && age <= 17){
console.log(`${name} is a teenager`);
} else if (age <= 0){
console.log(`${name} is not alive`);
} else {
console.log(`${name} is a adult`);
}
// Or ||
if(age < 16 || age > 65){
console.log(`${name} can not run in race`);
} else {
console.log(`${name} is registered for the race`);
}
// Ternary Operator
console.log(id === 100 ? 'Correct' : 'Incorrect');
// Without Braces
if(id === 100)
console.log('Correct');
else
console.log('Incorrect');
// For Loop
for(let i = 0; i <= 5; i++){
if(i === 2){
console.log('Number 2 is my favorite number');
continue;
}
if(i === 5){
console.log('Stop');
break;
}
console.log('Number ' + i);
}
// ---While Loop
i = 0;
while(i <=10){
console.log('#:' + i);
i++;
}
// ---Do while [Always gotta run]
let i = 0;
do {
console.log('Number ' + i);
i++
}
while(i < 10)
// Loop through Arrays
const cars = ['Honda', 'Chevy', 'Mitsubishi','Toyota']
for (let i =0; i < cars.length;i++){
console.log(cars[i]);
}
//----------
const darkAgesClass = ['Warrior','Monk','Priest','Wizard'];
for(let i = 0; i < darkAgesClass.length; i++){
console.log(`${darkAgesClass[1]} VS ${darkAgesClass[3]}`);
}
//----------ForEach Loop-------
const darkAgesClass = ['Warrior','Monk','Priest','Wizard'];
darkAgesClass.forEach(function(i){
console.log(i);
});
//-----------Map
const users = [
{id:1982, name: 'Mary', age: 21, country: 'Thailand'},
{id:2544, name: 'Jasmine', age: 29, country: 'Australia'},
{id:3231, name: 'Ronald', age: 17, country: 'USA'},
{id:4432, name: 'Greg', age: 26, country: 'USA'}
];
const ids = users.map(function(user){
return user.id;
});
console.log(ids);
//----------
const user = {
firstName: 'John',
lastName: 'Doe',
age: 26
};
for (let x in user){
console.log(`${x} : ${user[x]}`);
}
let val;
const today = new Date();
let birthday = new Date('9-16-1991');
birthday = new Date('September 16 1991');
birthday = new Date('9/16/1991');
val = today.getMonth();
val = today.getDate();
val = today.getDay();
val = today.getFullYear();
val = today.getHours();
val = today.getMinutes();
val = today.getSeconds();
val = today.getMilliseconds();
val = today.getTime();
birthday.setMonth(2);
birthday.setDate(12);
birthday.setFullYear(1992);
birthday.setHours(3);
birthday.setMinutes(30);
birthday.setSeconds(25);
console.log(birthday);
// Global Scope----------
var a = 1; let b = 2; const c = 3;
// Global Scope---------
console.log('Global Scope: ', a, b, c);
Function Scope --Note: var a is not affected by var a
function test () {
var a = 4;
let b = 5;
const c = 6;
console.log('Function Scope: ', a, b, c);
};
test();
// Block Scope
if(true){
var a = 4;
let b = 5;
const c = 6;
console.log('If Scope: ', a, b, c);
}
for (let a = 0; a < 10; a++){
console.log(`Loop: ${a}`);
}
// Create some arrays
const numbers = [43,45,33,23,44,78,5];
const numbers2 = new Array[43,45,33,23,44,78,5];
const numbers = ['Apple', 'Banana', 'Orange', 'Pear'];
const numbers = [22, 'Hello', true, undefined, null, {a:1, b:2}, new Date()];
let val;
// Get array length
val = numbers.length;
// Check if is array
val = Array.isArray(numbers);
// Get single value
val = numbers[3];
val = numbers[0];
// Insert into array
numbers[2] = 100;
// Find index of value;
val = numbers.indexOf(36);
//Mutating Arrays
// Add on to end
numbers.push(250);
// Addon to front;
numbers.unshift(120);
// Take off from end
numbers.pop();
// Take off from front
numbers.shift();
// Splice values
numbers.splice(1,3);
// Reverse
numbers.reverse();
// Concatenate array
val = numbers.concat(numbers2);
// Sorting arrays
val = fruit.sort();
val = numbers.sort();
// Use the "compare function"
val = numbers.soft(function(x,y){
return x - y;
});
// Reverse sort
val = numbers.sort(function(x, y){
return y - x;
});
// Find
function under50(num){
return num < 50;
}
val = numbers.find(under50);
console.log(numbers);
console.log(val);
const name = 'Ken';
const age = 26;
const job = 'Full Stack Web Developer';
const city = 'San Francisco';
let html;
// Without template strings (es5)
html = '<ul><li>Name: ' + name + '</li><li>Age: ' + age + '</li><li>Job: ' + job + ' </li><li>City: ' + city + '</li></ul> ';
//-----
html = '<ul>' +
'<li>Name: ' + name + '</li>' +
'<li>Age: ' + age + '</li>' +
'<li>Job: ' + job + '</li>' +
'<li>City: ' + city + '</li>' +
'</ul>';
// With template strings (es6)
html =
`
<ul>
<li>Name: ${name}</li>
<li>Age: ${age}</li>
<li>Job: ${job}</li>
<li>City: ${city}</li>
<li>${2+2}</li>
<li>C${hello}</li>
<li>${age > 30 ? 'Over 30' : 'Under 30'}</li>
</ul>
`;
document.body.innerHTML = html;
const firstName = 'William';
const lastName = 'Johnson';
const age = 26;
let val;
val = firstName + lastName;
//Concatenation
val = firstName + ' ' + lastName;
// Append
val = 'Ken ';
val += 'Truong';
val = 'Hello, my name is ' + firstName + ' and I am ' + age;
// Escaping
val = 'That\'s awesome, I can\'t wait';
// Length
val = firstName.length;
// concat()
val = firstName.concat(' ', lastName);
// change case
val = firstName.toUpperCase();
val = firstName.toLowerCase();
val = firstName[2];
// indexOf()
val = firstName.indexOf('1');
val = firstName.lastIndexOf('1');
// substring()
val = firstName.substring(0,4);
// slice()
val = str.split(' ');
val = tags.split(',');
// replace()
val = str.replace('Brad', 'Son');
// includes()
val = str.rincludes('foo');
console.log(val);
// var, let, const
var name = 'Ken Truong';
console.log(name);
name = 'James Logan';
console.log(name);
// Init var
var greeting;
console.log(greeting);
greeting = 'Hello';
console.log(greeting);
// letters, numbers, _, $
// Can not start with a number
// Multi word vars
var firstName = 'Steve'; // Camel case
var first_name = 'Sara'; // Underscore
var FirstName = 'Tom'; // Pascal case
var firstname;
//LET
let name;
name = 'John Doe';
console.log(name);
name = 'Steven Smith';
console.log(name);
// CONST
const name = 'John';
console.log(name);
// Const Cannot reassign
// name = 'sara';
// have to assign a value
// const greeting;
const person = {
name: 'John',
age: 30
}
person.name = 'sara';
person.age = 32;
console.log(person);
const numbers = [1,2,3,4,5];
numbers.push(6);
console.log();
// strings
"this is my string";
"my second string";
"my name is chris";
// numbers
10;
500;
3.14;
// booleans (truthy / falsy)
true;
false;
console.log(Boolean("Hello")); // String or not
// specials
undefined;
null; // no value
NaN;
// objects (important) - curl brackets
const user = {
name: "Ken",
username: "kencode"
};
// arrays
const users = ["ken", "james", "stephen", "lebron"];
const luckNumbers = [1, 23, 43, 12, 33, 66];
const whatever = ["chris", 1, "holly"];
const superUsers = [
{name: 'chris'},
{ name: 'ken' },
{ name: 'tuan' },
];
console.log(superUsers[2].name);
console.log(superUsers[1]['name']);
// declaring variables
var thing = "first";
const otherThing = "second";
let newThing = "third";
const otherThang = {
name: 'ken'
};
otherThang.name = 'James';
// =======================
let myVariable;
myVariable = 'something';
console.log(myVariable)
console.log('Hello World');
console.log(123);
console.log(true);
//console.log styling
console.log('%cWassup Nephew!', 'font-size:25px', 'color: #1ce');
var greeting = 'Hello';
console.log(greeting);
console.log([1,2,3,4]);
console.log({a:1, b:2});
console.table({a:1, b:2});
console.clear();
console.error('This is some error');
console.warn('This is warning');
console.time('Hello');
console.log('Hello World');
console.log('Hello World');
console.log('Hello World');
console.log('Hello World');
console.log('Hello World');
console.log('Hello World');
console.timeEnd('Hello');
const num1 = 100;
const num2 = 50;
let val;
// Simple Math with numbers
val = num1 + num2;
val = num1 * num2;
val = num1 - num2;
val = num1 / num2;
val = num1 % num2;
// Math Object
val = Math.PI;
val = Math.E;
val = Math.round(2.4);
val = Math.ceil(2.4);
val = Math.floor(2.8);
val = Math.sqrt(64);
val = Math.abs(-3);
val = Math.pow(8,2);
val = Math.min(2,33,4,1,55,6,3,-2);
val = Math.max(2,33,4,1,55,6,3,-2);
val = Math.random();
val = Math.sqrt(64);
console.log(val);
let val;
//Number to string
val = String(555);
val = String(4+4);
// Bool to string
val = String(true);
// Date to string
val = String(new Date());
// Array to string
val = String(1,2,3,4);
// toString()
val = (5).toString();
val = (true).toString();
// String to number
val = Number('5');
val = Number(true);
val = Number(false);
val = Number(null);
val = Number('hello');
val = Number([1,2,3]);
val = parseInt('100.30');
val = parseFloat('100.30');
// Output
// console.log(val);
// console.log(typeof val);
// console.log(val.length);
const val1 = String(5);
const val2 = 6;
const sum = Number(val1 + val2);
console.log(sum);
console.log(typeof sum);
// PRIMITIVE
// String
const name = 'James Doe';
// Number
const age = 45;
// Bolean
const hasKids = true;
// Null
const car = null;
// Undefined
let test;
// Symbol
const sym = Symbol();
// REFERENCE TYPES - Objects
// Array
const hobbies = ['movies', 'music'];
//Object literal
const address = {
city: 'boston',
state: 'MA'
}
const today = new Date();
console.log(today);
console.log(typeof hobbies);
以上是关于javascript JavaScript语言基础知识的主要内容,如果未能解决你的问题,请参考以下文章