JavaScript 10 — 論理演算子
ブール論理
ブール論理は、真と偽の値を処理する論理システムです。プログラミングでは、ブール論理が広範囲に使用されて、意思決定を行い、プログラムの流れを制御します。
ブール論理の 3 つの主要な論理演算子は、AND、OR、および NOT です。
- AND : AND 演算子は、両方のオペランドが true の場合にのみ true を返します。
- OR : OR 演算子は、オペランドのいずれかまたは両方が true の場合に true を返します。
- NOT : NOT 演算子は、指定されたオペランドの逆を返します。
コード内の論理演算子
&&JavaScript には、 (AND)、||(OR)、!(NOT)の 3 つの論理演算子があります。これらの演算子は、JavaScript でブール値を組み合わせて操作するためによく使用されます。
&& (AND) 演算子
演算子は、両方のオペランドが である場合に&&戻り、そうでない場合に戻ります。ここではいくつかの例を示します。truetruefalse
// Normal examples
console.log(true && true); // true
console.log(true && false); // false
console.log(false && true); // false
console.log(false && false); // false
// Type coercion examples
console.log("hello" && 42); // 42
console.log("" && 42); // ""
- この
&&演算子は、最初のオペランドが true の場合にのみ 2 番目のオペランドを評価するため、短絡演算子として知られています。これは、コードを最適化し、エラーを回避するのに役立ちます。
演算子は、オペランドの少なくとも 1 つが である場合に||戻り、そうでない場合に戻ります。ここではいくつかの例を示します。truetruefalse
// Normal examples
console.log(true || true); // true
console.log(true || false); // true
console.log(false || true); // true
console.log(false || false); // false
// Type coercion examples
console.log("" || "hello"); // "hello"
console.log(0 || 42); // 42
- この
||演算子は短絡演算子でもあり、最初のオペランドが false の場合にのみ 2 番目のオペランドを評価します。 - 演算子
||は、 のように、変数のデフォルト値を提供するためによく使用されますconst value = input || defaultValue;。
演算子!はブール値を否定し、trueオペランドが である場合false、およびfalseオペランドが である場合に戻りますtrue。ここではいくつかの例を示します。
// Normal examples
console.log(!true); // false
console.log(!false); // true
// Type coercion examples
console.log(!"hello"); // false
console.log(!undefined); // true
- のように、演算子
!を使用して値を 2 回否定することにより、値をブール型に変換できます!!value。
論理演算子の順序
複数の条件を評価する必要がある場合は、論理演算子の順序によって違いが生じることがあります。ここではいくつかの例を示します。
演算子の優先順位:論理 AND ( &&) は、論理 OR ( ) よりも優先順位が高くなります||。これは、&&が前に評価され||、条件の結果を変更できることを意味します。例えば:
// This condition will evaluate to true
if (true || false && true) {
// do something
}
// This condition will evaluate to false
if ((true || false) && true) {
// do something
}
2 番目の例では、(true || false)が最初に評価され、結果は になりますtrue。次に がtrue && true評価され、結果は になりますtrue。条件全体も true ですが、括弧のために評価が異なります。
短絡評価:論理 AND ( &&) および論理 OR ( ||) は短絡評価を使用します。つまり、2 番目のオペランドは必要な場合にのみ評価されます。例えば:
// This condition will evaluate to true without an error
if (x !== null && x.property === "value") {
// do something
}
// This condition will throw an error
if (x.property === "value" && x !== null) {
// do something
}
2 番目の例では、 if xisnullはプロパティを持たないx.propertyため、エラーをスローします。null2 番目のオペランドは最初のオペランドより前に評価されるため、慎重に使用しないとエラーが発生する可能性があります。
否定:論理 NOT ( !) は、条件を否定することによって条件の結果を変更できます。例えば:
let x = true;
// This condition will evaluate to false
if (!x) {
// do something
}
// This condition will evaluate to true
if (!!x) {
// do something
}
初心者は、論理演算子の順序に注意し、必要に応じて括弧を使用して順序を明確にすることが重要です。短絡評価とそれがエラーを防ぐ方法を理解することも重要です。否定は、条件を読みにくく理解しにくくする可能性があるため、注意して使用する必要があります。
実際の例
コードで使用される論理演算子の現実的な例を次に示します。例を読んでロジックを理解できるかどうかを確認してください。関数についてはまだ説明していないので、理解できなくても落胆しないでください。
ユーザー入力の検証:
function validateInput(input) {
const isString = typeof input === 'string';
const isNotEmpty = input !== '';
const isLessThanTenChars = input.length < 10;
return isString && isNotEmpty && isLessThanTenChars;
}
function filterProducts(products, minPrice, maxPrice, availableOnly) {
return products.filter(product => {
const isWithinPriceRange = product.price >= minPrice && product.price <= maxPrice;
const isAvailable = availableOnly ? product.stock > 0 : true;
return isWithinPriceRange && isAvailable;
});
}
function isEligibleForDiscount(user) {
const hasPaid = user.orders.some(order => order.status === 'paid');
const hasFrequentOrders = user.orders.length >= 5;
const hasValidCoupon = user.coupons.includes('DISCOUNT2022');
return (hasPaid || hasFrequentOrders) && hasValidCoupon;
}
function isProductOnSale(product) {
const isDiscounted = product.discount > 0;
const hasLowStock = product.stock <= 10;
return isDiscounted || hasLowStock;
}
function getTaskStatus(priority, isComplete) {
const isUrgent = priority === 'high' || priority === 'urgent';
const isOverdue = priority === 'low' && !isComplete;
const isInProgress = priority === 'medium' && !isComplete;
if (isUrgent) {
return 'Urgent';
} else if (isOverdue) {
return 'Overdue';
} else if (isInProgress) {
return 'In Progress';
} else {
return 'Pending';
}
}
![とにかく、リンクリストとは何ですか?[パート1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































