Tip 4: 使用JavaScript原生API

最后更新于:2022-04-01 01:51:02

随着更高版本JavaScript的普及, 像[Array prototype新增了很多API](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array#Methods)都可以在大多数浏览器中直接使用.例如: ~~~ // give me a new array of all values multiplied by 10 [5, 6, 7, 8, 900].map(function (value) { return value * 10; }); // [50, 60, 70, 80, 9000] // create links to specs and drop them into #links. var linksList = document.querySelector('#links'); var links = []; ['html5', 'css3', 'webgl'].forEach(function (value) { links.push(value.link('http://google.com/search?btnI=1&q=' + value + ' spec')); }); linksList.innerHTML = links.join(''); // return a new array of all mathematical constants under 2 [3.14, 2.718, 1.618].filter(function (number) { return number < 2; }); // you can also use these extras on other collections link nodeLists [].forEach.call(document.querySelectorAll('section[data-bucket]'), function (elem, i) { localStorage['bucket' + i] = elem.getAttribute('data-bucket'); }); ~~~ 通常情况下这些原生方法比手动编写循环要快: ~~~ for (var i = 0, len = arr.length; i < len; ++i) { } ~~~ 使用原生`JSON.parse()`比`json2.js`更加高效,安全. 原生的`String.prototype.trim`也是一个很好的例子, 这些功能不是HTML5中的,也应该得到广泛的应用.
';