10 个 JavaScript 容易犯的错误

2022-12-23 0 1,183

JavaScript 是两门单纯的如前所述C词汇,自学他很难,但词汇句法去不细致,这就引致了很难犯错误,但却不晓得严重错误在这儿,那时给他们列出呵呵10个 JavaScript 难犯的严重错误,或许你也那么干过?

10 个 JavaScript 容易犯的错误

1、遇害的四元组

JavaScript 时常犯的严重错误是略去括弧前面的新闻稿,比如说:if、else、 while 和 for 。尽管这是容许的,你要分外留神,即便此种作法常常是暗藏的难题和严重错误

// Say hello to Gandalfhello(Gandalf);function hello(name){// This code doesnt do what the indentation implies! if(name === undefined) console.log(Please enter a username!); fail();// The following line is never reached: success(name);}function success(name){ console.log(Hello, + name +!);}function fail(){ throw new Error(“Name is missing. Cant say hello!”);}

尽管 fail()表达式是对齐的,看上去好似是归属于 if 句子。因此四元组常常紧紧围绕当中的标识符块是两个较好的作法,即便是多于两个句子。

2、缺乏王劝

当 JavaScript 导出,有两个操作过程称作手动王劝的填入。简而言之,解释器是乐于把你遗失王劝。此机能的目地是使 JavaScript 更和蔼可亲,更难写的新手。不过你如果常常包涵王劝,即便有在忽视她们的脆弱。这儿有两个范例:

console.log(Welcome the fellowship!)[Frodo,Gandalf,Legolas,Gimli].forEach(function(name){ hello(name)})function hello(name){ console.log(Hello, + name +!)}

即便有两个王劝在3 行遇害,解释器假定已经开始第六展枝两个试著采用字符串句法出访特性出访器,而并非两个分立的字符串,这并非他们所期许的,在两个类别严重错误的结果。解决方法是单纯的常常写王劝。一些有经验的 JavaScript 开发者喜欢把王劝但,她们非常清楚的严重错误,这可能会引致和晓得如何阻止她们。

3、变量类别强制转换

JavaScript 是动态类别。这意味着,你不需要指定类别时,宣布两个新的变量,并可以自由转让或将其价值。这使得写的并非像 C 或 Java 非常难,但你打开门,潜在的严重错误,在其他词汇被编译步骤期间。这儿有两个范例:

var textBox = document.querySelector(input);textBox.addEventListener(input, function(){// textBox.value holds a string. Adding 10 appends // the string 10, it doesnt perform an addition.. console.log(textBox.value + +10= + (textBox.value +10));});

这个难题可以通过采用固定的难 parseInt(textBox.value,10)将字符串转换为数字前加10。取决于你如何采用变量,运行时可能会决定它如果在一种或另一种类别转换。这是众所周知的类别强制。为了防止类别的隐式转换比较时,变量如果报表,您可以采用严格的平等的检查(===)。

4、忘了 var

另一种作法,新手是有罪的,被遗忘的采用 var 关键词时,变量的新闻稿。JavaScript 是非常宽容的,并在第一时间看到你采用两个可变的无 var 句子,它将为你默默地宣布全球。这可以是微妙的严重错误源。这儿有两个范例,这也显示出不同的严重错误缺乏逗号时新闻稿多个变量一次:

var a =1, b =2, c =3;function alphabet(str){ var a =A, b =B// Oops, missing , here! c =C, d =D; return str + + a + b + c +…;}console.log( alphabet(“Lets say the alphabet!”));// Oh no! Something went wrong! c has a new value!console.log(a, b, c);

当解释器达到4 线,它会手动填入两个王劝,然后解释 C 和 D 5号线的新闻稿为全局。这将引致外部 C 变量的值的变化。

5、浮动小数的运算

几乎所有的C词汇都有这个严重错误,包括 JavaScript 。由于道路浮点数在内存中表示算术运算,并没有你想的那么精确。这儿有两个范例:

var a =0.1, b =0.2;// Surprise! this is false:console.log(a + b ==0.3);// Because 0.1+ 0.2 does not produce the number that you expect:console.log(0.1+ 0.2= , a + b);阅读更多JavaScript的陷阱在这儿。

为了解决这个难题,你不如果采用小数,如果你需要绝对正确采用整数。

6、在文字采用构造表达式

当 Java 和 C 程序员已经开始编写 JavaScript,她们通常更喜欢采用构造表达式创建对象:new Array()、 new Object()、new String()。尽管她们都非常支持,建议采用文字符号:[]{}””,即便构造表达式有微妙的特点:

/* Using array constructors is valid, but not recommended. Here is why.*/// Create an array with four elements:var elem4= new Array(1,2,3,4);console.log(Four element array: + elem4.length);// Create an array with one element. It doesnt do what you think it does:var elem1= new Array(23);console.log(One element array? + elem1.length);/* String objects also have their warts */var str1= new String(JavaScript), str2= “JavaScript”;// Strict equality breaks:console.log(“Is str1 the same as str2?”, str1=== str2);

解决的方法很单纯:试著常常采用文字符号。

7、不晓得变量的作用范围

新手的两个难以理解的概念是 JavaScript 的作用域规则和关闭。这是理所当然的:

// Print the numbers from 1 to 10,100ms apart. Or not.for(var i =0; i <10; i++){ setTimeout(function(){ console.log(i+1);},100*i);}/* To fix the bug, wrap the code in a self-executing function expression:for(var i =0; i <10; i++){(function(i){ setTimeout(function(){ console.log(i+1);},100*i);})(i);}*/

机能保留的能见度变量在其父母的范围。但,即便他们有两个延缓执行 setTimeout 的时候,机能,实际运行,循环已经完成 I 变量递增到11。自我评论工作执行的机能,即便它复制 I 变量的值和保持两个私人复制每个超时机能。

8、采用 eval

它被认为是一种不好的作法,当你采用它的时候,有两个更好、更快的方法。

/* Using eval to access properties dynamically */var obj ={ name:Foo Barski, age:30, profession:Programmer};// Which property to access?var access =profession;// This is a bad practice. Please dont do it:console.log( eval(obj.name +” is a “+ obj.+ access));// Instead, use array notation to access properties dynamically:console.log( obj.name +” is a “+ obj[access]);/* Using eval in setTimout */// Also bad practice. It is slow and difficult to read and debug:setTimeout( if(obj.age ==30) console.log(“This is eval-ed code,”+ obj[access]+ “!”);,100);// This is better:setTimeout(function(){ if(obj.age ==30){ console.log(This code is not eval-ed, + obj[access]+ !);}},100);

eval 是两个字符串。调试从 eval 块所产生的信息是难以理解的,你要逃避的单和双引号。更不用说它比 JavaScript 慢。不要采用 eval,除非你晓得你正在做什么。

9、不了解异步标识符

有一些独特的 JavaScript,几乎一切都是异步的,你需要通过回调表达式

var userData ={};// Fetch the location data for the current user.load();// Output the location of the user. Oops, it doesnt work! Why?console.log(Hello! Your IP address is + userData.ip + and your country is + userData.countryname);// The load function will detect the current visitors ip and location with ajax, using the// freegeoip service. It will place the returned data in the userData variable when its ready.function load(){$.getJSON(http://freegeoip.net/json/?callback=?, function(response){ userData = response;// Uncomment this line to see what is returned:// console.log(response);});}

即便 console.log 之后 load()表达式调用,它实际上是在执行读取数据。

10、滥用事件侦听器

让他们说,你想要听两个按钮点击,但多于两个复选框。这儿是如何两个新手可能做它(jQuery):

var checkbox =$(input[type=checkbox]), button =$(button);// We want to listen for clicks only when the checkbox is marked.checkbox.on(change, function(){// Is the checkbox checked? if(this.checked){// Listen for clicks on the button. button.on(click, function(){// This alert is called more than once. Why? alert(Hello!);});}});

这显然是严重错误的。理想情况下,你如果倾听事件多于一次,就像他们是复选框的变化事件。在按钮上绑定多个 button.on(click)事件侦听器,是永远不会被删除,结果我将把它作为为读者做这工作的两个练习。

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务