Javascript - 如何使 array.includes 使用字典列表?

问题描述 投票:0回答:1

假设我有一个包含多个字典的数组,如下所示:

var coords = [{'x': 0, 'y': 0}, {'x': 2, 'y': 5}, {'x': 1, 'y': 6}]

我尝试在其上运行

array.includes
,它根本不起作用:

console.log( coords.includes({'x': 0, 'y': 0}) )
// Output : false

仅当我使用包含字典的数组时,它才会执行此操作。例如,这很好用:

var coords = ['0-0', '2-5', '1-6']
console.log( coords.includes('0-0') )
// Output : true

这有什么原因吗?有没有办法让它与字典一起使用?

javascript arrays dictionary include
1个回答
0
投票

您可以使用

JSON.stringify()
在数组中搜索字典。

我们可以首先在数组上使用

map()
并将所有元素转换为 JSON 字符串。

const coords = [{'x': 0, 'y': 0}, {'x': 2, 'y': 5}, {'x': 1, 'y': 6}]
.map(elm => JSON.stringify(elm));

这样做之后,搜索就非常简单了。

const target = {'x': 0, 'y': 0}; // object you're searching for
console.log(coords.includes(JSON.stringify(target))); // true
© www.soinside.com 2019 - 2024. All rights reserved.