2017-05-26 65 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">