80后奔三ing 发表于 2012-7-23 22:04:08

JS数组也是引用传递么??

今天在从JS数组里随机读取不重复的数据的时候,遇到一个问题,就是当复制数组里面的数组元素被移空了以后,就从原数据再重新赋值给复制数组。可是在移除数组元素时,原数组和复制数组里的数组元素都在同时被移除。




var data =[];
var temp_data = '';
        data.push({'id':10,'title':10,'pic_url':'http://p.qpic.cn/act3/1/659f5b9f6415ce913b2cadf780efa427.jpg/140','act':0});
        data.push({'id':9,'title':9,'pic_url':'http://p.qpic.cn/act3/1/8004699e7d3d0e7dcb6f5020f4e019b8.jpg/140','act':0});
        data.push({'id':8,'title':8,'pic_url':'http://p.qpic.cn/act3/1/b34d590ea9dc7ddb874d30659921ac38.jpg/140','act':0});
        data.push({'id':7,'title':7,'pic_url':'http://p.qpic.cn/act3/1/449905f95658bed28c854496380329fd.jpg/140','act':0});
        data.push({'id':6,'title':6,'pic_url':'http://p.qpic.cn/act3/1/dfad3a51ef8e7d6f8a4424f495c572f1.jpg/140','act':0});
        data.push({'id':5,'title':5,'pic_url':'http://p.qpic.cn/act3/1/2095cbfde3ad11db6989b6fe2c6c0d99.jpg/140','act':0});
        data.push({'id':4,'title':4,'pic_url':'http://p.qpic.cn/act3/1/39108a3d76c410ece82d2380a9e3399c.jpg/140','act':0});
        data.push({'id':3,'title':3,'pic_url':'http://p.qpic.cn/act3/1/6f0f9187a43bc1cdbd1bb0866b82259c.jpg/140','act':0});
        data.push({'id':2,'title':2,'pic_url':'http://p.qpic.cn/act3/1/c61c8779fb23fcd0b84910c272afc010.jpg/140','act':0});
        data.push({'id':1,'title':1,'pic_url':'http://p.qpic.cn/act3/1/21690a2d20485db946ee1fe80e5edab0.jpg/140','act':0});


var temp_array = data;

function getArrayItems(temp_arr,num){
        /*var temp_arr = [];
        for(var index in data){
                temp_arr = data_array;//不想在这里构造复制数据,是担心当数组很大的时候,每次随机取出数组都要这样执行一次,耗损时间。
        }*/

        var return_array= new Array();
       
        for(var i = 0;i < num;i++){
                if(temp_arr.length > 0){
                        var arr_index = Math.floor(Math.random()*temp_arr.length);
                        return_array = temp_arr;
                        temp_arr.splice(arr_index, 1);
                }else{
                        break;
                }
        }

        return return_array;
}

function create_data(){

        temp_data = getArrayItems(temp_array,2);

        if(temp_data.length == 2){

                jQuery('.a').html('<h1>'+temp_data['title']+'</h1><img class="pic" src="'+temp_data['pic_url']+'" width="87" height="120" /><div id="vote_link_'+temp_data['id']+'" style="height:24px;font-weight:bold;"><input class="ho" type="button" value="ͶƱ"></div>');

                jQuery('.b').html('<h1>'+temp_data['title']+'</h1><img class="pic" src="'+temp_data['pic_url']+'" width="87" height="120" /><div id="vote_link_'+temp_data['id']+'" style="height:24px;font-weight:bold;"><input class="ho" type="button" value="ͶƱ"></div>');

        }else{
                //当temp_array的长度为0时,将data数组再次重新赋值给temp_array;然后再次调用create_data();
        }

}


80后奔三ing 发表于 2012-7-23 22:23:28

已经解决了

JS数组确实是按照类似PHP的引用传递。。。

temp_array = data.slice(0);这样就可以了

:lol
页: [1]
查看完整版本: JS数组也是引用传递么??