javascript - Best way to check if some coordinate is contained in an array (JavaScript)
问题描述
When dealing with arrays of coordinates, seen as arrays of length 2, it is necessary to check if some coordinate is contained in that array. However, JavaScript cannot really do that directly (here I use that ES2016 method Array.includes, but with the more classical Array.indexOf the same issue appears):
const a = [[1,2],[5,6]];
const find = a.includes([5,6]);
console.log(find);
This returns false. This has always bothered me. Can someone explain to me why it returns false? To solve this issue, I usually define a helper function:
function hasElement(arr,el) {
return arr.some(x => x[0] === el[0] && x[1] === el[1])
}
The inner condition here could also be replaced by x.toString() === el.toString()
. Then in the example above hasElement(a,[5,6])
returns true.
Is there a more elegant way to check the inclusion, preferably without writing helper functions?
解决方案
您可以使用JSON.stringify
方法将 javascript 对象或值转换为 JSON 字符串,然后对要搜索的数组执行相同操作,并检查主数组是否包含您要查找的数组。
const a = [[1,2],[5,6]], array = [5,6];
const find = JSON.stringify(a).includes(JSON.stringify(array));
console.log(find);
推荐阅读
- javascript - 如何让用户在警报javascript中进行选择
- javascript - 在 OOP 中将参数作为参数传递
- java - Transfer Manger to copy和s3Client中s3Client的copyObject函数之间的区别(java sdk)
- python - 如何在 Python 中实现排列组合公式?
- java - 使用数组在特定行中预订电影票
- reactjs - 如何在 Leaflet 中开发响应层容器?
- kubernetes - standard_init_linux.go:211: exec 用户进程导致“权限被拒绝”
- mysql - 如果记录来自另一个表的更新,MySQL如何创建触发器来推送数据
- sql-server - 如何解决 SQL 异常 0x80131904?
- python - "TypeError" when importing colour-science module in python