在JavaScript中将数字中的各个数字彼此相乘 [英] Multiplying individual digits in a number with each other in JavaScript

查看:90
本文介绍了在JavaScript中将数字中的各个数字彼此相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个程序,将数字中的数字相乘。因此 583 将为 5 * 8 * 3 = 120

I'm trying to make a program that will take the digits in a number and multiply them with each other. So 583 would be 5*8*3 = 120.

它没有按预期工作,它只是返回输入的数字

Its not working as intended, its just returning the number that was put in.

我该如何解决?

这里是代码:

function persistence(num) {
  //code me
  numString = num.toString();
  numArray = numString.split().map(function(t) {
    return parseInt(t)
  });


  function reducer(theNumArray) {
    let sum = 1;
    for (var i = 0; i < theNumArray.length; i++) {
      sum = sum * theNumArray[i];

    }
    return sum;
  }
  newNum = reducer(numArray);

  console.log(newNum);
};

persistence(485);

推荐答案

您可以将字符串拆分为空字符串,以获取单个数字。

You could split the string with an empty string, for getting single digits. Then covert, if required all strings to a number.

function reducer(theNumArray) {
    var i, sum = 1;
    for (i = 0; i < theNumArray.length; i++) {
        sum *= theNumArray[i];
    }
    return sum;
}

function persistence(num) {
    var numArray = num.toString().split('').map(Number);
    return reducer(numArray);
}

console.log(persistence(485));

一种较短的方法可能是通过使用带有字符串迭代器的扩展语法来获取单个数字,然后仅将值相乘并返回结果。

A shorter approach could be just taking the single digits by using a spread syntax with an iterator for strings, then just multiply the values and return the result.

function persistence(number) {
    return [...number.toString()].reduce((p, v) => p * v);
}

console.log(persistence(485));

这篇关于在JavaScript中将数字中的各个数字彼此相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆