Javascript 如何在类构造函数中设置限制?
Javascript 如何在类构造函数中设置限制?,javascript,ecmascript-6,Javascript,Ecmascript 6,Interpolation类的构造函数包含两个数组。如何设置限制,以便在创建对象期间,这两个数组的长度必须相等 class Interpolation { constructor (x, fx) { if ( x instanceof Array && fx instanceof Array ) { if ( x.length === fx.length ) { this.input = x;
Interpolation
类的构造函数包含两个数组。如何设置限制,以便在创建对象期间,这两个数组的长度必须相等
class Interpolation {
constructor (x, fx) {
if ( x instanceof Array && fx instanceof Array ) {
if ( x.length === fx.length ) {
this.input = x;
this.output = fx;
} else { throw 'Unmatching array' }
} else throw 'Please pass in array';
}
}
我尝试了这个,在创建对象的过程中,源代码也像这样打印在控制台上
C:\NeuralNetwork\interpolation.js:7
} else { throw('Invalid Array') }
^
Invalid Array
像这样:
class Interpolation {
constructor (x, fx) {
if(!(x instanceof Array)) {
throw('parameter `x` must be an Array.');
}
if(!(fx instanceof Array)) {
throw('parameter `fx` must be an Array,');
}
if(x.length !== fx.length) {
throw('the length of these two arrays(x, fx) must be equal');
}
this.input = x;
this.output = fx;
}
}
当数组长度不同时会发生什么情况?@gurvinder372抛出一个错误您已经在这样做了。您需要帮助的是什么?除此之外,您的代码似乎很好?@gurvinder372我的问题是错误在于显示的源代码似乎不整洁这是如何更好?