如何将数组复制到数组

时间:2012-03-28 07:22:43

标签: javascript

var ce_info=[
{location:"inchannel",name:"Jae Jung",volume:"50",url:"img/jae.jpeg",group:1},
{location:"inchannel",name:"Houston",volume:"50",url:"img/houston.jpeg",group:1},
{location:"inchannel",name:"Jun kuriha..",volume:"50",url:"img/jun.jpeg",group:1},
{location:"inchannel",name:"Andrea Melle",volume:"50",url:"img/andrea.jpeg",group:0},
{location:"inchannel",name:"Tomoaki Ohi..",volume:"50",url:"img/ohira.jpeg",group:0},
{location:"inchannel",name:"Woosuk Cha..",volume:"50",url:"img/woosuk.jpeg",group:0},
{location:"inchannel",name:"Luca Rigaz..",volume:"50",url:"img/luca.jpeg",group:0},
{location:"inchannel",name:"SooIn Nam",volume:"50",url:"img/sooin.jpeg",group:0}
];
var inch_info=[{location:"ichat",name:"",volume:"50",url:""}];

for(i=0;i<ce_info.length;i++)
{   

    if(ce_info[i].location=="inchat")
    {       

        inch_info[inchat_count].name=ce_info[i].name;
        inch_info[inchat_count].url=ce_info[i].url;
        inchat_count++;

    }
}

我正在尝试将ce_info复制到inch_info。 它似乎不起作用。当我尝试将ce_info复制到inch_info时发生错误 有什么想法吗?

4 个答案:

答案 0 :(得分:4)

复制本机JS数组非常简单。使用Array.slice()方法创建数组的部分/全部副本。

var foo = ['a','b','c','d','e'];
var bar = foo.slice();

现在foo和bar是'a','b','c','d','e'的5个成员数组

答案 1 :(得分:2)

inchat_count似乎未初始化。

var inch_info=[{location:"icha",name:"",volume:"50",url:""}];
var inchat_count = 0; // You forgot this line!!
for(i=0;i<ce_info.length;i++)
{   

    if(ce_info[i].location=="inchat")
    {       

        inch_info[inchat_count].name=ce_info[i].name;
        inch_info[inchat_count].url=ce_info[i].url;
        inchat_count++;

    }
}

答案 2 :(得分:1)

您的代码中仍有一个typeO

var inch_info=[{location:"ichat",name:"",volume:"50",url:""}];

不应该位置而不是ichat?因为这是你在这一行中检查的内容

if(ce_info[i].location=="inchat")

此外,在ce_info中没有名为inchat的位置,因此不会执行此段代码的结果。但是,如果ce_info中的某个元素具有该位置,那么这将是您需要将位置和名称添加到inch_info数组的代码。

更改你的for循环:

for(var eElem in ce_info)
{   
    if(ce_info[eElem].location=="inchannel")
    {
        var temp = {};
        temp.name=ce_info[eElem].name;
        temp.url=ce_info[eElem].url;
        inch_info.push(temp);

    }
}

答案 3 :(得分:0)

使用jQuery您可以轻松实现:

See a working demo here

遵循jQuery代码可确保您没有by reference ce_info对象。

jQuery代码:

var inch_info= jQuery.extend(true, {}, ce_info);

alert("inch_info: before changing text: "+inch_info[0].location);

inch_info[0].location = "hello world"

alert("inch_info: after changing text: "+inch_info[0].location);
alert("ce_info: after changing text: "+ce_info[0].location);