找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索本站精品资源

首页 教程频道 查看内容

es6怎么判断元素是否在数组中

作者:模板之家 2022-4-19 19:14 97人关注

判断方法:1、用“arr.includes(值)”,如果返回true则存在;2、用“arr.find(function(v){if(v==值{//true}})”语句;3、用“arr.some(i=i===值)”,如果返回true则存在。

判断方法:1、用“arr.includes(值)”,如果返回true则存在;2、用“arr.find(function(v){if(v==值{//true}})”语句;3、用“arr.some(i=>i===值)”,如果返回true则存在。

本教程操作环境:windows7系统、ECMAScript 6版、Dell G3电脑。

在es6中,可以利用includes、find、some方法来判断元素是否在数组中。下面具体介绍一下。

方法1:使用es6的includes方法

includes() 方法用来判断一个数组是否包含一个指定的值,返回 true或 false。语法:

array.includes(searchElement, fromIndex);
  • searchElement:要查找的元素;

  • fromIndex:开始查找的索引位置。

示例:

arr = [1,2,3,4,5]
console.log(arr.includes(5));

1.png

可以看到,返回值为true,则表示元素5在数组中。

方法2:使用es6的find方法

find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。

find() 方法为数组中的每个元素都调用一次函数执行:

  • 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。

  • 如果没有符合条件的元素返回 undefined

示例:

var arr = [1,2,3,4,5]
arr.find(function(value){
	if(value==5){
		console.log("指定元素在数组中");
	}
})

2.png

方法3:使用es6的some方法

some() 方法用来检测数组中是否存在符合指定条件的元素,存在就返回 true,不存在就返回 false。

arr = [1,2,3,4,5];
let istrue= arr.some(item => item === 45);
console.log(istrue);

3.png

可以看到,返回值为false,则表示元素不在数组中。

【相关推荐:javascript视频教程、web前端】

以上就是es6怎么判断元素是否在数组中的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章!


路过

雷人

握手

鲜花

鸡蛋
来自: 网络收集

全部回复(0)