Basic information for javascript
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
-
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()
-
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”
-
Converting Strings to Numbers
Number(“3.14”) // returns 3.14 Number(“ “) // returns 0 Number(“”) // returns 0 Number(“99 88”) // returns NaN
Some tips
Array and dynamic allocation
document.getElementById("myFrame").addEventListener("load", myFunction);
function myFunction() {
var arr = [];
arr.push("1");
arr.push("2");
arr.push("3");
var obj = {};
obj["test1"] = arr;
obj["test2"] = "aaa2";
obj["test3"] = "aaa3";
// obj['test1'] is another expression of obj.test1
// it's an object NOT array
document.getElementById('demo').innerHTML = JSON.stringify(obj);
// Allocate dynamically more complex example
var element1 = {};
if (element1['element2'] === undefined) element1['element2'] = {};
if (element1['element2']['element3'] === undefined) {
element1['element2']['element3'] = 3;
element1['element2']['element4'] = 4;
}
alert(element1['element2']['element3']);
// Result: 3
alert(Object.keys(element1['element2']));
// Result: element3, element4
alert(Object.keys(element1['element2'])[1]);
// Result: element4
Result: {“test1”:[“1”,”2”,”3”],”test2”:”aaa2”,”test3”:”aaa3”}
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;
innerHTML vs innerText
document.getElementById('name').innerHTML="Test";
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.
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
https://www.w3schools.com/jsref/jsref_tolocalestring.asp
parseInt(“123hui”) returns 123
Number(“123hui”) returns NaN
datetime
// yesterday
var d = new Date((new Date()).valueOf() - 1000*60*60*24);
Date format
// -----------------------------------------------
// get date string format (yyyy/MM/dd)
// -----------------------------------------------
function getFormatDate(date) {
var yyyy = date.getFullYear();
var mm = (1 + date.getMonth());
mm = mm >= 10 ? mm : '0' + mm;
var dd = date.getDate();
dd = dd >= 10 ? dd : '0' + dd;
return yyyy + '/' + mm + '/' + dd;
}
// -----------------------------------------------
// get time string format (HH:MM:SS)
// -----------------------------------------------
function getFormatTime(date) {
var HH = date.getHours();
HH = HH >= 10 ? HH : '0' + HH;
var MM = date.getMinutes();
MM = MM >= 10 ? MM : '0' + MM;
var SS = date.getSeconds();
SS = SS >= 10 ? SS : '0' + SS;
return HH + ':' + MM + ':' + SS;
}
// -----------------------------------------------
// get time string format (HH:MM:SS.sss)
// -----------------------------------------------
function getFormatTimeMs(date) {
var HH = date.getHours();
HH = HH >= 10 ? HH : '0' + HH;
var MM = date.getMinutes();
MM = MM >= 10 ? MM : '0' + MM;
var SS = date.getSeconds();
SS = SS >= 10 ? SS : '0' + SS;
var sss = date.getMilliseconds();
ms = sss >= 100 ? sss : (sss >= 10 ? '0' + sss : '00' + ms);
return HH + ':' + MM + ':' + SS + "." + sss;
}
function getCurrentDate() {
var _date = new Date();
//var cur_date = _date.toISOString().substring(0, 10) + " " + _date.toTimeString().substring(0, 8); // UTC date
var cur_date = getFormatDate(_date) + " " + getFormatTime(_date); // Local date
return cur_date;
}
function formatDateTime(tm)
{
var _date = new Date();
return getFormatTime(_date);
}
function formatDateTime(tm)
{
var _time = new Date();
if (tm) {
_time.setTime(Number(tm));
}
var year = _time.toISOString().substring(0,10); // yyyy-mm-dd (UTC time)
var time = _time.toTimeString().substring(0,8); // HH:MM:SS (Local time)
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