// JavaScript CS
// convert to string
// --------------------------------------------------------------------
let myNumber = 9;
let myString = String(score);
// convert to number
// --------------------------------------------------------------------
let myString = '44';
let myNumber = Number(myString);
// convert to boolean
// --------------------------------------------------------------------
let age = 0;
// good
let hasAge = Boolean(age);
// best
let hasAge = !!age;
// array map - Array.prototype.map()
// --------------------------------------------------------------------
let numbers = [1, 5, 10, 15];
let doubles = numbers.map(function(x) {
return x * 2;
});
// doubles is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
// es6 example
let numbers = [2, 4, 8, 10];
let halves = numbers.map(x => x / 2);
// halves is now [1, 2, 4, 5]
// numbers is still [2, 4, 8, 10]
let numbers = [1, 4, 9];
let roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
// array filter - Array.prototype.filter()
// --------------------------------------------------------------------
let words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];
let longWords = words.filter(function(word){
return word.length > 6;
});
// filtered array longWords is ["exuberant", "destruction", "present"]
// array find - Array.prototype.find()
// --------------------------------------------------------------------
function isBigEnough(element) {
return element >= 15;
}
[12, 5, 8, 130, 44].find(isBigEnough); // 130
// array slice - Array.prototype.slice()
// --------------------------------------------------------------------
let a = ['zero', 'one', 'two', 'three'];
let sliced = a.slice(1, 3);
console.log(a); // ['zero', 'one', 'two', 'three']
console.log(sliced); // ['one', 'two']
// array splice - Array.prototype.splice()
// --------------------------------------------------------------------
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
myFish.splice(2, 0, 'drum'); // insert 'drum' at 2-index position
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
myFish.splice(2, 1); // remove 1 item at 2-index position (that is, "drum")
// myFish is ["angel", "clown", "mandarin", "sturgeon"]
Last active
November 18, 2017 01:31
-
-
Save diogocapela/23c35e5b513756c82fedd2382af9c047 to your computer and use it in GitHub Desktop.
JavaScript CS
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment