JS:无法读取未定义的属性"排序" - 定义类函数的参数



我正在完成Twilioquest Javascript教程,最后的任务之一是构建一个带有一些函数的类。每次我跑这个我都会TypeError:无法读取未定义的属性"sort"。(在array.sort();(

class Ducktypium {
constructor(color) {
this.color = color;
if (color != 'red' || 'blue' || 'yellow' ){
throw error = ("Wrong color!");
}
}
calibrationSequence = [];
calibrate(input) {
let array = input;
let calibrationSorted = array.sort();
let calibrationMuliplied = calibrationSorted.forEach(item => {
item * 3;
});
return calibrationMuliplied
}
calibrationSequence = this.calibrate();
}
var dt = new Ducktypium('red');
dt.calibrate([3, 5, 1]);
console.log(dt.calibrationSequence); // prints [3, 9, 15]

Error位于类的calibrate((函数处。可能会有更多的错误,但我专注于控制台向我抛出的错误。我检查了类似的问题,认为我理解这个问题,但它们的背景不同,我就是无法解决。

据我所知,array没有接收到我试图通过dt.calibrate([3, 5, 15]);传递的值,因此.sort()函数不适用于任何内容。但是这个代码看起来和其他尝试类似,所以我就是找不到问题。

以下是带有详细解释的正确代码

class Ducktypium {
constructor(color) {
this.color = color;
// && means AND while || means OR
// You have to be specific with your conditions and the if statement
// only runs when the condition provided is met
if (color != 'red' && color != 'blue' && color != 'yellow' ) {
throw Error("Wrong color!");  // You throw an Error object
}
}
// calibrationSequence = [];
calibrate(input) {
let array = input;
let calibrationSorted = array.sort();
// This line is wrong. forEach loops through the items in your array and pass that item into a function but doesn't return anything
// let calibrationMuliplied = calibrationSorted.forEach(item => {
//     item * 3;
// });
// What you intended was the map() function
// map() calls the function you provide on each item and modifies them in the array
let calibrationMultiplied = calibrationSorted.map((item) => {
return item * 3
});
// The difference between forEach and map is that
// Lets say you have a box of numbered balls
// in forEach you take out each ball and note the number multiplied by two and put the
// ball back
// in map you take out each ball and actually rewrite the number as its number multiplied
// by two and put it back in

return calibrationMultiplied
}
// You are calling the calibrate method without passing anything into "input"
// that's why sort() is called on nothing and you get an error
// calibrationSequence = this.calibrate();
}

您对"CCD_ 5";,请让它像下面的代码一样;CCD_ 6";这应该具有和条件(this.color !== 'red' && this.color !== 'blue' && this.color !== 'yellow' )

calibrationSequence = [];
calibrate(input) {
let array = input;
let calibrationSorted = array.sort();
let calibrationMuliplied = calibrationSorted.forEach(item => {
item * 3;
});
return calibrationMuliplied
}
calibrationSequence = this.calibrate;
}

最新更新