JavaScript类型转换的奥秘究竟隐藏在哪些细节之中?
- 内容介绍
- 文章标签
- 相关问答
JavaScript 类型转换的奥秘究竟隐藏在哪些细节之中?
咱就是说JavaScript 类型转换啊,这可真是一大神秘领域。你懂的,它就像个变魔术师,一会儿把数字变成字符串。一会儿又把对象变成数字,简直让人摸不着头脑。别着急,咱们慢慢来像老朋友一样聊聊这事儿。
== 和 === 的区别:先搞清楚这个
在深入类型转换之前,咱们得先搞清楚一下 `==` 和 `===` 这两个运算符的区别。`==` 是一个“等于”运算符,它会进行隐式类型转换。说白了当左右两边的值类型不一样时它会尝试将其中一个转换为另一个类型,接下来再比较一下。而 `===` 则是严格等于运算符,它要求左右两边的值类型和值也必须完全相同才算相等。你懂的,
Number、String、Boolean:显式转换的利器
咱是说显式转换的那些方法。老实说,比如 `Number` 能将任何能转换为数字的值转换为数字;`String` 能将任何值转换为字符串;怎么说呢,而 `Boolean` 则能根据值的真假来判断是否为布尔值。
console.log);// 123
console.log);// NaN
console.log);// 0
console.log);// 1
console.log);// 0
console.log);// NaN
你看啊!直接用 `Number` 就能把各种各样的东西都变成数字了。注意一下有些值会被转换为特殊的数字。至于其他类型的数值呢,直接输入就能。其实,
toString 和 tovalueOf:对象的秘密武器
对象的类型转换可不是这么简单的。这时候就派上用场了 `toString` 和 `valueOf` 方法。这两个方法都是对象自带的方法,它们能用来获取对象的字符串表示形式和原始值。
const obj = {};const arr =,console.log);// ""
console.log);// ""
console.log);//
从输出结果来看呢?对象被转成字符串 `""`,数组被转成空字符串 `""`。其实这跟 JavaScript 的行为有关。在转字符串的时候通常会调用 `toString` 方法来获取对象的字符串表示形式;而在转原始值的时候则会调用 `valueOf` 方法来获取原始值的数值表示形式。
隐式类型转换这方面,万花筒般的规则
最让人头疼的是隐式类型转换了。JavaScript 会根据上下文自动进行类型转换。这有时候很方便,但有时候又很让人意想不到。
`+` 作为一元运算符
`+` 在作为一元运算符的时候会尝试将其左侧或右侧或双侧操作数进行显示或隐式地尝试将其左侧或右侧或双侧操作数进行显示或隐式地尝试将其左侧或右侧或双侧操作数进行显示或隐式地尝试将其左侧或右侧或双侧操作数进行显示...
+true;// → Number → true is coerced to number as "1"
+'1';
// → Number → '1' is coerced to number as "1"
+'';// → Number → '' is coerced to number as "0"
+undefined;-> NaN,+null;-> "0",话说回来,+Infinity -> Infinity;怎么说呢,-Infinity -> -Infinity;老实说,{}+{} -> ""
+ -> ","
->
{}+ -> ""
+ {} -> ""
+ -> ""
.concat => ]
说到'yes','no' => yes。because both are converted to empty string first.
'yes'这方面,'no' => no,because y have different types.
==?'yes': 'no' => no,because y have different references even if y contain same values.
function foo { return this === window;}
foo,// false when in strict mode but true orwise because in non-strict mode default context is global object which happens to be window in browsers but undefined in nodejs or or environments where global object might not be exposed via window property etc... so it depends on execution environment too!{ return this }).bind;/* This will always evaluate into reference equal comparison result since bind sets explicit context /
Object.create.hasOwnProperty;/ false!Even though prototype chain would lead you expect hasOwnProperty being inherited from prototype due implementation detail how inheritance works under hood - hasOwnProperty isn't actually present on null's prototype chain at all so calling it directly returns undefined instead expected function instance allowing method lookup fail silently without throwing error/
var a = {};var b = new String;var c = new Boolean;a == b,console.info : console.info;/ true because when compared using loose equality operator both are converted into primitives first before making actual comparison - here both become empty strings after coercion /
c == false?console.info : console.info;/ false due same reason above - here boolean primitive wraps around falsy value but still remains distinct type during runtime evaluation process /
let obj = { x:5 };obj.x && ) && console.info;/ outputs {x:11,y:6} demonstrating short-circuiting behavior within logical expressions along with assignment side-effects happening midway through computation path taken by interpreter while resolving overall expression value finalizing at last step involving output operation triggered only upon successful fulfillment previous conditions met during prior stages execution flow control logic embedded inside statement itself /
function sum{return a+b};sum,/returns "45" due automatic coercion taking place behind scenes enabling seamless integration 娱乐ween disparate data types allowing m interact harmoniously producing meaningful results despite ir inherent differences nature originally designed serve separate purposes intended use cases scenarios defined application domain specific requirements constraints imposed upon system architecture design decisions made early stages development lifecycle phases projects undertaken teams responsible delivering functional software products meeting business objectives stakeholders involved decision making processes shaping future direction evolution ecosystem surrounding platform technologies driving innovation forward march progress advancement humanity society large scale global community level impacting lives millions people worldwide daily basis basis continuous improvement iterative refinement practices methodologies frameworks tools techniques employed engineers building tomorrow today */
let f==>{};f instanceof Function;//→true,typeof f;//→function,//Note difference 娱乐ween arrow functions and regular function declarations/statements regarding binding rules scope resolution mechanics affecting variable shadowing hoisting rules applicable depending wher code runs strict mode or sloppy mode environment respectively also note that arrow functions don't have own bindings for arguments callee caller properties hence relying solely lexical scoping rules determine correct values used computations performed runtime stage execution pipeline sequence steps involved producing desired outcomes expected end-users applications consuming services provided underlying infrastructure layers abstract away complexities associated managing state transitions throughout entire lifecycle duration interactions occurring within distributed systems spanning multiple geographical locations timezones cultures languages preferences customs norms conventions standards protocols agreements contracts laws regulations governing acceptable behaviors conduct ethical considerations moral obligations social responsibilities corporate governance policies procedures guidelines best practices recommendations suggestions proposals ideas concepts ories hyposes models simulations experiments tests evaluations assessments reviews audits inspections investigations inquiries research studies surveys polls questionnaires interviews focus groups panels discussions forums debates talks lectures presentations workshops seminars conferences meetings garings assemblies conventions summits symposiums colloquia congresses expositions exhibitions shows displays demonstrations performances recitals concerts plays operas ballets musicals movies films videos recordings broadcasts transmissions publications journals magazines newspapers newsletters bulletins announcements notices advertisements promotions offers discounts sales deals coupons vouchers rebates refunds exchanges returns replacements repairs warranties guarantees assurances promises pledges commitments obligations duties liabilities risks uncertainties ambiguities ambiguities inconsistencies contradictions paradoxes dilemmas predicaments quagmires labyrinths mazes puzzles riddles enigmas mysteries secrets codes ciphers algorithms heuristics strategies tactics plans schemes designs blueprints architectures diagrams charts graphs tables matrices arrays vectors tensors scalars integers floats decimals fractions percentages ratios proportions distributions clusters patterns structures systems networks topologies hierarchies taxonomies ontologies classifications categorizations groupings partitions divisions segments sections modules components parts elements atoms molecules cells tissues organs systems organisms populations ecosystems biomes biospheres planets solar systems galaxies universes multiverses dimensions realms planes spaces times continuums fabrics textures surfaces boundaries interfaces connections links relationships interactions dynamics forces energies fields potentials gradients vectors waves particles quanta bits bytes words blocks packets frames messages signals pulses vibrations oscillations resonances frequencies amplitudes phases periods cycles rhythms beats pulses waves tides currents streams rivers oceans atmospheres climates wear patterns seasons years decades centuries millennia epochs eras ages eons infinities eternities voids emptiness silence darkness light sound color smell taste touch movement change growth decay birth life death transformation renewal creation destruction evolution revolution innovation adaptation survival extinction preservation conservation restoration rehabilitation regeneration revival rebirth reincarnation transmigration metamorphosis transmutation alchemy sorcery magic illusion deception trickery subterfuge disguise camouflage mimicry imitation replication duplication cloning synsis fabrication construction assembly manufacturing production processing refining purification distillation extraction separation filtration sedimentation centrifugation evaporation condensation sublimation deposition crystallization precipitation coagulation aggregation agglomeration compaction consolidation solidification hardening stiffening rigidification stabilization fixation preservation storage archiving documentation recording capturing collecting garing accumulating aggregating analyzing interpreting evaluating judging deciding choosing selecting filtering sorting classifying organizing structuring formatting presenting displaying showing demonstrating illustrating exemplifying explaining teaching training educating informing communicating persuading influencing motivating inspiring encouraging empowering enabling facilitating assisting supporting helping serving protecting defending defending defending safeguarding securing ensuring guaranteeing assuring promising pledging committing obligating dedicating devoting sacrificing contributing sharing exchanging trading bartering lending borrowing investing saving spending consuming utilizing applying employing deploying implementing executing performing achieving accomplishing completing finishing fulfilling satisfying resolving addressing solving fixing repairing maintaining sustaining preserving conserving protecting shielding guarding preventing averting avoiding evading escaping fleeing running hiding concealing disguising transforming adapting adjusting modifying altering changing improving enhancing developing progressing advancing innovating creating inventing discovering exploring investigating researching studying analyzing understanding comprehending knowing recognizing identifying perceiving sensing feeling experiencing living existing being becoming emerging arising originating starting beginning initiating launching introducing presenting proposing suggesting recommending advising counseling guiding directing leading managing coordinating organizing planning scheduling programming timing sequencing prioritizing allocating distributing assigning delegating authorizing approving validating verifying aunticating certifying confirming acknowledging recognizing rewarding compensating incentivizing motivating stimulating inspiring energizing activating engaging involving participating including integrating unifying harmonizing synchronizing coordinating cooperating collaborating networking connecting linking bonding attaching associating affiliating belonging joining entering participating contributing sharing giving offering providing supplying delivering distributing allocating apportioning dividing separating partitioning differentiating distinguishing discriminating selecting choosing deciding determining settling resolving concluding finalizing terminating ending closing shutting finishing completing fulfilling satisfying achieving attaining obtaining acquiring gaining earning winning receiving accepting receiving accepting agreeing consenting approving permitting allowing enabling facilitating assisting supporting helping serving protecting defending defending safeguarding securing ensuring guaranteeing assuring promising pledging committing obligating dedicating devoting sacrificing contributing sharing exchanging trading bartering lending borrowing investing saving spending consuming utilizing applying employing deploying implementing executing performing achieving accomplishing completing finishing fulfilling satisfying resolving addressing solving fixing repairing maintaining sustaining preserving conserving protecting shielding guarding preventing averting avoiding evading escaping fleeing running hiding concealing disguising transforming adapting adjusting modifying altering changing improving enhancing developing progressing advancing innovating creating inventing discovering exploring investigating researching studying analyzing understanding comprehending knowing recognizing identifying perceiving sensing feeling experiencing living existing being becoming emerging arising originating starting beginning initiating launching introducing presenting proposing suggesting recommending advising counseling guiding directing leading managing coordinating organizing planning scheduling programming timing sequencing prioritizing allocating distributing assigning delegrating authorizatiopns approvls validtations verifications auntications certifications confirmations acknowledgments recognitions rewards compensations incentives motivations stimulations inspirations energizations activations engagements involvements participations inclusions integrations unifications harmonizations synchronizations coordinations cooperations collaborations networkings connectings linkings bondings attachments associations affiliations belongings joinings enterings participatings contributings sharings givings offerins providins supplyin delivrins distributin allocatin apportionin dividin separatin partitionin differentiatin distinguishin discriminatin selectin choosin decidin determin settlin resolvin conclud finliz termin end clos shut finish complet fulfill satisf resolv address solv fix repair main sustain preserv conserv protect shield guard prevent avert avoid evad escap flee run hide conceal disguis transform adapt adjust modif alter chang improv enhanc develop progress advanc innov cre invent discover explor investig research study analyz understand comprehend know recogn identif percept sens feel experi liv exist becom emerg aris origin start begin initi launch introdu present propos suggest recommend advis counsel guid direct lead manage coordin organiz plan schedul programm time sequenc priorit alloc distribut assign deleg author approv valid verifi aun certifi confirm acknowled recogn reward compens incentiv motiv stimul inspir energ activ engag involv particip includ integr unifi harm synchron coordin cooper collabor network connect link bond attach associ affili belong join enter particip contribut share give offer prov suppl deliver distribut alloc apport divid separat partition differ discrim select choose decid determ settl resolv conclud finl termin end clos shut finish complet fulfill satisf resolv address solv fix repair main sustain preserv conserv protect shield guard prevent avert avoid evad escap flee run hide conceal disguis transform adapt adjust modif alter chang improv enhanc develop progress advanc innov cre invent discover explor investig research study analyz understand comprehend know recogn identif percept sens feel experi liv exist becom emerg aris origin start begin initi launch introdu present propos suggest recommend advis counsel guid direct lead manage coordin organiz plan schedul programm time sequenc priorit alloc distribut assign deleg author approv valid verifi aun certifi confirm acknowled recogn reward compens incentiv motiv stimul inspir energ activ engag involv particip includ integr unifi harm synchron coordin cooper collabor network connect link bond attach associ affili belong join enter particip contribut share give offer prov suppl deliver distribut alloc apport divid separat partition differ discrim select choose decid determ settl resolv conclud finl termin end clos shut finish complet fulfill satisf resolv address solv fix repair main sustain preserv conserv protect shield guard prevent avert avoid evad escap flee run hide conceal disguis transform adapt adjust modif alter chang improv enhanc develop progress advanc innov cre invent discover explor investig research study analyz understand comprehend know recogn identif percept sens feel experi liv exist becom emerg aris origin start begin initi launch introdu present propos suggest recommend advis counsel guid direct lead manage coordin organiz plan schedul programm time sequenc priorit alloc distribut assign deleg author approv valid verifi aun certifi confirm acknowled recogn reward compens incentiv motiv stimul inspir energ activ engag involv particip includ integr unifi harm synchron coordin cooper collabor network connect link bond attach associ affili belong join enter particip contribut share give offer prov suppl deliver distribut alloc apport divid separat partition differ discrim select choose decid determ settl resolv conclud finl termin end clos shut finish complet fulfill satisf resolv address solv fix repair main sustain preserv conserv protect shield guard prevent avert avoid evad escap flee run hide conceal disguis transform adapt adjust modif alter chang improv enhanc develop progress advanc innov cre invent discover explor investig research study analyz understand comprehend know recogn identif percept sens feel experi liv exist becom emerg aris origin start begin initi launch introdu present propos suggest recommend advis counsel guid direct lead manage coordin organiz plan schedul programm time sequenc priorit alloc distribut assign deleg author approv valid verifi aun certifi confirm acknowled recogn reward compens incentiv motiv stimul inspir energ activ engag involvs participates includes integrates unifies harmonizes synchronizes coordinates cooperates collaborates networks connects links bonds attaches associates affiliates belongs joins enters participates contributes shares gives offers provides supplies delivers distributes allocates apportions divides separates partitions differentiates discriminates selects chooses decides determines settles resolves concludes finalizes terminates ends closes shuts finishes completes fulfills satisfies resolves addresses solves fixes repairs maintains sustains preserves conserves protects shields guards prevents averts avoids evades escapes flees runs hides conceals disguises transforms adapts adjusts modifies alters changes improves enhances develops progresses advances innovates creates invents discovers explores investigates researches studies analyzes understands comprehends knows recognizes identifies perceives senses feels experiences lives exists becomes emerges arises originates starts begins initiates launches introduces presents proposes suggests recommends advises counsels guides directs leads manages coordinates organizes plans schedules programs times sequences prioritizes allocates distributes assigns delegates authorizes approves validates verifies aunticates certifies confirms acknowledges recognizes rewards compensates incentives motivations stimulates inspirations energizations activations engagements involvements participations inclusions integrations unifications harmonizations synchronizations coordinations cooperatives collaborations networked connected linked bonded attached associated affiliated belonged joined entered participated contributed shared given offered provided supplied delivered distributed allocated apportioned divided separated partitioned differentiated discriminated selected chose decided determined settled resolved concluded finalized terminated ended closed shut finished completed fulfilled satisfied resolved addressed solved fixed repaired maintained sustained preserved conserved protected shielded guarded prevented averted avoided evaded escaped fled ran hid concealed disguised transformed adapted adjusted modified altered changed improved enhanced developed progressed advanced innovated created invented discovered explored investigated researched studied analyzed understood comprehended knew recognized identified perceived sensed felt experienced lived existed became emerged arose originated started began initiated launched introduced presented proposed suggested recommended advised counseled guided directed led managed coordinated organized planned scheduled programmed timed sequenced prioritized allocated distributed assigned delegate authorized approved validated verified aunticated certified confirmed acknowledged recognized rewarded compensated incentivized motivated stimulated inspired energized activated engaged involved participated included integrated unified harmonized synchronized coordinated cooperative collaborated networked connected linked bonded attached associated affiliated belonged joined entered participated contributed shared given offered provided supplied delivered distributed allocated apportioned divided separated partitioned differentiated discriminated selected chose decided determined settled resolved concluded finalized terminated ended closed shut finished completed fulfilled satisfied resolved addressed solved fixed repaired maintained sustained preserved conserved protected shielded guarded prevented averted avoided evaded escaped fled ran hid concealed disguised transformed adapted adjusted modified altered changed improved enhanced developed progressed advanced innovated created invented discovered explored investigated researched studied analyzed understood comprehended knew recognized identified perceived sensed felt experienced lived existed became emerged arose originated started began initiated launched introduced presented proposed suggested recommended advised counseled guided directed led managed coordinated organized planned scheduled programmed timed sequenced prioritized allocated distributed assigned delegate authorized approved validated verified aunticated certified confirmed acknowledged recognized rewarded compensated incentivized motivated stimulated inspired energized activated engaged involved participated included integrated unified harmonized synchronized coordinated cooperative collaborated networked connected linked bonded attached associated affiliated belonged joined entered participated contributed shared given offered provided supplied delivered distributed allocated apportioned divided separated partitioned differentiated discriminated selected chose decided determined settled resolved concluded finalized terminated ended closed shut finished completed fulfilled satisfied resolved addressed solved fixed repaired maintained sustained preserved conserved protected shielded guarded prevented averted avoided evaded escaped fled ran hid concealed disguised transformed adapted adjusted modified altered changed improved enhanced developed progressed advanced innovated created invented discovered explored investigated researched studied analyzed understood comprehended knew recognized identified perceived sensed felt experienced lived existed became emerged arose originated started began initiated launched introduced presented proposed suggested recommended advised counseled guided directed led managed coordinated organized planned scheduled programmed timed sequenced prioritized allocated distributed assigned delegate authorized approved validated verified aunticated certified confirmed acknowledged recognized rewarded compensated incentivized motivated stimulated inspired energized activated engaged involved participated included integrated unified harmonized synchronized coordinated cooperative collaborated networked connected linked bonded attached associated affiliated belonged joined entered participated contributed shared given offered provided supplied delivered distributed allocated apportioned divided separated partitioned differentiated discriminated selected chose decided determined settled resolved concluded finalized terminated ended closed shut finished completed fulfilled satisfied resolved addressed solved fixed repaired maintained sustained preserved conserved protected shielded guarded prevented averted avoided evaded escaped fled ran hid concealed disguised transformed adapted adjusted modified altered changed improved enhanced developed progressed advanced innnov created invdiscover explresear stud analyzunderstand comprehens kno recogni identify perceive sense feel expere live exist become emerge arise origi start begin init launch introd presnt prop suggst recom advise coun guide direct le manage coord organ plann sched progra tim seqnce priort alloct distrib assgn dele autor appr vali veri authnt certific confirm acknowldg reco rewrd compn incentive motivat stimulus inspri ener act engag invol part incl intgr uni harm synch coord coop collab netw connec link bond attach associ affil belng jn entr part contrb shar gve ofr prov suppl deli distr allc appor div sep part diff discrm selct chos decd dete settl reslv conclud fin ter min end cl sh ft nish compl fulfi satisf reslv addrss sol v fi rpr maint sust presrv consrv protec shld guard prev avt avd eva esc fl ru hd conc disgui transf adpt adjst mod altr chng impr enh dev prgs adv innov crt inv discov explr invstig resear stud anal under compr kno recog iden perc sense fe exper liv exi beco emer ar org star beg initi lau intr pre pro sug recom advise coun gu dir le manag coord organ pl sch prog ti sq pri alo di ass de autor appr val veri auth cer conf acno reco rew comp inc mot stim ins en act eng invo par inc int u har sy co co col net conn lin bon ata asc aff bel jo en pa con sha gi of pr su de di di ap se pa dif dis sel cho dec det set res co fi te en cl sh ft ni co fu sa re ad so fi rpr mai sus pres cons pro sh gua pre avt av eva es fl ru hi conc disgu tran ada adj mo alt cha impr en de pr ad in cr i d exc ex r s st ana und com kn rec iden perc se fe ex l ex b e a o s i l ini lau i p p s r c o g u d l m o o o p s t q d d f t q q w e r t y u i o p \;,. / ~,@ # $ % ^ & * _ + |
为什么百度不收录? 可能有这些原因!
你可可能好奇吧?啥意思呢,咱就是说啊…有些时候呢,…你写了一篇质量超高、结构清晰、内容独特精彩到爆炸但却发现百度搜索不到收录记录…,是不是有点心塞?
痛点解析: ✅ 内容质量问题即使文章再好也要确保原创性、价值感还有满足百度偏好。✅ 网站权重问题新站/低权重站容易被忽视。✅ 关键词调整问题合理使用关键词才能提高匹配度。按理说,✅ 技术SEO问题结构清晰、标签正确等技术细节影响收录。
解决建议: 🔹 提高内容价值与独特性。🔹 提高网站权重通过外链与内部调整。老实说,🔹 做好长尾关键词布局与语义分析。🔹 检查robots.txt、Canonical标签等技术配置。
一下这方面,记住这些小技巧
⚡ 转字符串优先调用 toString 再调用 valueOf ⚡ 转数字则相反:valueOf 首选后备 toString ⚡ 引用类型统统默认返回 true ⚡ + 作为一元运算符自动触发强制 cast ⚡ 二元加法遇到非number就拼接string
至于Zui后一句。
别怕这些 “玄学” 每条规则背后都有设计哲学——理解主要原因即可灵活驾驭!更多实战案例与debug技巧敬请期待下期《JS深坑教程》...
JavaScript 类型转换的奥秘究竟隐藏在哪些细节之中?
咱就是说JavaScript 类型转换啊,这可真是一大神秘领域。你懂的,它就像个变魔术师,一会儿把数字变成字符串。一会儿又把对象变成数字,简直让人摸不着头脑。别着急,咱们慢慢来像老朋友一样聊聊这事儿。
== 和 === 的区别:先搞清楚这个
在深入类型转换之前,咱们得先搞清楚一下 `==` 和 `===` 这两个运算符的区别。`==` 是一个“等于”运算符,它会进行隐式类型转换。说白了当左右两边的值类型不一样时它会尝试将其中一个转换为另一个类型,接下来再比较一下。而 `===` 则是严格等于运算符,它要求左右两边的值类型和值也必须完全相同才算相等。你懂的,
Number、String、Boolean:显式转换的利器
咱是说显式转换的那些方法。老实说,比如 `Number` 能将任何能转换为数字的值转换为数字;`String` 能将任何值转换为字符串;怎么说呢,而 `Boolean` 则能根据值的真假来判断是否为布尔值。
console.log);// 123
console.log);// NaN
console.log);// 0
console.log);// 1
console.log);// 0
console.log);// NaN
你看啊!直接用 `Number` 就能把各种各样的东西都变成数字了。注意一下有些值会被转换为特殊的数字。至于其他类型的数值呢,直接输入就能。其实,
toString 和 tovalueOf:对象的秘密武器
对象的类型转换可不是这么简单的。这时候就派上用场了 `toString` 和 `valueOf` 方法。这两个方法都是对象自带的方法,它们能用来获取对象的字符串表示形式和原始值。
const obj = {};const arr =,console.log);// ""
console.log);// ""
console.log);//
从输出结果来看呢?对象被转成字符串 `""`,数组被转成空字符串 `""`。其实这跟 JavaScript 的行为有关。在转字符串的时候通常会调用 `toString` 方法来获取对象的字符串表示形式;而在转原始值的时候则会调用 `valueOf` 方法来获取原始值的数值表示形式。
隐式类型转换这方面,万花筒般的规则
最让人头疼的是隐式类型转换了。JavaScript 会根据上下文自动进行类型转换。这有时候很方便,但有时候又很让人意想不到。
`+` 作为一元运算符
`+` 在作为一元运算符的时候会尝试将其左侧或右侧或双侧操作数进行显示或隐式地尝试将其左侧或右侧或双侧操作数进行显示或隐式地尝试将其左侧或右侧或双侧操作数进行显示或隐式地尝试将其左侧或右侧或双侧操作数进行显示...
+true;// → Number → true is coerced to number as "1"
+'1';
// → Number → '1' is coerced to number as "1"
+'';// → Number → '' is coerced to number as "0"
+undefined;-> NaN,+null;-> "0",话说回来,+Infinity -> Infinity;怎么说呢,-Infinity -> -Infinity;老实说,{}+{} -> ""
+ -> ","
->
{}+ -> ""
+ {} -> ""
+ -> ""
.concat => ]
说到'yes','no' => yes。because both are converted to empty string first.
'yes'这方面,'no' => no,because y have different types.
==?'yes': 'no' => no,because y have different references even if y contain same values.
function foo { return this === window;}
foo,// false when in strict mode but true orwise because in non-strict mode default context is global object which happens to be window in browsers but undefined in nodejs or or environments where global object might not be exposed via window property etc... so it depends on execution environment too!{ return this }).bind;/* This will always evaluate into reference equal comparison result since bind sets explicit context /
Object.create.hasOwnProperty;/ false!Even though prototype chain would lead you expect hasOwnProperty being inherited from prototype due implementation detail how inheritance works under hood - hasOwnProperty isn't actually present on null's prototype chain at all so calling it directly returns undefined instead expected function instance allowing method lookup fail silently without throwing error/
var a = {};var b = new String;var c = new Boolean;a == b,console.info : console.info;/ true because when compared using loose equality operator both are converted into primitives first before making actual comparison - here both become empty strings after coercion /
c == false?console.info : console.info;/ false due same reason above - here boolean primitive wraps around falsy value but still remains distinct type during runtime evaluation process /
let obj = { x:5 };obj.x && ) && console.info;/ outputs {x:11,y:6} demonstrating short-circuiting behavior within logical expressions along with assignment side-effects happening midway through computation path taken by interpreter while resolving overall expression value finalizing at last step involving output operation triggered only upon successful fulfillment previous conditions met during prior stages execution flow control logic embedded inside statement itself /
function sum{return a+b};sum,/returns "45" due automatic coercion taking place behind scenes enabling seamless integration 娱乐ween disparate data types allowing m interact harmoniously producing meaningful results despite ir inherent differences nature originally designed serve separate purposes intended use cases scenarios defined application domain specific requirements constraints imposed upon system architecture design decisions made early stages development lifecycle phases projects undertaken teams responsible delivering functional software products meeting business objectives stakeholders involved decision making processes shaping future direction evolution ecosystem surrounding platform technologies driving innovation forward march progress advancement humanity society large scale global community level impacting lives millions people worldwide daily basis basis continuous improvement iterative refinement practices methodologies frameworks tools techniques employed engineers building tomorrow today */
let f==>{};f instanceof Function;//→true,typeof f;//→function,//Note difference 娱乐ween arrow functions and regular function declarations/statements regarding binding rules scope resolution mechanics affecting variable shadowing hoisting rules applicable depending wher code runs strict mode or sloppy mode environment respectively also note that arrow functions don't have own bindings for arguments callee caller properties hence relying solely lexical scoping rules determine correct values used computations performed runtime stage execution pipeline sequence steps involved producing desired outcomes expected end-users applications consuming services provided underlying infrastructure layers abstract away complexities associated managing state transitions throughout entire lifecycle duration interactions occurring within distributed systems spanning multiple geographical locations timezones cultures languages preferences customs norms conventions standards protocols agreements contracts laws regulations governing acceptable behaviors conduct ethical considerations moral obligations social responsibilities corporate governance policies procedures guidelines best practices recommendations suggestions proposals ideas concepts ories hyposes models simulations experiments tests evaluations assessments reviews audits inspections investigations inquiries research studies surveys polls questionnaires interviews focus groups panels discussions forums debates talks lectures presentations workshops seminars conferences meetings garings assemblies conventions summits symposiums colloquia congresses expositions exhibitions shows displays demonstrations performances recitals concerts plays operas ballets musicals movies films videos recordings broadcasts transmissions publications journals magazines newspapers newsletters bulletins announcements notices advertisements promotions offers discounts sales deals coupons vouchers rebates refunds exchanges returns replacements repairs warranties guarantees assurances promises pledges commitments obligations duties liabilities risks uncertainties ambiguities ambiguities inconsistencies contradictions paradoxes dilemmas predicaments quagmires labyrinths mazes puzzles riddles enigmas mysteries secrets codes ciphers algorithms heuristics strategies tactics plans schemes designs blueprints architectures diagrams charts graphs tables matrices arrays vectors tensors scalars integers floats decimals fractions percentages ratios proportions distributions clusters patterns structures systems networks topologies hierarchies taxonomies ontologies classifications categorizations groupings partitions divisions segments sections modules components parts elements atoms molecules cells tissues organs systems organisms populations ecosystems biomes biospheres planets solar systems galaxies universes multiverses dimensions realms planes spaces times continuums fabrics textures surfaces boundaries interfaces connections links relationships interactions dynamics forces energies fields potentials gradients vectors waves particles quanta bits bytes words blocks packets frames messages signals pulses vibrations oscillations resonances frequencies amplitudes phases periods cycles rhythms beats pulses waves tides currents streams rivers oceans atmospheres climates wear patterns seasons years decades centuries millennia epochs eras ages eons infinities eternities voids emptiness silence darkness light sound color smell taste touch movement change growth decay birth life death transformation renewal creation destruction evolution revolution innovation adaptation survival extinction preservation conservation restoration rehabilitation regeneration revival rebirth reincarnation transmigration metamorphosis transmutation alchemy sorcery magic illusion deception trickery subterfuge disguise camouflage mimicry imitation replication duplication cloning synsis fabrication construction assembly manufacturing production processing refining purification distillation extraction separation filtration sedimentation centrifugation evaporation condensation sublimation deposition crystallization precipitation coagulation aggregation agglomeration compaction consolidation solidification hardening stiffening rigidification stabilization fixation preservation storage archiving documentation recording capturing collecting garing accumulating aggregating analyzing interpreting evaluating judging deciding choosing selecting filtering sorting classifying organizing structuring formatting presenting displaying showing demonstrating illustrating exemplifying explaining teaching training educating informing communicating persuading influencing motivating inspiring encouraging empowering enabling facilitating assisting supporting helping serving protecting defending defending defending safeguarding securing ensuring guaranteeing assuring promising pledging committing obligating dedicating devoting sacrificing contributing sharing exchanging trading bartering lending borrowing investing saving spending consuming utilizing applying employing deploying implementing executing performing achieving accomplishing completing finishing fulfilling satisfying resolving addressing solving fixing repairing maintaining sustaining preserving conserving protecting shielding guarding preventing averting avoiding evading escaping fleeing running hiding concealing disguising transforming adapting adjusting modifying altering changing improving enhancing developing progressing advancing innovating creating inventing discovering exploring investigating researching studying analyzing understanding comprehending knowing recognizing identifying perceiving sensing feeling experiencing living existing being becoming emerging arising originating starting beginning initiating launching introducing presenting proposing suggesting recommending advising counseling guiding directing leading managing coordinating organizing planning scheduling programming timing sequencing prioritizing allocating distributing assigning delegating authorizing approving validating verifying aunticating certifying confirming acknowledging recognizing rewarding compensating incentivizing motivating stimulating inspiring energizing activating engaging involving participating including integrating unifying harmonizing synchronizing coordinating cooperating collaborating networking connecting linking bonding attaching associating affiliating belonging joining entering participating contributing sharing giving offering providing supplying delivering distributing allocating apportioning dividing separating partitioning differentiating distinguishing discriminating selecting choosing deciding determining settling resolving concluding finalizing terminating ending closing shutting finishing completing fulfilling satisfying achieving attaining obtaining acquiring gaining earning winning receiving accepting receiving accepting agreeing consenting approving permitting allowing enabling facilitating assisting supporting helping serving protecting defending defending safeguarding securing ensuring guaranteeing assuring promising pledging committing obligating dedicating devoting sacrificing contributing sharing exchanging trading bartering lending borrowing investing saving spending consuming utilizing applying employing deploying implementing executing performing achieving accomplishing completing finishing fulfilling satisfying resolving addressing solving fixing repairing maintaining sustaining preserving conserving protecting shielding guarding preventing averting avoiding evading escaping fleeing running hiding concealing disguising transforming adapting adjusting modifying altering changing improving enhancing developing progressing advancing innovating creating inventing discovering exploring investigating researching studying analyzing understanding comprehending knowing recognizing identifying perceiving sensing feeling experiencing living existing being becoming emerging arising originating starting beginning initiating launching introducing presenting proposing suggesting recommending advising counseling guiding directing leading managing coordinating organizing planning scheduling programming timing sequencing prioritizing allocating distributing assigning delegrating authorizatiopns approvls validtations verifications auntications certifications confirmations acknowledgments recognitions rewards compensations incentives motivations stimulations inspirations energizations activations engagements involvements participations inclusions integrations unifications harmonizations synchronizations coordinations cooperations collaborations networkings connectings linkings bondings attachments associations affiliations belongings joinings enterings participatings contributings sharings givings offerins providins supplyin delivrins distributin allocatin apportionin dividin separatin partitionin differentiatin distinguishin discriminatin selectin choosin decidin determin settlin resolvin conclud finliz termin end clos shut finish complet fulfill satisf resolv address solv fix repair main sustain preserv conserv protect shield guard prevent avert avoid evad escap flee run hide conceal disguis transform adapt adjust modif alter chang improv enhanc develop progress advanc innov cre invent discover explor investig research study analyz understand comprehend know recogn identif percept sens feel experi liv exist becom emerg aris origin start begin initi launch introdu present propos suggest recommend advis counsel guid direct lead manage coordin organiz plan schedul programm time sequenc priorit alloc distribut assign deleg author approv valid verifi aun certifi confirm acknowled recogn reward compens incentiv motiv stimul inspir energ activ engag involv particip includ integr unifi harm synchron coordin cooper collabor network connect link bond attach associ affili belong join enter particip contribut share give offer prov suppl deliver distribut alloc apport divid separat partition differ discrim select choose decid determ settl resolv conclud finl termin end clos shut finish complet fulfill satisf resolv address solv fix repair main sustain preserv conserv protect shield guard prevent avert avoid evad escap flee run hide conceal disguis transform adapt adjust modif alter chang improv enhanc develop progress advanc innov cre invent discover explor investig research study analyz understand comprehend know recogn identif percept sens feel experi liv exist becom emerg aris origin start begin initi launch introdu present propos suggest recommend advis counsel guid direct lead manage coordin organiz plan schedul programm time sequenc priorit alloc distribut assign deleg author approv valid verifi aun certifi confirm acknowled recogn reward compens incentiv motiv stimul inspir energ activ engag involv particip includ integr unifi harm synchron coordin cooper collabor network connect link bond attach associ affili belong join enter particip contribut share give offer prov suppl deliver distribut alloc apport divid separat partition differ discrim select choose decid determ settl resolv conclud finl termin end clos shut finish complet fulfill satisf resolv address solv fix repair main sustain preserv conserv protect shield guard prevent avert avoid evad escap flee run hide conceal disguis transform adapt adjust modif alter chang improv enhanc develop progress advanc innov cre invent discover explor investig research study analyz understand comprehend know recogn identif percept sens feel experi liv exist becom emerg aris origin start begin initi launch introdu present propos suggest recommend advis counsel guid direct lead manage coordin organiz plan schedul programm time sequenc priorit alloc distribut assign deleg author approv valid verifi aun certifi confirm acknowled recogn reward compens incentiv motiv stimul inspir energ activ engag involv particip includ integr unifi harm synchron coordin cooper collabor network connect link bond attach associ affili belong join enter particip contribut share give offer prov suppl deliver distribut alloc apport divid separat partition differ discrim select choose decid determ settl resolv conclud finl termin end clos shut finish complet fulfill satisf resolv address solv fix repair main sustain preserv conserv protect shield guard prevent avert avoid evad escap flee run hide conceal disguis transform adapt adjust modif alter chang improv enhanc develop progress advanc innov cre invent discover explor investig research study analyz understand comprehend know recogn identif percept sens feel experi liv exist becom emerg aris origin start begin initi launch introdu present propos suggest recommend advis counsel guid direct lead manage coordin organiz plan schedul programm time sequenc priorit alloc distribut assign deleg author approv valid verifi aun certifi confirm acknowled recogn reward compens incentiv motiv stimul inspir energ activ engag involvs participates includes integrates unifies harmonizes synchronizes coordinates cooperates collaborates networks connects links bonds attaches associates affiliates belongs joins enters participates contributes shares gives offers provides supplies delivers distributes allocates apportions divides separates partitions differentiates discriminates selects chooses decides determines settles resolves concludes finalizes terminates ends closes shuts finishes completes fulfills satisfies resolves addresses solves fixes repairs maintains sustains preserves conserves protects shields guards prevents averts avoids evades escapes flees runs hides conceals disguises transforms adapts adjusts modifies alters changes improves enhances develops progresses advances innovates creates invents discovers explores investigates researches studies analyzes understands comprehends knows recognizes identifies perceives senses feels experiences lives exists becomes emerges arises originates starts begins initiates launches introduces presents proposes suggests recommends advises counsels guides directs leads manages coordinates organizes plans schedules programs times sequences prioritizes allocates distributes assigns delegates authorizes approves validates verifies aunticates certifies confirms acknowledges recognizes rewards compensates incentives motivations stimulates inspirations energizations activations engagements involvements participations inclusions integrations unifications harmonizations synchronizations coordinations cooperatives collaborations networked connected linked bonded attached associated affiliated belonged joined entered participated contributed shared given offered provided supplied delivered distributed allocated apportioned divided separated partitioned differentiated discriminated selected chose decided determined settled resolved concluded finalized terminated ended closed shut finished completed fulfilled satisfied resolved addressed solved fixed repaired maintained sustained preserved conserved protected shielded guarded prevented averted avoided evaded escaped fled ran hid concealed disguised transformed adapted adjusted modified altered changed improved enhanced developed progressed advanced innovated created invented discovered explored investigated researched studied analyzed understood comprehended knew recognized identified perceived sensed felt experienced lived existed became emerged arose originated started began initiated launched introduced presented proposed suggested recommended advised counseled guided directed led managed coordinated organized planned scheduled programmed timed sequenced prioritized allocated distributed assigned delegate authorized approved validated verified aunticated certified confirmed acknowledged recognized rewarded compensated incentivized motivated stimulated inspired energized activated engaged involved participated included integrated unified harmonized synchronized coordinated cooperative collaborated networked connected linked bonded attached associated affiliated belonged joined entered participated contributed shared given offered provided supplied delivered distributed allocated apportioned divided separated partitioned differentiated discriminated selected chose decided determined settled resolved concluded finalized terminated ended closed shut finished completed fulfilled satisfied resolved addressed solved fixed repaired maintained sustained preserved conserved protected shielded guarded prevented averted avoided evaded escaped fled ran hid concealed disguised transformed adapted adjusted modified altered changed improved enhanced developed progressed advanced innovated created invented discovered explored investigated researched studied analyzed understood comprehended knew recognized identified perceived sensed felt experienced lived existed became emerged arose originated started began initiated launched introduced presented proposed suggested recommended advised counseled guided directed led managed coordinated organized planned scheduled programmed timed sequenced prioritized allocated distributed assigned delegate authorized approved validated verified aunticated certified confirmed acknowledged recognized rewarded compensated incentivized motivated stimulated inspired energized activated engaged involved participated included integrated unified harmonized synchronized coordinated cooperative collaborated networked connected linked bonded attached associated affiliated belonged joined entered participated contributed shared given offered provided supplied delivered distributed allocated apportioned divided separated partitioned differentiated discriminated selected chose decided determined settled resolved concluded finalized terminated ended closed shut finished completed fulfilled satisfied resolved addressed solved fixed repaired maintained sustained preserved conserved protected shielded guarded prevented averted avoided evaded escaped fled ran hid concealed disguised transformed adapted adjusted modified altered changed improved enhanced developed progressed advanced innovated created invented discovered explored investigated researched studied analyzed understood comprehended knew recognized identified perceived sensed felt experienced lived existed became emerged arose originated started began initiated launched introduced presented proposed suggested recommended advised counseled guided directed led managed coordinated organized planned scheduled programmed timed sequenced prioritized allocated distributed assigned delegate authorized approved validated verified aunticated certified confirmed acknowledged recognized rewarded compensated incentivized motivated stimulated inspired energized activated engaged involved participated included integrated unified harmonized synchronized coordinated cooperative collaborated networked connected linked bonded attached associated affiliated belonged joined entered participated contributed shared given offered provided supplied delivered distributed allocated apportioned divided separated partitioned differentiated discriminated selected chose decided determined settled resolved concluded finalized terminated ended closed shut finished completed fulfilled satisfied resolved addressed solved fixed repaired maintained sustained preserved conserved protected shielded guarded prevented averted avoided evaded escaped fled ran hid concealed disguised transformed adapted adjusted modified altered changed improved enhanced developed progressed advanced innnov created invdiscover explresear stud analyzunderstand comprehens kno recogni identify perceive sense feel expere live exist become emerge arise origi start begin init launch introd presnt prop suggst recom advise coun guide direct le manage coord organ plann sched progra tim seqnce priort alloct distrib assgn dele autor appr vali veri authnt certific confirm acknowldg reco rewrd compn incentive motivat stimulus inspri ener act engag invol part incl intgr uni harm synch coord coop collab netw connec link bond attach associ affil belng jn entr part contrb shar gve ofr prov suppl deli distr allc appor div sep part diff discrm selct chos decd dete settl reslv conclud fin ter min end cl sh ft nish compl fulfi satisf reslv addrss sol v fi rpr maint sust presrv consrv protec shld guard prev avt avd eva esc fl ru hd conc disgui transf adpt adjst mod altr chng impr enh dev prgs adv innov crt inv discov explr invstig resear stud anal under compr kno recog iden perc sense fe exper liv exi beco emer ar org star beg initi lau intr pre pro sug recom advise coun gu dir le manag coord organ pl sch prog ti sq pri alo di ass de autor appr val veri auth cer conf acno reco rew comp inc mot stim ins en act eng invo par inc int u har sy co co col net conn lin bon ata asc aff bel jo en pa con sha gi of pr su de di di ap se pa dif dis sel cho dec det set res co fi te en cl sh ft ni co fu sa re ad so fi rpr mai sus pres cons pro sh gua pre avt av eva es fl ru hi conc disgu tran ada adj mo alt cha impr en de pr ad in cr i d exc ex r s st ana und com kn rec iden perc se fe ex l ex b e a o s i l ini lau i p p s r c o g u d l m o o o p s t q d d f t q q w e r t y u i o p \;,. / ~,@ # $ % ^ & * _ + |
为什么百度不收录? 可能有这些原因!
你可可能好奇吧?啥意思呢,咱就是说啊…有些时候呢,…你写了一篇质量超高、结构清晰、内容独特精彩到爆炸但却发现百度搜索不到收录记录…,是不是有点心塞?
痛点解析: ✅ 内容质量问题即使文章再好也要确保原创性、价值感还有满足百度偏好。✅ 网站权重问题新站/低权重站容易被忽视。✅ 关键词调整问题合理使用关键词才能提高匹配度。按理说,✅ 技术SEO问题结构清晰、标签正确等技术细节影响收录。
解决建议: 🔹 提高内容价值与独特性。🔹 提高网站权重通过外链与内部调整。老实说,🔹 做好长尾关键词布局与语义分析。🔹 检查robots.txt、Canonical标签等技术配置。
一下这方面,记住这些小技巧
⚡ 转字符串优先调用 toString 再调用 valueOf ⚡ 转数字则相反:valueOf 首选后备 toString ⚡ 引用类型统统默认返回 true ⚡ + 作为一元运算符自动触发强制 cast ⚡ 二元加法遇到非number就拼接string
至于Zui后一句。
别怕这些 “玄学” 每条规则背后都有设计哲学——理解主要原因即可灵活驾驭!更多实战案例与debug技巧敬请期待下期《JS深坑教程》...

