Tree-structured data is often used in writing libraries, and some tree-structured data is very demanding from root to leaf paths. For example, the entire routing table of a site is such a tree, and its "path" is actually the path part of the URL. So I have a few times with a lunatic array of inheritance to achieve, below to share with you.
In JavaScript, an array is also part of Object, and it can also be inherited. Any two objects themselves can have inheritance relationships, and arrays are no exception. So we let any node of a tree be an array, and it only maintains the value of the element that is the largest of its own subscript. The values of other elements are inherited from ancestor nodes through prototype inheritance. This allows us to access the path from the root node on the leaf node as we would a generic array. Here's a simple implementation:
Run
<script>
//define node class
var tnode = function (value) {
This.push (value);
Tnode.prototype = [];
TNode.prototype.constructor = tnode;
TNode.prototype.createChild = function (value) {
var node = object.create (this);
Tnode.call (node, value);
return node;
};
Using nodes to create a simple tree
var root = new Tnode (' root ');
var a = Root.createchild (' a ');
var B = a.createchild (' b ');
The leaf node is treated as an array, and the path
document.write (B.join ('/')) is directly obtained; <!--root/a/b
</script>
This usage is rather dark magic, and it may be difficult to understand the principle of archetype inheritance. So if just as a library implementation might be able to write this (I've used it many times, it turns out that there is no pit), but directly in the business code if this is used, it may be spit to death. Although this usage does not violate the core idea of JavaScript as a language. A feature of the
is that an ancestor node's value is automatically synchronized to all child nodes when it is updated. Although prototype link access also has performance overhead, it is much faster than traversing the tree itself at the code level. Of course, if there is no such demand, just want to achieve a simple number or use the traditional way is better. After all, this is so dependent on language that it may be difficult to migrate to another programming language later.