js converts the Number array into a number

If all elements in the array are numeric strings, you can use the Array.map() method and the Number() function to convert them to numeric types:

const strArray = ["1", "2", "3", "4"];
const numArray = strArray.map(Number);
console.log(numArray); // [1, 2, 3, 4]

If you want to convert an array of numbers to integers with commas, you can use JavaScript's map() method as follows:

const myArray = [1, 2, 3, 4, 5];  
const myInt = myArray.map(function(item) {
    
      
  return Number(item);  
}).join(',');  
console.log(myInt); // 输出 1,2,3,4,5

The number array calculates an integer from the number array according to tens of digits and hundreds of digits

const nums = [3, 1, 4, 1, 5, 9, 2, 6, 5];

const result = nums.reduce((acc, cur, idx) => {
    
    
  return acc + cur * Math.pow(10, nums.length - 1 - idx);
}, 0);

console.log(result); // 314159265

First, we define a numeric array nums. Then, we use the reduce method to bitwise convert each element in the array to an integer and add them together to finally get an integer result. In the callback function, acc is the accumulator with an initial value of 0, cur is the value of the current element, and idx is the index of the current element. We use the Math.pow() method to calculate the number of digits where the current element is, and then multiply it by the value of the current element and add it to the accumulator. Finally, the reduce method returns the final value of the accumulator.


If the elements in the array are not numeric strings, they need to be type checked and converted first. For example, you can use the parseInt() function to convert a string to an integer:

const mixedArray = ["1", "2", "three", "4"];
const numArray = mixedArray.map((element) => {
    
    
  if (!isNaN(parseInt(element))) {
    
    
    return parseInt(element);
  } else {
    
    
    return NaN;
  }
});
console.log(numArray); // [1, 2, NaN, 4]

In this example, we check whether each element can be converted to a number using the isNaN() function. If it can, we convert it to an integer using the parseInt() function. Otherwise, we return NaN values.

Guess you like

Origin blog.csdn.net/mingketao/article/details/130689126