Week 7 Section 6
.map() vs .every() Objects, JSON localStorage debbugger;
by jazahn
HTML
<h3>Array.prototype.every() vs Array.prototype.map()</h3>
<ul>
<li>.map() <strong>returns a new Array</strong> of objects created by taking some action on the original item.</li>
<li>.every() <strong>returns a boolean</strong> - true if every element in this array satisfies the provided testing function. An important difference with .every() is that the test function may not always be called for every element in the array. Once the testing function returns false for any element, no more array elements are iterated. Therefore, the testing function should usually have no side effects.</li>
</ul>
<h3>Objects</h3>
<ul>
<li><strong>key: </strong>value</li>
<li>JSON</li>
<li>localStorage</li>
</ul>
<h3>debugger;</h3>
<h3>function prototypes</h3>
JavaScript
"use strict";
var numbers = [1, 2, -3, 4, 5, 6, 7, 8, 9];
var arePositive = numbers.every(function(value){
if(value >= 0){
return true;
}
return false;
});
//console.log(arePositive);
// anything less than 5 will be set to 5
/*for(var i = 0; i < numbers.length; i++){
if(numbers[i] < 5){
numbers[i] = 5;
}
}*/
//console.log(numbers);
//console.log(numbers);
var squares = numbers.map(function(value){
return value * value;
});
//console.log(squares);
var newNumbers = numbers.map(function(value){
if(value < 5){
return 5;
}
return value;
});
//console.log(newNumbers);
var people = [
{'fname': "john", 'lname': "doe"},
{'fname': "jane", 'lname': "doe"},
{'fname': "peter", 'lname': "parker"},
{'fname': "clark", 'lname': "kent"}
];
// MAP through people and make capitalize their names
var capFirst = function(word){
var firstLetter = word.substring(0, 1).toUpperCase();
var rest = word.substring(1).toLowerCase();
return firstLetter + rest;
};
//console.log(capFirst("jazahn"));
var capitalizedPeople = people.map(function(obj){
var fname = capFirst(obj.fname);
var lname = capFirst(obj.lname);
var person = {
fname: fname,
lname: lname
};
return person;
});
console.log(capitalizedPeople);
var person = {
fname: "JaZahn",
lname: "Clevenger",
email: "[email protected]"
};
//console.log(person);
// ADD a phone var to the obj
//console.log(person);
// LOOP through the person object and output
// SET localStorage person obj
// GET localStorage person obj
// CREATE person function obj
var Person = function(fname, lname, email){
this.fname = fname;
this.lname = lname;
this.email = email;
this.books = [];
};
Person.prototype.addBook = function(book){
this.books.push(book);
};
var jazahn = new Person("JaZahn", "Clevenger",...