不知道你的最終目標是什麼。有人可能會說一列是字符串如果的任何的值是一個字符串,並且數字只有在所有項是數字。
小心使用變量污染全局空間。通常你會限制在封閉的範圍內。
更多字符串或更多數字也必須考慮在計數等於案件。例如。五個數字和五個字符串。
下面可能是一個開始:
// Should be expanded to fully meet needs.
function isNumber(n) {
return !isNaN(n + 0) /* && varius */;
}
// Count types of data in column.
// Return array with one object for each column.
function arrTypeStat(ar) {
var type = [], i, j;
// Loop by column
for (i = 0; i < ar[0].length; ++i) {
// Type-stats for column 'i'
type[i] = {num: 0, str: 0};
// Loop rows for current column.
for (j = 1; j < ar.length; ++j) {
if (isNumber(ar[j][i]))
++type[i].num;
else
++type[i].str;
}
}
return type;
}
// Add a row after header with value equal to 'num' or 'str' depending
// on which type is most frequent. Favoring string if count is equal.
function arrAddColType(ar) {
var type = arrTypeStat(ar);
// Add new array as second item in 'ar'
// as in: add a new (empty) row. This is the row to be filled
// with data types.
ar.splice(1, 0, []);
// Note:
// Favour string over number if count is equal.
for (i = 0; i < type.length; ++i) {
ar[1][i] = type[i].num > type[i].str ? 'num' : 'str';
}
return ar;
}
Sample fiddle.使用控制檯,F12,查看測試結果。請注意,在此示例中,數字表示爲帶引號和不帶引號。
// Sample array.
var arrTest = [
['album','artist','price'],
[50,5,'50'],
[5,5,'5'],
['Lateralus', 'Tool', '13'],
['Ænima','Tool','12'],
['10,000 days','Tool',14]
];
// Test
var test = arrAddColType(arrTest);
// Log
console.log(
JSON.stringify(test)
.replace(/],\[/g, '],\n['));
產量:
[["album","artist","price"],
["str","str","num"],
[50,5,"50"],
[5,5,"5"],
["Lateralus","Tool","13"],
["Ænima","Tool","12"],
["10,000 days","Tool",14]]
我覺得你的描述是不夠的,知道你想做到完美的。請附上更多您想要的示例矩陣和結果數組。 – toshi
有一個'splice'功能,您可以刪除/添加特定索引上的項目。 ** [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)** –
我沒有得到您的數據與結果。什麼是每列50和5?他們是數據的一部分嗎?通過計算每種數據類型的總和,你的意思是什麼?你的意思是計數每列中的項目數量?你的*「結果陣列」*中的最大值等等? – user13500