In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what are the practical skills of javascript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Operation of js integers
Using | 0 and ~ ~ can convert floating point to integer and is faster than similar parseInt,Math.round in terms of efficiency, which is useful when dealing with effects such as pixel and animation displacement. For performance comparison, see here.
Var foo = (12.4 / 4.13) | 0 governance / result is 3var bar = ~ (12.4 / 4.13); / / result is 3
There is another trick, that is! 2 exclamation marks, you can say a value, quickly converted to a Boolean value. You can test it!
Var eee= "eee"; alert (!! eee)
True is returned, which means that any value is preceded by!! Can always be equal to true. Unless this value is already a Boolean, or undefined, null, 0, false, NaN,'', because I mentioned undefined, null, 0, false, NaN,'', these are already false, so I added two!! After that, it's still fasle.
Second, rewrite the native alert and record the number of pop-ups (function () {var oldAlert = window.alert, count = 0; window.alert = function (a) {count++; oldAlert (a + "\ n You've called alert" + count+ "times now. Stop, it's evil!");};}) (); alert ("Hello Haorooms"); third, the method of digital exchange without declaring intermediate variables
To exchange between two numbers, our general practice is to declare an intermediate variable, but today's practice is rather bizarre, do not declare intermediate variables, see how it is implemented!
Var aplom1 and / or the export of aRom 2 and [b]. [0]; console.log ('aRV).
So, does this method have a new feeling?
IV. All things are objects
In the world of JavaScript, everything is an object. In addition to null and undefined, other basic types of numbers, strings, and Boolean values all have corresponding wrapper objects. One of the features of an object is that you can call methods directly on it.
For numeric primitive types, an attempt to call the toString method on it will fail, but the call will not fail after it is enclosed in parentheses. The internal implementation is to convert the primitive type to an object with the corresponding wrapper object. So (1) .toString () is equivalent to new Number (1) .toString (). Therefore, you can really use the basic types of numbers, strings, Boolean, etc., as objects, just pay attention to the syntax appropriately.
At the same time, we notice that there is no distinction between floating point and shaping in JavaScript. All numbers are actually floating point, but the decimal point is omitted. For example, the 1 you see can be written as 1. That's why you will report an error when you try to 1.toString (), so the correct way to write it is: 1..toString (), or add parentheses as described above, the function of parentheses here is to correct the JS parser. Don't treat the dot after 1 as a decimal point. The internal implementation, as described above, is to set 1. Convert the wrapper object to an object and then call the method.
Fifth, the deformation of If sentence
When you need to write an if statement, try an easier way to use the logical operators in JavaScript instead.
For example, the above code, first get today's date, if it is Sunday, then pop-up window, otherwise do nothing. We know that the logic operation has a short circuit, for logic and expression, only if both are true can the result be true. If the previous day variable is judged to be false, then the result is false for the whole and expression, so it will not continue to execute the following alert. If the previous day is true, then continue to execute the following code to determine the authenticity of the entire expression. Take advantage of this to achieve the effect of if.
For traditional if statements, if you execute more than one statement, you need curly braces, while with a comma expression, you can execute any piece of code without curly braces.
If (conditoin) alert (1), alert (2), console.log (3)
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 7, using closures to implement the private variable 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;} Function Person (firstName, lastName) {this.firstName = firstName; this.lastName = lastName;} var Saad = new Person ("Saad", "Mousliki"); IX. Use typeof, instanceof and constructorvar arr = ["a", "b", "c"] carefully; typeof arr; / / return "object" arr instanceof Array / / truearr.constructor (); / / [] X. 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 is automatically executed immediately after creation.
It is usually as follows:
(function () {/ / some private code that will be executed automatically}) (); (function (amemb) {var result = astatb; return result;}) (10Power20) 11. Get a random term var items = [12,548,'a', 2, 5478, 'foo', 8852,' Doe', 2145] from the array; var randomItem = items [Math.floor (Math.random () * items.length)] 12. 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 and maximum values.
Var x = Math.floor (Math.random () * (max-min + 1)) + min; XIII. Generate an array of numbers between 0 and the set maximum value var numbersArray = [], max = 100 for (var iTunes 1; numbersArray.push (iTunes +))
< max;); // numbers = [0,1,2,3 ... 100]十四、生成一个随机的数字字母字符串function generateRandomAlphaNum(len) { var rdmstring = ""; for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2)); return rdmString.substr(0, len);}//调用方法generateRandomAlphaNum(15);十五、打乱一个数字数组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] */十六、 String的trim函数String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");};十七、 附加(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] */十八、将arguments对象转换成一个数组var argArray = Array.prototype.slice.call(arguments); 【译者注:arguments对象是一个类数组对象,但不是一个真正的数组】 十九、验证参数是否是数字(number) function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n); } 二十、验证参数是否是数组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 framesarr instanceof Array; // false 【译者注:关于如何判断数组网上有不少讨论,大家可以google一下。这篇就写的挺详细的。】 二十一、获取一个数字数组中的最大值或最小值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方法传递参数的技巧】 二十二、清空一个数组var myArray = [12 , 222 , 1000 ];myArray.length = 0; // myArray will be equal to [].二十三、不要使用 delete 来删除一个数组中的项。 使用 splice 而不要使用 delete 来删除数组中的某个项。使用 delete 只是用 undefined 来替换掉原有的项,并不是真正的从数组中删除。 不要使用这种方式: var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];items.length; // return 11delete items[3]; // return trueitems.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 11items.splice(3,1) ;items.length; // return 10/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */ delete 方法应该被用来删除一个对象的某个属性。 二十四、使用 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 10myArray[myArray.length - 1] ; // undefined二十五、使用逻辑 AND/OR 做条件判断 同(五),if变形语句! 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}二十六、使用 map() 方法来遍历一个数组里的项var squares = [1,2,3,4].map(function (val) { return val * val;});// squares will be equal to [1, 4, 9, 16]二十七、四舍五入一个数字,保留N位小数var num =2.443242342;num = num.toFixed(4); // num will be equal to 2.4432二十八、浮点数问题0.1 + 0.2 === 0.3 // is false9007199254740992 + 1 // is equal to 90071992547409929007199254740992 + 2 // is equal to 9007199254740994 为什么会这样? 0.1+0.2等于0.30000000000000004。你要知道,所有的JavaScript数字在内部都是以64位二进制表示的浮点数,符合IEEE 754标准。更多的介绍,可以阅读这篇博文。你可以使用 toFixed() 和 toPrecision() 方法解决这个问题。 二十九、使用for-in遍历一个对象内部属性的时候注意检查属性 下面的代码片段能够避免在遍历一个对象属性的时候访问原型的属性 for (var name in object) { if (object.hasOwnProperty(name)) { // do something with name }}三十、 逗号操作符var a = 0;var b = ( a++, 99 );console.log(a); // a will be equal to 1console.log(b); // b is equal to 99三十一、缓存需要计算和查询(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');三十二、在调用 isFinite()之前验证参数isFinite(0/0) ; // falseisFinite("foo"); // falseisFinite("10"); // trueisFinite(10); // trueisFinite(undifined); // falseisFinite(); // falseisFinite(null); // true !!!三十三、避免数组中的负数索引(negative indexes)var numbersArray = [1,2,3,4,5];var from = numbersArray.indexOf("foo") ; // from is equal to -1numbersArray.splice(from,2); // will return [5] 确保调用 indexOf 时的参数不是负数。 三十四、基于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 */三十五、避免使用 eval() 和 Function 构造函数 使用 eval 和 Function 构造函数是非常昂贵的操作,因为每次他们都会调用脚本引擎将源代码转换成可执行代码。 var func1 = new Function(functionCode);var func2 = eval(functionCode);三十六、避免使用 with() 使用 with() 会插入一个全局变量。因此,同名的变量会被覆盖值而引起不必要的麻烦。 三十七、避免使用 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每次循环的时候都会被计算。 三十八、在调用 setTimeout() 和 setInterval() 的时候传入函数,而不是字符串。 如果你将字符串传递给 setTimeout() 或者 setInterval() ,这个字符串将被如使用 eval 一样被解析,这个是非常耗时的。 不要使用: setInterval('doSomethingPeriodically()', 1000);setTimeOut('doSomethingAfterFiveSeconds()', 5000) 而用: setInterval(doSomethingPeriodically, 1000);setTimeOut(doSomethingAfterFiveSeconds, 5000);三十九、使用 switch/case 语句,而不是一长串的 if/else 在判断情况大于2种的时候,使用 switch/case 更高效,而且更优雅(更易于组织代码)。但在判断的情况超过10种的时候不要使用 switch/case。 四十、在判断数值范围时使用 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.