gpt4 book ai didi

javascript - 如何在 JS 中使用三元运算符返回值?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:29:55 26 4
gpt4 key购买 nike

我有一个函数来检查数组中的和:

function checkSum(array, sum) {
// array = [1,4,6,11] sum = 10
var answers = [];
var map = new Map();

for (var x = 0; x < array.length; x++) {
if (map.has(array[x])) {
answers.push([sum - array[x], array[x]])
} else {
map.set(sum - array[x])
}
}


answers.length != 0 ? console.log(answers) : console.log("nada")
}

我最初只有最后一行 return answers; 但假设我不想返回一个空数组——相反,我宁愿只记录一个语句。

为什么 return 在像这样的三元条件工作中:

answers.length != 0 ? return answers : console.log("nada")

最佳答案

您需要使用 return answers.length != 0 吗?答案:console.log("nada")。它失败的原因是因为三元条件在其条件中不支持 return。事实上,三元运算符的计算结果是一个表达式,而表达式不包含 return 语句。

function checkSum(array, sum) {
// array = [1,4,6,11] sum = 10
var answers = [];
var map = new Map();

for (var x = 0; x < array.length; x++) {
if (map.has(array[x])) {
answers.push([sum - array[x], array[x]])
} else {
map.set(sum - array[x])
}
}


return answers.length != 0 ? answers : console.log("nada")
}

console.log(checkSum([1, 4, 6, 11], 10));

关于javascript - 如何在 JS 中使用三元运算符返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51797003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com