Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

javascript - Typechecking in vanilla JS – why use typeof for string but typeof .matches for booleans?

I'm checking some variables from localStorage before continuing my script. First this:

const hasStorageValue = typeof storageValue === 'string'

Then I read an example of something similar for booleans. Like this:

const hasStorageValue = typeof storageValue.matches === 'boolean'

Curious if the two uses are equivalent or if there's another requirement for booleans than for strings?

Edit: Found back to the original code I was looking at. It's like this:

const mql = window.matchMedia('(prefers-color-scheme: dark)');
  const hasMediaQueryPreference = typeof mql.matches === 'boolean';

From "A first pass" in this article.

window.matchMedia() returns an object, as Nicolas correctly points to in the comments:

enter image description here

I mixed element.matches() with window.matchMedia().matches – which was the reason for asking here.

question from:https://stackoverflow.com/questions/65895288/typechecking-in-vanilla-js-why-use-typeof-for-string-but-typeof-matches-for-b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...