这可能是一个初学者级别的问题,但我在这里找不到答案。
我有一个像这样的函数原型:
function Car (name, brand) {
this.name = name;
this.brand = brand;
}
我有另一个从Car函数获取参数的函数。这里名称数组包含所有品牌的所有名称和品牌数组。现在我想返回一个Car对象数组,如" i3" :"宝马"," AMG GT" :" Marcedes"如果数组的长度不相等或为零,或者任何数组为空,则为每辆汽车的汽车信息或空数组。
function createCar(names, brands) {
}
这样做的主要目的是学习将数组从一个函数传递到另一个函数并将相关信息作为键值对返回。
答案 0 :(得分:1)
首先:
[{carName: "A8", carBrand:"Audi"}, ...]
)代码
您想要创建更多汽车,而不只是一辆汽车,因此请确保在您的代码中反映出来
function createCars
现在我们已经解决了这个问题,这是代码,注释了我们正在做的事情:
function createCars(names, brands) {
// before blindly checking if names or brands are of the same length
// check if names and brands are arrays in the first place
if (!(Array.isArray(names) && Array.isArray(brands)))
throw new Error("Please provide the 'names' and 'brands' array");
// do we have expected lengths?
if (names.length == 0 || brands.length == 0 || brands.length != names.length)
throw new Error("Please provide arrays of the same length, with at least one item");
// As you saw, I threw errors in case something went wrong. Doing that
// helped me to make sure that if we ever reach THIS line, then we have
// expected values. If something will go wrong, JS will stop the execution anyway
// Ok so all good. Next, since We'll return something
// let's reflect that in our code. Initialize with significant name:
var carsToReturn = [];
// Let's loop and create the cars for each element
for (var i = 0; i<names.length;i++){
carsToReturn.push(new Car(names[i], brands[i]));
}
// Done. Simple, right? :).
// All that's left is to return the cars
return carsToReturn;
}