Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the error-prone holes in JS?

2025-05-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail what are the error-prone holes in JS. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

. VS = operator priority let a = {n: 1}; let b = a; a.x = a = {n: 2}; console.log (a.x) console.log (b.x)

What is the output?

Have you really figured it out?

Undefined {n: 2}

Do you really know the scope?

Var a = 0, b = 0; function A (a) {A = function (b) {console.log (a + baked +)} console.log (aura +)} A (1) A (2)

For you to think about, I made a mistake the first time (; '⌒')

Answer 1 4

You can think about it, and you will open up.

Lengthvar obj of the class array = {"2": 3, "3": 4, "length": 2, "splice": Array.prototype.splice, "push": Array.prototype.push} obj.push (1) obj.push (2) console.log (obj)

What is the execution result of this code?

Answer: Object (4) [empty × 2,1,2, splice: answer, push: answer]

Interpretation is the first time to use the push method of the push,obj object to set obj [2] = 1 subscript obj. Interpretation. interpretation is the first time to use the push method of the push,obj object to set obj [3] = 2. When you use the console.log () method to output, because there are length properties and splice methods on the obj, it is printed as array output because the array does not set the values of 0 and 1, so the printed result is empty. Actively get obj [0] = undefined non-anonymous self-executing function, function name read-only var b = 10 (function b () {/ / 'use strict' b = 20 console.log (b)}) ()

What is the result of the output?

Function b-like title, non-anonymous self-executing function, function name cannot be modified, strict mode will TypeError,-in non-strict mode, no error is reported, and modification is useless. -when looking for variable b, executing the function immediately will have internal scope, and will first find out whether there is a declaration of variable b, and if so, copy it directly-it does find the named function Function b () {}, so it is used as the value of b-IIFE cannot be copied inside the function (similar to const)

Non-anonymous self-executing function II

Var b = 10; (function b () {/ / 'use strict' var b = 20 console.log (window.b) console.log (b)}) ()

What is the output?

10 20 / / when accessing the b variable, it is found that var b = 20; the b variable is found in the current scope, so the value of b is 20

Non-anonymous self-executing function III

Var b = 10; (function b () {console.log (b) b = 5 console.log (window.b) var b = 20 console.log (b)}) ()

What is the result of the output?

This question should not be difficult. I'll leave it to you to think about.

Variable promotion var name = 'Worldworkers'; (function () {if (typeof name = 'undefined') {var name =' Jack'; console.log ('Goodbye' + name);} else {console.log ('Hello' + name);}}) ()

In JavaScript, Fun and var will be promoted

Equivalent to

(function () {var name; if (typeof name = 'undefined') {name =' Jack'; console.log ('Goodbye' + name);} else {console.log ('Hello' + name);}}) ()

Consolidate:

(function (name) {if (typeof name = 'undefined') {var name =' Jack'; console.log ('Goodbye' + name);} else {console.log ('Hello' + name);}}) (str); answer: Hello World because name has become the largest integer var END = Math.pow (2,53) of the local variable in the function Var START = END-100; var count = 0; for (var I = START; i true 3 in ary; = > false 10 in ary; = > true, that is, from 3 to 9 are uninitialized pits!, these indexes do not exist in the array. These "pits" will be skipped when array's function is called.

So the answer is []

Floating point operation var two = 0.2 var one = 0.1 var eight = 0.8 var six = 0.6 [two-one = = one, eight-six = = two]

What do you think the result is? How should I answer this question in the interview?

[true,false]

Take a look at these articles:

Explore the problem of JavaScript accuracy and its solution

Look at the Number types in JS from 0.1 to 0.2 to 0.300000000000004.

Switchfunction showCase (value) {switch (value) {case'Aids: console.log ('Case A'); break; case'Balls: console.log ('Case B'); break; case undefined: console.log (' undefined'); break; default: console.log ('Do not knowns');} showCase (new String ('A'))

What is the result of the operation?

Switch is a strict comparison, String instances are not the same as strings. Naturally, the answer is'Do not know', so in general, if you write a switch statement, it is also recommended to write default.

String ("A")

Function showCase2 (value) {switch (value) {case'Aids: console.log ('Case A'); break; case'Balls: console.log ('Case B'); break; case undefined: console.log (' undefined'); break; default: console.log ('Do not knowns');} showCase2 (String ('A'))

What's the result of the operation?

Answer: Case A parsing: String ('A') returns a string% operator function isOdd (num) {return num% 2 = = 1;} function isEven (num) {return num% 2 = = 0;} function isSane (num) {return isEven (num) | | isOdd (num);} var values = [7, 4,'13 percent,-9, Infinity]; values.map (isSane)

What is the result of the operation?

Answer: [true, false, false] parse:% if it is not a numerical value, it will call Number () to convert'13'% 2 / / 1 Infinity% 2 / / NaN Infinity is infinity-9% 2 / /-1 consolidate: what is the Array.isArray (Array.prototype) of the sign of 9%-2 / / 1 remainder with the prototype of the first Operand array

What is the execution result of this code?

Answer: true parsing: Array.prototype is an array. The prototype of the array is the array, the prototype of the object is the object, and the prototype of the function is the function loose equality = = [] = = []

What is the answer

Answer: false parsing: two reference types, = = comparing the reference address = = and! Priority [] =! []

The result?

(1)! The priority is higher than = =, the right Boolean ([]) is true, the return is equal to false (2) A reference type and a value to compare the conversion of a reference type to a value type, left 0 (3) so 0 = = false the answer is the addition and subtraction of the true number and the string'5' + 3'5'-3

What is the result?

Answer: 532 parsing: the plus sign has splicing function, and the minus sign is the consolidation of logical operations: typeof (+ "1") / / "number" to non-numeric values +-is often used for type conversion equivalent to Number () a wave of operations +-+ 1 +-+-+ 1.

What's the result?

Answer: 2 Analysis: +-is the unary addition and subtraction operation symbol, which is the plus and minus sign in mathematics. The negatives are positive. Consolidation: another common use of unary operators is to change the function of a self-executing function from a function declaration to an expression. The commonly used ones are +-~! Void + function () {}-function () {} ~ function () {} void function () {} is a sparse array again? Array.prototype.map () var ary = Array (3); ary [0] = 2 ary.map (function (elem) {return '1targets;})

What is the output?

The array in the sparse array topic is actually an array of length 3 but no content, and the operation on array skips these uninitialized pits. So the answer is [1 ", empty x 2]

Array.prototype.map 's polyfill is posted here.

Array.prototype.map = function (callback, thisArg) {var T, A, k; if (this = = null) {throw new TypeError ('this is null or not defined');} var O = Object (this); var len = O.length > 0; if (typeof callback! = =' function') {throw new TypeError (callback +'is not a function') } if (arguments.length > 1) {T = thisArg;} A = new Array (len); k = 0; while (k)

< len) { var kValue, mappedValue; if (k in O) { kValue = O[k]; mappedValue = callback.call(T, kValue, k, O); A[k] = mappedValue; } k++; } return A; };JS是如何存储var a = 111111111111111110000, b = 1111; a + b; 这段代码的执行结果? 答案:11111111111111111000 解析:在JavaScript中number类型在JavaScript中以64位(8byte)来存储。 这64位中有符号位1位、指数位11位、实数位52位。 2的53次方时,是最大值。 其值为:9007199254740992(0x20000000000000)。 超过这个值的话,运算的结果就会不对.数组比较大小var a = [1, 2, 3], b = [1, 2, 3], c = [1, 2, 4] a == b a === b a >

C a

< c 这段代码的执行结果? 答案:false, false, false, true 解析:相等(==)和全等(===)还是比较引用地址 引用类型间比较大小是按照字典序比较,就是先比第一项谁大,相同再去比第二项。三元运算符优先级var val = 'smtg'; console.log('Value is ' + (val === 'smtg') ? 'Something' : 'Nothing'); 这段代码的执行结果? 答案:Something 解析:字符串连接比三元运算有更高的优先级 所以原题等价于 'Value is true' ? 'Somthing' : 'Nonthing' 而不是 'Value is' + (true ? 'Something' : 'Nonthing') 巩固: 1 || fn() && fn() //1 1 || 1 ? 2 : 3 ; //2原型var a = {}, b = Object.prototype; [a.prototype === b, Object.getPrototypeOf(a) === b] 执行结果是多少呢 答案:false, true 解析:Object 的实例是 a,a上并没有prototype属性 a的__poroto__ 指向的是Object.prototype,也就是Object.getPrototypeOf(a)。a的原型对象是b原型IIfunction f() {} var a = f.prototype, b = Object.getPrototypeOf(f); a === b 这段代码的执行结果? 答案:false 解析:a是构造函数f的原型 : {constructor: ƒ} b是实例f的原型对象 : ƒ () { [native code] }函数名称function foo() { } var oldName = foo.name; foo.name = "bar"; [oldName, foo.name] 代码执行结果是什么? 答案:["foo", "foo"] 解析:函数的名字不可变.[typeof null, null instanceof Object]答案:["object", false] 解析:null代表空对象指针,所以typeof判断成一个对象。可以说JS设计上的一个BUG instanceof 实际上判断的是对象上构造函数,null是空当然不可能有构造函数 巩固:null == undefined //true null === undefined //flase[ [3,2,1].reduce(Math.pow), [].reduce(Math.pow) ]答案:Error 解析:Math.pow (x , y) x 的 y 次幂的值 reduce(fn,total) fn (total, currentValue, currentIndex, arr) 如果一个函数不传初始值,数组第一个组默认为初始值. [3,2,1].reduce(Math.pow) Math.pow(3,2) //9 Math.pow(9,1) //9 巩固题,可以做一做: [].reduce(Math.pow) //空数组会报TypeError [1].reduce(Math.pow) //只有初始值就不会执行回调函数,直接返回1 [].reduce(Math.pow,1) //只有初始值就不会执行回调函数,直接返回1 [2].reduce(Math.pow,3) //传入初始值,执行回调函数,返回9replace"1 2 3".replace(/\d/g, parseInt) 输出是什么呢? 答案:"1 NaN 3" 解析:replace() 回调函数的四个参数: 1、匹配项 2、与模式中的子表达式匹配的字符串 3、出现的位置 4、stringObject 本身 。 如果没有与子表达式匹配的项,第二参数为出现的位置.所以第一个参数是匹配项,第二个参数是位置 parseInt('1', 0) parseInt('2', 2) //2进制中不可能有2 parseInt('3', 4)eval用法function f() {} var parent = Object.getPrototypeOf(f); f.name // ? parent.name // ? typeof eval(f.name) // ? typeof eval(parent.name) // ? 这段代码的执行结果? 答案:"f", "Empty", "function", error 解析:f的函数名就是f parent是f原型对象的名字为"" , 先计算eval(f.name) 为 f,f的数据类型是function eval(parent.name) 为undefined, "undefined" new Date() var a = new Date("2014-03-19"), b = new Date(2014, 03, 19); [a.getDay() === b.getDay(), a.getMonth() === b.getMonth()] 这段代码的执行结果? 答案:[false, false] 解析:var a = new Date("2014-03-19") //能够识别这样的字符串,返回想要的日期 Wed Mar 19 2014 08:00:00 GMT+0800 (CST) b = new Date(2014, 03, 19); //参数要按照索引来 Sat Apr 19 2014 00:00:00 GMT+0800 (CST) 月是从0索引,日期是从1 getDay()是获取星期几 getMonth()是获取月份所以都不同 巩固: [a.getDate() === b.getDate()] //truenew Date() IIvar a = Date(0); var b = new Date(0); var c = new Date(); [a === b, b === c, a === c] 这段代码的执行结果? 答案:[false, false, false] 解析:当日期被作为构造函数调用时,它返回一个相对于划时代的对象(JAN 01 1970)。 当参数丢失时,它返回当前日期。当它作为函数调用时,它返回当前时间的字符串表示形式。 a是字符串 a === b // 数据类型都不同,肯定是false b是对象 b === c // 引用类型,比的是引用地址 c也是对象 a === c // 数据类型都不同,肯定是falsenew Date() IIIvar a = new Date("epoch") 你认为结果是多少呢? 答案:Invalid Date {} 解析:您得到"无效日期",这是一个实际的日期对象(一个日期的日期为true)。但无效。这是因为时间内部保持为一个数字,在这种情况下,它是NA。 在chrome上是undefined 正确的是格式是var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);Function.lengthvar a = Function.length, b = new Function().length a === b 这段代码的执行结果是? 答案:false 解析:首先new在函数带()时运算优先级和.一样所以从左向右执行 new Function() 的函数长度为0 巩固:function fn () { var a = 1; } console.log(fn.length) //0 fn和new Function()一样 要是看过往期的这篇文章[诚意满满✍]带你填一些JS容易出错的坑 就可以给我点个赞?关注一下啦,下面的内容都是这篇文章的内容。 [1,2,5,10].sort() 不写回调函数的话,是按照什么排序呢? JavaScript默认使用字典序(alphanumeric)来排序。因此结果是[1,10,2,5] 正确排序的话,应该[1,2,5,10].sort( (a,b) =>

AMub)

"b" + "a" + + "a" + "a"

What do you think the output is?

The above expression is the equivalent of 'baked since') + (+'a') +'a', because (+'a') is NaN, so:

'baked baby baby' + (+'a') +'a baby girl b'+'a girl + "NaN" +'a baby baby baNaNa'

Closure

This is a classic JavaScript interview question.

Let res = new Array () for (var I = 0; I

< 10; i++){ res.push(function(){ return console.log(i) }) } res[0]() res[1]() res[2]() 期望输出的是0,1,2,实际上却不会。原因就是涉及作用域,怎么解决呢? [x] 使用let代替var,形成块级作用域 [x] 使用bind函数。 res.push(console.log.bind(null, i)) 解法还有其他的,比如使用IIFE,形成私有作用域等等做法。 又一经典闭包问题function fun(n,o) { console.log(o) return { fun:function(m){ return fun(m,n); } }; } var a = fun(0); a.fun(1); a.fun(2); a.fun(3);//undefined,?,?,? var b = fun(0).fun(1).fun(2).fun(3);//undefined,?,?,? var c = fun(0).fun(1); c.fun(2); c.fun(3);//undefined,?,?,? 留给你们思考 隐式转换var a = [0]; if (a) { console.log(a == true); } else { console.log("wut"); } 你们觉得答案是多少呢?这题涉及到隐式转换了,这个坑我自己的好好补一补 // 答案:false 再来一道? function fn() { return 20; } console.log(fn + 10); // 输出结果是多少function fn() { return 20; } fn.toString = function() { return 10; } console.log(fn + 10); // 输出结果是多少?function fn() { return 20; } fn.toString = function() { return 10; } fn.valueOf = function() { return 5; } console.log(fn + 10); // 输出结果是多少? 说到底JS类型转换的好好补一补了 你真的理解操作符吗[1 value !== value;Number.isFinite & isFiniteNumber.isFinite('0') === isFinite('0') Number.isFinite(0) === isFinite('0') 打印结果是什么,能不能具体说一说? Number.isFinite()检测有穷性的值,唯一和全局isFinite()函数相比,这个方法不会强制将一个非数值的参数转换成数值,这就意味着,只有数值类型的值,且是有穷的(finite),才返回 true。 自然答案就是 false,true 一道容易被人轻视的面试题function Foo() { getName = function () { alert (1); }; return this; } Foo.getName = function () { alert (2);}; Foo.prototype.getName = function () { alert (3);}; var getName = function () { alert (4);}; function getName() { alert (5);} //请写出以下输出结果: Foo.getName(); getName(); Foo().getName(); getName(); new Foo.getName(); new Foo().getName(); new new Foo().getName();push方法let newList = [1,2,3].push(4) console.log(newList.push(4)) 认为输出什么? // Error 原因在于Array.prototype.push()返回的是新数组的长度,所以呢4.push(5)自然Error 自动分号插入function foo1() { return { bar: "hello" }; } function foo2() { return { bar: "hello" }; } var a=foo1(); var b=foo2(); console.log(a) //Object {bar: "hello"} console.log(b) //underfind //仔细看就知道了 // 会在第10行加入一个`;` 会在第10行自动加一个分号; 所以返回的就是undefined let varfunction foo() { let a = b = 0; a++; return a; } foo(); typeof a; // =>

??? Typeof b; / / = >?

The above let a = b = 0; equivalent to window.b = 0, let a = b

Eyesight problem const length = 4; const numbers = []; for (var I = 0; I

< length; i++);{ numbers.push(i + 1); } numbers; // =>

???

The only thing to pay attention to is that there is a sand sculpture after the for statement.

If you add;, you will think that for is finished, so all you specify are empty statements, and finally the numbers is [5].

Get the specific index character console.log ('Hello World' [4]) in the string

Square brackets are used to get the characters of a specific index of a string. It is worth noting that the lower version of IE7 uses charAt ().

So the output of this question o

! = const name = 'TianTianUp' console.log (! typeof name =' string') console.log (! typeof name = 'object')

Typeof name returns a 'string', string' string' is a truth value. So! typeof name returns a Boolean value of false. So

False = 'string'

And false = = 'object' returns false

(to detect a type of value, we should use! = instead of! typeof)

ForEachconst nums = [1,2,3,4,5,6]; let firstEven; nums.forEach (n = > {if (n% 2 = 0) {firstEven = n; return n;}}); console.log (firstEven)

The only thing to pay attention to is how the forEach source code is written. Anyone who has read the source code knows that forEach cannot stop the loop with return, or each time the callback function is called, it terminates the current one, not the whole loop.

Naturally, the result is 6.

This is the end of this article on "what are the error-prone pits in JS?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report