JavaScript basic

JavaScript basic 

  •  double slashes // or between /* and */ is treated as a comment
  • the first character must be a letter, or an underscore (_), or a dollar sign ($).
  • case sensitive
  • If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.
  • JavaScript will try to convert strings to numbers in all numeric operations, but uses the + operator to concatenate the strings
  • a variable without a value, has the value undefined
  • Undefined and null are equal in value but different in type
typeof undefined           // undefined
typeof null                // object

null === undefined         // false
null == undefined          // true
  • access object properties in two ways
objectName.propertyName

objectName["propertyName"]
  • If you access a method without (), it will return the function definition
    var person = {
        firstName: "John",
        lastName : "Doe",
        id       : 5566,
        fullName : function() {
           return this.firstName + " " + this.lastName;
        }
    };
    
    document.getElementById("demo").innerHTML = person.fullName;
    
    //result : function () { return this.firstName + " " + this.lastName; }
  • Do Not Declare Strings, Numbers, and Booleans as Objects!  (They complicate your code and slow down execution speed.)
  • If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
myFunction();

// code here can use carName as a global variable
document.getElementById("demo").innerHTML = "I can display " + carName;

function myFunction() {
    carName = "Volvo";    // has not been declared
}
  • All global variables belong to the window object.
var carName = "Volvo";

// code here can use window.carName
document.getElementById("demo").innerHTML = "I can display " + window.carName;
  • In a web browser, global variables are deleted when you close the browser window (or tab), but remain available to new pages loaded into the same window.
  • break up a code line within a text string with a single backslash or a string addition
document.getElementById("demo").innerHTML = "Hello \
Dolly!";


//A safer way to break up a string
document.getElementById("demo").innerHTML = "Hello " + 
"Dolly!";

//result : Hello Dolly!   
  • The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");

//result : 7
  • The lastIndexOf() method returns the index of the last occurrence of a specified text in a string
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
document.getElementById("demo").innerHTML = pos;

//result : 21
  • There are 3 methods for extracting a part of a string: slice(start, end) 、 substring(start, end) cannot accept negative indexes、 substr(start, length)second parameter specifies the length of the extracted part
  •  replace() function is case sensitive, use a regular expression with an /i flag (insensitive) and  replace all matches, use a regular expression with a /g flag (global match)
  • Formally said: Strings are immutable: Strings cannot be changed, only replaced.
  • JavaScript function isNaN() to find out if a value is a number
  • The pop() method returns the value that was "popped out".  
  • The push() method adds a new element to an array (at the end)
  • The shift() method removes the first array element and "shifts" all other elements to a lower index.
  • The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements
  • Using delete may leave undefined holes in the array. Use pop() or shift() instead.
  • The length property provides an easy way to append a new element to an array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi";          // Appends "Kiwi" to fruit
  • The concat() method does not change the existing arrays. It always returns a new array.
  • The slice() method creates a new array. It does not remove any elements from the source array.
  • Numeric Sort
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});

//result : 1,5,10,25,40,100

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
//result : 100,40,25,10,5,1


//Reason

/*When comparing 40 and 100, the sort() method calls the compare function(40,100).

The function calculates 40-100, and returns -60 (a negative value).

The sort function will sort 40 as a value lower than 100.*/
  • Sorting an Array in Random Order
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()});
  • The fastest solution about sort() is to use a "home made" method.
function myArrayMax(arr) {
    var len = arr.length
    var max = -Infinity;
    while (len--) {
        if (arr[len] > max) {
            max = arr[len];
        }
    }
    return max;
}
  • UTC (Universal Time Coordinated) is the same as GMT (Greenwich Mean Time).
  • var d = new Date("Jan 25 2015")
  • In JavaScript, the first month (January) is month number 0, so December returns month number 11.
    var d = new Date();
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    document.getElementById("demo").innerHTML = months[d.getMonth()];

     

  • Math.random() always returns a number lower than 1.
  • Math.random() used with Math.floor() can be used to return random integers.
Math.floor(Math.random() * 10);     // returns a number between 0 and 9
  • In JavaScript there are 5 different data types that can contain values.  ( string、number、boolean、object、function )
  • There are 3 types of objects. ( Object、Date、Array ) 
  •  2 data types that cannot contain values. ( Null、Undefined)
  • JavaScript Type Conversion ( By the use of a JavaScript function 、Automatically by JavaScript itself  The result is not always what you expect)

  • Undefined is Not Null  ( With JavaScript, null is for objects, undefined is for variables, properties, and methods.) 

    //Incorrect: 
    //this will throw an error if the object is undefined
    
    if (myObj !== null && typeof myObj !== "undefined")
    
    
    //Correct:
    //must test typeof() first
    if (typeof myObj !== "undefined" && myObj !== null) 

     

 

JavaScript Performance

  •  
  • Accessing the HTML DOM is very slow, compared to other JavaScript statements.
  • Reduce DOM Size

  • Avoid Unnecessary Variables

JavaScript Object Constructors name constructor functions with an upper-case first letter.

// Constructor function for Person objects
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

// Create a Person object
var myFather = new Person("John", "Doe", 50, "blue");

// Display age
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + "."; 
  • A function defined as the property of an object, is called a method to the object.
  • A function designed to create new objects, is called an object constructor.
  • With call(), you can use a method belonging to another object. call() takes any function arguments separately. ex:  person .call(this,"1","2","3");

  • The apply() method is similar to the call() method.  apply() takes any function arguments as an array.  ex:  person .apply(this, ["1", "2", "3"]);

var person = {
    firstName:"John",
    lastName: "Doe",
    fullName: function(arg1, arg2) {
        return this.firstName + " " + this.lastName + arg1+ arg2;
    }
}
var myObject = {
    firstName:"Mary",
    lastName: "Doe",
}
//myObject 透過 call()/ apply() 去使用 person 物件的方法
//x=person.fullName.call(myObject,"/use","/call");  // Will return "Mary Doe use call"
x=person.fullName.apply(myObject,["/use","/apply"]);  // Will return "Mary Doe/use/apply"
document.getElementById("demo").innerHTML = x; 
  • self-invoking functions  //防止區域變數受外在因素影響
    
    <button type="button" onclick="myFunction()">Count!</button>
    
    <p id="demo">0</p>
    
    <script>
    var add = (function () {
        var counter = 0;
        return function () {return counter += 1;}
    })();
    
    function myFunction(){
        document.getElementById("demo").innerHTML = add();
    }
    </script>

     

The HTML DOM Document Object

  • Finding HTML Elements

    Method Description
    document.getElementById(id) Find an element by element id
    document.getElementsByTagName(name) Find elements by tag name
    document.getElementsByClassName(name) Find elements by class name
  • Changing HTML Elements

    Method Description
    element.innerHTML =  new html content Change the inner HTML of an element
    element.attribute = new value Change the attribute value of an HTML element
    element.setAttribute(attribute, value) Change the attribute value of an HTML element
    element.style.property = new style Change the style of an HTML element
  • Adding and Deleting Elements

    Method Description
    document.createElement(element) Create an HTML element
    document.removeChild(element) Remove an HTML element
    document.appendChild(element) Add an HTML element
    document.replaceChild(element) Replace an HTML element
    document.write(text) Write into the HTML output stream
  • Never use document.write() after the document is loaded. It will overwrite the document.

<h1 id="id01">My First Page</h1>
<p id="id02"></p>
<p id="id03"></p>

<script>
//兩個方法 給於值
document.getElementById("id02").innerHTML = document.getElementById("id01").innerHTML;

var myTitle = document.getElementById("id01").childNodes[0].nodeValue;

document.getElementById("id03").innerHTML =myTitle;
</script>
  • Creating New HTML Elements (Nodes)  ( appendChild() 、insertBefore() )

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");

//appendChild()-----------------------
element.appendChild(para);

//insertBefore()-----------------------------
var child = document.getElementById("p1");
element.insertBefore(para, child);  //insertBefore(插入元素,插入位置前)
</script>
  • The Difference Between an HTMLCollection and a NodeList

    HTMLCollection NodeList
    a collection of HTML elements.  a collection of document nodes.
    can be accessed by their name, id, or index number. only be accessed by their index number.
      can contain attribute nodes and text nodes.
//HTMLCollection -> getElementsByTagName()

<h2>JavaScript HTML DOM</h2>

<p>Hello World!</p>

<p>Hello Norway!</p>

<p id="demo"></p>

<script>
var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = 
"This document contains " + myCollection.length + " paragraphs.";
</script>



// NodeList-> querySelectorAll()
<h2>JavaScript HTML DOM!</h2>

<p>Hellow World!</p>

<p>Hellow Norway!</p>

<p id="demo"></p>

<script>
var myNodelist = document.querySelectorAll("p");
document.getElementById("demo").innerHTML =
"This document contains " + myNodelist.length + " paragraphs.";
</script>

 

  •