javascript读书笔记(数组的总结)

一、数组的介绍

javascript中数据集合有:数组、对象、Map集合、Set集合,数组中可以包括任意数据类型。

二、创建数组方式

  • 1、使用字面量创建

    let arry = ['哈哈', '你好', 1, 2, {'name': '哈哈'}];
    复制代码
  • 2、使用类的实例创建

    let array = new Array('哈哈', 1, 24, {'name': '男', 'gender': '男'});
    复制代码

三、修改数组的方式

  • 1、使用push()尾部追加数组

    可以一次追加一个也可以一次性追加多个,使用push后的返回值是数组的长度

    let ary = [1,2,3,4];
    ary.push(21, 12);
    复制代码
  • 2、使用unshift()头部追加数组

    push一样的可以一次追加多个元素,返回的值是当前数组的长度

    ary.unshift(12,12);
    复制代码
  • 3、使用pop()删除数组最后一个

  • 4、使用shift()删除数组第一个元素

  • 5、使用splice()删除元素、添加元素

    • 当传递参数是一个参数的时候(默认第二个参数为数组长度)

    • 当传递是两个参数的时候是删除元素(第一个参数表示从什么下标开始, 删除数组的元素个数),返回值是被删除的元素

      let ary = [1, 2, 3, 4, 5, 6, 7, 8, 9];
      let result = ary.splice(2, 4);
      // result = [3, 4, 5, 6]
      // ary = [1, 2, 7, 8, 9];
      复制代码
    • 当传递的参数是大于等于三个的时候(返回值跟上面的一样)

      var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9];
      ary.splice(1, 1, '哈哈'); // 相当于直接替换一个,从第一个元素开始到第一个元素,
      ary.splice(1, 2, '哈哈', '哈哈', '呵呵'); // 从第一个个元素开始删除两个元素,用后面的几个元素来填充
      ary.splice(1, 2, ['哈哈', '嘻嘻', '呵呵']) // 第三个参数可以是集合
      复制代码
  • 6、slice()提取数据,不修改原来数据

    var ary = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    ary.slice(1,3); // 返回2, 3
    复制代码
  • 7、delete删除数组

    删除数组,但是数组长度不变,只是被删除的位置是empty

    let ary = [1, 2, 3, 4];
    delete ary[1];
    console.log(ary);
    复制代码
  • 8、总结:

    • 1.如果要修改数组的时候劲量使用poppush这样仅仅是改变数组最后一位
    • 2.shiftunshiftsplice会改动数组的位置,性能要低点

四、数组遍历

  • 1、传统的for遍历

  • 2、ES6for..of遍历

    let ary3 = ['哈哈', '嘻嘻', '呵呵'];
    // 直接使用
    for(let item of ary3){
    	console.log(item);
    }
    // 带序列号的
    for(let [index, item] of ary3.entries()){
    	console.log(index, item);
    }
    // 使用keys
    for (let index of ary3.keys()){
    	console.log(index, ary3[index]);
    }
    
    // 使用values()
    for(let k of ary3.values()){
    	console.log(k)
    }
    复制代码
  • 3、使用forEach()遍历,无返回值

    // forEach定义:forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
    ary3.forEach((item, index, ary) => {
    	console.log(item, index, ary)
    });
    复制代码

五、映射数组

  • 1、map()返回新的数组

    // map定义: map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
    let ary4 = ary3.map((item, index, ary) => {
    
    })
    复制代码

六、测试数组

  • 1、some()一个返回true就返回true

    some定义:some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean;

  • 2、every()一个返回false就返回false

    ``every定义: every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean;`

  • 3、Array.isArray(数组)判断是否为数组

七、数组查找

  • 1、find()查找第一个返回的结果

    let ary3 = ['哈哈', '嘻嘻', '呵呵'];
    let res = ary3.find((item, index, ary) => {
    	console.log(item, index, ary)
    	return item == '哈哈';
    });
    
    console.log(res)
    复制代码
  • 2、findIndex()返回第一个序列号

    let res2 = ary3.findIndex((item, index, ary) => {
    	return item == '嘻嘻';
    });
    
    console.log(res2);
    复制代码
  • 3、indexOf(查找的元素, 开始查找位置)查找返回序列号,如果没有查找到就返回-1

    // indexOf定义方式: indexOf(searchElement: T, fromIndex?: number): number;
    ary.indexOf(1, 2)
    复制代码
  • 4、lastIndexOf()indexOf()一样的

  • 5、filter()过来数组,返回的一个新数组

    let ary4 = [12, 13, 30, 1, 4, 6, 2, 7, 9, 10];
    
    let res4 = ary4.sort((a, b) => a - b);
    console.log(res4);
    
    let res5 = ary4.filter((item, index ,ary) => {
    	return item > 5;
    });
    
    console.log(res5);
    复制代码
  • 6、includes()查找一个元素是否在数组中

    ary4.includes(查找的元素, 起始位置[可以不写]);
    复制代码

八、数组的排序

  • 1、sort()排序

    // 源码定义方式:sort(compareFn?: (a: T, b: T) => number): this
    复制代码

九、合计数组

  • 1、reducer()的使用

    /**
     * reduce(函数, 初始化值)
     * 其中函数的参数(计算后的结果, 当前值, 当前值的序列号, 数组)
     */
    let result = [1, 2, 3, 4, 5].reduce((total, currentVal, currentIndex, ary) => {
    	console.log(total)
    	return total + currentVal
    }, 0)
    console.log(result)
    复制代码

十、数组的转换

  • 1、Array.from()

    可以将类数组、可迭代对象转换为数组

    Array.from('hello')
    // ['h', 'e', 'l', 'l', 'o']
    
    let namesSet = new Set(['a', 'b'])
    Array.from(namesSet) // ['a', 'b']
    复制代码
  • 2、...转换为数组

    [...'hello']
    ["h", "e", "l", "l", "o"]
    复制代码
  • 3、Array.of()方法用于将一组值,转换为数组

    Array.of(3, 11, 8) // [3,11,8]
    复制代码
  • 4、join()数组转换为字符串

    [...'hello'].join('')
    复制代码
  • 5、split()是字符的方法,转换为数组

  • 6、toString()只是join()的简化版(用,连接数组)

十一、数组的拷贝

  • 1、concat()方法不改变原来数组,返回一个新数组

    • 1.如果concat()里面不传递参数表示数组的拷贝
    • 2.如果concat()里面含有参数,或者集合都是合并到新数组中
  • 2.copyWithin()数组内部的复制,直接修改了原数组,返回当前数组

    /**
     * Array.prototype.copyWithin(target, start = 0, end = this.length)
     * target: 是必须的,表示要替换的位置
     * start: 表示数组内从哪里开始取值
     * end: 表示数组内取值结束位置
     * 如果是负数就用数组长度 + 负数值
     * */
    let ary5 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    // 把第八个元素拷贝替换到第二个位置上
    ary5.copyWithin(2, 8, 9);
    console.log(ary5);
    // 把从第六位开始到最后拷贝到第二位,
    ary5.copyWithin(2, 5);
    console.log(ary5);
    复制代码

十二、网上比较常用的方法

  • 1、数组最大值

    const arrMax = (arr) => Math.max.apply(null, arr);
    复制代码
  • 2、数组最小值

    const arrMin = (arr) => Math.min.apply(null, arr);
    复制代码
  • 3、数组随机排序

    const shuffle1 = (target) => {
    	function randomsort(a, b) {
    		return Math.random() > .5 ? -1 : 1;
    		//用Math.random()函数生成0~1之间的随机数与0.5比较,返回-1或1  
    	}
    	return target.sort(randomsort);
    };
    复制代码
  • 4、数组中随机取出一个值

    const randomItem = (ary) => {
    	return ary[Math.ceil(Math.random() * ary.length)];
    }
    复制代码
  • 5、判断数组中是否有重复的值

    const isRepeat: function(arr) { //arr是否有重复元素
    	var hash = {};
    	for(var i of arr) {
    		if(hash[arr[i]]) return true;
    		hash[arr[i]] = true;
    	}
    	return false;
    }
    复制代码
  • 6、数组去重(根据对象key不能重复)

    const unique = (ary) => {
    	var result = [],
    		hash = {};
    	for(var i = 0, elem;
    		(elem = arr[i]) != null; i++) {
    		if(!hash[elem]) {
    			result.push(elem);
    			hash[elem] = true;
    		}
    	}
    	return result;
    };
    复制代码
  • 7、使用ES6新方法去重

    const unique = (ary) => [...new Set(ary)];
    复制代码

十三、扩展数组原型(不建议直接扩展)

  • 1、查看数组本来的方法属性console.dir(Array.prototype)

  • 2、自己重写数组的forEach方法

    Array.prototype.myForEach = function (fn) {
    	for (let [index, item] of this.entries()) {
    		fn(item, index, this);
    	}
    };
    [1, 2, 3, 5].myForEach((item, index ,ary) => {
    	console.log(item, index, ary);
    })
    复制代码
  • 3、自己重写map方法

    Array.prototype.myMap = function (fn) {
    	let result = [];
    	for (let [index, item] of this.entries()) {
    		result.push(fn(item, index, this));
    	}
    	return result;
    };
    let result1 = [1,2,3,4].myMap((item, index, ary) => {
    	return item * 2;
    });
    
    console.log(result1);
    复制代码
  • 4、自己重写reduce方法

    Array.prototype.myReduce = function(fn, initVal) {
    	let total;
    	if (initVal != undefined) {
    		total = initVal;
    	} else {
    		total = this[0];
    	}
    	if (initVal === undefined) {
    		for (let i = 1; i < this.length; i++) {
    			total = fn(total, this[i], i, this);
    		}
    	} else {
    		for (let [index, val] of this.entries()) {
    			total = fn(total, val, index, this);
    		}
    	}
    	return total;
    };
    
    let result1 = [1, 2, 3, 4, 5].myReduce((total, currentVal) => {
    	return total + currentVal;
    });
    
    console.log(result1);
    复制代码
  • 5、判断一个数组是否包含在另外一个数组里面

    /**
     * 判断一个数组元素是不是在数组里面
     * @param obj
     * @returns {boolean}
     */
    Array.prototype.contains = function(obj) {
    	var i = this.length;
    	while(i--) {
    		if(this[i] === obj) {
    			return true;
    		}
    	}
    	return false;
    };
    复制代码
  • 6、如果自己喜欢可以把自己想要的方法放到原型上

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值