JavaScript 如何将数字转换为数组

JavaScript 如何将数字转换为数组

给定一个数字,任务是使用JavaScript将给定的数字转换为数组。

示例:

Input: 235283
Output: [2, 3, 5, 2, 8, 3]

Input: 8998123
Output: [8, 9, 9, 8, 1, 2, 3]

Input: 1234567
Output: [1, 2, 3, 4, 5, 6, 7]

在本文中,我们将使用三种不同的方法将给定的数字转换成数组。

方法1:使用Array.from()方法

JavaScript的 Array from() 方法可以将具有length属性或可迭代对象的任何对象转换为数组对象。

语法:

Array.from(object, mapFunction, thisValue)

方法:

  1. 将一个数字存储在一个变量中。
  2. 使用Array.from()方法,在其第一个参数中输入字符串类型的值。
  3. 在第二个参数中,我们使用一个函数,即myFunc,在每次迭代时会调用该函数。
  4. myFunc函数将接受由Array.from()方法的迭代返回的参数。我们将数字强制转换为字符串,因此参数的类型是字符串,但是我们将其强制转换为整数并返回。
  5. Array.from()返回的值就是我们的结果。

示例:

<script> 
    var myInt = 235345; 
      
    // Getting the string as a parameter 
    // and typecasting it into an integer 
    let myFunc = num => Number(num); 
      
    var intArr = Array.from(String(myInt), myFunc); 
      
    // Print the result array 
    console.log(intArr); 
</script>

输出:

[2, 3, 5, 3, 4, 5 ]

方法2:使用map()方法

在JavaScript中,map()方法通过在父数组中的每个元素上调用特定函数来创建一个数组。它是一个非变异方法。通常,map()方法用于遍历数组并在数组的每个元素上调用函数。

语法:

array.map(function(currentValue, index, arr), thisValue)

方法:

  1. 将整数值存储在一个变量中。
  2. 将整数强制转换为字符串。
  3. 使用split()方法将其转换为字符串数组。
  4. 使用map()方法遍历该数组。
  5. 使用map()方法将字符串数组转换为整数数组。

示例:

<script> 
    // Declare a variable and store an 
    // integer value 
    var num = 235345 
      
    // Here we typecasting the num 
    // Splitting the num, so that 
    // we got an array of strings 
    // Then use map function to 
    // convert the array of strings 
    // into array of numbers 
      
    var myArr = String(num).split("").map((num)=>{ 
      return Number(num) 
    }) 
      
    console.log(myArr) 
</script>

输出:

[2, 3, 5, 3, 4, 5]

方法3:使用reduce()函数

reduce函数用于将数组缩减为单个值,并对数组的每个值执行一个提供的函数。

语法:

array.reduce( function(total, currValue, currIndex, arr), initialValue )

方法:

  1. 将整数值存储在一个变量中。
  2. 将整数强制转换为字符串。
  3. 使用扩展运算符将字符数组形成一个数组。
  4. 使用reduce()方法遍历该数组。
  5. 使用reduce()方法将字符串数组转换为整数数组。
<script> 
    var myInt = 235345; 
      
    // number to string conversion  
    var temp = ''+myInt 
    // forming array with numbers as element 
    var intArr = [...temp].reduce((acc, n)=> acc.concat(+n), [] ); 
      
    // Print the result array 
    console.log(intArr); 
</script>

输出:

[ 2, 3, 5, 3, 4, 5 ]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程