JavaScript----- 列表练习题

增加一个向列表中插入元素的方法,该方法只在待插元素大于列表中的所有元素时才执 行插入操作。这里的大于有多重含义,对于数字,它是指数值上的大小;对于字母,它 是指在字母表中出现的先后顺序。

题目 分析  

1、一个向列表中插入元素的方法

2、只在待插元素大于列表中的所有元素时才执 行插入操作

3、大于的包括数字的大小字母先后顺序

思路 

1 、 获取列表数据  然后进行拷贝  排序 然后获取最后一个 对比 针对 字母

2、循环对比 针对数组

function maXpush(element) {
    let newList = JSON.parse(JSON.stringify(this.dataStore))// 深拷贝数据
    newList.sort() //排序
    if (typeof (element) == 'string') {
        if (element > newList[newList.length - 1]) {  // 获取排序完后的最后一个元素对比
            this.dataStore[this.listSize++] = element;
        }
    } else if (typeof (element) === 'number') {  // 数字
        print(element)
        for (let i = 0; i < newList.length; i++) { // 循环对比 然后插入
            if (newList[i] < element) {
                this.append(element)
                return true
            }
        }
    }
}
  1. 增加一个向列表中插入元素的方法,该方法只在待插元素小于列表中的所有元素时才执 行插入操作。

function minPush(element) {
    let newList = [] // 深拷贝数据
    for (let i = 0; i < this.dataStore.length; ++i) {
        if (typeof (this.dataStore[i]) == 'string') {
            newList.push(this.dataStore[i])
        }
    }
    newList.sort()
    if (typeof (element) == 'string') {
        if (element < newList[0]) {  // 获取排序完后的最后一个元素对比
            this.dataStore[this.listSize++] = element;
        }
    } else if (typeof (element) === 'number') {  // 数字
        print(element)
        for (let i = 0; i < newList.length; i++) { // 循环对比 然后插入
            if (newList[i] > element) {
                this.append(element)
                return true
            }
        }
    }
}

思路一样 过滤一下数组中的数字类型

猜你喜欢

转载自blog.csdn.net/wanghongpu9305/article/details/110129929