假设我有这个数组:

[1, 2, 2, 3, 3, 3, 4]

如何返回一个数组/对象,该数组/对象包含一个值出现的次数,如:
{1:1, 2:2:, 3:3, 4:1}

以下是我目前掌握的情况:
// sort first
arr.sort();

for (var i = 0, l = arr.length, i < l, i++) {
    // what should go here ????
}

最佳答案

// Our results will be loaded into cont
var cont = {};

// For each number in our value array
for ( var i = 0; i < vals.length; i++ ) {
   // If it's found in the result array
   cont[ vals[i] ]
     // Increment it
     ? cont[ vals[i] ]++
     // Else, set it to 1
     : cont[ vals[i] ] = 1 ;
}

可以使用while循环和变量赋值使之更加简单:
var vals = [1, 2, 2, 3, 3, 3, 4], // Values to cycle through
    cont = {},                    // Object to store results in
    indx = i = -1;                // Index and Counting variables

while ( indx = vals[ ++i ] )      // While a value exists for location i
  cont[ indx ]                    // Check to see if it's in the result object
    ? cont[ indx ]++              // If it is, increment it
    : cont[ indx ] = 1 ;          // If it is not, set it to 1

10-01 06:43
查看更多