JS 中常用的数组方法和实现

在处理数据的过程中,经常会涉及到数组的变换和处理,掌握常用的数组方法,对于我们平时写代码和面试都十分有用;

以下整理出几个使用率较高的几个方法以及实现方式:

目录

关于数组的判断  Array.isArray()

类数组对象转成数组 Array.from()

关于多个数组的连接 & 数组转换成字符串

关于查找符合条件的数组

关于符合条件数组的 index 查找

关于数组的遍历

关于数组的增删改

1、删除元素

2、添加元素

3、修改数组

关于数组的排序


关于数组的判断  Array.isArray()

// 用来判断一个对象是否为数组
var arr = [1,2,3];

console.log(Array.isArray(arr)); // true

该方法的实现:

Array.myIsArray = function(o){
    return Object.prototype.toString.call(Object(o) === '[Object Array]');
};

类数组对象转成数组 Array.from()

用于通过拥有length属性的对象或可迭代的对象来返回一个数组

// 返回新的数组实例,对于原始结构不影响
let arr1 = Array.from("foo");
console.log(arr1); // ["f","o","o"];

// 该方法有三个参数:
// 1. 接受一个类数组或可迭代对象
// 2. 新数组中每个元素都会执行的回调函数
// 3. 指定第二个参数的this对象
var arr = Array.from([1,2,3],x=>x*10);
// arr[0] = 10;
// arr[1] = 20;
// arr[2] = 30;

关于多个数组的连接 & 数组转换成字符串

Array.prototype.concat() 用于连接两个或多个数组,且不会改变现有数组

var arr1 = ["苹果","香蕉","橘子"];
var arr2 = ["梨","西瓜","火龙果"];
var arr = arr1.concat(arr2)
console.log(arr); // ["苹果","香蕉","橘子","梨","西瓜","火龙果"]

Array.prototype.join() 把数组的所有元素转换成一个字符串

var fruits = ["西瓜","哈密瓜","榴莲"];
 console.log(fruits.join()); // 西瓜,哈密瓜,榴莲

关于查找符合条件的数组

Array.prototype.every() 用于检测数值元素的所有元素是否都符合条件

语法:

array.every(function(currentValue,index,arr), thisValue)

  • 如果数组中检测到一个元素不满足条件,则整个返回 false,剩余元素就不会再进行检测
  • 不会对空数组进行检测,也不会改变原始数组

var ages = [33,56,16,28];
function checkAdult(ages){
    
    return ages >=18;
}
ages.every(checkAdult); // false

Array.prototype.some() 检测数组元素中是否有元素符合指定条件

语法:

array.some(function(currentValue,index,arr), thisValue)

  • 如果数组中检测到一个元素满足条件,则整个返回 true,剩余元素就不会再进行检测
  • 不会对空数组进行检测,也不会改变原始数组
var ages = [33,20,16,50];
function checkAdult(age){
	return age >= 18;
}
ages.some(checkAdult); // true

Array.prototype.filter() 用于检测数值元素,并返回符合条件的所有元素的数组

语法:

array.filter(function(currentValue,index,arr), thisValue)

  • 返回值是一个新数组
  • 不会对空数组进行检测,也不会改变原始数组
var ages = [33,20,16,50];
function checkAdult(age){
	return age >= 18;
}
ages.filter(checkAdult); // [33,20,50]

该方法的实现:

var ages = [33,20,16,50];

Array.prototype.myFilter = function(fn){
    var arr = [];

    for(var i=0;i<this.length;i++){
        
        if(fn(this[i],i)){
            arr.push(this[i])
        }
    }
    return arr;
}

var newArr = ages.myFilter(function(ele,index){

    if(ele >= 18){
        return true
    }else{
        return false
    }

})

console.log(newArr); // [33,20,50]

Array.prototype.find() 返回符合条件的第一个元素的值,剩余的就不会再检测

语法:

array.find(function(currentValue,index,arr), thisValue)

  • 不会对空数组进行检测,也不会改变原始数组
  • 没有符合条件的值就返回 undefined

Array.prototype.includes() 判断一个数组是否包含一个指定值,有就返回true,否则返回 false

语法:

array.includes(searchElement,fromIndex)

关于符合条件数组的 index 查找

Array.prototype.indexOf() 搜素数组中的元素,返回它所在的位置

  • 从头开始检索,找到 item 第一次出现的位置,返回它的索引值
  • 没有就返回-1
var fruits = ["西瓜","哈密瓜","哈密瓜","榴莲"];
console.log(fruits.indexOf("哈密瓜"));//1

Array.prototype.lastIndexOf() 返回指定内容最后出现的位置

  • 从后向前进行检索,找到 item 第一次出现的位置,返回它的索引值
  • 没有就返回-1
var fruits = ["西瓜","哈密瓜","哈密瓜","榴莲"];
console.log(fruits.lastIndexOf("哈密瓜")); //2

关于数组的遍历

Array.prototype.forEach() 遍历方法,对数组中的每个元素都执行一次回调函数,返回值是undefined

语法:

array.forEach(function(item,index,arr),thisArg)

  • 不会对空数组执行回调函数
  • 第二个参数,用来绑定 this
var arr = [4,9,16,25];
arr.forEach(function(item,index){
	console.log(item)
}); 


// forEach方法中的回调函数中的this就指向reporter
var reporter = {
    report: function(key, value) {
        console.log("Key: %s, Value: %s", key, value); 
    }
};
arr.forEach(function(value, key, map) { 
    this.report(key, value);
}, reporter);
// Key: 0, Value: 4
// Key: 1, Value: 9
// Key: 2, Value: 16
// Key: 3, Value: 25

该方法的实现:

Array.prototype.myForEach = function(fn){

    for(var i=0; i<this.length; i++){
        fn(this[i],i)
    }

}

arr.myForEach(function(item,index){

    console.log(item,index)

})

关于数组的增删改

1、删除元素

Array.prototype.pop() 删除数组的最后一个元素,并返回删除的元素

Array.prototype.shift() 删除数组的第一个元素,并返回删除的元素

// Array.prototype.pop()

var arr1 = [10,20,30,40];
var arr2 = arr1.pop();
console.log(arr1); // [10,20,30]
console.log(arr2); // 40


// Array.prototype.shift()
var arr1 = [10,20,30,40];
var arr2 = arr1.shift();
console.log(arr1); // [20,30,40]
console.log(arr2); // 10

2、添加元素

Array.prototype.push() 向数组末尾添加一个或多个元素,并返回新的长度

Array.prototype.unshift() 向数组开头添加一个或多个元素,并返回新的长度

// Array.prototype.push()
var arr1 = [10,20,30,40];
var arr2 = arr1.push(50);
console.log(arr1); // [10,20,30,40,50]
console.log(arr2); // 5



// Array.prototype.unshift()
var arr1 = [10,20,30,40];
var arr2 = arr1.unshift(50);
console.log(arr1); // [50,10,20,30,40]
console.log(arr2); // 5

3、修改数组

Array.prototype.reverse() 反转数组的元素顺序

Array.prototype.slice(start,end) 选取数组的一部分,并返回一个新数组

语法:

arr.slice(start,end) 

  • end ---不包含这个值
  • 不会改变原始数组

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var re = fruits.slice(1,3);
console.log(re); // ["Orange","Lemon"]

Array.prototype.splice(index,num,item) 从数组中添加或删除元素

语法:

arr.splice(index,num,item) 

  • 会改变原始数组
  • 该方法返回的是被删除元素组成的数组
  • item---要添加的新元素
var sites = ["Runoob","Google","Taobao"];
// 该方法返回的是被删除元素组成的数组
var re = sites.splice(2,1,"GGGGG");
console.log(sites); //["Runoob","Google","GGGGG"]
console.log(re); // ["Taobao"]



var sites = ["Runoob","Google","Taobao"];
// 该方法返回的是被删除元素组成的数组
var re = sites.splice(2,0,"GGGGG");
console.log(sites); //["Runoob","Google","GGGGG","Taobao"]
console.log(re); // []

关于数组的排序

Array.prototype.sort() 对数组的元素进行排序

// 该方法将改变原始数组
var points = [40,100,1,5,25,10];
points.sort(function(a,b){
	return a-b;
}); // 1,5,10,25,40,100 (升序排列)

// 也可以给字母排序
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // ["Apple","Banana","Mango","Orange"];

Array.prototype.reduce() 将数组元素计算为一个值

语法:

arr.reduce(function(pre,cur,index,arr),initialValue)

// 对于空数组不会执行回调函数的
// 接收一个函数作为累加器,对数组中的每个值进行累加计算
var num = [10,20,30,40,50];
var result = num.reduce(function(pre,cur){
	return pre + cur;
})
console.log(result); // 150

这个方法的实现:

Array.prototype.myReduce = function(callback, initialValue) {
  let accumulator = initialValue ? initialValue : this[0];
  for (let i = initialValue ? 0 : 1; i < this.length; i++) {
    let _this = this;
    accumulator = callback(accumulator, this[i], i, _this);
  }
  return accumulator;
};

Array.prototype.map(callback,[thisObject]) 通过指定函数处理数组的每个元素,并返回处理后的数组

// 返回一个新数组,新数组中的元素都是原始数组处理后的值
// 不会对空数组进行检测,也不会改变原始数组
var numbers = [4,9,16,25,36];
var newNum = numbers.map(Math.sqrt);
console.log(newNum); // [2,3,4,5,6]

var arr1 = [1,4,9,16];
const map1 = arr1.map(x=>{
// 只有当x=4时,才进行操作
	if(x == 4){
		return x*2;
	}
// 其他值时,就直接返回
	return x;
})
console.log(map1); // [1,8,9,16]

这个方法的实现:

Array.prototype.myMap = function(callback, thisArg) {
  let arr = [];
  for (let i = 0; i < this.length; i++) {
    arr.push(callback.call(thisArg, this[i], i, this));
  }
  return arr;
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值