Basic information for javascript

6 minute read

Grammar

Primitive Types

  • string
  • number
  • boolean
  • null
  • undefined
  • symbol

Wrapper Object

  • Boolean
  • Number
  • String
  • Symbol
var num = 3;
var num = new Number(3);

var s1 = "hello";
var s2 = new String("hello");
var s3 = new String("hello");
 
alert(typeof s1);    // "string"
alert(typeof s2);    // "object"

alert("s1 == s2 : " + (s1 == s2));    // true
alert("s2 == s3 : " + (s2 == s3));    // false

alert("s1 === s2 : " + (s1 === s2));    // false
alert("s2 === s3 : " + (s2 === s3));    // false

Array

// Create Array
var arr = new Array(); // length 0
var arr = []; // length 0 with literal notation
var arr = new Array(10); // length 10

// Initialize Array
var arr = new Array(1, 2, 3, 'abc');
var arr = [1,2,3,'abc'];

Array : push

Add data to the end of the array.

arr.push(6);

Array : slice

slice(start, end)

  • from start to end-1
    array.splice(index,howmany,item1,…..,itemX)
    The splice() method adds/removes items to/from an array, and returns the removed item(s). array.splice(start, deleteCount[, item1[, item2[, …]]])
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);
// Orange,Lemon

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var myBest = fruits.slice(-3, -1);
// Lemon,Apple

Array : splice

  • Add items to the array
  • array.splice(index, howmany, item1,…..,itemX)
  • can be used to remove
    var array = [0, 1, 2, 3, 4, 5];
    array.splice(2, 1);
    //[0, 1, 3, 4, 5]
    

JSON

JSON OBJECT <—> JSON STRING

var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

var obj = JSON.parse(text);

var json_text = JSON.stringify(obj, null, 4);
document.write( '<p>Substring from 1 to 4 : ' + str.substring( 1, 4 ) + '</p>' );
document.write( '<p>Substring from 0 to 4 : ' + str.substring( 0, 4 ) + '</p>' );

Initailize

// Initialize
window.Puttist = window.Puttist || {};
window.backButtonTime = window.backButtonTime || 0;

// Check numeric
isNaN(123);       // false
isNaN('123');     // false
isNaN('1e10000'); // false  (number is Infinity)
isNaN('foo');     // true
isNaN('10px');    // true

// Type operator
if (typeof (clickCallback) != "function") {
    clickCallback();
}

if ( typeof(object) != "Object" ) {
    alert('Not an object');
}

if ( typeof 'AAA'  != 'Number' ) {
    alert('Not a number');
}

Statement

// for statement
for (var i in arr) {
    document.write(arr[i], '<br />');
}

URL encoding/decoding

var d_str = encodeURI(e_str);
var e_str = decodeURI(d_str);

Type conversion

  1. Converting Numbers to Strings

    It can be used on any type of numbers, literals, variables, or expressions:

    String(x)         // returns a string from a number variable x
    String(123)       // returns a string from a number literal 123
    String(100 + 23)  // returns a string from a number from an expression
    

    The Number method toString() does the same.

    String aa = x.toString()
    String bb = (123).toString()
    String cc = (100 + 23).toString()
    
  2. Converting Booleans to Strings

    The global method String() can convert booleans to strings. String(false) // returns “false” String(true) // returns “true”

    The Boolean method toString() does the same. false.toString() // returns “false” true.toString() // returns “true”

  3. Converting Strings to Numbers

    Number(“3.14”) // returns 3.14 Number(“ “) // returns 0 Number(“”) // returns 0 Number(“99 88”) // returns NaN

Some tips

How to use local storage

var CfgInfo = {};

// Save Config
localStorage.setItem("CFGINFO", JSON.stringify(CfgInfo));

// Load Config
var tmp = $.parseJSON(localStorage.getItem("CFGINFO"));
if (tmp) CfgInfo = tmp;

Selection

// getSelection using document
function selection(){
    if (document.getSelection)
       return document.getSelection();
}

// getSelection using window
function selection(){
    if (window.getSelection)
       return window.getSelection();
}

// getSelectionHtml
function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}

// Set Selection
function selectText() {
  const input = document.getElementById('text-box');  
  input.focus();
  input.setSelectionRange(2, 5);
}

eval vs function

eval

  • eval(codeString)
  • The eval function allows you to dynamically run JavaScript source code.
  • The codeString string is parsed and executed by JavaScript parser.
  • The code passed to the eval function runs under the same situation that the eval function is called.
  • Use the JSON.parse function to deserialize the JSON (JavaScript Object Notation) text in all possible cases. The JSON.parse function is safer than the eval function and faster to run.
  • Not recommended because of the risk of running a securely dangerous javascript code immediately
  • String entered as a parameter for the eval function is analyzed and executed by javascript parser.
  • Unintentionally, it can be manipulated by the outside. var name=’test’; eval(“name=’test2’”); The variable name is changed to test2.

Link : eval

eval vs function

  • The function of generating dynamic functions is the same
  • eval (“var name=’test’”); The variable name remains a variable in the scope in which the eval function was executed
  • In other words, if this code is not included in the function and executed, it becomes a global variable.
  • Function eliminates the phenomenon that the variable generated from the inside to the var automatically becomes the global variable
  • It is desirable to use the function generator when the code must be dynamically performed

The base way to check true/false

  • false
  • 0
  • null
  • ””
  • NaN
  • undefined
if (!jsobj) {
    // jsobj is false
} else {
    // jsobj is true
}

Auto Scroll Down

// Auto Scroll Down
var element = document.getElementById('viewlist');
element.scrollTop = element.scrollHeight - element.clientHeight;

window.scrollTo(0, document.body.scrollHeight);

parseInt vs Number

parseInt(“123hui”) returns 123

Number(“123hui”) returns NaN

Date format


function getCurrentDate() {
    var _time = new Date();
    var cur_date = _time.toISOString().substring(0, 10) + " " + _time.toTimeString().substring(0, 8);
    return cur_date;
}

function formatDateTime(tm)
{
    var _time = new Date();
    _time.setTime(Number(tm));
    return _time.toTimeString().substring(0,8);
}

function formatDateTime(tm)
{
    var _time = new Date();
    if (tm) {
        _time.setTime(Number(tm));
    }

    var year = _time.toISOString().substring(0,10); // yyyy-mm-dd
    var time = _time.toTimeString().substring(0,8); // HH:MM:SS
    var msec = _time.getMilliseconds(); // sss
    
    return year + " " + time + "." + msec;
}

function convertUTCDateToLocalDate(strUTCTime) {
    var _elsp = Date.parse(strUTCTime);
    var _time = new Date();
    _time.setTime(Number(_elsp));
    return _time.toISOString().substring(0, 10) + " " + _time.toTimeString().substring(0, 8)
}

var _time = new Date();
console.log(_time.toTimeString());
console.log(_time.toString());

// yyyy-mm-dd HH:MM:SS
_time.toISOString().substring(0,10) + " " + _time.toTimeString().substring(0,8)

// MILLI SECONDS
getTime()

// Set date case #1
var d = new Date();
d.setTime(1332403882588);

// Set date case #2
new Date(2015, 4, 25)
new Date(2015, 4, 25, 12, 0)

// Set date case #3
var d = new Date("2015-03-25");

indexOf (cf. substring, contains)

if (str.indexOf("Heartbeat") > -1) return true;

substring vs substr

subString(start, End) substr(start,length)

SORTING

// Sorting
json_data.DAT.sort(function (a, b)
{
    var dataA = a.yoursortKey;
    var dataB = b.yoursortkey;
    if (dataA < dataB) // ascending
        return -1;
    else if (dataA > dataB)
        return 1;
    return 0;
});

Filtering

// Filtering
json_data.DAT = $.map(json_data.DAT, function (val)
{
    var condition1, condition2;

    switch (CONDITION1) {
        case 0:
            condition1 = true;
            break;
        case 1:
            condition1 = (Number(val.diffTime) > 300 * 1000); // seconds
            break;
        case 2:
            condition1 = (Number(val.diffTime) == 0);
            break;
        default:
            condition1 = true;
    }

    switch (CONDITION2) {
        case 0:
            condition2 = true;
            break;
        case 1:
            condition2 = (val.Server == "sunos" || val.fepServer == "solaris");
            break;
        case 2:
            condition2 = (val.Server == "linux" || val.fepServer == "ubuntu");
            break;
        default:
            condition2 = true;
    }

    if ((condition1 && condition2) == true) return val;
});

Leave a comment