0

我想创建一个多维数组。可以说我想把这个变成两个:

{
        "fighters": [
            {
                "name": "Muhammad Ali",
                "nickname": "The Greatest",
                "image": "http://upload.wikimedia.org/wikipedia/commons/1/13/Clyde_The_Bulldog.jpg"
            },
            {
                "name": "Chuck Liddell",
                "nickname": "The Iceman",
                "image": "http://images.pictureshunt.com/pics/s/saint_bernard-12924.jpg"
            },
            {
                "name": "Rocky Marciano",
                "nickname": "The Brockton Blockbuster",
                "image": "http://www.goodhousekeeping.com/cm/goodhousekeeping/images/IO/alaskan-malamute-fb.jpg"
            },
            {
                "name": "Randy Couture",
                "nickname": "The Natural",
                "image": "http://slog.thestranger.com/files/2006/09/bigdog.jpg"
            },
            {
                "name": "Fedor Emelianenko",
                "nickname": "The Last Emperor",
                "image": "http://affordablehousinginstitute.org/blogs/us/wp-content/uploads/small_dog_on_big_dog.jpg"
            },
            {
                "name": "Jon Jones",
                "nickname": "Bones"
            },
            {
                "name": "George Foreman",
                "nickname": "Big George"
            },
            {
                "name": "Wanderlei Silva",
                "nickname": "The Axe Murderer"
            },
            {
                "name": "Gearges St. Pierre",
                "nickname": "Rush"
            },
            {
                "name": "Manny Pacquiao",
                "nickname": "Pac-Man"
            }
        ]
    } 

假设我想将前五个项目放入一个名为“dogs”的数组中,然后我想将其他五个项目放入一个名为“noDogs”的数组中。我该怎么做?

4

2 回答 2

1

假设 original_array 变量包含上面的数组,这将做你想要的:

var dogs = [];
var noDogs = [];    

for(var i=0; i<original_array.fighters.length; i++){
  var fighter = original_array.fighters[i];
  if(i<5){
    dogs.push(fighter);
  } else {
    noDogs.push(fighter);
  }  
}
于 2012-10-15T13:23:48.597 回答
1

另一种方法是使用此处记录的内置 javascriptslice()方法。

您的代码将如下所示:

var dogs = fighters.slice(0, 5); //Take items 0, 1, 2, 3, 4
var noDogs = fighters.slice(5, fighters.length) //Take items 5 onwards
于 2012-10-18T10:13:27.213 回答