js基础算法学习

person smartzeng    watch_later 2018-04-22 20:33:24
visibility 16421    class javascript,数组,算法    bookmark 分享

  1.  移除数组 arr 中的所有值与 item 相等的元素。不要直接修改数组 arr,结果返回新的数组

//递归实现
function remove(arr, item) {
    var newArr = arr.slice(0);
    if (newArr.indexOf(item) === -1) {
        return newArr;
    }
    newArr.splice(newArr.indexOf(item), 1)
    return remove(newArr, item);
}
//循环遍历实现
function remove1(arr, item) {
    var newArr = [];
    arr.forEach(function(e, index, arr){
        if(e !== item){
            newArr.push(e);
        }
    })
    return newArr;
}

2.直接在原数组上操作

function removeWithoutCopy(arr, item) {
    if (arr.indexOf(item) === -1) {
        return arr;
    }
    arr.splice(arr.indexOf(item), 1)
    return removeWithoutCopy(arr, item);
}

3. 查找数组中重复出现的数字

//不改变原数组
function duplicates(arr) {
    var newArr = [];
    arr.forEach(function(e, index){
        if ((arr.slice(index + 1)).indexOf(e) !== -1) {
            if (newArr.indexOf(e) === -1) {
                newArr.push(e);
            }
        }
    });
    return newArr;
}
//第二种方式
function duplicates1(arr) {
    var newArr = [];
    arr.forEach(function(e, index){
        if (arr.indexOf(e) !== arr.lastIndexOf(e) && newArr.indexOf(e) === -1) {
            newArr.push(e);
        }
    });
    return newArr;
}

4. 数组去重

function duplicates2(arr) {
    var newArr = [];
    arr.forEach(function(e, index){
        if (newArr.indexOf(e) === -1) {
            newArr.push(e);
        }
    });
    return newArr;
}

5. 在数组 arr 的 index 处添加元素 item。不要直接修改数组 arr,结果返回新的数组

function insert(arr, item, index) {
    var newArr = [];
    for (var key in arr) {
        if (key == index) {
            newArr.push(item);
            newArr.push(arr[key]);
        } else {
            newArr.push(arr[key]);
        }
    }
    return !newArr.length ? [item] : newArr;
}


//利用slice+concat
function insert1(arr, item, index) {
    return arr.slice(0,index).concat(item,arr.slice(index));
}
//利用concat +splice
function insert2(arr, item, index) {
    var newArr=arr.concat();
    newArr.splice(index,0,item);
    return newArr;
}
//利用slice+splice
function insert3(arr, item, index) {
    var newArr=arr.slice(0);
    newArr.splice(index,0,item);
    return newArr;
}
//利用push.apply+splice
function insert4(arr, item, index) {
    var newArr=[];
    [].push.apply(newArr, arr);
    newArr.splice(index,0,item);
    return newArr;
}
//普通的迭代拷贝
function insert5(arr, item, index) {
    var newArr=[];
    for(var i=0;i<arr.length;i++){
        newArr.push(arr[i]);
    }
    newArr.splice(index,0,item);
    return newArr;
}


评论区
评论列表
menu