在 1 行中调用三元运算符的值

Calling a value of a ternary operator in 1 line

我有这个三元运算符

function digPow(n, p){
  return Number.isInteger((""+n).split("").map((num,index) => Math.pow(parseInt(num),(p+index))).reduce((a, b) => a + b, 0)/n) ? (""+n).split("").map((num,index) => Math.pow(parseInt(num),(p+index))).reduce((a, b) => a + b, 0)/n : -1;
}

如您所见,这是一个非常长的 1 衬里。我的问题是,如何调用 Number.isInteger() 中的值,这样我就不必在 1 行中为三元运算符再次重复它。

这是我需要的值的代码:-

    (""+n).split("").map((num,index) => Math.pow(parseInt(num),(p+index)))
      .reduce((a, b) => a + b, 0)/n 

这有什么语法吗?我对 JS 比较陌生

编辑: 主要问题实际上是:“是否可以在不使用变量的情况下从三元运算符内部调用值”

EDIT-2: 对不起,我的编码不好。这里有一个更简单的方式来问我的问题

const x = 6
const y = 3
console.log(Number.isInteger(x+y/3) ? x+y/3 : -1)

是否可以在不重复或创建新变量的情况下调用 x+y/3 值?

不太确定,你的函数在做什么或者它应该接受什么参数,但你可以使用 Self-Executing 匿名函数 又名 IIFE(立即调用的函数表达式)。

让我们从格式化您当前拥有的内容开始:

const digPow = (n, p) => Number.isInteger(
  ("" + n)
  .split("")
  .map((num, index) => Math.pow(parseInt(num), (p + index)))
  .reduce((a, b) => a + b, 0) / n
)
  ? ("" + n)
    .split("")
    .map((num, index) => Math.pow(parseInt(num), (p + index)))
    .reduce((a, b) => a + b, 0) / n
  : -1;
    
console.log(digPow(6, 3)); // 36

看起来这部分在条件内,如果结果是整数,也是 return:

("" + n)
  .split("")
  .map((num, index) => Math.pow(parseInt(num), (p + index)))
  .reduce((a, b) => a + b, 0) / n

您可以将您的逻辑简化为以下 (pseudo-code):

const digPow = (x => Number.isInteger(x) ? x : -1)(split/map/reduce/divide);

让我们将其传递到 IIFE 中:

const digPow = (n, p) => (
  (value) => Number.isInteger(value) ? value : -1)
  (("" + n)
    .split("")
    .map((num, index) => Math.pow(parseInt(num), (p + index)))
    .reduce((a, b) => a + b, 0) / n);
    
console.log(digPow(6, 3)); // 36