您好,登錄后才能下訂單哦!
在 JavaScript 中,除了使用 instanceof 運(yùn)算符進(jìn)行類型斷言之外,還可以使用 typeof 運(yùn)算符、 Object.prototype.toString.call() 方法和 constructor 屬性來(lái)進(jìn)行類型判斷。
const value = 'Hello';
if (typeof value === 'string') {
console.log('value is a string');
}
const value = [1, 2, 3];
if (Object.prototype.toString.call(value) === '[object Array]') {
console.log('value is an array');
}
function Person(name) {
this.name = name;
}
const person = new Person('John');
if (person.constructor === Person) {
console.log('person is an instance of Person');
}
這些替代方案都可以用來(lái)判斷一個(gè)變量的類型,但具體使用哪種方式取決于具體的情況和個(gè)人偏好。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。