隨著更高版本JavaScript的普及, 像Array prototype新增了很多API都可以在大多數(shù)瀏覽器中直接使用.例如:
// 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');
});
通常情況下這些原生方法比手動(dòng)編寫循環(huán)要快:
for (var i = 0, len = arr.length; i < len; ++i) {
}
使用原生JSON.parse()
比json2.js
更加高效,安全.
原生的String.prototype.trim
也是一個(gè)很好的例子, 這些功能不是HTML5中的,也應(yīng)該得到廣泛的應(yīng)用.
更多建議: