About the basic usage of find in js

Array.prototype.find() is an array method in JavaScript, which is used to find a qualified element in an array. Once the first element that meets the conditions is found, find() will immediately return the value of this element, otherwise it will return undefined.

The following is the basic syntax of the find() method:

arr.find(callback(element[, index[, array]])[, thisArg])

Parameters:
callback: callback function, executed on each element of the array, accepting three parameters:

currentValue: The current element in the array being processed.
index (optional): The index of the current element in the array being processed.
array (optional): The array on which the find() method is called.
thisArg (optional): The object used as this when executing the callback.
Return value:
Returns the value of the first element in the array that satisfies the provided test function, otherwise returns undefined.

1. Use the currentValue parameter:

// 例子1:寻找数组中第一个大于10的元素
let array = [5, 12, 8, 130, 44];
/**
我们传给 find() 函数一个回调函数,该函数会对数组的每个元素进行测试。当找到第一个大于10的数时,find() 就立即返回这个数。
*/
let found = array.find(element => element > 10);

console.log(found,'-----------found'); // 输出: 12

Insert image description here
2. Use currentValue and index parameters

/**
例子2:除了检查元素是否大于10,我们还检查其索引是否大于2。因此,find() 返回的是第一个在索引大于2且值大于10的元素。
*/
var array2 = [5, 12, 8, 130, 44];

var found = array2.find(function(element, index) {
    
    
  return element > 10 && index > 2;
});

console.log(found); // 130

3. Use currentValue, index and arr parameters

/**
例子3:我们查找最后一个元素(索引等于数组长度减一)且该元素大于10的元素。因为44不满足条件,所以返回 undefined。
*/

var array3 = [5, 12, 8, 130, 44];

var found = array3.find(function(element, index, arr) {
    
    
  return element > 10 && index === arr.length - 1;
});

console.log(found); // undefined

4.Others

// 例子4:取出testData中与test对应的对象
const testData = ref([{
    
    
  id:1,
  name:'测试1'
},{
    
    
  id:2,
  name:'测试2'
},{
    
    
  id:3,
  name:'测试3'
},{
    
    
  id:4,
  name:'测试4'
},])

const test = ref(testData.value[0].id) // 1
const findTest = testData.value.find((item)=> item.id == test.value)

console.log(testData.value,'-----------testData');
console.log(test.value,'-----------test');//1
console.log(findTest,'-----------findTest'); // { id:1, name:'测试1' }

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_56733569/article/details/134571586