打印动物的最佳方式是什么,同时确保列出未来的动物而不更改代码?我的试训非常不成熟......
var animals = ["Cows", "Chickens", "Pigs", "Horses"];
var printFarm = function(a, b, c, d){
console.log("You have " + a + " " + animals[0]);
console.log("You have " + b + " " + animals[1]);
console.log("You have " + c + " " + animals[2]);
console.log("You have " + d + " " + animals[3]);
};
printFarm(3, 6, 17, 54);
答案 0 :(得分:1)
以下两种方式......
var animals = ["Cows", "Chickens", "Pigs", "Horses"];
function printFarm(arrAnimals) {
for (var i = 0; i < arrAnimals.length; i++) {
var animalGroup = arrAnimals[i];
var amount = printFarm.arguments[i + 1];
if (amount) {
console.log('You have ' + amount + ' ' + animalGroup + '.');
} else {
console.log('No amount was found for ' + animalGroup + '.');
}
}
}
printFarm(animals, 3, 6, 17, 54);
所以,你需要做的就是改变你的数组以包含一个新的动物,然后简单地将金额追加到printFarm函数调用的末尾,就像我上面所做的那样。或者,除了动物阵列之外,您还可以将一系列动物计数传递给该函数。
或者传递一组animalCount对象,这些对象具有动物的名称和计数作为对象的一部分。像这样......
var animals = [{ name:'cows', count:3 },
{ name:'chickens', count:6 },
{ name:'pigs', count:17 },
{ name:'horses', count:54 }];
function printFarm(arrAnimals) {
for (var i = 0; i < arrAnimals.length; i++) {
var animalGroup = arrAnimals[i];
var name = animalGroup.name;
var amount = animalGroup.count;
console.log('You have ' + amount + ' ' + name + '.');
}
}
printFarm(animals);
答案 1 :(得分:1)
为什么不将整数数组传递给函数,然后使用animals数组或整数数组中的最小项数进行循环?
var animals = ["Cows", "Chickens", "Pigs", "Horses"];
var printFarm = function(animalCounts) {
var index = Math.min(animals.length, animalCounts.length);
for (var i = 0; i < index; i++) {
console.log("You have " + animalCounts[i] + " " + animals[i];
}
}
printFarm([1,2,3,4]);
答案 2 :(得分:1)
更好的方法是创建一个Animal类并为每个所需的动物创建一个对象。这是一个粗略的例子,但显示了这个想法。
function Animal(type, count) {
this.type = type;
this.count = count;
this.print = function() {
console.log("You have " + this.count + " " + this.type);
}
}
可能更好的方法是动物基类,每个新的动物类型都添加了子类化,但这样就可以了。