JavaScript 如何获取第一个非空/未定义的参数
很多时候,我们需要找到传递给函数的第一个非空或非undefined参数。这被称为合并。
方法1
在ES6之前的JavaScript中,我们可以通过循环遍历参数,并检查哪个参数等于NULL来实现合并。然后我们立即返回不为NULL的参数。
示例:
<script>
function coalesce() {
for (let i = 0; i < arguments.length; i++) {
if (arguments[i] != null) {
return arguments[i];
}
}
}
console.log(
coalesce(null, undefined, "First",
1, 2, 3, null)
);
</script>
输出:
First
方法2
我们可以使用ES6中的另一种方法来实现类似的效果。使用ES6中的Rest参数,我们将所有参数收集到args可迭代对象中。我们将一个肥箭头函数作为回调传递给find方法,该方法迭代args的每个元素。我们在回调中使用一个临时变量_作为元素的标识符。最后,我们使用includes()方法检查回调中由_标识的元素是否属于null或undefined。第一个不满足测试条件的元素就是我们的输出。
示例:
<script>
const coalesceES6 = (...args) =>
args.find(_ =>
![null,undefined].includes(_)
);
console.log(
coalesceES6(null, undefined, "Value One",
1, 2, 3, null)
);
</script>
输出:
Value One
合并使用情况
现在我们已经了解到如何实现合并,让我们讨论一下一些使用情况。
使用案例1: 填充数组对象中的null/undefined值
示例: 假如你有一个包含许多产品列表的产品目录。每个产品都有一个描述和一个摘要。你想通过从这个数据库中提取数据来显示描述和摘要。在这种情况下,你可以使用带有两个参数的合并函数,当摘要不存在时,使用摘要值和截断的描述值填充。
<script>
let products = [
{
id: 1,
desc: `The best in class toaster that has 140
watt power consumption with nice features that
roast your bread just fine. Also comes bundled
in a nice cute case.`,
summ: `Get world class breakfasts`,
},
{
id: 2,
desc: `A massager that relieves all your pains
without the hassles of charging it daily
or even hourly as it comes packed with Li-Ion
batteries that last upto 8 hrs.`,
summ: "Warm comfort for your back",
},
{
id: 3,
desc: `An air conditioner with a difference that
not only cools your room to the best temperatures
but also provides cleanliness and disinfection at
best in class standards`,
summ: null,
},
];
const coalesceES6 = (...args) =>
args.find((_) =>
![null, undefined].includes(_));
function displayProdCat(products) {
for (let product of products) {
console.log(`ID = {product.id}`);
console.log(`Description ={product.desc}`);
let summProd =
coalesceES6(product.summ,
product.desc.slice(0, 50) + "...");
console.log(`Summary = ${summProd}`);
}
}
displayProdCat(products);
</script>
输出: 使用coalesce函数,如果summary的值存在,它将被显示。如果summary缺失(为null或undefined),则coalesce函数将选择第二个参数并在summary字段中显示一个截断的描述。
ID = 1
Description = The best in class toaster that has 140
watt power consumption with nice features that
roast your bread just fine. Also comes bundled
in a nice cute case.
Summary = Get world class breakfasts
ID = 2
Description = A massager that relieves all your pains
without the hassles of charging it daily
or even hourly as it comes packed with Li-Ion
batteries that last upto 8 hrs.
Summary = Warm comfort for your back
ID = 3
Description = An air conditioner with a difference that
not only cools your room to the best temperatures
but also provides cleanliness and disinfection at
best in class standards
Summary = An air conditioner with a difference that
not ...
示例2: 在表达式中存在缺失的数值时填充值以进行计算
示例: 假设你有一年的月收入数组,其中有一些缺失的值。现在,你想要计算总年收入,你决定在缺失数据的月份用一个基本默认值1000替代。我们对月收入数据数组应用reduce方法。我们在迭代中将每次的和存储在累加器中,有一个小变化是,我们对当前项应用coalesce函数,并将月收入(如果存在)或默认值(如果月收入为null或undefined)添加到累加器中。
<script>
const incomeFigures = {
default: 1000,
monthWise: [1200, , 600, 2100, , 329,
1490, , 780, 980, , 1210],
};
const coalesceES6 = (...args) =>
args.find((_) =>
![null, undefined].includes(_));
function yearlyIncome(incomeFig) {
return incomeFig.monthWise.reduce(
(total, inc) => total +
coalesceES6(inc, incomeFig.default)
);
}
console.log(
`Yearly income equals
${yearlyIncome(incomeFigures)}`
);
</script>
输出:
Yearly income equals 8689
极客教程