for example, if there is a class whose parameters are invalid when declaring, you should not successfully create an instance but return null,. How to implement it?
in addition, there is another scenario. If I use Array.some to verify an array parameter, how can I make it stop and return null immediately?
// demo: https://7kk7xolr7j.codesandbox.io/
class Foo {
constructor(props) {
for (let item in props) {
try {
console.log(item);
if (item < 1) {
throw new Error(item + " is invalid");
}
} catch (e) {
console.error(e);
return;
// null
}
}
}
}
let testArrA = [1, 1, 1, 0, 0];
let testArrB = [1, 1, 1, 1];
const b = new Foo(testArrB);
const a = new Foo(testArrA);
console.log(b, a); // expected `Foo{} null` but get `Foo{} Foo{}`