Array
>>> var a = new Array();
is same as
>>> var a = [];
>>> var a2 = new Array(5);
>>> a2;
[undefined, undefined, undefined, undefined, undefined]
>>> typeof a;
"object"
>>> a.toString();
"1,2,3,four"
>>> a.constructor
Array()
Array objects have a length property automatically defined for them, while normal objects do not
It's OK to add both numeric and non-numeric properties to both arrays and objects
>>> a[0] = 1; o[0] = 1;
>>> a.prop = 2; o.prop = 2;
The length property can also be set by you
>>> a.length = 5
5
>>> a
[1, undefined, undefined, undefined, undefined]
Interesting Array methods
In addition to the methods inherited from the parent object, array objects also have methods, such as sort(), join(), and slice(), among others
>>> var a = [3, 5, 1, 7, 'test'];
>>> a.push('new')
6
>>> a
[3, 5, 1, 7, "test", "new"]
>>> var b = a.sort();
>>> b
[1, 3, 5, 7, "test"]
>>> a.join(' is not ');
join() returns a string
"1 is not 3 is not 5 is not 7 is not test"
slice() returns a piece of the array without modifying the source array
>>> b = a.slice(1, 3);
[3, 5]
>>> b = a.slice(0, 1);
[1]
splice() modifies the source array
It removes a slice, returns it, and optionally fills the gap with new elements
>>> b = a.splice(1, 2, 100, 101, 102);
[3, 5]
>>> a
[1, 100, 101, 102, 7, "test"]
>>> a.splice(1, 3)
[100, 101, 102]
>>> a
[1, 7, "test"]
No comments:
Post a Comment