Commonly used js function method accumulation

Commonly used js function accumulation

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

map() method

  1. Syntax
    arr.map(callback, thisValue)

  2. analyze

    • The callback function
      executes the function of each value in the array, including 3 parameters:
      1. item Each item of the array element
      2. index (the index of the current element in the array)
      3. array (calling the array)

    • thisValue
      thisValue can modify the this point when looping, and the default is the global object.

    • Notes
      a. map generates a new array, if you do not intend to use the returned new array, please use forEach or for-of instead; when using map, you need to write return in the callback function.
      b. map() will not change the original array, but can be changed in the callback.
      c. Empty arrays do not call map.

  3. common method

/**
 * 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. Syntax:
    arr.reduce(callback,[initialValue])

  2. analyze

    • 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
      initialization value: as the first parameter of calling callback for the first time

  3. common method

/** 数组求和 */
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() function

filter is used to filter the array. It creates a new array whose elements are checked by checking all elements in the specified array that meet the criteria

  1. Syntax: arr. filter(callback, thisValue)
  2. analyze
    • callback function
      A function that executes each value in the array, including 3 parameters
      1. currentValue is abbreviated as cur (the value of the current element in the array)
      2. index (the index of the current element in the array)
      3. array (the array that calls the filter)

    • thisValue
      thisValue can modify the this point when looping, and the default is the global object.

    • Note that
      a. filter() will not detect empty arrays and will not change the original array

  3. common method
// 过滤
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() function

The find() method returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined

  1. Syntax: arr. find(callback, thisValue)

  2. analyze

    • callback function
      Executes the function of each value in the array, including 3 parameters
      1.currentValue (the value of the current element in the array)
      2.index (the index of the current element in the array)
      3.array (the array that calls find)

    • thisValue
      The object used as this when executing the callback.

    • Note point
      a. The find method does not change the array.

  3. common method


/**
 * 用对象的属性查找数组里的对象:
 * */
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() function

The every() method tests whether all elements in an array pass the test of a specified function. It returns a boolean value.
Note: This method returns true in any case if an empty array is received.

  1. Syntax: arr.every(callback,thisArg)
  2. analyze
    • The callback function
      executes the function of each value in the array, including 3 parameters
      1. element (the value of the current element in the array)
      2. index (the index of the current element in the array)
      3. array (the current array that calls every)

    • thisArg
      The this value used when executing callback. .

    • Note point
      a. every will not change the original array.
      b. The range of elements traversed by every is determined before the callback is called for the first time. Elements that are deleted or never assigned a value after calling every will not be accessed.
      c. every is similar to "all" in mathematics, and returns true when all elements meet the conditions. Because of this, passing an empty array will return true no matter what.

  3. common method
/**
 * 检测所有数组元素的大小
 * */
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() function

The some() method tests whether at least 1 element in the array passes the provided function test. It returns a value of type Boolean.
If tested with an empty array, it returns false in all cases.

  1. Syntax: arr.some(callback,thisArg)

  2. analyze

    • The callback function
      executes the function of each value in the array, including 3 parameters
      1. element (the value of the current element in the array)
      2. index (the index of the current element in the array)
      3. array (the current array that calls some)

    • thisArg
      The this value used when executing callback. .

    • Note point
      a. some will not change the original array.
      b. The range of elements traversed by some is determined before the callback is called for the first time. Elements that are deleted or never assigned a value after calling some will not be accessed.
      c. If tested with an empty array, it returns false in all cases.

  3. common method

/**
 * 测试数组元素的值
 * */
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() function

The includes() method is used to determine whether an array contains a specified value. According to the situation, if it is included, it returns true, otherwise it returns false.
Comparing strings and characters using includes() is case-sensitive.

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

  2. analyze

    • searchElement: The element value to be searched.

    • fromIndex (optional)
      Start searching for the searchElement at the fromIndex index.
      If it is a negative value, start searching from the index of array.length + fromIndex in ascending order (even jump forward from the end to the absolute value of fromIndex index, and then search backward).
      The default is 0.

    • Note that
      the values ​​of point a. 0 are all considered equal regardless of sign (ie -0 is equal to 0 and +0), but false is not considered equal to 0.
      b. If fromIndex is greater than or equal to the length of the array, it will directly return false, and the array will not be searched.
      c. If fromIndex is negative, the calculated index will be used as the starting position to search for searchElement. If the calculated index is less than 0, the entire array is searched.

  3. common method

// 如果 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');

unfinished

Guess you like

Origin blog.csdn.net/weixin_44897255/article/details/129669371