AABB
AlignmentBehavior
ArriveBehavior
AStar
BFS
BoundingSphere
BVH
BVHNode
Cell
CellSpacePartitioning
CohesionBehavior
CompositeGoal
ConvexHull
Corridor
CostTable
DFS
Dijkstra
Edge
EntityManager
EvadeBehavior
EventDispatcher
Behavior
FollowPathBehavior
FuzzyAND
FuzzyCompositeTerm
FuzzyFAIRLY
FuzzyModule
FuzzyOR
FuzzyRule
FuzzySet
FuzzyTerm
FuzzyVariable
FuzzyVERY
GameEntity
Goal
GoalEvaluator
Graph
GraphUtils
HalfEdge
HeuristicPolicyDijkstra
HeuristicPolicyEuclid
HeuristicPolicyEuclidSquared
HeuristicPolicyManhattan
InterposeBehavior
LeftSCurveFuzzySet
LeftShoulderFuzzySet
LineSegment
Logger
MathUtils
Matrix3
Matrix4
MemoryRecord
MemorySystem
MeshGeometry
MessageDispatcher
MovingEntity
NavEdge
NavMesh
NavMeshLoader
NavNode
Node
NormalDistFuzzySet
OBB
ObstacleAvoidanceBehavior
OffsetPursuitBehavior
OnPathBehavior
Path
Plane
Polygon
Polyhedron
PriorityQueue
PursuitBehavior
Quaternion
Ray
RectangleTriggerRegion
Regular
RightSCurveFuzzySet
RightShoulderFuzzySet
SAT
SeekBehavior
SeparationBehavior
SingletonFuzzySet
Smoother
SphericalTriggerRegion
State
StateMachine
SteeringBehavior
SteeringManager
Task
TaskQueue
Telegram
Think
Time
TriangularFuzzySet
Trigger
TriggerRegion
Vector3
Vehicle
Version
WanderBehavior

source

介绍

source是Yuka js库中的一部分,它提供了一些用于遍历对象树的函数。

API

depthFirstSearch(root, visitor)

depthFirstSearch函数通过深度优先遍历来遍历对象树。root参数是要遍历的对象,visitor参数是一个函数,用来处理遍历时访问到的每个节点。

visitor函数的三个参数分别为:

  • node: 当前访问到的节点
  • parent: 当前节点的父节点
  • depth: 当前节点的深度

例如:

const object = {
  a: {
    b: {
      c: {
        d: 'Hello World!'
      }
    }
  }
};

function visitor(node, parent, depth) {
  console.log('Node:', node, 'Parent:', parent, 'Depth:', depth);
}

depthFirstSearch(object, visitor);

运行结果为:

Node: { b: { c: { d: 'Hello World!' } } } Parent: { a: { b: { c: { d: 'Hello World!' } } } } Depth: 1
Node: { c: { d: 'Hello World!' } } Parent: { b: { c: { d: 'Hello World!' } } } Depth: 2
Node: { d: 'Hello World!' } Parent: { c: { d: 'Hello World!' } } Depth: 3

breadthFirstSearch(root, visitor)

breadthFirstSearch函数通过广度优先遍历来遍历对象树。root参数是要遍历的对象,visitor参数是一个函数,用来处理遍历时访问到的每个节点。与depthFirstSearch函数不同的是,breadthFirstSearch函数返回一个Promise对象,在遍历完成后会resolve该对象。

visitor函数的三个参数同样为:

  • node: 当前访问到的节点
  • parent: 当前节点的父节点
  • depth: 当前节点的深度

例如:

const object = {
  a: {
    b: {
      c: {
        d: 'Hello World!'
      }
    }
  }
};

function visitor(node, parent, depth) {
  console.log('Node:', node, 'Parent:', parent, 'Depth:', depth);
}

breadthFirstSearch(object, visitor).then(() => {
  console.log('Traversal done!');
});

运行结果为:

Node: { a: { b: { c: { d: 'Hello World!' } } } } Parent: null Depth: 0
Node: { b: { c: { d: 'Hello World!' } } } Parent: { a: { b: { c: { d: 'Hello World!' } } } } Depth: 1
Node: { c: { d: 'Hello World!' } } Parent: { b: { c: { d: 'Hello World!' } } } Depth: 2
Node: { d: 'Hello World!' } Parent: { c: { d: 'Hello World!' } } Depth: 3
Traversal done!

结语

source提供了两种遍历对象树的方式,分别是深度优先遍历和广度优先遍历。通过这些函数,我们可以方便地遍历一个对象及其嵌套的子对象,并对每个节点进行处理。