[removed] Calculate the nth root of a number

前端 未结 9 1433
长情又很酷
长情又很酷 2020-12-04 20:26

I\'m trying to get the nth root of a number using JavaScript, but I don\'t see a way to do it using the built in Math object. Am I overlooking something?
If

9条回答
  •  攒了一身酷
    2020-12-04 21:18

    For the special cases of square and cubic root, it's best to use the native functions Math.sqrt and Math.cbrt respectively.

    As of ES7, the exponentiation operator ** can be used to calculate the nth root as the 1/nth power of a non-negative base:

    let root1 = Math.PI ** (1 / 3); // cube root of π
    
    let root2 = 81 ** 0.25;         // 4th root of 81
    

    This doesn't work with negative bases, though.

    let root3 = (-32) ** 5;         // NaN
    

提交回复
热议问题