JavaScript中Array数组的tips的讲解

不言
不言 原创
2018-07-13 10:01:30 1130浏览

这篇文章主要介绍了关于JavaScript中Array数组的tips的讲解,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

1. Array.prototype.push()

像数组一样使用对象:

var obj = {
    length: 0,

    addElem: function addElem (elem) {
        // obj.length is automatically incremented 
        // every time an element is added.
        [].push.call(this, elem);
    }
};

// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length);
// → 2

尽管 obj 不是数组,但是 push 方法成功地使 obj 的 length 属性增长了,就像我们处理一个实际的数组一样。

2. Array.prototype.sort()

arr.sort(compareFunction)

参数:compareFunction
可选。用来指定按某种顺序进行排列的函数。如果省略,元素按照转换为的字符串的各个字符的Unicode位点进行排序。

如果指明了compareFunction,那么数组会按照调用该函数的返回值排序。即 a 和 b 是两个将要被比较的元素:

  • 如果compareFunction(a, b)小于 0 ,那么 a 会被排列到 b 之前;

  • 如果compareFunction(a, b)等于 0 , a 和 b 的相对位置不变;

  • 如果compareFunction(a, b)大于 0 , b 会被排列到 a 之前。

比较函数格式如下(字符串与数组都可以比较):

function compare(a, b) {
    if (a < b ) {           // 按某种排序标准进行比较, a 小于 b
        return -1;
    }
    if (a > b ) {
        return 1;
    }
    // a must be equal to b
    return 0;
}

3. Array.prototype.unshift()

var arr = [1, 2];
arr.unshift(-2, -1);    // = 5
// arr is [-2, -1, 1, 2]

4. Array.prototype.concat()

返回新的数组(浅拷贝),不会影响原数组。

  • 如果参数是数组,则把数组的元素放入结果中;

  • 如果参数不是数组,则把参数本身放入结果中。

var num1 = [1, 2, 3],
    num2 = [4, 5, 6],
    num3 = [7, 8, 9];

var nums = num1.concat(num2, num3);

console.log(nums); 
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9];

var alpha = ['a', 'b', 'c'];

var alphaNumeric = alpha.concat(1, [2, 3]);

console.log(alphaNumeric); 
// results in ['a', 'b', 'c', 1, 2, 3]

5. Array.prototype.forEach()

array.forEach(callback(currentValue, index, array){
    //do something
}, thisArg)

array.forEach(callback[, thisArg])

其中:thisArg为可选参数,当执行回调 函数时用作this的值(参考对象)。

下列函数也有thisArg这个可选参数,用法与Array.prototype.forEach()一致:

  • Array.prototype.forEach()

  • Array.prototype.every()

  • Array.prototype.some()

  • Array.prototype.filter()

  • Array.prototype.map()

  • Array.prototype.reduce()

  • Array.prototype.reduceRight()

6. Array.prototype.map()

使用技巧案例

// 下面的语句返回什么呢:
["1", "2", "3"].map(parseInt);
// 你可能觉的会是[1, 2, 3]
// 但实际的结果是 [1, NaN, NaN]

// 通常使用parseInt时,只需要传递一个参数.
// 但实际上,parseInt可以有两个参数.第二个参数是进制数.
// 可以通过语句"alert(parseInt.length)===2"来验证.
// map方法在调用callback函数时,会给它传递三个参数:当前正在遍历的元素, 
// 元素索引, 原数组本身.
// 第三个参数parseInt会忽视, 但第二个参数不会,也就是说,
// parseInt把传过来的索引值当成进制数来使用.从而返回了NaN.

function returnInt(element) {
  return parseInt(element, 10);
}

['1', '2', '3'].map(returnInt); // [1, 2, 3]
// 意料之中的结果

// 也可以使用简单的箭头函数,结果同上
['1', '2', '3'].map( str => parseInt(str) );

// 一个更简单的方式:
['1', '2', '3'].map(Number); // [1, 2, 3]
// 与`parseInt` 不同,下面的结果会返回浮点数或指数:
['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]

7.Array.prototype.reduce()

arr.reduce(callback[, initialValue])

Array.prototype.reduceRight()是与其用法类似,是从右向左遍历。

参数:

  • callback: 执行数组中每个值的函数,包含四个参数:

    • accumulator: 累加器累加回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(如下所示)。

    • currentValue: 数组中正在处理的元素。

    • currentIndex: 可选,数组中正在处理的当前元素的索引。 如果提供了initialValue,则索引号为0,否则为索引为1。

    • array: 可选,调用reduce的数组。

  • initialValue: 可选,用作第一个调用 callback的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用reduce将报错。

reduce如何运行

[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
  return accumulator + currentValue;
}, 10);

// 20

实例:将二维数组转化为一维

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(a, b) {
    return a.concat(b);
  },
  []
);
// flattened is [0, 1, 2, 3, 4, 5]

实例:使用扩展运算符和initialValue绑定包含在对象数组中的数组

// friends - an array of objects 
// where object field "books" - list of favorite books 
var friends = [{
  name: 'Anna',
  books: ['Bible', 'Harry Potter'],
  age: 21
}, {
  name: 'Bob',
  books: ['War and peace', 'Romeo and Juliet'],
  age: 26
}, {
  name: 'Alice',
  books: ['The Lord of the Rings', 'The Shining'],
  age: 18
}];

// allbooks - list which will contain all friends' books +  
// additional list contained in initialValue
var allbooks = friends.reduce(function(prev, curr) {
  return [...prev, ...curr.books];
}, ['Alphabet']);

// allbooks = [
//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace', 
//   'Romeo and Juliet', 'The Lord of the Rings',
//   'The Shining'
// ]

实例:数组去重

let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
let result = arr.sort().reduce((init, current)=>{
    if(init.length===0 || init[init.length-1]!==current){
        init.push(current);
    }
    return init;
}, []);
console.log(result); //[1,2,3,4,5]

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

以上就是JavaScript中Array数组的tips的讲解的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。