不满足条件时如何输出错误?

问题描述

我有一个 generaterandomArray 函数,如果参数不是数组,它应该停止函数执行并将错误输出到控制台,而不打印传递的参数。如果参数是一个数组,它应该继续。但是,上面的代码不起作用。

{{1}}

我尝试过 return; 来停止函数执行,但它不起作用。

解决方法

这是因为您使用错误的方法检查数组。您需要使用 Array.isArray(array) 来检查数组的变量类型。

编辑:您也可以使用 _.isArray(array) 方法检查 Lodash

,

这个问题的最佳解决方案是 throw new Error("one error") 就像所说的 blex。 但是如果你在有用户的时候停止执行你的程序,这对你没有好处……所以这就是为什么你应该使用 console.error("another error")

,

typeof array 是 Object 所以你需要使用这个 { Array.isArray(array) } 并抛出 new Error('Error Message');

,
<script>
function generateRandomArray(array){
if(typeof array != 'array'){
console.log("Uncaught typeError: the argument is not a array");
}
var storage = Math.floor(Math.random() * array.length);
return array[storage];
}
var arrayer = generateRandomArray('d');
console.log(arrayer );
</script>

如前所述,您正在尝试检查 javascript 数组中的 typeof 数组也属于对象,或者简而言之,数组也是对象,因此 typeof 数组将是“对象”,因此您可以检查 typeof 数组!=“对象”或您可以简单地使用将返回布尔值 true 或 false 的 Array.isArray() 函数。 希望你明白我的意思