要將字串化數字陣列映射到實際數字,我可以簡單地傳遞 Number 函式:
let arr = ["0", "1", "-2.5"];
console.log(arr.map(Number));
現在我想使用相同的方法document.getElementById將字串串列映射id到它們對應的 DOM 節點:
let arr = ["a", "b"];
console.log(arr.map(document.getElementById));
<div id="a">a <span id="b">b</span></div>
這給了我
"TypeError: 'getElementById' called on an object that does not implement interface Document."
有人可以解釋錯誤嗎?
uj5u.com熱心網友回復:
您可以在此處找到對正在發生的事情的解釋:
拋出此錯誤時,將呼叫一個函式(在給定物件上),
this其型別與函式預期的型別不對應。
Function.prototype.call()當使用orFunction.prototype.apply()方法并提供this不具有預期型別的??引數時,可能會出現此問題。當提供一個作為物件屬性存盤的函式作為另一個函式的引數時,也會發生此問題。
this在這種情況下,存盤該函式的物件在被其他函式呼叫時不會成為該函式的目標。要解決此問題,您將需要提供進行呼叫的 lambda,或使用該Function.prototype.bind()函式將this引數強制為預期物件。
我還添加了我的替代解決方案:該方法有一個多載map,允許您在第二個引數中設定背景關系:
let arr = ["a", "b"];
console.log(arr.map(document.getElementById, document));
<div id="a">a <span id="b">b</span></div>
uj5u.com熱心網友回復:
進行實驗時,它似乎與作為回呼傳遞給時this不再指向正確的背景關系(這將是document)有關,因此顯式傳遞系結就可以了:document.getElementByIdmapgetElementById
let arr = ["a", "b"];
console.log(arr.map(document.getElementById.bind(document)));
<div id="a">a <span id="b">b</span></div>
不幸的是,這也違背了該方法的目的,即簡潔,因為這可以從
arr.map(document.getElementById.bind(document))
// to
arr.map(id=>document.getElementById(id))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/481771.html
標籤:javascript dom 数组映射
