元问答栏目视频美女
  1. 编程问答
  2. 答案列表
  3. 答案正文

怎么使用 JavaScript 编写更好的条件语句

4.默认参数和解构。
当使用 javascript 工作时,我们总是需要检查 null/undefined 值并赋默认值,否则可能编译失败。
function printvegetableswithquantity(vegetable,quantity = 1) {
// if quantity has no value,assign 1。
if (!vegetable) return;
console.log(we have ${quantity} ${vegetable}!);
}
//results
printvegetableswithquantity('cabbage');// we have 1 cabbage
printvegetableswithquantity('potato',2);// we have 2 potato
如果 vegetable 是一个对象呢?我们能赋一个默认参数吗?
function printvegetablename(vegetable) {
if (vegetable &&vegetable.name) {
console.log (vegetable.name);
} else {
console.log('unknown');
}
}
printvegetablename(undefined);// unknown
printvegetablename({});// unknown
printvegetablename({ name:'cabbage',quantity:2 });// cabbage
在上面的例子中,如果vegetable 存在,我们想要打印 vegetable name,否则打印"unknown"
我们能通过使用默认参数和解构来避免条件语句 if (vegetable &&vegetable.name) {}
// destructing - get name property only
// assign default empty object {}
function printvegetablename({name} = {}) {
console.log (name || 'unknown');
}
printvegetablename(undefined);// unknown
printvegetablename({ });// unknown
printvegetablename({ name:'cabbage',quantity:2 });// cabbage
因为我们只需要 name 属性,所以我们可以使用 { name } 解构参数,然后我们就能在代码中使用 name 作为变量,而不是 vegetable.name
我们还赋了一个空对象 {} 作为默认值,因为当执行 printvegetablename(undefined) 时会得到一个错误:不能从 undefined 或 null 解构属性 name,因为在 undefined 中没有 name 属性。
5.用 array.every &array.some 匹配全部/部分内容。
我们能使用数组方法减少代码行。查看下面的代码,我们想要检查是否所有的水果都是红色的:
const fruits = [。
{ name:'apple',color:'red'}
{ name:'banana',color:'yellow'}
{ name:'grape',color:'purple'}
];
function test() {
let isallred = true;
// condition:all fruits must be red
for (let f of fruits) {
if (!isallred) break;
isallred = (f.color == 'red');
}
console.log(isallred);// false
}
这代码太长了!我们能用 array.every 来减少代码行数:
const fruits = [。
{ name:'apple',color:'red'}
{ name:'banana',color:'yellow'}
{ name:'grape',color:'purple'}
];
function test() {
// condition:short way,all fruits must be red
const isallred = fruits.every(f =>f.color == 'red');
console.log(isallred);// false
}
相似地,如果我们想测试是否有任何红色的水果,我们能用一行 array.some 来实现它。
const fruits = [。
{ name:'apple',color:'red'}
{ name:'banana',color:'yellow'}
{ name:'grape',color:'purple'}
];
function test() {
// condition:if any fruit is red
const isanyred = fruits.some(f =>f.color == 'red');
console.log(isanyred);// true
}
6.使用可选链和空值合并。
这有两个为编写更清晰的条件语句而即将成为 javascript 增强的功能。当写这篇文章时,它们还没有被完全支持,你需要使用 babel 来编译。
可选链允许我们没有明确检查中间节点是否存在地处理 tree-like 结构,空值合并和可选链组合起来工作得很好,以确保为不存在的值赋一个默认值。
这有一个例子:
const car = {
model:'fiesta'
manufacturer:{
name:'ford'
address:{
street:'some street name'
number:'5555'
state:'usa'
}
}
}
// to get the car model
const model = car &&car.model || 'default model';
// to get the manufacturer street
const street = car &&car.manufacturer &&car.manufacturer.address &&
car.manufacturer.address.street || 'default street';
// request an un-existing property
const phonenumber = car &&car.manufacturer &&car.manufacturer.address
&&car.manufacturer.phonenumber;
console.log(model) // 'fiesta'
console.log(street) // 'some street name'
console.log(phonenumber) // undefined
所以,如果我们想要打印是否车辆生产商来自美国,代码将看起来像这样:
const ismanufacturerfromusa = () =>{
if(car &&car.manufacturer &&car.manufacturer.address &&
car.manufacturer.address.state === 'usa') {
console.log('true');
}
}
checkcarmanufacturerstate() // 'true'
你能清晰地看到当有一个更复杂的对象结构时,这能变得多乱。有一些第三方的库有它们自己的函数,像 lodash 或 idx。例如 lodash 有 _.get 方法。然而,javascript 语言本身被引入这个特性是非常酷的。
这展示了这些新特性如何工作:
// to get the car model
const model = car?.model??'default model';
// to get the manufacturer street
const street = car?.manufacturer?.address?.street??'default street';
// to check if the car manufacturer is from the usa
const ismanufacturerfromusa = () =>{
if(car?.manufacturer?.address?.state === 'usa') {
console.log('true');
}
}
这看起来很美观并容易维护。它已经到 tc39 stage 3 阶段,让我们等待它获得批准,然后我们就能无处不在地看到这难以置信的语法的使用。
总结。
让我们为了编写更清晰、易维护的代码,学习并尝试新的技巧和技术,因为在几个月后,长长的条件看起来像搬石头砸自己的脚。
感谢大家的阅读。
@lkgetkk评:0
猜你喜欢