JS–Array

Array is one part of programming language, which i really don’t like. But I met it everyday, so here is some basic methods for how to deal with array.

My example:

11

1. x.push()123x.push() is adding element to the end of array

 

2. x.unshift()123PNG.PNGx.unshift() is adding element to the beginning of array

3. x.pop()123.PNG

x.pop() is to delete the last element from array

4. x.shift()

123

x.shift() is to delete the first element from array

5. x.indexOf()

123.PNG

x.indexOf() can show which position the element is, in this example, pear is x[1], so the number is 1 . If there is no this element in array, number will be -1.

Advanced parts:

1.easy way to add element at the end of array

1234

But we cannot use this way  to add element to any position.

123

And adding element with high indexes can create undefined “holes” in an array

1234.PNG

2. delete

we also can use delete to remove element from array. However, it leaves undefined “hole “, so try to use pop() and shift() instead.

1234.PNG

3. x.splice()

How to add new elements in any position. And how to remove any element from any position.

1234

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s