检查数组是否仅包含 JavaScript 中的数字

在 JavaScript 中检查一个数组是否只包含数字

Check if Array contains only Numbers in JavaScript

检查数组是否只包含数字:

  1. 使用该Array.every()方法遍历数组。
  2. 检查每个元素的类型是否为number.
  3. 如果数组仅包含数字,则every()方法将返回,否则返回。truefalse
索引.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

一个简单的思考方法是:

  1. ( isNaN()is Not a Number) 函数尝试将传入的元素转换为数字,true如果不能则返回。
  2. 我们使用逻辑 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:

  1. Use a for...of loop to iterate over the array.
  2. Check if the type of each element is not equal to number.
  3. 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否则返回。