Array Methods

2418 ワード

  • join()
    var a = [1, 2, 3];    // Create a new array with these three elements
    var s = a.join();       // s == "1,2,3"
    
    The following invocation specifies the optional separator to produce a slightly different result:
    
    s = a.join(", ");   // s == "1, 2, 3"
     
  • reverse()
  • sort()
    var a = [33, 4, 1111, 222];
    a.sort();                 // Alphabetical order:  1111, 222, 33, 4
    a.sort(function(a,b) {    // Numerical order: 4, 33, 222, 1111
               return a-b;    // Returns < 0, 0, or > 0, depending on order
           });
    
     
  • concat()
    var a = [1,2,3];
    a.concat(4, 5)          // Returns [1,2,3,4,5]
    a.concat([4,5]);        // Returns [1,2,3,4,5]
    a.concat([4,5],[6,7])   // Returns [1,2,3,4,5,6,7]
    a.concat(4, [5,[6,7]])  // Returns [1,2,3,4,5,[6,7]]
    
     
  • slice()
    var a = [1,2,3,4,5];
    a.slice(0,3);    // Returns [1,2,3]
    a.slice(3);      // Returns [4,5]
    a.slice(1,-1);   // Returns [2,3,4]
    a.slice(-3,-2);  // Returns [3]
    
     
  • splice()
    var a = [1,2,3,4,5,6,7,8];
    a.splice(4);    // Returns [5,6,7,8]; a is [1,2,3,4]
    a.splice(1,2);  // Returns [2,3]; a is [1,4]
    a.splice(1,1);  // Returns [4]; a is [1]
    
    var a = [1,2,3,4,5];
    a.splice(2,0,'a','b');  // Returns []; a is [1,2,'a','b',3,4,5]
    a.splice(2,2,[1,2],3);  // Returns ['a','b']; a is [1,2,[1,2],3,3,4,5]
    
     
  • push() and pop()
  • unshift() and shift()
    var a = [];            // a:[]
    a.unshift(1);          // a:[1]         Returns: 1
    a.unshift(22);         // a:[22,1]      Returns: 2
    a.shift();                // a:[1]         Returns: 22
    a.unshift(3,[4,5]);    // a:[3,[4,5],1] Returns: 3
    a.shift();                // a:[[4,5],1]   Returns: 3
    a.shift();                // a:[1]         Returns: [4,5]
    a.shift();                // a:[]          Returns: 1
    
     
  • toString() and toLocaleString()Note that the join() method returns the same string when it is invoked with no arguments.