JSONArray创建后出现的额外数字

时间:2013-01-01 17:32:08

标签: javascript json node.js arrays

我正在用javascript创建一个JSONArray,我的新数组发生了一些奇怪的事情:

var arrayfinal = new Array();

//Order array by elements
function SortByPuntuation(x,y) {
   return x.puntuation - y.puntuation; 
}

for (var i = data.length - 1; i >= 0; i--) {
    if(arrayfinal){
        arrayfinal[i] = arrayfinal.push({'cathegory':data[i].cname , 'puntuation' : 2 * data[i].cnumber + data[i].click});
    }
    else{
        arrayfinal[i] = {'cathegory':data[i].cname , 'puntuation' : 2 * data[i].cnumber + data[i].click };
    }
};

arrayfinal = arrayfinal.sort(SortByPuntuation);

数据是另一个数组:

{"cname":"Sillas","cnumber":0,"click":1},
{"cname":"Mesas","cnumber":0,"click":2},
{"cname":"Plastico diferente","cnumber":0,"click":0},
{"cname":"Vasos","cnumber":5,"click":7},
{"cname":"Ordenadores","cnumber":0,"click":2},
{"cname":"Envases cuadrados","cnumber":0,"click":0},
{"cname":"Envases redondos","cnumber":0,"click":0},
{"cname":"Teclados ordenador","cnumber":0,"click":0},
{"cname":"Film transparente","cnumber":0,"click":0},
{"cname":"Pantallas","cnumber":0,"click":1},
{"cname":"Papeles","cnumber":0,"click":2},
{"cname":"Otro","cnumber":0,"click":0},
{"cname":"Coches","cnumber":0,"click":9},
{"cname":"Libros","cnumber":0,"click":2},
{"cname":"Asus","cnumber":0,"click":1}

finalarray的结果是:

[ 29,
  { cathegory: 'Plastico diferente', puntuation: 0 },
  { cathegory: 'Envases cuadrados', puntuation: 0 },
  { cathegory: 'Otro', puntuation: 0 },
  { cathegory: 'Envases redondos', puntuation: 0 },
  { cathegory: 'Film transparente', puntuation: 0 },
  { cathegory: 'Teclados ordenador', puntuation: 0 },
  22,
  21,
  20,
  19,
  18,
  17,
  16,
  28,
  { cathegory: 'Sillas', puntuation: 1 },
  27,
  26,
  25,
  { cathegory: 'Pantallas', puntuation: 1 },
  24,
  23,
  { cathegory: 'Papeles', puntuation: 2 },
  { cathegory: 'Ordenadores', puntuation: 2 },
  { cathegory: 'Libros', puntuation: 2 },
  { cathegory: 'Mesas', puntuation: 2 },
  { cathegory: 'Coches', puntuation: 9 },
  { cathegory: 'Vasos', puntuation: 17 },
  1 ]

finalarray中出现的数字来自哪里?

2 个答案:

答案 0 :(得分:2)

这是因为您要将push(这是新长度)的结果分配给arrayfinal[i]

更改

arrayfinal[i] = arrayfinal.push({'cathegory':data[i].cname , 'puntuation' : 2 * data[i].cnumber + data[i].click});

arrayfinal.push({'cathegory':data[i].cname , 'puntuation' : 2 * data[i].cnumber + data[i].click});

答案 1 :(得分:1)

您的代码通常可以通过初始化数组来工作,使用正向循环并将每个元素推送到数组。

var arrayfinal = [];
for(var i = 0; i < data.length; i++) {
    arrayfinal.push({
      'cathegory':data[i].cname ,
      'puntuation' : 2 * data[i].cnumber + data[i].click
    });
};

通过混合数组查找和Array#push来避免您创建的问题:

arrayfinal[i] = arrayfinal.push(...);

在元素添加到数组后返回数组的新长度。


或者,您可以使用Array#map

var arrayfinal = data.map(function(category){
  return {
    'cathegory': category.cname,
    'puntuation': 2 * category.cnumber + category.click
  };
});