Top Left Text cha

Web & App Development

A cheatsheet of array methods:

  • To add/remove elements:

    • push(...items) – adds items to the end,
    • pop() – extracts an item from the end,
    • shift() – extracts an item from the beginning,
    • unshift(...items) – adds items to the beginning.
    • splice(pos, deleteCount, ...items) – at index pos delete deleteCount elements and insert items.
    • slice(start, end) – creates a new array, copies elements from position start till end (not inclusive) into it.
    • concat(...items) – returns a new array: copies all members of the current one and adds items to it. If any of itemsis an array, then its elements are taken.
  • To search among elements:

    • indexOf/lastIndexOf(item, pos) – look for item starting from position pos, return the index or -1 if not found.
    • includes(value) – returns true if the array has value, otherwise false.
    • find/filter(func) – filter elements through the function, return first/all values that make it return true.
    • findIndex is like find, but returns the index instead of a value.
  • To transform the array:

    • map(func) – creates a new array from results of calling func for every element.
    • sort(func) – sorts the array in-place, then returns it.
    • reverse() – reverses the array in-place, then returns it.
    • split/join – convert a string to array and back.
    • reduce(func, initial) – calculate a single value over the array by calling func for each element and passing an intermediate result between the calls.
  • To iterate over elements:

    • forEach(func) – calls func for every element, does not return anything.
  • Additionally:

    • Array.isArray(arr) checks arr for being an array.
Comment (0) Hits: 1649
Just a little reference to recall syntax of some basic Javascript...

List of useful Basic Syntax

Number(value)  //convert to number *same for objects
Boolean(value)  //convert to boolean
String(value)  //convert to string
[Symbol.toPrimitive]
toString() & valueOf()  //converting to string or number
Math.floor & Math.ceil & Math.round  //rounding
.toFixed(n)  //returns string so Number() should be used if needed for calculation
isNaN(value) & ifFinite(value)  
Object.is(a, b)  //compare 2 vaues
parseInt() & parseFloat() //returns number from string (until it gets to a NaN)
Math.random()  //Returns a random number from 0 to 1 (not including 1)
Math.max(a, b, c...) & Math.min(a, b, c...)  //Returns the greatest & smallest from the arbitrary number of arguments.
Math.pow(n, power)
Math.sign(x)  //positive, negative or zero
string.length  //length of the string
string[0]  & string.charAt(0)  //first character
string[string.length - 1]  //last character
for (let char of string) {do something}
toLowerCase() & toUpperCase()
string.indexOf(substr, pos)  // pos = start position (optional)  substr = needle, string = haystack
string.lastIndexOf(pos)  // starts at end of string
string.includes(substr, pos)  // pos = starting position (optional)
.startsWith() & .endsWith()
.slice(0, 5)  & .slice(-5, -1)  //returns chunk of string between 0 and 5 characters; negatives work from the end of the string
.substring(a, b)  //returns chunk between 2 positions
.substr(start pos, length)  //start pos can be negative and start from end

arr.splice(index, delete count[, val1, val2, valN]);
arr.splice(start at, number to delete, add value 1, add value 2);
arr.splice(2, 0, "value1", "value2");  //start at position 2, delete none, then insert value 1 & value 2 (at position 2) & also works with negative index
arr.slice(from index, to before position) //works with negs also
arr.indexOf(item, from) //looks for item starting from index from, and returns the index where it was found, otherwise -1.
arr.lastIndexOf(item, from) //same as ^, but looks from right to left.
arr.includes(item, from) //looks for item starting from index from, returns true if found.
let result = arr.find(function(item, index, array)  // should return true if the item is what we are looking for
let result = arr.map(function(item, index, array) {} // It calls the function for each element of the array and returns the array of results. like:  let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length)
arr.sort(); //only works on strings unless you add a function to compare
arr.reverse();  //reverses the order of an array
str.split(delimeter) //let str = "a, b, c"; let arr = str.split(", ") turns string into array like explode in PHP [optional array length as 2nd argument]
arr.join(delimeter); //reverse of split... like PHP implode
Array.isArray(value); //true if value is array
map.set(key, value)  //Probably useless - like array but stores keys of any type (even functions)
map.get(key); map.has(key); map.delete(key); map.clear(); map.size()  //map is just the name of the map in these
map.set('1', 'str1').set(1, 'num1').set(true, 'bool1');  //can be chained - also on new lines for each
new Set(iterable) //has same syntax as map above - only keeps unique values (duplicates thrown out)









Simple function Declaration syntax (can be used anywhere)

function showMessage(msg) {
    alert(msg);
}

let xxx = "hello";
showMessage(xxx); // alerts 'hello'

Function expression syntax (can only be used after declared)

let sayHi = function() {
    alert("Hello");
};

Arrow Functions

let func = (arg1, arg2, ...argN) => expression

let sum = (a, b) => a + b;

same as

let sum = function(a, b) {
    return a + b;
};

and...

let double = function(n) { return n * 2 }

is the same as...

let double = n => n * 2;

Objects can be either:

let object = {
key1 = value1,
key2 = value2,
keyN = valueN
}

or similar to PHP (less common)...

let object = new Object();

When using an object, you can do it by either method below... but any variable can be put in square brackets and will be converted

let abc = "key2";
let example = object.key1;
let example = object[key1];
let example = object[abc];  // same as object [key2]

Property values declaration in shorthand... The use-case of making a property from a variable is so common, that there’s a special property value shorthand to make it shorter.

function makeUser(name, age) {
    return {
        name: name,
        age: age
        // ...other properties
    };
}

Can be written as:

function makeUser(name, age) {
    return {
        name,
        age
        // ...other properties
    };
}

For...in Loop

for(let key in object) {
    // do something with the keys in loop (ignores symbols);
    continue; // breaks, then continues from beginning of loop
    break; // ends loop
}

Clone the object, user:

let clone = Object.assign({}, user);

Basic Syntax for assigning both multiple other objects and keys:

Object.assign(dest[, src1, src2, src3...] [,{key = value, keyN = valueN})

Symbols

let id = Symbol("id");  // "id" is just used as directions/notes - not used at ALL

Global Symbols

let id = Symbol.for("id");

to get the name (remember, name is only used for debugging purposes)

let symbolName = Symbol.keyfor(id);

Shorthand for writing method in function:

let user = {
    name: "John",
    age: 30,
    sayHi() { // same as "sayHi: function()"
        alert("Hello");
    }
};

Constructor Function

function User(name) {
     this.name = "John"; 
     this.isAdmin = false;
};
let user = new User("abc");


let user = new function() {  //one use constructor function
     this.name = "John";
     this.isAdmin = false;
};

Arrays

let arr = new Array();
let arr = [];  //same as above, but more common

let arr = ["nissan", "toyota"];  // arr[1] would be toyota

for (let i = 0; i < 5; i++) {do something} // after 2nd value, undefined
for (let i = 0; i < arr.length; i++) {do something} // works - not shortest but fastest and will skip non-numeric keys
for (let key in arr) {do something}  // much easier but slower and will spit out non-numeric keys

lenghtOfArray = arr.length;

arr.pop //removes last item [fast]
arr.push //append element(s) to end [fast]
arr.shift //extracts 1st element, returns it and removes it [slow]
arr.unshift //add element(s) to beginning [slow]

Multidimensional Arrays

let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ];
Comment (0) Hits: 1541
Note: I've seen this not work - especially with WordPress sites that have caching plugins installed.

<div class="hidden">
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
"http://domain.com/path-to-image1.jpg",
"http://domain.com/path-to-image2.jpg",
"http://domain.com/path-to-image3.jpg"
)
//--><!]]>
</script>
</div>
Comment (0) Hits: 1194
Just a little Javascript will do the trick...
    <script>
        window.onbeforeunload = function(e){
            document.getElementById('idOfElementToChange').className = 'classAddedAfterClick';
        }
    </script>

 Pretty self-explanatory.  Replace idOfElementToChange with the ID of the element that will incur the new class.  And ClassAddedAfterClick is the new class that will be added.  Probably didn't need to say this.

Comment (0) Hits: 3626

Simplest of Simple Javascript Lightbox Scripts...

CSS:

 

.black_overlay{
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: black;
    z-index:1001;
    -moz-opacity: 0.8;
    opacity:.80;
    filter: alpha(opacity=80);
}
 
.white_content {
    display: none;
    position: absolute;
    top: 15%;
    left: 50%;
    width: 500px;
    height: 580px;
    padding: 16px;
    border: 16px solid #555;
    background-color: white;
    z-index:1002;
    overflow: auto;
    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;
    -khtml-border-radius:5px;
    behavior:url(border-radius.htc);
}

Javascript/HTML:

 

<div id="content" class="white_content">
<button style="float:right" onclick = "document.getElementById('content').style.display='none';document.getElementById('fade').style.display='none'">Close</button>
 
content or image goes here...
 
<button style="margin-bottom:20px;" onclick = "document.getElementById('content').style.display='none';document.getElementById('fade').style.display='none'">Close</button>
</div>
<div id="fade" class="black_overlay"></div>

Link:

 

<a href = "javascript:void(0)" onclick = "document.getElementById('content').style.display='block';document.getElementById('fade').style.display='block'">View Lightbox</a>
 
 
 
Comment (0) Hits: 2643
X