In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the practical JavaScript skills". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the practical JavaScript skills"?
1-Don't forget to use the var keyword when assigning a value to a variable * *
Assigning a value to an undefined variable causes a global variable to be created. Avoid global variables.
2-use = instead of =
The = = (or! =) operator automatically performs type conversions when needed. The = = (or! =) operation does not perform any conversion. It compares values and types and is considered to be better than = = in terms of speed.
[10] = = 10 / / is false [10] = 10 / / is true '10' = = 10 / / is true' 10' = = 10 / / is false [] = 0 / / is true [] = = 0 / / is false''= = false / / is true but true = "a" is false''= false / / is false
3-use closures to implement private variables (added by translator)
Function Person (name, age) {this.getName = function () {return name;}; this.setName = function (newName) {name = newName;}; this.getAge = function () {return age;}; this.setAge = function (newAge) {age = newAge;}; / / property var occupation; this.getOccupation = function () {return occupation;} that is not initialized in the constructor This.setOccupation = function (newOcc) {occupation = newOcc;};}
4-use colons at the end of the line
It is a good practice to use colons at the end of a line. You won't be warned if you forget to write, because in most cases the JavaScript interpreter will add a colon for you.
5-create the constructor of the object
Function Person (firstName, lastName) {this.firstName = firstName; this.lastName = lastName;} var Saad = new Person ("Saad", "Mousliki")
6-be careful with typeof, instanceof, and constructor
Var arr = ["a", "b", "c"]; typeof arr; / / return "object" arr instanceof Array / / true arr.constructor (); / / []
7-create a self-calling function (Self-calling Funtion)
This is often referred to as self-calling anonymous functions (Self-Invoked Anonymous Function) or instant call function expressions (IIFE-Immediately Invoked Function Expression). This is a function that executes automatically immediately after creation, usually as follows:
(function () {/ / some private code that will be executed automatically}) (); (function (amemb) {var result = axib; return result;}) (10meme 20)
-get a random item from the array
Var items = [12,548,'a', 2, 5478, 'foo', 8852,' Doe', 2145]; var randomItem = items [Math.floor (Math.random () * items.length)]
9-get a random number within a specific range
This code snippet is useful when you want to generate test data, such as a random salary value between the minimum * values.
Var x = Math.floor (Math.random () * (max-min + 1)) + min
10-generates an array of numbers between 0 and the set * value
Var numbersArray = [], max = 100; for (var iTunes 1; numbersArray.push (iTunes +)
< max;); // numbers = [0,1,2,3 ... 100] 11 – 生成一个随机的数字字母字符串 function generateRandomAlphaNum(len) { var rdmstring = ""; for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2)); return rdmString.substr(0, len); } 【译者注:特意查了一下Math.random()生成0到1之间的随机数,number.toString(36)是将这个数字转换成36进制(0-9,a-z),***substr去掉前面的"0."字符串】 12 – 打乱一个数字数组 var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411]; numbers = numbers.sort(function(){ return Math.random() - 0.5}); /* the array numbers will be equal for example to [120, 5, 228, -215, 400, 458, -85411, 122205] */ 13 – String的trim函数 在Java、C#、PHP和很多其他语言中都有一个经典的 trim 函数,用来去除字符串中的空格符,而在JavaScript中并没有,所以我们需要在String对象上加上这个函数。 String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");}; 【译者注:去掉字符串的前后空格,不包括字符串内部空格】 14 – 附加(append)一个数组到另一个数组上 var array1 = [12 , "foo" , {name: "Joe"} , -2458]; var array2 = ["Doe" , 555 , 100]; Array.prototype.push.apply(array1, array2); /* array1 will be equal to [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */ 【译者注:其实concat可以直接实现两个数组的连接,但是它的返回值是一个新的数组。这里是直接改变array1】 15 – 将arguments对象转换成一个数组 var argArray = Array.prototype.slice.call(arguments); 【译者注:arguments对象是一个类数组对象,但不是一个真正的数组】 16 – 验证参数是否是数字(number) function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n); } 17 – 验证参数是否是数组 function isArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]' ; } 注意:如果toString()方法被重写了(overridden),你使用这个技巧就不能得到想要的结果了。或者你可以使用: Array.isArray(obj); // 这是一个新的array的方法 如果你不在使用多重frames的情况下,你还可以使用 instanceof 方法。但如果你有多个上下文,你就会得到错误的结果。 var myFrame = document.createElement('iframe'); document.body.appendChild(myFrame); var myArray = window.frames[window.frames.length-1].Array; var arr = new myArray(a,b,10); // [a,b,10] // instanceof will not work correctly, myArray loses his constructor // constructor is not shared between frames arr instanceof Array; // false 【译者注:关于如何判断数组网上有不少讨论,大家可以google一下。这篇就写的挺详细的。】 18 – 获取一个数字数组中的***值或最小值 var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411]; var maxInNumbers = Math.max.apply(Math, numbers); var minInNumbers = Math.min.apply(Math, numbers); 译者注:这里使用了Function.prototype.apply方法传递参数的技巧】 19 – 清空一个数组 var myArray = [12 , 222 , 1000 ]; myArray.length = 0; // myArray will be equal to []. 20 – 不要使用 delete 来删除一个数组中的项。 使用 splice 而不要使用 delete 来删除数组中的某个项。使用 delete 只是用 undefined 来替换掉原有的项,并不是真正的从数组中删除。 不要使用这种方式: var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ]; items.length; // return 11 delete items[3]; // return true items.length; // return 11 /* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */ 而使用: var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ]; items.length; // return 11 items.splice(3,1) ; items.length; // return 10 /* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */ delete 方法应该被用来删除一个对象的某个属性。 21 – 使用 length 来截短一个数组 跟上面的清空数组的方式类似,我们使用 length 属性来截短一个数组。 var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ]; myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124]. 此外,如果你将一个数组的 length 设置成一个比现在大的值,那么这个数组的长度就会被改变,会增加新的 undefined 的项补上。 数组的 length 不是一个只读属性。 myArray.length = 10; // the new array length is 10 myArray[myArray.length - 1] ; // undefined 22 – 使用逻辑 AND/OR 做条件判断 var foo = 10; foo == 10 && doSomething(); // 等价于 if (foo == 10) doSomething(); foo == 5 || doSomething(); // 等价于 if (foo != 5) doSomething(); 逻辑 AND 还可以被使用来为函数参数设置默认值 function doSomething(arg1){ Arg1 = arg1 || 10; // 如果arg1没有被设置的话,Arg1将被默认设成10 } 23 – 使用 map() 方法来遍历一个数组里的项 var squares = [1,2,3,4].map(function (val) { return val * val; }); // squares will be equal to [1, 4, 9, 16] 24 – 四舍五入一个数字,保留N位小数 var num =2.443242342; num = num.toFixed(4); // num will be equal to 2.4432 25 – 浮点数问题 0.1 + 0.2 === 0.3 // is false 9007199254740992 + 1 // is equal to 9007199254740992 9007199254740992 + 2 // is equal to 9007199254740994 为什么会这样? 0.1+0.2等于0.30000000000000004。你要知道,所有的JavaScript数字在内部都是以64位二进制表示的浮点数,符合IEEE 754标准。更多的介绍,可以阅读这篇博文。你可以使用 toFixed() 和 toPrecision() 方法解决这个问题。 26 – 使用for-in遍历一个对象内部属性的时候注意检查属性 下面的代码片段能够避免在遍历一个对象属性的时候访问原型的属性 for (var name in object) { if (object.hasOwnProperty(name)) { // do something with name } } 27 – 逗号操作符 var a = 0; var b = ( a++, 99 ); console.log(a); // a will be equal to 1 console.log(b); // b is equal to 99 28 – 缓存需要计算和查询(calculation or querying)的变量 对于jQuery选择器,我们***缓存这些DOM元素。 var navright = document.querySelector('#right'); var navleft = document.querySelector('#left'); var navup = document.querySelector('#up'); var navdown = document.querySelector('#down'); 29 – 在调用 isFinite()之前验证参数 isFinite(0/0) ; // false isFinite("foo"); // false isFinite("10"); // true isFinite(10); // true isFinite(undifined); // false isFinite(); // false isFinite(null); // true !!! 30 – 避免数组中的负数索引(negative indexes) var numbersArray = [1,2,3,4,5]; var from = numbersArray.indexOf("foo") ; // from is equal to -1 numbersArray.splice(from,2); // will return [5] 确保调用 indexOf 时的参数不是负数。 31 – 基于JSON的序列化和反序列化(serialization and deserialization) var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} }; var stringFromPerson = JSON.stringify(person); /* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */ var personFromString = JSON.parse(stringFromPerson); /* personFromString is equal to person object */ 32 – 避免使用 eval() 和 Function 构造函数 使用 eval 和 Function 构造函数是非常昂贵的操作,因为每次他们都会调用脚本引擎将源代码转换成可执行代码。 var func1 = new Function(functionCode); var func2 = eval(functionCode); 33 – 避免使用 with() 使用 with() 会插入一个全局变量。因此,同名的变量会被覆盖值而引起不必要的麻烦。 34 – 避免使用 for-in 来遍历一个数组 避免使用这样的方式: var sum = 0; for (var i in arrayNumbers) { sum += arrayNumbers[i]; } 更好的方式是: var sum = 0; for (var i = 0, len = arrayNumbers.length; i < len; i++) { sum += arrayNumbers[i]; } 附加的好处是,i 和 len 两个变量的取值都只执行了一次,会比下面的方式更高效: for (var i = 0; i < arrayNumbers.length; i++) 为什么?因为arrayNumbers.length每次循环的时候都会被计算。 35 – 在调用 setTimeout() 和 setInterval() 的时候传入函数,而不是字符串。 如果你将字符串传递给 setTimeout() 或者 setInterval(),这个字符串将被如使用 eval 一样被解析,这个是非常耗时的。 不要使用: setInterval('doSomethingPeriodically()', 1000); setTimeOut('doSomethingAfterFiveSeconds()', 5000) 而用: setInterval(doSomethingPeriodically, 1000); setTimeOut(doSomethingAfterFiveSeconds, 5000); 36 – 使用 switch/case 语句,而不是一长串的 if/else 在判断情况大于2种的时候,使用 switch/case 更高效,而且更优雅(更易于组织代码)。但在判断的情况超过10种的时候不要使用 switch/case。 【译者注:查了一下文献,大家可以看一下这篇介绍】 37 – 在判断数值范围时使用 switch/case 在下面的这种情况,使用 switch/case 判断数值范围的时候是合理的: function getCategory(age) { var category = ""; switch (true) { case isNaN(age): category = "not an age"; break; case (age >= 50): category = "Old"; break; case (age
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.