if...else...
function getAge(age) {
if (age <= 12) {
return "儿童";
} else if (age > 12 && age <= 28) {
return "青年";
} else if (age > 28 && age <= 50) {
return "青年";
} else {
return "老年";
}
}
console.log(getAge(54));
const foodMap = {
香蕉: 20,
苹果: 12,
草莓: 33,
菠萝: 21,
};
function getFood(name) {
return foodMap[name];
}
console.log(getFood("草莓"));
const foods = [
{
name: "香蕉",
price: 12,
},
{
name: "苹果",
price: 13,
},
{
name: "菠萝",
price: 14,
},
{
name: "葡萄",
price: 14,
},
{
name: "蜜枣",
price: 15,
},
];
// 找出价格为14的水果
const name = foods.filter((i) => i.price === 14).map((k) => k.name);
console.log(name); // ['菠萝', '葡萄']
const apple = foods.find((i) => i.name === "苹果" && i.price === 13);
console.log("apple", apple); // {name: '苹果', price: 13}
运算符
if (val !== null && val !== undefined) {
const num = val;
} else {
const num = "";
}
const num = val ?? "";