javascript - 遍历json模式?
问题描述
我创建了一个 json 模式,以这种格式表示岛屿地图以及它们之间的连接:
MAP:{ sky: [ 'valley' ],
valley: [ 'koopa' ],
mushroom: [ 'toad' ],
toad: [ 'koopa' ],
koopa: [],
twin: [ 'valley' ],
forest: [ 'twin' ] }
我有一个位置A和一个目的地B;知道地图中始终存在路径,我需要创建一个函数来查找地图中从 A 到 B 的路径吗?
我的代码:
Graph.prototype.getHimHome = function (position, destination, n){
const arr = this.adjList;
let isHome = false;
let path = [destination];
while( !isHome && n>0) {
for( el in arr) { // looping through the json schemma
arr[el].forEach( element => {
if(element === path[path.length - 1])//this means we're on the path;
{
path.push(el);
} else {
path.push(el);
}
})
} ;
if(path[path.length - 1] === position){
isHome = true;
}
n--;
}
console.log(path);
}
解决方案
推荐阅读
- html - Html:JavaScript:输入:razor:minRange 和 maxRange
- swift - 为什么在 Swift 中使用 AnyObject 时出现“valueForUndefinedKey”错误?
- django - Django:如果数据库中存在值,则将其作为变量从视图传递到模板
- php - 使用 PHP 将用户添加到数据库时遇到问题
- flutter - 如何实现 GeoLocator StreamController 并通过屏幕获取数据 - Flutter
- javascript - javascript上的.net mvc视图循环仅更新表中的第一行
- javascript - 使用 cookie 将 localStorage 项设置为过期 VS
- vuejs2 - 蚂蚁设计 Vue | 以表格上传 | 如何设置初始值
- python - 我如何访问另一个模型中与它有多对多关系的模型的属性(在 django 中)
- python - Databricks 作业找不到集群中导入的 python 库