Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ประตูตรรกะ (Boolean Gates) ใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของค่า Boolean และตัวดำเนินการตรรกะ (logical operator) ฟังก์ชันควรคืนค่าผลลัพธ์ Boolean จากการนำตัวดำเนินการไปใช้กับค่าในอาร์เรย์ตามลำดับ

ตัวอย่าง

โค้ดตัวอย่างดังนี้:

const array = [true, true, false];
const op = 'AND';
function logicalCalc(array, op){
  var result = array[0];
  for(var i = 1; i < array.length; i++){
    if(op == "AND"){
      result = result && array[i];
    }
    if(op == "OR"){
      result = result || array[i];
    }
    if(op == "XOR"){
      result = result != array[i];
    }
  }
  return result;
}
console.log(logicalCalc(array, op));

ผลลัพธ์

false