JavaScript中includes在数组中使用时的注意点

JavaScript中的includes在数组中使用时的注意点❗

Array.prototype.includes(): includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。

语法:arr.includes(valueToFind[, fromIndex])

  • valueToFind: 需要查找的元素值。
  • fromIndex(可选):从fromIndex 索引处开始查找 valueToFind。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜 (即使从末尾开始往前跳 fromIndex 的绝对值个索引,然后往后搜寻)。默认为 0。
遇到的问题

上面只是简单的一个介绍,由于本人不是专业的前端,在开发是遇到这样一个问题:

let list = [
	{
		id: 1,
		name: "test1",
		age: 1
	},
	{
		id: 2,
		name: "test2",
		age: 2
	}
];
let item = {id:1,name:"test1",age:1};
console.log(list.includes(item));	//这里打印为false

上面就是我在使用它时候遇到的问题。明明是相等的却不相等,经过查询在下面这篇文章中找到了答案:
https://www.it1352.com/1882304.html
上面的问题是由于item和list中的第一个元素虽然内容相同,但它们不是同一个对象,所以会返回false。下面的代码会返回true:

let list = [];
let item1 = {id:1,name: 'test1',age: 23}
let item2	 = {id:2,name: 'test2',age: 24}
list.push(item1);
list.push(item2);
console.log(list.includes(item1));		//打印为true
总结

Array.includes()方法在进行使用时参数需要是该数组中的子元素,也就是它们是同一个对象。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
JavaScript,有多种方法可以实现数组去重。下面我会介绍几种常见的方法: 1. 使用 Set 数据结构:Set 是 ES6 新增的数据结构,它只存储唯一值。我们可以利用 Set 的特性,将数组转换为 Set,然后再将 Set 转换回数组即可实现去重。 ```javascript const array = [1, 2, 2, 3, 3, 4, 5, 5]; const uniqueArray = Array.from(new Set(array)); console.log(uniqueArray); // [1, 2, 3, 4, 5] ``` 2. 使用 indexOf() 方法:遍历原始数组,利用 indexOf() 方法检查当前元素在数组中的索引位置,如果索引位置与当前遍历的索引位置不一致,则说明该元素是重复的,可以忽略。 ```javascript const array = [1, 2, 2, 3, 3, 4, 5, 5]; const uniqueArray = array.filter((value, index) => { return array.indexOf(value) === index; }); console.log(uniqueArray); // [1, 2, 3, 4, 5] ``` 3. 使用 includes() 方法:类似于 indexOf() 方法,遍历原始数组,利用 includes() 方法检查当前元素是否已经存在于新数组中,如果不存在,则将该元素添加到新数组中。 ```javascript const array = [1, 2, 2, 3, 3, 4, 5, 5]; const uniqueArray = []; array.forEach((value) => { if (!uniqueArray.includes(value)) { uniqueArray.push(value); } }); console.log(uniqueArray); // [1, 2, 3, 4, 5] ``` 这些方法都可以实现数组去重,具体使用哪种方法取决于个人偏好和需求。需要注意的是,使用 Set 的方法在保留元素顺序方面可能会有些差异,而使用 indexOf() 或 includes() 方法可以保持原始数组的顺序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@胡海龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值