大家好,我正在努力创建一个表达式来检查特定数组是否只包含指定类型值。下面是我的尝试:
const isArrayOfType = (arr, type) =>
arr.forEach((item) => typeof item == type) ? true : false;
const arr = [1, 2, 3];
const typ = 'number';
console.log(isArrayOfType(arr, typ));
主要目的是不在表达式中使用return。
forEach
不返回任何东西,我认为你正在寻找every
(和三元运算符是不必要的,因为它已经返回一个布尔值)
const isArrayOfType = (arr, type) =>
arr.every((item) => typeof item == type);
const arr = [1, 2, 3];
const typ = 'number';
console.log(isArrayOfType(arr, typ));
console.log(isArrayOfType(["one",2,3], typ));