2

我正在使用 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 中出现的数字是从哪里来的?

4

2 回答 2

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});
于 2013-01-01T17:39:56.830 回答
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
  };
});
于 2013-01-01T17:46:32.610 回答