#Object and Array in JavaScript
// Data Sets
var listOfNumbers = [2,3,5,7,11];
console.log(listOfNumbers[1]);
console.log(listOfNumbers[1-1]);
##Properties and Methods
// Almost all JS values have properties except null and undefined
var pet_name = "Mila";
console.log(pet_name.length);
console.log(null.length); //-> error
// Methods
var doh = "Dod";
console.log(typeof doh.toUpperCase);
console.log(doh.toUpperCase());
<!--toUpperCase is a function, of course, but there is no argument inside it, -->
<!--so how can it know the value of doh? CHAPTER 6 inteprete it-->
##Object
var day1 = {
squrrel: false,
events: ["work", "touched tree", "pizza", "running", "television"]
};
console.log(day1.squrrel);
console.log(day1.wolf);
day1.wolf = false;
console.log(day1.wolf);
// equal operator
var object = {a: 1};
object["a"] = 2; //-> if property existed, then replace value
object["b"] = 2; //-> if didnt, create a new property
// delete operator
var descriptions = {
work: "Went to work",
"touched tree": "touched a tree"
}
console.log(descriptions.work);
delete descriptions.work;
console.log(descriptions.work);
console.log("work" in descriptions);
console.log("touched tree" in descriptions);
// different between delete a property and set value of properties to undefined
// Array of Objects
var journal = [{
events: ["work", "touched tree", "pizza", "running", "television"],
squirrel: false
},
{
events: ["work", "ice cream", "pizza", "swimming", "game"],
squirrel: false
},
{
events: ["weekend", "climbing", "peanuts"],
squirrel: true
}];
// Array is just a type of object.
// mutable and immutable
// With immutable value(number, string, boolean,..)
var str1 = "abc";
var str2 = str1;
str1 = "def";
console.log(str1, str2);
// With mutable value(Objects)
var object1 = {value: 10};
var object2 = object1;
var object3 = {value: 10};
console.log(object1 == object2);
console.log(object1 == object3);
object1.value = 15;
console.log(object2.value);
console.log(object3.value);
##Some useful function
// Push and Pop
var a = [1,2,3,4];
console.log(a);
console.log(a.pop(), a);
console.log(a.push(3), a);
// shift and unshift
console.log(a.shift(), a);
console.log(a.unshift(1), a);
// indexOf and lastIndexOf
var b = [1,2,3,4,2,3,1];
console.log(b.indexOf(1));
console.log(b.lastIndexOf(1));
// slice
console.log([0,1,2,3,4].slice(2,4));
console.log([0,1,2,3,4].slice(2));
// concat
var a = [1,2,3];
var b = [4,5,6];
a.concat(b);
console.log(a);
##The arguments object
// The argument object
function argumentCounter() {
console.log("you gave me", arguments.length, "argument.");
}
argumentCounter("Straw man", "Tautology", "Ad hominem");
##The Global Object
// the global scope, can be apprpached as an object
// and the global scope object is stored in the window variable
function test(){
var local = 10;
console.log("local" in window);
console.log(window.local);
}
test();
var global = 10;
console.log("global" in window);
console.log(window.global);