我正在尝试解决这个问题,我需要检查数组的每个元素是否具有相同的类型,我需要使用方法“every”来完成。但我不知道为什么我的代码不起作用,请你帮帮我好吗?谢谢
function allSameType(i) {
return (typeof i === typeof i[0]);
}
const c = [1, 2, 3];
const d = [1, 2, 3, "4"];
console.log(c.every(allSameType));
console.log(d.every(allSameType));
预期的输出应该是 True 和 False,但我得到的都是 False
最佳答案
您正在尝试访问作为数组传递到 allSameType
中的第一个元素,但它不是数组,而是数组的一个元素。
您可以将数组作为第三个参数传递给 allSameType()
函数,因为 Array.prototype.every
回调接受三个参数:
- 元素 (
i
) - 元素的索引(
_
) - 调用它的数组本身。 (
到达
)
function allSameType(i, _, arr) {
return (typeof i === typeof arr[0]);
}
const c = [1, 2, 3];
const d = [1, 2, 3, "4"];
console.log(c.every(allSameType));
console.log(d.every(allSameType));
关于javascript - 如何使这个工作?使用方法 "every"检查数组中所有相同类型的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58472484/