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>

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值