將函數(shù)的實(shí)際參數(shù)轉(zhuǎn)換成數(shù)組的方法
var args = Array.prototype.slice.call(arguments);
對于slice 方法,ECMAScript 262 中 15.4.4.10 Array.prototype.slice (start, end) 章節(jié)有備注:
The slice function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the slice function can be applied successfully to a host object is implementation-dependent.
《Pro JavaScript Design Patterns》(《JavaScript 設(shè)計(jì)模式》)的作者 Dustin Diaz 曾指出:
instead of…
var args = Array.prototype.slice.call(arguments); // 懌飛注:下稱方法一
do this…
var args = [].slice.call(arguments, 0); // 懌飛注:下稱方法二
但二者的性能差異真的存在嗎?經(jīng)過個(gè)人簡單測試發(fā)現(xiàn):
在 arguments.length 較小的時(shí)候,方法二性能上稍有一點(diǎn)點(diǎn)優(yōu)勢,而在arguments.length 較大的時(shí)候,方法一卻又稍有優(yōu)勢。
最后附上方法三,最老土的方式:
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
不過對于平常來說,個(gè)人建議還是使用第二種方法,但任何解決方案,沒有最好的,只有最合適:
var args = [].slice.call(arguments, 0);
理由有二:
一般的函數(shù)的 arguments.length 都在 10 以內(nèi),方法二有優(yōu)勢;
方法二的代碼量上也比第一種少,至少可以減小一點(diǎn)字節(jié) ^^
如何將 NodeList (比如:document.getElementsByTagName('div'))轉(zhuǎn)換成數(shù)組呢?
解決方案簡單如下:
function nodeListToArray(nodes){
var arr, length;
try {
// works in every browser except IE
arr = [].slice.call(nodes);
return arr;
} catch(err){
// slower, but works in IE
arr = [];
length = nodes.length;
for(var i = 0; i < length; i++){
arr.push(nodes[i]);
}
return arr;
}
}
為什么 IE 中 NodeList 不可以使用 [].slice.call(nodes) 方法轉(zhuǎn)換呢?
In Internet Explorer it throws an error that it can't run Array.prototype.slice.call(nodes) because a DOM NodeList is not a JavaScript object.
相關(guān)文章
微信小程序?qū)崿F(xiàn)的一鍵復(fù)制功能示例
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)的一鍵復(fù)制功能,結(jié)合實(shí)例形式分析了微信小程序wx.setClipboardData接口實(shí)現(xiàn)操作粘貼板進(jìn)行復(fù)制操作的相關(guān)使用技巧,需要的朋友可以參考下2019-04-04微信小程序調(diào)用PHP后臺(tái)接口 解析純html文本
這篇文章主要為大家詳細(xì)介紹了微信小程序調(diào)用PHP后臺(tái)接口,解析純html文本的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06javascript 彈出窗口中是否顯示地址欄的實(shí)現(xiàn)代碼
程序中通過點(diǎn)擊一個(gè)“發(fā)貨提醒”鏈接彈出另一個(gè)窗口,使用的方法是用javascript 的openUrl()方法。2011-04-04實(shí)現(xiàn)網(wǎng)頁內(nèi)容水平或垂直滾動(dòng)的Javascript代碼
用Javascript實(shí)現(xiàn)新聞內(nèi)容的水平或垂直滾動(dòng),主要的優(yōu)點(diǎn)是我們可以實(shí)現(xiàn)自定義滾動(dòng)風(fēng)格或特效,應(yīng)用效果比起傳統(tǒng)的marquee更加具有特色,方法也比較簡單2012-10-10