>  기사  >  웹 프론트엔드  >  es6에서 find()를 사용하는 방법

es6에서 find()를 사용하는 방법

青灯夜游
青灯夜游원래의
2022-10-28 19:20:502541검색

es6에서는 콜백 함수를 통해 배열에서 조건을 충족하는 첫 번째 요소의 값을 찾는 데 find()가 사용되며 구문은 "array.find(function(...),thisValue)"입니다. find()는 배열의 각 요소에 대해 함수 실행을 호출합니다. 조건을 테스트할 때 배열의 요소가 true를 반환하면 find()는 조건을 충족하는 요소를 반환하고 이후 값에 대해서는 실행 함수가 호출되지 않습니다. ; 일치하는 요소가 없으면 정의되지 않은 값이 반환됩니다.

es6에서 find()를 사용하는 방법

이 튜토리얼의 운영 환경: Windows 7 시스템, ECMAScript 버전 6, Dell G3 컴퓨터.

es6 find() 소개

find() 메서드는 테스트를 통과한 배열의 첫 번째 요소 값을 반환합니다(함수 내에서 판단).

find() 메서드는 배열의 각 요소에 대해 한 번씩 함수 실행을 호출합니다.

  • 조건을 테스트할 때 배열의 요소가 true를 반환하면 find()는 조건을 충족하는 요소와 후속 값을 반환합니다. ​​will not 그런 다음 실행 함수를 호출합니다.

  • 일치하는 요소가 없으면 정의되지 않은 값을 반환합니다.

구문:

array.find(function(currentValue, index, arr),thisValue)
Parameters Description
function(currentValue, index, arr) 필수입니다. 배열의 각 요소에 대해 실행되어야 하는 함수입니다.
함수 매개변수: 매개변수 설명 currentValue가 필요합니다. 현재 요소 인덱스는 선택 사항입니다. 현재 요소의 인덱스 값 arr은 선택 사항입니다. 현재 요소가 속한 배열 객체
thisValue 선택 사항입니다. 함수에 전달되는 값은 일반적으로 "this" 값을 사용합니다.
이 매개변수가 비어 있으면 "정의되지 않음"이 "this" 값으로 전달됩니다

返回值:返回符合测试条件的第一个数组元素值,如果没有符合条件的则返回 undefined。    

注意: 

  • find() 对于空数组,函数是不会执行的。

  • find() 并没有改变数组的原始值。

基本使用

Array.prototype.find
返回第一个满足条件的数组元素

const arr = [1, 2, 3, 4, 5];
const item = arr.find(function (item) {
  return item > 3;
});

console.log(item);//4

如果没有一个元素满足条件 返回undefined

const arr = [1, 2, 3, 4, 5];
const item = arr.find(function (item) {
  return item > 5;
});

console.log(item); //undefined

返回的元素和数组对应下标的元素是同一个引用

const arr = [
  {
    id: 1,
    name: '张三',
  },
  {
    id: 2,
    name: '李四',
  },
  {
    id: 3,
    name: '王五',
  },
];

const item = arr.find((item) => item.name === '李四');
console.log(item);

es6에서 find()를 사용하는 방법
回调函数的返回值是boolean 第一个返回true的对应数组元素作为find的返回值

const arr = [
  {
    id: 1,
    name: '张三',
  },
  {
    id: 2,
    name: '李四',
  },
  {
    id: 3,
    name: '王五',
  },
];
const item = arr.find(function (item) {
  return item.id > 1;
});
console.log(item);

es6에서 find()를 사용하는 방법

回调的参数

当前遍历的元素 当前遍历出的元素对应的下标 当前的数组

const arr = [
  {
    id: 1,
    name: '张三',
  },
  {
    id: 2,
    name: '李四',
  },
  {
    id: 3,
    name: '王五',
  },
];
const item = arr.find(function (item, index, arr) {
  console.log(item, index, arr);
});

es6에서 find()를 사용하는 방법

find的第二个参数

更改回调函数内部的this指向

const arr = [
  {
    id: 1,
    name: '张三',
  },
  {
    id: 2,
    name: '李四',
  },
  {
    id: 3,
    name: '王五',
  },
];
const item = arr.find(
  function (item, index, arr) {
    console.log(item, index, arr);
    console.log(this);
  },
  { a: 1 }
);

es6에서 find()를 사용하는 방법
如果没有第二个参数
非严格模式下 this -> window

const arr = [
  {
    id: 1,
    name: '张三',
  },
  {
    id: 2,
    name: '李四',
  },
  {
    id: 3,
    name: '王五',
  },
];
const item = arr.find(function (item, index, arr) {
  console.log(item, index, arr);
  console.log(this);
});

es6에서 find()를 사용하는 방법
在严格模式下
不传入第二个参数 this为undefined 与严格模式规定相同

'use strict';
const arr = [
  {
    id: 1,
    name: '张三',
  },
  {
    id: 2,
    name: '李四',
  },
  {
    id: 3,
    name: '王五',
  },
];
const item = arr.find(function (item, index, arr) {
  console.log(item, index, arr);
  console.log(this);
});

es6에서 find()를 사용하는 방법

稀疏数组find

find会遍历稀疏数组的空隙 empty
具体遍历出的值 由undefined占位

const arr = Array(5);
arr[0] = 1;
arr[2] = 3;
arr[4] = 5;
const item = arr.find(function (item) {
  console.log(item);
  return false;
});

es6에서 find()를 사용하는 방법
而ES5数组扩展方法forEach,map,filter,reduce,reduceRight,every,some 只会遍历有值的数组
find的遍历效率是低于ES5数组扩展方法的

find不会更改数组

虽然新增了元素 但是find会在第一次执行回调函数的时候 拿到这个数组最初的索引范围

const arr = [1, 2, 3, 4, 5];
const item = arr.find(function (item) {
  arr.push(6);
  console.log(item);
});
console.log(arr);

es6에서 find()를 사용하는 방법

const arr = [1, 2, 3, 4, 5];
const item = arr.find(function (item) {
  arr.splice(1, 1);
  console.log(item);
});
console.log(arr);

es6에서 find()를 사용하는 방법
splice 删除对应项 该项位置不保留 在数据最后补上undefined

const arr = [1, 2, 3, , , , 7, 8, 9];
arr.find(function (item, index) {
  if (index === 0) {
    arr.splice(1, 1);
  }
  console.log(item);
});

es6에서 find()를 사용하는 방법
delete
删除该项的值 并填入undefined

const arr = [1, 2, 3, , , , 7, 8, 9];
arr.find(function (item, index) {
  if (index === 0) {
    delete arr[2];
  }
  console.log(item);
});

es6에서 find()를 사용하는 방법
pop
删除该项的值 并填入undefined

const arr = [1, 2, 3, , , , 7, 8, 9];
arr.find(function (item, index) {
  if (index === 0) {
    arr.pop();
  }
  console.log(item);
});

es6에서 find()를 사용하는 방법

创建myFind

Array.prototype.myFind = function (cb) {
  if (this === null) {
    throw new TypeError('"this" is null');
  }
  if (typeof cb !== 'function') {
    throw new TypeError('Callback must be a function type');
  }
  var obj = Object(this),
    len = obj.length >>> 0,
    arg2 = arguments[1],
    step = 0;
  while (step <p>【相关推荐:<a href="https://www.php.cn/course/list/17.html" target="_blank" textvalue="javascript视频教程">javascript视频教程</a>、<a href="https://www.php.cn/course.html" target="_blank" textvalue="编程视频">编程视频</a>】</p>

위 내용은 es6에서 find()를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.