在 JavaScript 中检查一个数组是否只包含数字
Check if Array contains only Numbers in JavaScript
检查数组是否只包含数字:
- 使用该
Array.every()
方法遍历数组。 - 检查每个元素的类型是否为
number
. - 如果数组仅包含数字,则该
every()
方法将返回,否则返回。true
false
索引.js
const arr1 = [1, 2, 3]; const arr2 = [1, 2, 'three']; const arr3 = ['1', '2', '3']; function onlyNumbers(array) { return array.every(element => { return typeof element === 'number'; }); } console.log(onlyNumbers(arr1)); // 👉️ true console.log(onlyNumbers(arr2)); // 👉️ false console.log(onlyNumbers(arr3)); // 👉️ false
我们传递给
Array.every()
方法的函数会针对数组中的每个元素进行调用,直到它返回一个虚假值或遍历整个数组。
如果该函数返回一个假值,则该
every()
方法短路返回false
.在每次迭代中,我们检查元素是否具有类型number
并返回结果。
必须满足所有数组元素的条件,every()
方法才能返回true
。
如果您的数组包含可能属于 类型的数字string
,请改用以下方法。
索引.js
const arr1 = [1, 2, 3]; const arr2 = [1, 2, 'three']; const arr3 = ['1', '2', '3']; function onlyNumbers(array) { return array.every(element => { return !isNaN(element); }); } console.log(onlyNumbers(arr1)); // 👉️ true console.log(onlyNumbers(arr2)); // 👉️ false console.log(onlyNumbers(arr3)); // 👉️ true
我们使用
isNaN
函数来判断传入的值是否可以转换为数字。
索引.js
console.log(isNaN('test')); // 👉️ true console.log(isNaN('1')); // 👉️ false
一个简单的思考方法是:
- (
isNaN()
is Not a Number) 函数尝试将传入的元素转换为数字,true
如果不能则返回。 - 我们使用逻辑 NOT
!
运算符对结果求反,以检查数组中的所有元素是否都可以转换为数字。
You can also use a for...of
loop to check if an array contains only numbers.
Check if an array contains only numbers using a for...of
loop #
To check if an array contains only numbers:
- Use a
for...of
loop to iterate over the array. - Check if the type of each element is not equal to
number
. - If the condition is met, return
false
and exit the loop.
index.js
function onlyNumbers(array) { let containsOnlyNumbers = true; for (const element of array) { if (typeof element !== 'number') { containsOnlyNumbers = false; break; } } return containsOnlyNumbers; } const arr1 = [1, 2, 3]; const arr2 = [1, 2, 'three']; const arr3 = ['1', '2', '3']; console.log(onlyNumbers(arr1)); // 👉️ true console.log(onlyNumbers(arr2)); // 👉️ false console.log(onlyNumbers(arr3)); // 👉️ false
The
for…of
statement is used to loop over iterable objects like arrays, strings, Map
,
Set
and NodeList
objects and generators
.
On each iteration, we check if the current element doesn’t have a type of
number
.
如果满足条件,我们将containsOnlyNumbers
布尔值设置为false
并使用该break
语句退出for...of
循环。
该onlyNumbers()
函数接受一个数组,true
如果该数组仅包含数字则返回,false
否则返回。