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 }
使用可选链和 Nullish 合并这两个功能对于 JavaScript 编写更简洁的条件非常有用。在编写本文时,它们还没有得到完全的支持,可能需要使用Babel进行编译。
可选链接能够处理类似树的结构,而不需要显式地检查中间节点是否存在,并且Nullish与可选链接结合使用非常有效,可以确保不存在节点的默认值。
举个例子:
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"); } };
目前在 Stage 3 阶段。
以上就是基于JavaScript实现条件表达式的一些分享,希望对你能有所帮助~
以上就是浅谈JS如何写出漂亮的条件表达式的详细内容,更多关于JS如何写出漂亮的条件表达式的资料请关注脚本之家其它相关文章!
您可能感兴趣的文章: