(JavaScript) Array的tips

news/2024/6/26 19:42:44

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]

参考

Array - MDN


http://www.niftyadmin.cn/n/2745331.html

相关文章

Springboot中@Ehable**学习

2019独角兽企业重金招聘Python工程师标准>>> Springboot版本是1.5.release. Springboot中使用EnableAutoConfiguration注解&#xff0c;如下所示&#xff1a; List-1 Target(ElementType.TYPE) Retention(RetentionPolicy.RUNTIME) Documented Inherited AutoConfig…

产妇坐月子可以碰水吗?

产妇坐月子可以碰水吗? 坐月子对于产妇来说是很重要的&#xff0c;这不仅仅是一项历史传统。若是在坐月子期间没有好好护理&#xff0c;很容易影响恢复&#xff0c;甚至可以出现各种后遗症。那么&#xff0c;产妇坐月子可以碰水吗?这个问题是很多朋友想要了解的。下面我们一起…

新版ButterKnifeの坑

2019独角兽企业重金招聘Python工程师标准>>> 日常习惯用ButterKnife进行控件绑定 GIitHub 心血来潮... 升级使用最新版本 10.1.0编译不能通过 dependencies {implementation com.jakewharton:butterknife:10.1.0annotationProcessor com.jakewharton:butterknife-co…

ArcGIS中的多个栅格波段合成一幅影像

此处用到了ArcGIS栅格处理中的Composite Bands工具&#xff08; Data Management Tools --> Raster --> Raster Processing&#xff09;。具体操作如下图所示。

产妇做月子期间有哪些注意事项?

产妇做月子期间有哪些注意事项? 坐月子女性朋友一生中很重要的时刻&#xff0c;这个时候可以改变他们的体质&#xff0c;所以在做月子的时候要注意保护&#xff0c;那么&#xff0c;产妇做月子期间有哪些注意事项?针对这个问题&#xff0c;下面就一起来看看专家的介绍。 产妇…

Django的restframework的序列化组件之对单条数据的处理

之前我们学习的都是处理书籍或者出版社的所有的数据的方法&#xff0c;下面我们来看下处理单个书籍&#xff0c;或者单个出版社的方法 这个时候我们就需要重新写一个类&#xff0c;这个类的方法&#xff0c;就需要有3个参数&#xff0c;参数1是self&#xff0c;参数2是request&…

MySQL SQL优化教程

转自:https://www.cnblogs.com/duanxz/archive/2013/02/01/2889413.html 一&#xff0c;查询SQL执行效率 通过show status命令了解各种SQL的执行效率。 ?123456789101112131415161718mysql> show status like Com_%;----------------------------------| Variable_name …

关于Flash的一些介绍(一)

一、flash介绍 Flash的前身是Future Wave公司的Future Splash&#xff0c;是世界上第一个商用的二维矢量动画软件&#xff0c;用于设计和编辑Flash文档。1996年美国Macromedia公司收购了Future Wave&#xff0c;并将其改名为Flash。在出到Flash 8以后&#xff0c;Macromedia又被…