常用js函数方法积累

这篇文章详细介绍了JavaScript中几个常用的数组方法,包括map()用于创建新数组,reduce()用于累加和处理数组元素,filter()用于过滤数组元素,find()查找数组中满足条件的元素,every()和some()用于检查所有或至少一个元素是否满足条件,以及includes()用于判断数组是否包含特定元素。这些方法在处理和操作数据时非常实用。
摘要由CSDN通过智能技术生成

常用js函数积累

参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array

map() 方法

  1. 语法
    arr.map(callback,thisValue)

  2. 解析

    • callback 函数
      执行数组中每个值的函数,包含3个参数 :
      1. item 数组元素的每一项
      2. index (当前元素在数组中的索引)
      3. array (调用数组)

    • thisValue
      thisValue 可以修改循环时候的 this 指向,默认是全局对象。

    • 注意事项
      a. map 生成一个新数组,当你不打算使用返回的新数组请用 forEach 或者 for-of 替代;使用 map 的时候,需要在回调函数中写上 return 。
      b. map() 不会改变原始数组,但是可以在回调中改变。
      c. 空数组不会调用 map 。

  3. 常用方法

/**
 * 1、做数据处理,返回新数组
 * */
let arr = [{name:'1',age:1},{name:'2',age:2}]
let ages = arr.map((item)=>{
	return item.age
})
console.log(ages)
// 输出 [1, 2]

/**
 * 使用 map 重新格式化数组中的对象
 * */
const kvArray = [
  { key: 1, value: 10 },
  { key: 2, value: 20 },
  { key: 3, value: 30 },
];
const reformattedArray = kvArray.map(({ key, value}) => ({ [key]: value }));
// reformattedArray 现在是 [{1: 10}, {2: 20}, {3: 30}],

// kvArray 依然是:
// [{key: 1, value: 10},
//  {key: 2, value: 20},
//  {key: 3, value: 30}]


/**
 * 2、
 * [1] 两数之和 (leetcode)
 * 输入:nums = [2,7,11,15], target = 9
 * 输出:[0,1]
 * 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 * map.has (该方法主要用来检查Map中是否存在具有制定键的元素)
 * Map.set()方法 为Map对象添加一个指定键(key)和值(value)的新元素
 * Map.get(key)方法 用来获取一个Map对象指定的元素,返回的是键所对应的值,如果不存在则会返回undefined
 * */
var sum = function(nums, target) {
    let map = new Map
    for(let i=0;i<nums.length;i++){
        let x=target-nums[i];
        if(map.has(x)){
            return([map.get(x),i])
        }
        map.set(nums[i],i)
    }
};

reduce()

  1. 语法:
    arr.reduce(callback,[initialValue])

  2. 解析

    • callback 函数
      执行数组中每个值的函数,包含四个参数
      1. previousValue 简写为 pre (上一次调用 callbackFn 时的返回值。在第一次调用时,若指定了初始值 initialValue,其值则为 initialValue,否则为数组索引为 0 的元素 array[0]。)
      2. currentValue 简写为 cur(数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1])
      3. index (数组中正在处理的元素的索引。若指定了初始值 initialValue,则起始索引号为 0,否则从索引 1 起始)
      4. array (调用 reduce 的数组)

    • initialValue
      初始化值: 作为第一次调用 callback 的第一个参数

  3. 常用方法

/** 数组求和 */
let arr = [1,2,3,4]
let sum = arr.reduce((pre,cur,i,arr)=>{
	consloe.log(pre,cur,i)
	return pre + cur
},0)
consloe.log(sum)
// 输出 10
let arr2 = [{name:'1',age:1},{name:'2',age:2}]
let ages = arr2.reduce((pre,cur,i,arr)=>{
	consloe.log(pre,cur,i)
	return cur.age + pre
},0)
consloe.log(ages)
// 输出 3

/** 去重 */
let arr3 = [1,2,3,4,4,1]
let newArr = arr3.reduce((pre,cur)=>{
    if(!pre.includes(cur)){
      return pre.concat(cur)
    }else{
      return pre
    }
},[])
console.log(newArr);
// 输出 [1, 2, 3, 4]

/** 二维数组转一维数组 */
let arr4 = [[0, 1], [2, 3], [4, 5]]
let newArr2 = arr4.reduce((pre,cur)=>{
    return pre.concat(cur)
},[])
console.log(newArr2); 
// 输出 [0, 1, 2, 3, 4, 5]

/** 多维转一 */
let arr5 = [[0, 1], [2, 3], [4,[5,6,7]]]
const newArr3 = function(arr){
   return arr.reduce((pre,cur)=>pre.concat(Array.isArray(cur)?newArr3(cur):cur),[])
}
console.log(newArr(arr5)); 
// 输出  [0, 1, 2, 3, 4, 5, 6, 7]

/** 计算数组中每个元素出现的次数 */
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
let nameNum = names.reduce((pre,cur)=>{
  if(cur in pre){
    pre[cur]++
  }else{
    pre[cur] = 1 
  }
  return pre
},{})
console.log(nameNum); 
//{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}

/**
 * 按属性对 object 分类
 * */
let people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})
}
let groupedPeople = groupBy(people, 'age')
// groupedPeople is:
// {
//   20: [
//     { name: 'Max', age: 20 },
//     { name: 'Jane', age: 20 }
//   ],
//   21: [{ name: 'Alice', age: 21 }]
// }

l1 = [1,0,3]
l2 = [0,2,1]
// 301+120 = 421
// [4,2,1]
function sun(l1.l2){
  var a,b;
  for (let i = l1.length-1; i < 0; i--) {
    a += String(l1[i]);
  }
  for (let i = l2.length-1; i < 0; i--) {
    b += String(l2[i]);
  }
  console.log("a: ",a)
  console.log("b: ",b)
  let sum = Number(a)+Number(b)
  console.log("sum: ",sum)
}

filter() 函数

filter用于对数组进行过滤。它创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素

  1. 语法: arr.filter(callback,thisValue)
  2. 解析
    • callback 函数
      执行数组中每个值的函数,包含3个参数
      1. currentValue 简写为 cur(数组中当前元素的值)
      2. index (当前元素在数组中的索引)
      3. array (调用 filter 的数组)

    • thisValue
      thisValue 可以修改循环时候的 this 指向,默认是全局对象。

    • 注意点
      a. filter()不会对空数组进行检测、不会改变原始数组

  3. 常用方法
// 过滤
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let res = nums.filter((num) => {
  return num > 5;
});
console.log(res);  
// [6, 7, 8, 9, 10]

/**
 * 判断数组里面是否存在某个值:
 * */
 var newarr = [14, 17, 18, 32, 33, 16, 40];
 newarr.filter(item => item.num==14); 
 //判断数组中是否有14
 console.log(newarr.filter(item => item.num==14)) //true
 
 /**
  * 去掉数组中的空字符串(不能包含空格)、undefined、null
  * */
var array = ['1','2',undefined, '3.png',undefined, 'a','',null,' ']
var newArray = array.filter(item => item)
console.log(newArray) //返回结果:['1','2', '3.png', 'a',' ']

//去掉数组中的空字符串的另一种方式
var array = ['1','2',undefined, '3.png', '', undefined, 'a', '  '];
let newArray=array.filter(i=>i && i.trim());     
// 注意:IE9以下的版本没有这个trim()方法
console.log(newArray);   //返回结果:['1','2', '3.png', 'a']

/**
 * 把对象数组a中的某个属性值取出来存到数组b中
 * */
var arrayA = [{name:"a",type:"letter"},{name:1,type:"digital"},{name:”c”,type:"letter"},{name:2,type:"digital"},];
var arrayB = arrayA.filter(function(array){   
	//对arrayA数组对象过滤如果array.type === "letter"就return出去, 再用一个变量接收
	return array.type === "letter"
});
console.log(arrayB); 
//输出结果:[{name:"a",type:"letter"},{name:”c”,type:"letter"},]

/**
 * filter()和find()结合使用,实现从数组中查找想要的元素
 * */
 projectDetail() {
	 if (this.value) {
		 return this.sourcedata.filter((item) => {      
			return [item.ProjectName, item.ProjectNewNo].find(
			 //通过item.ProjectName、item.ProjectNewNo来匹配是否是想要查找的元素            
			    (si) => {
					return si.indexOf(this.value) != -1;  //根据是否输入来匹配           
				}          
		    );        
		});      
	}     
	return this.sourcedata; //最后返回想要的元素的数组   
}

find() 函数

find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

  1. 语法: arr.find(callback,thisValue)

  2. 解析

    • callback 函数
      执行数组中每个值的函数,包含3个参数
      1.currentValue (数组中当前元素的值)
      2.index (当前元素在数组中的索引)
      3.array (调用 find 的数组)

    • thisValue
      执行回调时用作 this 的对象。

    • 注意点
      a. find 方法不会改变数组。

  3. 常用方法


/**
 * 用对象的属性查找数组里的对象:
 * */
const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];
const result = inventory.find(({ name }) => name === 'cherries');
console.log(result) // { name: 'cherries', quantity: 5 }
 
/**
 * filter()和find()结合使用,实现从数组中查找想要的元素
 * */
 projectDetail() {
	 if (this.value) {
		 return this.sourcedata.filter((item) => {      
			return [item.ProjectName, item.ProjectNewNo].find(
			 //通过item.ProjectName、item.ProjectNewNo来匹配是否是想要查找的元素            
			    (si) => {
					return si.indexOf(this.value) != -1;  //根据是否输入来匹配           
				}          
		    );        
		});      
	}     
	return this.sourcedata; //最后返回想要的元素的数组   
}

every() 函数

every() 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。
备注: 若收到一个空数组,此方法在任何情况下都会返回 true。

  1. 语法: arr.every(callback,thisArg)
  2. 解析
    • callback 函数
      执行数组中每个值的函数,包含3个参数
      1. element (数组中当前元素的值)
      2. index (当前元素在数组中的索引)
      3. array (调用 every 的当前数组)

    • thisArg
      执行 callback 时使用的 this 值。。

    • 注意点
      a. every 不会改变原数组。
      b. every 遍历的元素范围在第一次调用 callback 之前就已确定了。在调用 every 之后那些被删除的元素或从来未被赋值的元素将不会被访问到。
      c. every 和数学中的"所有"类似,当所有的元素都符合条件才会返回 true。正因如此,若传入一个空数组,无论如何都会返回 true。

  3. 常用方法
/**
 * 检测所有数组元素的大小
 * */
function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
// 箭头函数
[12, 5, 8, 130, 44].every(x => x >= 10); // false
[12, 54, 18, 130, 44].every(x => x >= 10); // true

some()函数

some() 方法测试数组中是不是至少有 1 个元素通过了被提供的函数测试。它返回的是一个 Boolean 类型的值。
如果用一个空数组进行测试,在任何情况下它返回的都是false。

  1. 语法: arr.some(callback,thisArg)

  2. 解析

    • callback 函数
      执行数组中每个值的函数,包含3个参数
      1. element (数组中当前元素的值)
      2. index (当前元素在数组中的索引)
      3. array (调用 some 的当前数组)

    • thisArg
      执行 callback 时使用的 this 值。。

    • 注意点
      a. some 不会改变原数组。
      b. some 遍历的元素范围在第一次调用 callback 之前就已确定了。在调用 some 之后那些被删除的元素或从来未被赋值的元素将不会被访问到。
      c. 如果用一个空数组进行测试,在任何情况下它返回的都是false。

  3. 常用方法

/**
 * 测试数组元素的值
 * */
function isBiggerThan10(element, index, array) {
  return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
// 箭头函数
[2, 5, 8, 1, 4].some(x => x > 10);  // false
[12, 5, 8, 1, 4].some(x => x > 10); // true


/**
 * 判断数组元素中是否存在某个值
 * */
var fruits = ['apple', 'banana', 'mango', 'guava'];
function checkAvailability(arr, val) {
  return arr.some(function(arrVal) {
    return val === arrVal;
  });
}
// 箭头函数
function checkAvailability1(arr, val) {
  return arr.some(arrVal => val === arrVal);
}
checkAvailability(fruits, 'kela');   // false
checkAvailability1(fruits, 'banana'); // true


/**
 * 将任意值转换为布尔类型
 * */
var TRUTHY_VALUES = [true, 'true', 1];
function getBoolean(value) {
  'use strict';
  if (typeof value === 'string') {
    value = value.toLowerCase().trim();
  }
  return TRUTHY_VALUES.some(function(t) {
    return t === value;
  });
}
getBoolean(false);   // false
getBoolean('false'); // false
getBoolean(1);       // true
getBoolean('true');  // true

includes() 函数

includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。
使用 includes() 比较字符串和字符时是区分大小写的.

  1. 语法:
    includes(searchElement)
    includes(searchElement, fromIndex)

  2. 解析

    • searchElement: 需要查找的元素值。

    • fromIndex (可选值)
      从fromIndex 索引处开始查找 searchElement。
      如果为负值,则按升序从 array.length + fromIndex 的索引开始搜(即使从末尾开始往前跳 fromIndex 的绝对值个索引,然后往后搜寻)。
      默认为 0。

    • 注意点
      a. 0 的值将全部视为相等,与符号无关(即 -0 与 0 和 +0 相等),但 false 不被认为与 0 相等。
      b. 如果 fromIndex 大于等于数组的长度,则将直接返回 false,且不搜索该数组。
      c. 如果 fromIndex 为负值,计算出的索引将作为开始搜索searchElement的位置。如果计算出的索引小于 0,则整个数组都会被搜索。

  3. 常用方法

// 如果 fromIndex 大于等于数组的长度,则将直接返回 false,且不搜索该数组
var arr = ['a', 'b', 'c'];
arr.includes('c', 3);   // false
arr.includes('c', 100); // false
//  如果 fromIndex 为负值,计算出的索引将作为开始搜索searchElement的位置。如果计算出的索引小于 0,则整个数组都会被搜索。
arr.includes('a', -100); // true
arr.includes('a', -2); // false

var str = "I love JavaScript.";
var word = str.includes("javaScript"); // true

/**
 * 作为通用方法的 includes()
 * includes() 方法有意设计为通用方法。它不要求this值是数组对象,所以它可以被用于其他类型的对象 (比如类数组对象)
 * */
(function() {
  console.log([].includes.call(arguments, 'a')); // true
  console.log([].includes.call(arguments, 'd')); // false
})('a','b','c');

未完···

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值