Dealing with == and ===
false == 0 or "" == 0 return true.
always use the === and !==
Operators that check both the values and the type of the exPRessions you compare:
var zero = 0;if (zero === false) { // not executing because zero is 0, not false}// antipatternif (zero == false) { // this block is executed...}
Avoiding eval()
// antipatternvar property = "name";alert(eval("obj." + property));// preferredvar property = "name";alert(obj[property]);
Security implications (e.g. JSON response from an Ajax request)
1. For browsers that don't support JSON.parse() natively, you can use a library from JSON.org.
2. passing strings to setInterval(), setTimeout(), and the Function() constructor is, for the most part, similar to using eval()and therefore should be avoided.
// antipatternssetTimeout("myFunc()", 1000);setTimeout("myFunc(1, 2, 3)", 1000);// preferredsetTimeout(myFunc, 1000);setTimeout(function () { myFunc(1, 2, 3);}, 1000);
3. Using the new Function() constructor is similar to eval() and should be approached with care.
console.log(typeof un); // "undefined"console.log(typeof deux); // "undefined"console.log(typeof trois); // "undefined"var jsstring = "var un = 1; console.log(un);";eval(jsstring); // logs "1"jsstring = "var deux = 2; console.log(deux);";new Function(jsstring)(); // logs "2"jsstring = "var trois = 3; console.log(trois);";(function () { eval(jsstring);}()); // logs "3"console.log(typeof un); // "number"console.log(typeof deux); // "undefined"console.log(typeof trois); // "undefined"
(function () { var local = 1; eval("local = 3; console.log(local)"); // logs 3 console.log(local); // logs 3}());(function () { var local = 1; Function("console.log(typeof local);")(); // logs undefined}());
新闻热点
疑难解答