从另一个数组返回带有阶乘数的数组

时间:2018-01-11 15:08:36

标签: javascript arrays recursion

此函数将接收一个正整数数组,它应返回一个新数组,其中包含每个数字的阶乘。

到目前为止,我想出了这个,但它不起作用,我不知道问题出在哪里,有什么想法?

function getFactorials (nums) {
  let arr = [];
  for(let i = 0; i < nums.length; i++) {
    if(nums[i] <= 1) {
      return 1;
     } else {
      arr.push(nums[i] * getFactorials(nums[i] - 1));
     }
   }
  return arr;
 }

6 个答案:

答案 0 :(得分:6)

试试这个使用地图

var a = [1, 2, 3, 4, 5];

function fact(x) {
   return (x == 0) ? 1 : x * fact(x-1);
}

console.log(a.map(fact));

答案 1 :(得分:1)

尝试这种方式:

function factorial(n) {
  if (n === 0) {
    return 1;
  }
  return n * factorial(n - 1);
}

function getFactorials (nums) {
  let arr = [];
  for(let i = 0; i < nums.length; i++) {
     arr.push(factorial(nums[i]));
  }
  return arr;
}

getFactorials([6,5,3])

答案 2 :(得分:1)

const factorial = (n) => {
  let res = [];
  while(n != 0){ 
    //get all integers less than or equal to n
    res.push(n);
    n--;
  }
  return res.reduce((x, y) => {
    return x * y; 
    //reduce the array of integers into a single number via multiplication
  });
}

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

const factorialArr = (arr) => {
  return arr.map(n => {
    //iterate through a list of numbers and return the factorial of each
    return factorial(n);
  });
}

const result = factorialArr(nums);
console.log(result) -> // Array [ 1, 2, 6, 24, 120 ]

答案 3 :(得分:1)

尝试以下方法:

function getFactorials (nums) {
  let arr = [];
  for(let i = 0; i < nums.length; i++) {
    let j, fact;
    fact=1;
    for(let j=1; j<=nums[i]; j++)  
    {
      fact= fact*j;
    }
    arr.push(fact);
   }
  return arr;
}
let res = getFactorials([5,9])
console.log(res);

答案 4 :(得分:0)

function getFactorials(nums) {
    const factNums = nums.map(
        function factorial (num) {
            return (num == 0 ? 1 : num * factorial(num -1));
        }
    )

    return factNums;
}

答案 5 :(得分:-3)

const click = () => {
  console.log('click');
  return (
    <View>
      <Text>a</Text>
    </View>
  );
};

tabBarOnPress: (tab) => {
  click();
},

// Main Page Navigator
export const Main = TabNavigator({
  Home: {
    screen: HomeNavigator,
  },
  Explore: {
    screen: ExploreNavigator,
  },
  Upload: {
    screen: UploadMain,
    navigationOptions: ({ navigation }) => ({
      tabBarLabel: 'Upload',
      tabBarIcon: ({ tintColor }) => (
        <View>
          <Icon name="camera" size={26} color={tintColor} />
        </View>
      ),
      tabBarOnPress: (tab) => {
        click();
      },
    }),
  },
}, {
  tabBarComponent: TabBarBottom,
  tabBarPosition: 'bottom',
  backBehavior: 'none',
  swipeEnabled: false,
  lazy: true,
  animationEnabled: false,
  showIcon: true,
  tabBarOptions: {
    activeTintColor: 'black',
  },
});