การแปลงค่าเป็นประเภทบูลีนใน JavaScript
ตอนนี้เรามาศึกษาการแปลงประเภทข้อมูลอื่นๆ
เป็นบูลีนกัน การแปลงแบบนี้
ทำได้โดยใช้ฟังก์ชัน Boolean
นี่คือค่าต่างๆ ที่เมื่อแปลงเป็นประเภทบูลีนแล้ว
จะได้ false:
console.log(Boolean(0)); // false
console.log(Boolean(-0)); // false
console.log(Boolean(+0)); // false
console.log(Boolean(null)); // false
console.log(Boolean(false)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean('')); // false
ค่าอื่นๆ ทั้งหมดใน JavaScript (ในภาษาโปรแกรมอื่น
อาจไม่เป็นเช่นนี้) จะให้ true นี่คือ
ค่าบางค่าที่แปลงเป็น true แต่
อาจทำให้คุณสับสนได้:
console.log(Boolean(-1)); // true
console.log(Boolean(Infinity)); // true
console.log(Boolean(-Infinity)); // true
ค่าต่อไปนี้เป็นสตริง เนื่องจาก
อยู่ในเครื่องหมายคำพูด และจะแปลงเป็น
true เช่นกัน:
console.log(Boolean('0')); // true
console.log(Boolean('false')); // true
console.log(Boolean('NaN')); // true
console.log(Boolean('null')); // true
console.log(Boolean('undefined')); // true
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(3);
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(0);
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(-1);
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(-0);
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(+0);
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean('abc');
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean('');
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean('0');
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(true);
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(false);
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean('true');
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean('false');
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(null);
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean('null');
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(undefined);
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean('undefined');
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(NaN);
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean('NaN');
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(3 * 'abc');
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(Infinity);
alert(test);
โดยไม่ต้องรันโค้ด จงระบุว่าอะไรจะแสดงผล บนหน้าจอ:
let test = Boolean(1 / 0);
alert(test);