Algorithm

When writing JavaScript codes, **properly use const, var and let** can speed up the algorithm and save memory sapce.

Leetcode 4 寻找两个正序数组的中位数

示例 1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2
示例 2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
image.png
So happy to write them by myself without looking up ideas and codes online(^▽^) (^▽^) (^▽^)

  1. /**
  2. * @param {number[]} nums1
  3. * @param {number[]} nums2
  4. * @return {number}
  5. */
  6. var findMedianSortedArrays = function(nums1, nums2) {
  7. var nums3=nums1.concat(nums2); //combine two arrays into a new one
  8. nums3.sort((a,b)=>a-b); //sort nums ascending
  9. length=nums3.length;
  10. if (length % 2 === 1){ //when length is odd, find median
  11. return nums3[Math.floor(length*0.5)];
  12. }else{
  13. return (nums3[length*0.5-1] + nums3[length*0.5])*0.5;//when length is even, find median
  14. }
  15. };

Review

Learning Resources

  • MDN Web Docs,(the Mozilla Developer Network),an evolving learning platform for Web technologies and the software that powers the Web, including CSS, HTML, and JavaScript. It also have a detailed set of beginner’s learning material — see Learn Web development.
  • W3,CSS 2.1 Specification
  • DEV Community,a community of software developers helping one another out. DEV provides a place for developers to collaborate and network while learning and sharing their knowledge.
  • Stack Overflowa question and answer site for programmers with tons of questions and answers on a wide range of topics in computer programming. You can learn from already asked and answered questions, share your programming knowledge by answering asked questions or share your issues/bugs here.
  • Can I use,provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile web browsers.
  • Repl.it, a simple yet powerful online IDE, Editor, Compiler, Interpreter, and **REPL**. Code, compile, run, and host in 50+ programming languages. This is helpful if you want to edit and share code right from your browser.
  • JavaScript & JQuery, Jon Duckett,full-color book,showing you how to make your websites more interactive and your interfaces more interesting and intuitive.
  • Eloquent JavaScript - a free EBook,about JavaScript, programming, and the wonders of the digital.
  • Cracking the Coding Interview (6th Edition), Gayle Laakamann McDowell, enabling you to **perform at your very best in top companies interview.

    Tip

    Javascript Variables & Functions

  • var keyword is used in pre-ES6 versions of JS.

  • case sensitive, so myName and myname would be different variables
  • cannot be the same as keywords. For a comprehensive list of keywords check out MDN’s keyword documentation.
  • If we don’t assign a value to a variable declared using the let keyword, it automatically has a value of undefined.

    1. let price;
    2. console.log(price); // Output: undefined
    3. price = 350;
    4. console.log(price); // Output: 350
  • Constant variables must be assigned a value when declared. If you try to declare a const variable without a value, you’ll get a SyntaxError.

    1. const myName = 'Gilberto';
    2. console.log(myName); // Output: Gilberto
  • mathematical assignment operators ```javascript let x = 20; x -= 5; // Can be written as x = x - 5 console.log(x); // Output: 15

let y = 50; y = 2; // Can be written as y = y 2 console.log(y); // Output: 100

let z = 8; z /= 2; // Can be written as z = z / 2 console.log(z); // Output: 4

  1. - **template literals**, in ES6, use backticks ``` and `${}` to interpolate values into a string, **preventing escaping double quotes or single quotes. **
  2. ```javascript
  3. const myPet = 'armadillo';
  4. console.log(`I own a pet ${myPet}.`);
  5. // Output: I own a pet armadillo.
  • check if the variable exists

0, false, empty strings like “ “ or ‘ ‘, null (no value), undefined (a declared variable lacks a value), NaN (Not a Number) means do not exist;

let defaultName = username || 'Stranger';   /*easier ways to code*/

let defaultName;
if (username) {                           /*check if username exists*/
  defaultName = username;
} else {
  defaultName = 'Stranger';
}
isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');
   /*ternary operator to simplify*/ 

if (isNightTime) {
  console.log('Turn on the lights!');
} else {
  console.log('Turn off the lights!');
}

favoritePhrase==='Love That!' ? console.log('I love that!'): console.log("I don't love that!");  /*when having a string in judgement condition*/
  • generating random numbers from 0-7

    let randomNumber=Math.floor(Math.random() * 8);
    
  • JavaScript only hoists declarations( creating functions), not initializations.

  • Parameters and Arguments, also called 形参和实参,which translation is disgusting.

image.pngimage.png

  • Default Parameter in function

    function greeting (name = 'stranger') {
    console.log(`Hello, ${name}!`)
    }
    
  • Arrow Functions, a shorter way to write functions by using the special “fat arrow” () => notation.

image.pngimage.png

const plantNeedsWater = day=> {     //with one parameter
  if (day === 'Wednesday') {
    return true;
  } else {
    return false;
  }
};

const plantNeedsWater = day=>day==='Wednesday'? true:false;  //easier way to code
const squareNum = num => num * num;  //single line can omit curly braces

Javascript Arrays & Loops & Objects

//update elements
let groceryList = ['bread', 'tomatoes', 'milk'];
groceryList[1]='avocados';                             

//Variables declared with the const keyword cannot be reassigned. However, elements in an array declared with const remain mutable.
let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha'];
const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork'];
condiments= ['Mayo']; //ok
utensils= ['Mayo'];  //error

//find length
const objectives = ['Learn a new languages', 'Read 52 books', 'Run a marathon'];
console.log(objectives.length);

//add items to the end of an array
const itemTracker = ['item 0', 'item 1', 'item 2'];
itemTracker.push('item 3', 'item 4');

//removes the last item of an array
const newItemTracker = ['item 0', 'item 1', 'item 2'];
const removed = newItemTracker.pop();

//remove the first element of array & return it
const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];
groceryList.shift();

//add element to the head of array;
groceryList.unshift('popcorn');

//select a portion of an array from start to end (not included) in a new array
const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];
groceryList.slice(1,4);

//return the first index of a given element in an array, or -1 if it is not present.
const pastaIndex=groceryList.indexOf('pasta');

//nested array
const nestedArr = [[1], [2, 3]];
console.log(nestedArr[1]); // Output: [2, 3]
console.log(nestedArr[1][0]); // Output: 2

//join array elements into a string
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join()); // expected output: "Fire,Air,Water"
console.log(elements.join('')); // expected output: "FireAirWater"
console.log(elements.join('-')); // expected output: "Fire-Air-Water"

//for loop,the second is stop condition, it continues if true , and stops if false
const animals = ['Grizzly Bear', 'Sloth', 'Sea Lion'];
for (let i = 0; i < animals.length; i++){
  console.log(animals[i]);
}

//a nested loop,find matchs from two arrays, prints a string
const myArray = [6, 19, 20];
const yourArray = [19, 81, 2];
for (let i = 0; i < myArray.length; i++) {
  for (let j = 0; j < yourArray.length; j++) {
    if (myArray[i] === yourArray[j]) {
      console.log('Both loops have the number: ' + yourArray[j])
    }
  }
};

//consecutively use two functions
console.log(myArray.join('').toUpperCase());

// An object literal with two key-value pairs
let spaceship = {
  'Fuel Type': 'diesel',
  color: 'silver'
};

//Bracket Notation 1
['A', 'B', 'C'][0];  //returns 'A'

//Bracket Notation 2
let spaceship = {
  'Fuel Type': 'Turbo Fuel',
  'Active Duty': true,
  homePlanet: 'Earth',
  numCrew: 5
};
spaceship['Active Duty'];   // need to use [] for a string property
let returnAnyProp = (objectName, propName) => objectName[propName];
returnAnyProp(spaceship, 'homePlanet'); // Returns 'Earth'

//change or delete a property from an object
spaceship.type = 'alien';
delete spaceship.mission; 

//console is a global javascript object and .log() is a method on that object. 
//Math is a global javascript object and .floor() is a method on that object.
const alienShip={
  retreat(){
    console.log(retreatMessage)
  },
  takeOff(){
    console.log('Spim... Borp... Glix... Blastoff!')
  }
};
alienShip.retreat();
alienShip.takeOff();

//let spaceship = {
  passengers: [{name:'Space Dog'},{name:'Harry Porter'}],  //assign an array of objects
  telescope: {
    yearBuilt: 2018,
    model: "91031-XLT",
    focalLength: 2032 
  },
 let firstPassenger = spaceship.passengers[0];  //print {name:'Space Dog'}

//pass by reference
const spaceship = {
  homePlanet : 'Earth',
  color : 'silver'
};
let paintIt = obj => {
  obj.color = 'glorious gold'
};
paintIt(spaceship);
spaceship.color // Returns 'glorious gold'

//Looping Through Objects
let spaceship = {
    crew: {
    captain: { 
        name: 'Lily', 
        degree: 'Computer Engineering', 
        cheerTeam() { console.log('You got this!') } 
        },
    'chief officer': { 
        name: 'Dan', 
        degree: 'Aerospace Engineering', 
        agree() { console.log('I agree, captain!') } 
        },
    medic: { 
        name: 'Clementine', 
        degree: 'Physics', 
        announce() { console.log(`Jets on!`) } },
    translator: {
        name: 'Shauna', 
        degree: 'Conservation Science', 
        powerFuel() { console.log('The tank is full!') } 
        }
    }
}; 

for (let crewMember in spaceship.crew) {
  console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`);
}    /*print captain: Lily
             chief officer: Dan
             medic: Clementine
             translator: Shauna */

About JQuery

JQuery, helps you deal with cross-browser inconsistentices.

Objects & Properties & Events & Methods

  • The relationship of these 4 items are described in the picture below, it shows how to create models in computer’s world, just like how to build an estate in real-world.

image.png

  • JavaScript function can be written either by in HTML, or only be shared file links like in HTML. But it is better to keep JavaScript code in its own file.

    Creating Objects by Literal Notation

    image.png

    Creating Many Objects by Constructor Notation

    image.png

    Arrays in an Object & Objects in an Array

    image.png

    Built-in Objects in JavaScript

    image.png

    Making Upload Image Grey

    image.png ```html

    convert image to gray image

Filename:

```css
canvas{
  height:200px;
  border:1px solid lightgray;
}
window.CP.PenTimer.MAX_TIME_IN_LOOP_WO_EXIT = 6000;
var image;
var canvas;
function upload(){
  //get canvas
  canvas=document.getElementById("can");
  var graycanvas=document.getElementById("can1");

  //get input from text input
  var fileinput=document.getElementById("finput");
  //var filename=fileinput.value; 
  image=new SimpleImage(fileinput);
  grayimage=image;
  grayimage.drawTo(graycanvas);

  //draw image on canvas
  image.drawTo(canvas);
}

function makeGray(){
  for(var pixel of grayimage.values()){
    var avg=(pixel.getRed()+pixel.getGreen()+pixel.getBlue())/3;
    pixel.setRed(avg);
    pixel.setGreen(avg);
    pixel.setBlue(avg);
  }
  canvas=document.getElementById("can1");
  image.drawTo(canvas);
}

Share

Debugging Node In Visual Studio Code With Basic Example

Getting started with containerd

Week 5 - 图12

Containers VS Virtual Machines

Week 5 - 图13