Tip 4: 使用JavaScript原生API

随着更高版本JavaScript的普及, 像Array prototype新增了很多API都可以在大多数浏览器中直接使用.例如:

  1. // give me a new array of all values multiplied by 10
  2. [5, 6, 7, 8, 900].map(function (value) {
  3. return value * 10;
  4. });
  5. // [50, 60, 70, 80, 9000]
  6. // create links to specs and drop them into #links.
  7. var linksList = document.querySelector('#links');
  8. var links = [];
  9. ['html5', 'css3', 'webgl'].forEach(function (value) {
  10. links.push(value.link('http://google.com/search?btnI=1&q=' + value + ' spec'));
  11. });
  12. linksList.innerHTML = links.join('');
  13. // return a new array of all mathematical constants under 2
  14. [3.14, 2.718, 1.618].filter(function (number) {
  15. return number < 2;
  16. });
  17. // you can also use these extras on other collections link nodeLists
  18. [].forEach.call(document.querySelectorAll('section[data-bucket]'),
  19. function (elem, i) {
  20. localStorage['bucket' + i] = elem.getAttribute('data-bucket');
  21. });

通常情况下这些原生方法比手动编写循环要快:

  1. for (var i = 0, len = arr.length; i < len; ++i) {
  2. }

使用原生JSON.parse()json2.js更加高效,安全.

原生的String.prototype.trim也是一个很好的例子, 这些功能不是HTML5中的,也应该得到广泛的应用.