2017-05-26 64 views
0

剛剛發現在YouTube的教程此代碼,並發現它是非常詳細:這個dom-to-vars代碼如何在JavaScript中縮短?

Verbose JS code

因此,我認爲,不能這樣被縮短?是不是有某種ES2015魔術或者可以讓它成爲單線?

,我能想出的最聰明的是這樣的:

const els = ['txtEmail', 'txtPassword', 'btnLogin', 'btnSignUp', 'btnLogout']; 
const values = {}; 
for (var i=0; i<els.length; i++) { 
    values[els[i]] = document.getElementById(els[i]); 
} 

這不是要短得多,但如果有更多的DOM元素,這將肯定從長遠來看還清。

但是,如何優化爲儘可能非冗長?

+0

@Rajesh正如我所說的,這是從YouTube的教程這裏https://www.youtube.com/watch?v=-OKrloDzGpU - 對於這個問題的答案,這是無關緊要。 – Timo

+0

創建一個函數'const getById = id => document.getElementById(id)' - 確實可以在將來輸入更少的內容。 – wostex

+1

不要陷入縮短一切。這往往是一件壞事。每個聲明的一行代碼是完全可以的,並且很容易看到它的作用。做一個循環或功能,下一個人閱讀它必須弄清楚它的功能。 – Archer

回答

2

你可以做的列表元素與map

const ids = ["txtEmail", "txtPassword", "btnLogin", "btnSignUp", "btnLogout"]; 
const elems = ids.map(id => document.getElementById(id)); 

或者您可以用reduce製作一個對象。

const ids = ["txtEmail", "txtPassword", "btnLogin", "btnSignUp", "btnLogout"]; 
const elems = ids.reduce((obj, id) => { 
    obj[id] = document.getElementById(id); 
    return obj; 
}, {}); 
+0

我真的很喜歡地圖解決方案,謝謝:-) – Timo

0

隨着減少

const els = ['txtEmail', 'txtPassword', 'btnLogin', 'btnSignUp', 'btnLogout']; 
const elms = els.reduce((o, id) => { 
    o[id] = document.getElementById(id); 
    return o 
}, {}) 

沒有脂肪箭頭

const els = ['txtEmail', 'txtPassword', 'btnLogin', 'btnSignUp', 'btnLogout']; 
const elms = els.reduce(function (o, id) { 
    o[id] = document.getElementById(id); 
    return o 
}, {}) 

最後,不知道它的好處是什麼....

0

另一種解決方案

var fields={ 
txtEmail, 
txtPassword 
} 

Object.keys(fields).forEach(e=>fields[e]=document.getElementById(e)); 

console.log(fields.txtEmail); 
0

可以使用解構分配

const [txtEmail, txtPassword, btnLogin, btnSignUp, btnLogout] = [ 
 
     document.getElementById("txtEmail") 
 
     , document.getElementById("txtPassword") 
 
     , document.getElementById("btnLogin") 
 
     , document.getElementById("btnSignUp") 
 
     , document.getElementById("btnLogout") 
 
     ]; 
 

 
console.log(txtEmail, txtPassword, btnLogin, btnSignUp, btnLogout);
<input id="txtEmail"> 
 
<input id="txtPassword"> 
 
<input id="btnLogin"> 
 
<input id="btnSignUp"> 
 
<input id="btnLogout">

或者,使用與.querySelectorAll()屬性始於選擇器和擴散元件

const [txtEmail, txtPassword, btnLogin, btnSignUp, btnLogout] = [ 
 
     ...document.querySelectorAll("input[id^=txt]") 
 
     , ...document.querySelectorAll("input[id^=btn]") 
 
     ]; 
 
     
 
console.log(txtEmail, txtPassword, btnLogin, btnSignUp, btnLogout);
<input id="txtEmail"> 
 
<input id="txtPassword"> 
 
<input id="btnLogin"> 
 
<input id="btnSignUp"> 
 
<input id="btnLogout">