JS改变数组中某元素位置的函数

20121101更新:
atrl同学给出了一行代码的实现,很漂亮:

[].splice.apply(arr, [].concat.apply([ toPos ,0], arr.splice(pos,1) ) );

 

———————–

搞重构JS写得少了,jQuery很不熟,不知道有没有预设的这个方法,只好自己先写了个。

function changeArrayItemPos(arr, pos, toPos){
    //目标索引溢出修复下
    toPos = Math.min(Math.max(0, toPos), arr.length - 1);
    //待换索引溢出或与目标索引相同,则不做处理
    if(pos === toPos || pos < 0 || pos > arr.length - 1){ 
        return [].concat(arr);
    }
    
    var _arr = [], after = pos > toPos;
    for(var i = 0, len = arr.length; i < len ; i++){
        //待换索引直接pass
        if(i === pos){
            continue;
        }else{
            if(i === toPos){
                //目标索引与待换索引前后位置有关系
                if(after){
                    _arr.push(arr[pos]);
                    _arr.push(arr[i]);
                }else{
                    _arr.push(arr[i]);
                    _arr.push(arr[pos]);
                }   
            }else{
                _arr.push(arr[i]);
            }
        }
    }
    return _arr;
}

 

 

posted @ 2012-10-25 21:17  猫哥_kaiye  阅读(2231)  评论(0编辑  收藏  举报