搜尋
首頁web前端前端問答es6中find()怎麼用

es6中find()怎麼用

Oct 28, 2022 pm 07:20 PM
javascriptes6

在es6中,find()用於透過回呼函數找出陣列中符合條件的第一個元素的值,語法「array.find(function(...),thisValue)」。 find()會為數組中的每個元素都呼叫一次函數執行,當數組中的元素在測試條件時傳回true時,find()傳回符合條件的該元素,之後的值不會再呼叫執行函數;如果沒有符合條件的元素回傳undefined。

es6中find()怎麼用

本教學操作環境:windows7系統、ECMAScript 6版、Dell G3電腦。

es6 find()的介紹

find() 方法傳回通過測試(函數內判​​斷)的陣列的第一個元素的值。

find() 方法為數組中的每個元素都呼叫一次函數執行:

  • #當數組中的元素在測試條件時傳回true 時, find( ) 傳回符合條件的元素,之後的值不會再呼叫執行函數。

  • 如果沒有符合條件的元素回傳undefined

#語法:

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


參數
#########function(currentValue, index,arr)#########必要。數組每個元素需要執行的函數。 ###函數參數:參數描述currentValue必要。當前元素index可選。目前元素的索引值arr可選。目前元素所屬的陣列物件###############thisValue##########可選。傳遞給函數的值一般用 "this" 值。 ###如果這個參數為空, "undefined" 會傳遞給 "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
CSS IDS vs類:哪個更適合可訪問性?CSS IDS vs類:哪個更適合可訪問性?May 10, 2025 am 12:02 AM

classebetterforaccoctibalyinwebdevelopment.1)classCanbeAppliedTomultiplelements,可確保ConsistentStentStyleSandLeSandBehaviors,woaidsuserserswithdisabilities.2)heSfacilitateTatheefariaTheeofariaAttributesCrossCroscrosproupscroscrosproupSoflementsperementsperients.3)

CSS:了解類和ID選擇器之間的區別CSS:了解類和ID選擇器之間的區別May 09, 2025 pm 06:13 PM

classSelectorSareReusable -ableFormultIlts,wheridSelectorSareectorSareEniqueAnduseNceperPage.1)class,deotedByDoperiod(。),areidealforStyealForStylingMultilestIllementsLikeButtons.2)IDS,DENOTEDBYBYAHASH(#),ASEPERFECTFORECTFORECTFORECTFORECTORFECTFOFECTFORUNICELELENSLIEMENTLIEMELLEMELLELEMENLELIKEANAVICEANAVICENU.3)

CSS樣式:在類和ID選擇器之間進行選擇CSS樣式:在類和ID選擇器之間進行選擇May 09, 2025 pm 06:09 PM

在CSS樣式中,應根據項目需求選擇類選擇器或ID選擇器:1)類選擇器適合重複使用,適用於多個元素的相同樣式;2)ID選擇器適用於唯一元素,具有更高優先級,但應謹慎使用以避免維護困難。

HTML5:限制HTML5:限制May 09, 2025 pm 05:57 PM

HTML5hasseverallimitationsincludinglackofsupportforadvancedgraphics,basicformvalidation,cross-browsercompatibilityissues,performanceimpacts,andsecurityconcerns.1)Forcomplexgraphics,HTML5'scanvasisinsufficient,requiringlibrarieslikeWebGLorThree.js.2)I

CSS:一種樣式比另一種樣式更優先嗎?CSS:一種樣式比另一種樣式更優先嗎?May 09, 2025 pm 05:33 PM

Yes,onestylecanhavemoreprioritythananotherinCSSduetospecificityandthecascade.1)Specificityactsasascoringsystemwheremorespecificselectorshavehigherpriority.2)Thecascadedeterminesstyleapplicationorder,withlaterrulesoverridingearlieronesofequalspecifici

HTML5規範的重要目標是什麼?HTML5規範的重要目標是什麼?May 09, 2025 pm 05:25 PM

thtml5 aretoenhancemultimultimeDiasupport,susehumanantability,susehumantability ofhtmllagalsemantability.1)

反應的局限性是什麼?反應的局限性是什麼?May 02, 2025 am 12:26 AM

Include:1)AsteeplearningCurvedUetoItsVasteCosystem,2)SeochallengesWithClient-SiderEndering,3)潛在的PersperformanceissuesInsuesInlArgeApplications,4)ComplexStateStateManagementAsappsgrow和5)TheneedtokeEedtokeEedtokeEppwithitsrapideDrapidevoltolution.thereedtokeEppectortorservolution.thereedthersrapidevolution.ththesefactorsshesssheou

React的學習曲線:新開發人員的挑戰React的學習曲線:新開發人員的挑戰May 02, 2025 am 12:24 AM

reactischallengingforbeginnersduetoitssteplearningcurveandparadigmshifttocoment oparchitecent.1)startwithofficialdocumentationforasolidFoundation.2)了解jsxandhowtoembedjavascriptwithinit.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)