在代码中,我有:
house = ["red","blue","yellow"];
car = ["fast","big","safe"];
sofa = ["cozy","modern","elegant"];
如何计算并列出代码中的所有数组?
喜欢"我有多少个阵列?"
回答" 3阵列 - 房子,汽车,沙发"。
答案 0 :(得分:1)
根据您的代码和较少的代码行回答:
var house = ["red","blue","yellow"];
var car = ["fast","big","safe"];
var sofa = ["cozy","modern","elegant"];
var arrayCount = 0;
var arrayString = "";
for (var property in window) {
if (Array.isArray(window[property])){
arrayCount++;
arrayString += arrayCount > 1 ? ", " + property : property;
}
}
console.log(arrayCount + " arrays - " + arrayString);
上运行
答案 1 :(得分:0)
最简单的方法是将所有数组放在一个对象中
var items = require('../app/controllers/itemBackend');
app.get('/api/items/:itemId', items.getItem);
在此示例中, Arrays = {
house: ["red","blue","yellow"],
cars: ["fast","big","safe"],
sofa: ["cozy","modern","elegant"]
}
numberOfArrays = Object.keys(Arrays).length;
sentence = numberOfArrays + ' Arrays - ' + Object.keys(Arrays).join(', ');
将为sentence
答案 2 :(得分:0)
var arrayCount = 0;
for (var property in window) {
var obj = window[property];
if (Object.prototype.toString.call( obj ) === '[object Array]')
arrayCount++;
}
console.log(arrayCount);
编辑:最好不要在窗口对象上执行此操作,我在jsfiddle和jsbin上得到不同的结果。产品:>
答案 3 :(得分:0)
那很奇怪。您正在声明所有阵列。所以你总能知道答案。
但你可以在另一个数组包装器中声明它,如下所示:
var items = [["red","blue","yellow"],
["fast","big","safe"],
["cozy","modern","elegant"]];
然后,您可以通过访问此包装器items.length
来获取数组的数量。
答案 4 :(得分:0)
如果您有一组相关的数组,则应将它们放在对象中而不是全局命名空间中。然后,您可以调用该对象上的方法来获取有关数组的信息。
var MyArrays = {
house: ["red", "blue", "yellow"],
car: ["fast", "big", "safe"],
sofa: ["cozy", "modern", "elegant"]
};
function countArrays(obj){
var counter = 0;
for(var key in obj)
if(obj[key] instanceof Array)
counter++;
return counter;
}
function getArrayNames(obj){
var names = [];
for(var key in obj)
if(obj[key] instanceof Array)
names.push(key)
return names;
}
var info = "There are " + countArrays(MyArrays) + " arrays: " + getArrayNames(MyArrays).join(", ");