js使用List,在指定数据前面插入数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>列表</title>
</head>
<body>

</body>


<script>
    function List() {
        this.dataStore = [];
        this.append = function (data) {
            //根据当前数组的长度插入新的数据
            this.dataStore[this.length()] = data;
        }

        this.length = function () {
            //获得数组的长度
            var length = this.dataStore.length;
            return length;
        }

        //如果找到当前的数据,就返回当前数据的下标,如果没有找到数据就返回-1
        this.find = function (data) {
            //1,获得数组的长度
            var length = this.length();
            //2,设置返回数据的下标
            var index = -1;
            //3,遍历数据
            for (var i = 0; i < length; i++) {
                if (data == this.dataStore[i]) {
                    index = i;
                    return index;
                }
            }
            return index;
        }

        this.forEach = function (call) {
            //1,获得数组的长度
            var length = this.length();
            //2,遍历数据
            for (var i = 0; i < length; i++) {
                call(this.dataStore[i]);
            }
        }

        //在before前面插入数据,如果before有数据,就插入在before前面,如果before没有数据,就把data插入到最前面的数据
        this.insertBefore = function (data,before) {
            //1,找到当前before数据的下标
            var index = this.find(before);
            var length = this.length();
            if(index==-1) {
                for (var i = length - 1; i >= 0; i--) {
                    this.dataStore[i + 1] = this.dataStore[i]
                }
                this.dataStore[0] = data;
            }
            else {
                for (var i = length - 1; i >= index; i--) {
                    this.dataStore[i + 1] = this.dataStore[i]
                }
                this.dataStore[index] = data;
            }
        }
    }

    var list = new List();
    list.append(1);
    list.append(2);
    list.append(0);
    list.append(10);
    list.append(9);

    list.insertBefore("在2之前插入数据",2);

    list.forEach(function (data) {
        console.log(data);
    });


</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_34607371/article/details/81085575
今日推荐