我有一个二维数组。我正在尝试计算内部数组中的值。我知道JS array.length
。但是做testData.length
会产生5.这是准确的。但是,我想计算每个子数组中的项目数。
testData[0].length
会产生6.但是我如何动态计算每个子数组? (因为它会改变)。
var testData = [["column1","test1","test1","tea","party", "water bottle"],
["column2","test2","test2","test2 test2"],
["column3","test2","test2","test2 test2 "],
["column4","test2","test2 test2f asdfsdf"],
["column5","test2","test2 test2f asdfsdfasdfasdfasa asda asdfsas"]
]
答案 0 :(得分:3)
使用Array.forEach
s=0;
testData.forEach(function(e,i,a){s += e.length; });
另请参阅:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
答案 1 :(得分:2)
使用reduce
:
ES6:
testData.reduce((count, row) => count + row.length, 0);
ES5:
testData.reduce(function(count, row) {
return count + row.length;
}, 0);
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
答案 2 :(得分:0)
var testData = [
["column1","test1","test1","tea","party", "water bottle"],
["column2","test2","test2","test2 test2"],
["column3","test2","test2","test2 test2 "],
["column4","test2","test2 test2f asdfsdf"],
["column5","test2","test2 test2f asdfsdfasdfasdfasa asda asdfsas"]
];
for(var i=0;i < testData.length;i++){
for(var j=0;j<testData[i].length;j++){
alert(testData[i][j]);
}
}
答案 3 :(得分:0)
尝试向Array对象添加新属性。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<title>New Property</title>
<script type="text/javascript" language="JavaScript">
Array.prototype.biLength = function(){
numItems = 0;
numRows = this.length;
for (var i = 0; i < numRows; i++){
row = testData[i];
numCols = row.length;
for (var j = 0; j < numCols; j++){
numItems++;
}
}
return numItems;
};
var testData = [
["column1","test1","test1","tea","party", "water bottle"],
["column2","test2","test2","test2 test2"],
["column3","test2","test2","test2 test2 "],
["column4","test2","test2 test2f asdfsdf"],
["column5","test2","test2 test2f asdfsdfasdfasdfasa asda asdfsas"]
];
alert(testData.biLength());
</script>
</head>
<body>
</body>
</html>