Basic information for javascript

4 minute read

Some tips

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");

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);

indexOf (cf. substring, contains)

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

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

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]
    

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;
});

Grammar

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.

    x.toString() (123).toString() (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

Leave a comment