假设我有一个包含多个字典的数组,如下所示:
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
这有什么原因吗?有没有办法让它与字典一起使用?
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