在添加时对数组项排序

Ordering array items while adding

本文关键字:排序 数组 添加      更新时间:2023-09-26

我得到了一个空数组

var empArr = [];

我正在创建多个base64 url字符串并将它们添加到上面的数组中。到目前为止一切顺利。我的问题是,而在添加这些url字符串在数组我怎么能订购他们的方式,我需要?

我用splice()。但是由于一些url字符串生成更快,这种方法似乎不起作用。

empArr.splice(i, 0, "Lychee"); // i = the position

这是一种方法来创建一个临时数组与i值,然后拼接当所有的基础64字符串完成?或者还有其他更有效的方法吗?

根据我的理解,你想在数组变量right中添加额外的填充。

你可以添加数组变量,如

//It will add at last
empArr.splice((empArr.length-1), 0, "Lychee");
//It will add at first
empArr.splice(0, 0, "Lychee");

这是一个非常基本的b树的例子;它可以做两件事:插入新数据,并按顺序提取数据。这应该是你箱子里需要的所有东西了。

function Tree() {					// CONSTRUCTOR
    var root = null;
    this.insert = function(item) {
        var newLeaf = new Leaf(item);			// CREATE NEW LEAF WITH DATA
        var branch, leaf = this.root;
        var before;
        while (leaf != null) {				// FIND PLACE IN TREE
            branch = leaf;
            before = newLeaf.comesBefore(leaf);
            if (before) leaf = branch.left
            else leaf = branch.right;
        }
        if (this.root == null) this.root = newLeaf	// FIRST LEAF IN EMPTY TREE
        else if (before) branch.left = new Leaf(item)	// ATTACH LEAF TO BRANCH
        else branch.right = new Leaf(item);
    }
    this.shift = function() {
        var branch = this.root, leaf = this.root;
        if (leaf == null) return null;			// EMPTY TREE
        while (leaf.left != null) {			// SEARCH LEFTMOST LEAF
            branch = leaf;
            leaf = branch.left;
        }
        if (leaf == this.root) this.root = leaf.right	// ROOT IS LEFTMOST
        else branch.left = leaf.right;			// BRANCH INHERITS RIGHT SIDE
        return leaf.item;
    }
    function Leaf(item) {				// CONSTRUCTOR
        this.item = item;
        this.left = null;
        this.right = null;
        this.comesBefore = function(other) {		// REPLACE BY REAL DATA COMPARISON
            return (this.item < other.item);
        }
    }
}
var t = new Tree();
t.insert("lychee");
t.insert("pomegranate");
t.insert("tangerine");
t.insert("banana");
t.insert("starfruit");
t.insert("grapefruit");
t.insert("apple");
while (result = t.shift()) console.log(result);