[英]Object remapping problem - property undefined
好的,我可能忽略了一個非常明顯的問題,但是我無法弄清楚為什么會這樣(在Firefox和Chrome中都是如此)。 這是我的代碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> body, html { background-color: #ffffff; } div { text-align: center; color: #000000; } table, th, td { border: 1px solid #000000; border-collapse: collapse; } table { table-layout: fixed; } th,td { padding: 5px; } #err { background-color: #ff0000; } </style> <script type="text/javascript"> function main() { if(document.readyState == 'complete') { var Arr = [ {a: 'a0', b: 'b0', c: 'c0'}, {a: 'a1', b: 'b1', c: 'c1'}, {a: 'a2', b: 'b2', c: 'c2'}, {a: 'a3', b: 'b3', c: 'c3'}, {a: 'a4', b: 'b4', c: 'c4'} ]; var strErr; var strMsg; var strRsl = document.querySelector('#rsl').innerHTML; document.querySelector('#prc').addEventListener('click', getResults, false); function getResults() { strErr = ''; strMsg = strRsl; document.querySelector('#err').innerHTML = strErr; document.querySelector('#rsl').innerHTML = strMsg; Arr = Arr.map(remap); } function remap(value, index, array) { return { d: value.a, e: value.a.toLowerCase().replace(/ /g, '_'), f: value.c.toLowerCase(), g: value.b, h: '', k: -1 }; } } else { setTimeout(function() { main(); }, 1000); } } </script> </head> <body onload="javascript: main();"> <div> <input type="button" id="prc" value="Do Stuff" style="cursor: pointer;"> <p id="err"></p> <table id="msg" align="center"> <tr><th>d</th><th>e</th><th>f</th><th>g</th><th>h</th><th>k</th></tr> <tfoot id="rsl" align="center"></tfoot> </table> </div> </body> </html>
Firefox控制台返回(第39行):
TypeError:value.a未定義
Chrome控制台返回(第39行):
未捕獲的TypeError:無法讀取未定義的屬性“ toLowerCase”
在某些情況下,當發生相同的錯誤時,出於某些不可思議的原因,仍然可以成功地重新映射對象。 同樣,僅在兩次單擊“ Do Stuff”按鈕之后才似乎創建了對象。
它與僅在頁面加載時調用的函數中實例化的事實有關嗎?
在第一次remap
調用之后。 Arr
變得不具有對象的數組a
屬性,從而e: value.a.toLowerCase().replace(/ /g, '_'),
引發因為沒有value.a
。
如果希望映射始終成功,請始終為返回的對象的a
(和c
)屬性分配一個字符串,或者在輸入對象上不存在a
或c
忽略e
和f
屬性。
它與僅在頁面加載時調用的函數中實例化的事實有關嗎?
不可以。您可以將腳本標簽移至下半身標簽,以消除if-load和超時。 或添加“ defer”屬性,並使用src =“ external / path / script.js”放入外部文件
舉例說明@CertainPerformance注釋:
var remap = v => ({
d: v.a,
e: v.a.toLowerCase().replace(/ /g, '_'),
f: v.c.toLowerCase(),
g: v.b,
h: '',
k: -1
})
var Arr = [
{a: 'a0', b: 'b0', c: 'c0'},
{a: 'a1', b: 'b1', c: 'c1'},
{a: 'a2', b: 'b2', c: 'c2'},
{a: 'a3', b: 'b3', c: 'c3'},
{a: 'a4', b: 'b4', c: 'c4'}
]
var ArrMappedOnce = Arr.map(remap)
var ArrMappedTwice = ArrMappedOnce.map(remap) //it bugs
也許您會喜歡Object.assign :
var remap2 = v => Object.assign(v, {
d: v.a,
e: v.a.toLowerCase().replace(/ /g, '_'),
f: v.c.toLowerCase(),
g: v.b,
h: '',
k: -1
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.