Arrays
Array literals
var not_empty = ['hello', 'world'];
not_empty['0'];
not_empty['1'];
Object Literal
var not_empty_obj = {
'0': 'hello',
'1': 'world'
}
Need not be homogenous
Difference between Object and Array?
Length Property
If you add a new element, length will be incremented.
WAIT ... that is not it
non_empty[1000] = "checkinng!";
non_empty.length ?
[] operator uses the expression's toString method, if it has one.
DElete, Enumeration
var numbers = ['zero', 'one', 'two', 'shi', 'go'];
delete numbers[2];
numbers.splice(2,1)?
MethODS
Array.method('reduce', function(f,value) {
var i;
for(i=0; i<this.length;i++){
value = f(this[i], value)
}return value;
});
)
INtialization
Initialize an array of length 10 with zeroes
Initialize a 3D array with dim m,n,p with 1s
ARRAY Methods
var a = []; / / first array
var b=[]; / / 2nd array
var c = a.concat(b,'hey');
concat // new array with with both arrays and item in the end
join //returns a string with a separatorpop
pushreverse //modifies the array
shift // removes first element and returns itslice (start, end) // shallow copy of the array. start at start and end at end.sort(comparefn) // default compare is string comparision. In place sorting
splice(start,deleteCount, item...)// replace with items starting form start
unshift(item...) // insert in the beginning
AWFUL PARTS
Global Variablesvar foo = value; // outside of any functionwindow.foo = value;foo = value; //confusing!
AWFUL pARTS
ScopeNo Block scope, can be confusing for C programmersSemicolon insertionreturn{status:true};
AWFUL PARTS
Reserved Words
var method; //okvar class; //illegalobject = {box:value} //okobject = {case:value} //illegal
object.case = value; //illegalobject['case'] = value; //ok
AWFUL PARTS
typeof
typeof 98.6typeof nullNaNtypeof NaN === 'number' //trueNaN === NaN ?NaN !== NaN ?
Arrays
By Vijay Kalangi
Arrays
- 458