1.Insert item inside an Array(向数组中插入元素)
 
向一个数组中插入元素是平时很常见的一件事情。你可以使用push在数组尾部插入元素,可以用unshift在数组头部插入元素,也可以用splice在数组中间插入元素。
 
   var arr = [1,2,3,4,5];

   //old method

   arr.push(6);

   //new method 快43%

   arr[arr.length] = 6;      

   var arr = [1,2,3,4,5];

  //old method

   arr.unshift(0);

  //new method 快98%

  [0].concat(arr);
 
2.Improve Nested Conditionals(优化嵌套的条件语句) 
 
面对大量的if-else语句
 
 
   //method1

       if (color) {

           if (color === 'black') {

               printBlackBackground();

           } else if (color === 'red') {

               printRedBackground();

          } else if (color === 'blue') {

               printBlueBackground();

          } else if (color === 'green') {

              printGreenBackground();

          } else {

              printYellowBackground();

          }

     }

      

  //method2

      switch(color) {

          case 'black':

              printBlackBackground();

              break;

          case 'red':

              printRedBackground();

              break;

          case 'blue':

              printBlueBackground();

              break;

          case 'green':

              printGreenBackground();

              break;

          default:

              printYellowBackground();

      }      

  //method3

      switch(true) {

          case (typeof color === 'string' && color === 'black'):

              printBlackBackground();

              break;

          case (typeof color === 'string' && color === 'red'):

              printRedBackground();

              break;

          case (typeof color === 'string' && color === 'blue'):

              printBlueBackground();

              break;

          case (typeof color === 'string' && color === 'green'):

              printGreenBackground();

              break;

          case (typeof color === 'string' && color === 'yellow'):

              printYellowBackground();

              break;

}      

  //method4

      var colorObj = {

          'black': printBlackBackground,

       'red': printRedBackground,

        'blue': printBlueBackground,

       'green': printGreenBackground,

    'yellow': printYellowBackground

   };

 if (color in colorObj) {

   colorObj[color]();

    }
 
 
 
3.Sorting strings with accented characters(排列含音节字母的字符串)
 
Javascript有一个原生方法sort可以排列数组。一次简单的array.sort()将每一个数组元素视为字符串并按照字母表排列。但是当你试图整理一个非ASCII元素的数组时,你可能会得到一个奇怪的结果。
 
 
  ['Shanghai', 'New York', 'Mumbai', 'Buenos Aires'].sort();

// ["Buenos Aires", "Mumbai", "New York", "Shanghai"] 

 //method1

   // 西班牙语

  ['único','árbol', 'cosas', 'fútbol'].sort();

   // ["cosas", "fútbol", "árbol", "único"] // bad order

 // 德语

  ['Woche', 'wöchentlich', 'wäre', 'Wann'].sort();

 // ["Wann", "Woche", "wäre", "wöchentlich"] // bad order

 //method2

  ['único','árbol', 'cosas', 'fútbol'].sort(Intl.Collator().compare);

  // ["árbol", "cosas", "fútbol", "único"]

  ['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(Intl.Collator().compare);

   // ["Wann", "wäre", "Woche", "wöchentlich"]
 
 
 
4.Differences between undefined and null(undefined与null的区别)
 
undefined表示一个变量没有被声明,或者被声明了但没有被赋值


null是一个表示“没有值”的值


Javascript将未赋值的变量默认值设为undefined


Javascript从来不会将变量设为null。它是用来让程序员表明某个用var声明的变量时没有值的。


undefined不是一个有效的JSON,而null是


undefined的类型(typeof)是undefined


null的类型(typeof)是object. 


它们都是基本类型


null === undefined // false
 
 
 
5.Check if a property is in a Object(检查某对象是否有某属性)
 
 
 //method1

   var myObject = {

   name: '@tips_js'

   };

 if (myObject.name) { }

//method2

 var myObject = {

   name: '@tips_js'

     };


 myObject.hasOwnProperty('name'); // true

  'name' in myObject; // true


   myObject.hasOwnProperty('valueOf'); // false, valueOf 继承自原型链

     'valueOf' in myObject; // true
 
两者检查属性的深度不同,换言之hasOwnProperty只在本身有此属性时返回true,而in操作符不区分属性来自于本身或继承自原型链。
 
 
 
6.Tip to measure performance of a javascript block(测量javascript代码块性能的小知识)
 
快速的测量javascript的性能,我们可以使用console的方法,例如 
 
 
console.time("Array initialize");

 var arr = new Array(100),

   len = arr.length,

 i;

for (i = 0; i < len; i++) {

    arr[i] = new Object();

 };

 console.timeEnd("Array initialize"); // 0.711ms
 
 
 
7.Fat Arrow Functions(箭头函数)
 
语法: 更少的代码行; 不再需要一遍一遍的打function了
 
语义: 从上下文中捕获this关键字
 
 
// 使用functions

 var arr = [5,3,2,9,1];

 var arrFunc = arr.map(function(x) {

return x * x;

});

console.log(arrFunc )

 // 使用箭头函数

 var arr = [5,3,2,9,1];

var arrFunc = arr.map((x) => x*x);

  console.log(arrFunc )
 
箭头函数在这种情况下省去了写小括号,function以及return的时间。
 
 
 
8.Even simpler way of using indexOf as a contains clause(更简单的使用indexOf实现contains功能)
 
JavaScript并未提供contains方法。检测子字符串是否存在于字符串或者变量是否存在于数组你可能会这样做。
 
 
 var someText = 'javascript rules';

 if (someText.indexOf('javascript') !== -1) {

}

 // or

 if (someText.indexOf('javascript') >= 0) {

}
 
建议的方法:
 
  var someText = 'text';

 !!~someText.indexOf('tex'); // someText contains "tex" - true

 !~someText.indexOf('tex'); // someText NOT contains "tex" - false

  ~someText.indexOf('asd'); // someText doesn't contain "asd" - false

  ~someText.indexOf('ext'); // someText contains "ext" - true
 
 
9.Rounding the fast way(更快的取整)
 
一个位操作符 ~ 将输入的32位的数字(input)转换为 -(input+1). 两个位操作符将输入(input)转变为 -(-(input + 1)+1) 是一个使结果趋向于0的取整好工具. 对于数字, 负数就像使用Math.ceil()方法而正数就像使用Math.floor()方法. 转换失败时,返回0,这在Math.floor()方法转换失败返回NaN时或许会派上用场。
 
// 单个 ~
console.log(~1337)    // -1338

  // 数字输入

 console.log(~~47.11)  // -> 47

 console.log(~~-12.88) // -> -12

 console.log(~~1.9999) // -> 1

  console.log(~~3)      // -> 3

  // 转换失败

 console.log(~~[]) // -> 0

console.log(~~NaN)  // -> 0

 console.log(~~null) // -> 0

  // 大于32位整数时转换失败

  console.log(~~(2147483647 + 1) === (2147483647 + 1)) // -> 0
 
 
 
10.Safe string concatenation
 
 
 //method 1

 var one = 1;

 var two = 2;

 var three = '3';

  var result = ''.concat(one, two, three); //"123"

  //method 2

 var one = 1;

var two = 2;

 var three = '3';

var result = one + two + three; //"33" instead of "123"



拼接时使用加号,可能会导致意想不到的错误结果。
 
 
 
11.Return objects to enable chaining of functions(返回对象,使方法可以链式调用)
 
 
function Person(name) {

 this.name = name;

  this.sayName = function() {

    console.log("Hello my name is: ", this.name);

   return this;

  };

  this.changeName = function(name) {

    this.name = name;

    return this;

 };

 }

var person = new Person("John");

 person.sayName().changeName("Timmy").sayName();



 在面向对象的Javascript中为对象建立一个方法时,返回当前对象可以让你在一条链上调用方法。
 
 
 
12.Converting to number fast way(转换为数字的更快方法)
 
将字符串转换为数字是极为常见的。最简单和快速的方法是使用+(加号) 来实现。
 
 var one = '1';

 var numberOne = +one; // Number 1

var one = '1';

  var negativeNumberOne = -one; // Number -1
  
 
13.Use === instead of ==(使用 === 而不是 ==)
 
== (或者 !=) 操作在需要的情况下自动进行了类型转换。=== (或 !==)操作不会执行任何转换。===在比较值和类型时,可以说比==更快。
 
 
 [10] ==  10      // 为 true

 [10] === 10      // 为 false

 '10' ==  10      // 为 true

'10' === 10      // 为 false

  []  ==  0       // 为 true

 []  === 0       // 为 false

 ''  ==  false   // 为 true 但 true == "a" 为false

   ''  === false   // 为 false 
 
 
 
14.Filtering and Sorting a List of Strings(过滤并排序字符串列表)
 
你可能有一个很多名字组成的列表,需要过滤掉重复的名字并按字母表将其排序。
 
 
  var keywords = ['do', 'if', 'in', 'for', 'new', 'try', 'var', 'case', 'else', 'enum', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'delete', 'export', 'import', 'return', 'switch', 'typeof', 'default', 'extends', 'finally', 'continue', 'debugger', 'function', 'do', 'if', 'in', 'for', 'int', 'new', 'try', 'var', 'byte', 'case', 'char', 'else', 'enum', 'goto', 'long', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'final', 'float', 'short', 'super', 'throw', 'while', 'delete', 'double', 'export', 'import', 'native', 'public', 'return', 'static', 'switch', 'throws', 'typeof', 'boolean', 'default', 'extends', 'finally', 'package', 'private', 'abstract', 'continue', 'debugger', 'function', 'volatile', 'interface', 'protected', 'transient', 'implements', 'instanceof', 'synchronized', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'await', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof'];

 var filteredAndSortedKeywords = keywords

   .filter(function (keyword, index) {

    return keywords.lastIndexOf(keyword) === index;

   })

    .sort(function (a, b) {

   return a < b ? -1 : 1;

    });
 
 因为我们不想改变我们的原始列表,所以我们准备用高阶函数叫做filter,它将基于我们传递的回调方法返回一个新的过滤后的数组。回调方法将比较当前关键字在原始列表里的索引和新列表中的索引,仅当索引匹配时将当前关键字push到新数组。
 
最后我们准备使用sort方法排序过滤后的列表,sort只接受一个比较方法作为参数,并返回按字母表排序后的列表。
 
 const filteredAndSortedKeywords = keywords

   .filter((keyword, index) => keywords.lastIndexOf(keyword) === index)

.sort((a, b) => a < b ? -1 : 1);

console.log(filteredAndSortedKeywords);

  // ['abstract', 'arguments', 'await', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'double', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'final', 'finally', 'float', 'for', 'function', 'goto', 'if', 'implements', 'import', 'in', 'instanceof', 'int', 'interface', 'let', 'long', 'native', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'short', 'static', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'true', 'try', 'typeof', 'var', 'void', 'volatile', 'while', 'with', 'yield']
 
 
15.Short circuit evaluation in JS(JS中的短路求值)
 
短路求值是说, 只有当第一个运算数的值无法确定逻辑运算的结果时,才对第二个运算数进行求值:当AND(&&)的第一个运算数的值为false时,其结果必定为false;当OR(||)的第一个运算数为true时,最后结果必定为true。
 
逻辑或可以用来给参数设置默认值。
 
 function theSameOldFoo(name){

     name = name || 'Bar' ;

    console.log("My best friend's name is " + name);

 }

theSameOldFoo();  // My best friend's name is Bar

theSameOldFoo('Bhaskar');  // My best friend's name is Bhaskar
 逻辑与可以用来避免调用undefined参数的属性时报错
 
 
var dog = {

   bark: function(){

      console.log('Woof Woof');

   }

};

  // 调用 dog.bark();

dog.bark(); // Woof Woof.

// 但是当dog未定义时,dog.bark() 将会抛出"Cannot read property 'bark' of undefined." 错误

// 防止这种情况,我们可以使用 &&.

  dog&&dog.bark();   // This will only call dog.bark(), if dog is defined.
 
 
 
 
 
 
 !!"" // false

   !!0 // false

   !!null // false

  !!undefined // false



!!"hello" // true

!!1 // true

!!{} // true

  !![] // true
 
 
 
17.Avoid modifying or passing arguments into other functions — it kills optimization(避免修改和传递arguments给其他方法 — 影响优化)
 
在JavaScript的方法里,arguments参数可以让你访问传递给该方法的所有参数。arguments是一个类数组对象;arguments可是使用数组标记访问,而且它有length参数,但是它没有filter, map, forEach这样内建到数组内的方法。因此,如下代码是一个非常常见的将arguments转换为数组的办法:
 
1 var args = Array.prototype.slice.call(arguments);
2 //或者
3 var args = [].slice.call(arguments);
不幸的是,传递arguments给任何参数,将导致Chrome和Node中使用的V8引擎跳过对其的优化,这也将使性能相当慢。所以,正确的做法只有:
 
 var args = new Array(arguments.length);

  for(var i = 0; i < args.length; ++i) {

      args[i] = arguments[i];

    }

 
 
18.Implementing asynchronous loop(实现异步循环)
 
试着写一个异步方法,每秒打印一次循环的索引值。
 
for (var i=0; i<5; i++) {

 setTimeout(function(){

 console.log(i); 

 }, 1000);

 }  
但输出的结果会是5,5,5,5,5。这明显是有问题的,原因是:每次时间结束(timeout)都指向原始的i,而并非它的拷贝。所以,for循环使i增长到5,之后timeout运行并调用了当前i的值(也就是5)。
 
解决的办法是:有几个不同的方式可以拷贝i。最普通且常用方法是通过声明函数来建立一个闭包,并将i传给此函数。我们这里使用了自调用函数。
 
 
 for (var i=0; i<5; i++) {

  (function(num){

 setTimeout(function(){

      console.log(num); 

   }, 1000); 

 })(i);  

 }  

 
19.Flattening multidimensional Arrays in JavaScript(Javascript多维数组扁平化)
 
 
20.Using JSON.Stringify(使用JSON.Stringify)
 
加入有一个对象具有参数"prop1", "prop2", "prop3"。 我们可以通过传递 附加参数 给 JSON.stringify 来选择性将参数生成字符串,像这样:
 
 
var obj = {

  'prop1': 'value1',

  'prop2': 'value2',

  'prop3': 'value3'

 };

 var selectedProperties = ['prop1', 'prop2'];

  var str = JSON.stringify(obj, selectedProperties);
 

// str

// {"prop1":"value1","prop2":"value2"}