Javascript -- Array

Converting Arrays to Strings

<script>
  var fruits = ["Banana","Orange","Apple","Mango"];
  var fruitsString = fruits.toString();
</script>
View Code

Join(): like toString(), but in addition the seprator

 

add element

  *push(): adds a new element to an array at the end.

  *unshift(): adds a new element to an array at the head.

  *fruits[fruits.length]="";

delete element

  *pop(): removes the last element from an array. (返回最后一个元素)

  *shift(): removes the frist element from an array. (返回第一个元素)

  *delete fruits[0]

modify element

  *fruits[0] = "";

Splicing an Array

  *splice

<script>
    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.splice(2, 0, "Lemon", "Kiwi"); 
    //returns "Banana","Lemon"","Kiwi" "Orange", "Apple", "Mango"
</script>

The first parameter (2) defines the position where new elements should be added (spliced in).

The second parameter (0) defines how many elements should be removed.

The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.

  *remove elements

<script>
    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.splice(0, 1);        // Removes the first element of fruits
</script>

Sorting an Array
  *sort() method sorts an array alphabetically.

  *reverse() method reverse the elements in an array

  *Numeric Sort: by default, sort funciton values as strings, but we can specify the sort method.

<script>
  var points = [];
  points.sort(function(a,b){return a-b}); //sort the array in ascending order
//
points.sort(function(a,b){return b-a}); sort the array in descending order
</script>

Joining Arrays

  *concat() method creates a new array by concatenating two arrays:

<script>
    var arr1 = ["Cecilie", "Lone"];
    var arr2 = ["Emil", "Tobias","Linus"];
    var arr3 = ["Robin", "Morgan"];
    var myChildren = arr1.concat(arr2, arr3);     // Concatenates arr1 with arr2 and arr3
</script>

 

 

 

holder

posted on 2016-04-22 16:45  yeatschen  阅读(86)  评论(0编辑  收藏  举报

导航