MXOXW

Life always finds a way.

JavaScript 权威指南-数组

| Comments

7.8数组方法

  • join()

    1
    2
    3
    4
    5
    6
    var a = [1, 2, 3];          // Create a new array with these three elements
    a.join(); // => "1,2,3"
    a.join(" "); // => "1 2 3"
    a.join(""); // => "123"
    var b = new Array(10); // An array of length 10 with no elements
    b.join('-') // => '---------': a string of 9 hyphens
  • reverse()

    1
    2
    var a = [1,2,3];
    a.reverse().join() // => "3,2,1" and a is now [3,2,1]
  • sort()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    var a = new Array("banana", "cherry", "apple");
    a.sort();
    var s = a.join(", "); // s == "apple, banana, cherry"

    /**
    * [a description]
    * @type {Array}
    */

    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
    Core JavaScript
    return a - b; // Returns < 0, 0, or > 0, depending on order
    });
    a.sort(function(a, b) {
    return b - a
    }); // Reverse numerical order

    /**
    * [a description]
    * @type {Array}
    */

    a = ['ant', 'Bug', 'cat', 'Dog']
    a.sort(); // case-sensitive sort: ['Bug','Dog','ant',cat']
    a.sort(function(s, t) { // Case-insensitive sort
    var a = s.toLowerCase();
    var b = t.toLowerCase();
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
    }); // => ['ant','Bug','cat','Dog']
  • concat()

    1
    2
    3
    4
    5
    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()

    1
    2
    3
    4
    5
    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()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    /**
    * 第一个参数指定插入和(或)删除的起始位置
    * 第二个参数指定应该从数组删除元素的个数,如果省略,从起始到数组结尾的所有元素都将删除
    * 第三个开始之后的参数指定插入到起始位置的元素
    * 返回由删除元素组成的数组,没有元素删除返回空数组
    */

    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()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    var stack = [];         // stack: []
    stack.push(1,2); // stack: [1,2] Returns 2
    stack.pop(); // stack: [1] Returns 2
    Core JavaScript
    stack.push(3); // stack: [1,3] Returns 2
    stack.pop(); // stack: [1] Returns 3
    stack.push([4,5]); // stack: [1,[4,5]] Returns 2
    stack.pop() // stack: [1] Returns [4,5]
    stack.pop(); // stack: [] Returns 1
  • unshift() and shift()

    1
    2
    3
    4
    5
    6
    7
    8
    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

7.9 ECMAScript 5 数组方法

大多数方法的第一个参数接收一个函数,并且对数组的每个元素(或一些元素)调用一次该函数。如果是稀疏数组,对不存在的元素不调用传递的函数。在大多数情况下,调用提供的函数使用三个参数:数组元素、元素的索引和数组本身。通常,只需要第一个参数值,可以忽略后两个参数.大多数ECMAScript 5数组方法的第一个参数是一个函数,第二个参数是可选的。如果有第二个参数,则调用的函数被看做是第二个参数的方法。也就是说,在调用函数时传递进去的第二个参数作为它的this关键字的值来使用。被调用的函数的返回值非常重要,但是不同的方法处理返回值的方式也不一样。ECMAScript 5中的数组方法都不会修改它们调用的原始数组。当然,传递给这些方法的函数是可以修改这些数组的。

  • forEach()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    var data = [1, 2, 3, 4, 5]; // An array to sum
    // Compute the sum of the array elements
    var sum = 0; // Start at 0
    data.forEach(function(value) {
    sum += value;
    }); // Add each value to sum
    sum // => 15
    // Now increment each array element
    data.forEach(function(v, i, a) {
    a[i] = v + 1;
    });
    data // => [2,3,4,5,6]

    /**
    * **break问题**
    */

    function foreach(a, f, t) {
    try {
    a.forEach(f, t);
    }
    catch (e) {
    if (e === foreach.break) return;
    else throw e;
    }
    }
    foreach.break = new Error("StopIteration");
  • map()
    传递给map()的函数的调用方式和传递给于forEach的函数的调用方式一样。但传递给map()的函数应该有返回值。注意map()返回的是新数组:它不修改调用的数组。如果是稀疏数组,返回的也是相同方式的稀疏数组:它具有相同的长度,相同的缺失元素。

    1
    2
    a = [1, 2, 3];
    b = a.map(function(x) { return x*x; }); // b is [1, 4, 9]
  • filter()

    1
    2
    3
    4
    5
    6
    7
    a = [5, 4, 3, 2, 1];
    smallvalues = a.filter(function(x) { return x < 3 }); // [2, 1]
    everyother = a.filter(function(x,i) { return i%2==0 }); // [5, 3, 1]

    var dense = sparse.filter(function() { return true; });

    a = a.filter(function(x) { return x !== undefined && x != null; });
  • every() and some()
    数组逻辑判定

    1
    2
    3
    4
    5
    6
    7
    8
    a = [1,2,3,4,5];
    a.every(function(x) { return x < 10; }) // => true: all values < 10.
    a.every(function(x) { return x % 2 === 0; }) // => false: not all values even.


    a = [1,2,3,4,5];
    a.some(function(x) { return x%2===0; }) // => true a has some even numbers.
    a.some(isNaN) // => false: a has no non-numbers.
  • reduce() and reduceRight()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var a = [1,2,3,4,5]
    var sum = a.reduce(function(x,y) { return x+y }, 0); // Sum of values
    var product = a.reduce(function(x,y) { return x*y }, 1); // Product of values
    var max = a.reduce(function(x,y) { return (x>y)?x:y; }); // Largest value

    var a = [2, 3, 4]
    // Compute 2^(3^4). Exponentiation has right-to-left precedence
    var big = a.reduceRight(function(accumulator,value) {
    return Math.pow(value,accumulator);
    });
  • indexOf() and lastIndexOf()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    a = [0,1,2,1,0];
    a.indexOf(1) // => 1: a[1] is 1
    a.lastIndexOf(1) // => 3: a[3] is 1
    a.indexOf(3) // => -1: no element has value 3

    /**
    * 在数组中查找所有出现的x,并返回一个包含匹配索引的数组
    */

    function findall(a, x){
    var results = [], //将会返回的数组
    len = a.length, //待搜索数组的长度
    p05 = 0; //开始搜索的位置
    while (pos < len) { //循环搜索多个元素…
    pos = a.indexOf(x, pos); //搜索
    if (pos === -1) break; //未找到,就完成搜索
    results.push(pos); //否则,在数组中存储索引
    pos = pos + 1; //并从下一个位置开始搜索
    }
    return results; //返回包含索引的数组
    }

评论