Difference between revisions of "Useful Functions"

From rbachwiki
Jump to navigation Jump to search
 
Line 66: Line 66:
  var pos = str.indexOf("world");
  var pos = str.indexOf("world");
-1 is returned when item is not found
-1 is returned when item is not found
''' Array indexOf '''
var myarray=[1,2,3];
myarray.indexOf(2);
Returns position


== Split ==
== Split ==

Latest revision as of 21:00, 13 December 2016

Map function

will duplicate an array to another
This will retrieve the ages of everyone 18 or over and add them to the array full

var ages[12, 13, 16, 21]
var full = ages.map(function(curr){
return cur >=18;
})

This will get the 'true' boolean value of ages>= 18 then we have to use the indexOf to find the element position

console.log(ages[full.indexOf(true)]);

ES6 Equivalent This returns the index

var index = ages.findIndex(cur => cur >= 18);

This returns the actual age

var ageover18 = ages.find(cur => 18);

Apply

 function addFourAges(a,b,c,d){
 return a+b+c+d;
 };
 var sum1 = addFourAges(18,19,20,21);

Each age is passed as a variable to the function, but if the ages were in an array, we can use the apply method to pass them into the function

var ages = [18,21,22,23];
var sum2 = addFourAges.apply(null, ages);
// the null refers to the this 

ES6 Spread Operator

ES6 Equivalent Spread Operator

const sum3 = addFourAges(...ages);
// the ... means the ages array is expanded into individual components.

Join two Arrays

const arrayOne= ['hello', 'two'];
const arrayTwo = ['three', 'four'];
const arrayThree = [...arrayOne, ...arrayTow];

Looping through all elements and changing the color

const h = document.querySelector(h1)
const boxes = documwnt.querySelectorAll('.box');
const all = [h, ...boxes];
Array.form(all).forEach(cur=> cur.style.color='purple') // returns an array

Argument function

Allows you to pass an unlimited number of arguments to a function

function isFullAge(){
var args = Array.prototype.slice.call(arguments);
args.forEach(function(cur){
console.log(2016 - cur) >= 18);
})
isFullAge(1990,1921,1967);

ES6 Equivalent Rest Parameter

function isFullAge(...years){
years.forEach(cur=> (216-cur)>=18);
}
 isFullAge(1990,1921,1967);

Splice

indexOf

return the starting position of a string

var str = "Hello World";
var pos = str.indexOf("world");

-1 is returned when item is not found Array indexOf

var myarray=[1,2,3];
myarray.indexOf(2);

Returns position

Split

Used to split text given a delimiter into an array of substrings

var myText = 'hello-1'
var mysplit = myText.split('-')

Will Yield

['hello', 1]

Slice for Text and Arrays

Extracts parts of a string and returns the extracted parts in a new string.

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

The result of citrus will be:

Orange,Lemon

Extract parts of a string

var str = "Hello world!";
var res = str.slice(1,5);

The result of res will be:

ello

Back To Top- Home - Category