假设HTML, CSS
和之前的JS
工作,我的实验代码是否会像我的工作代码一样工作/行为?
如果没有,为什么?此外,我该怎么做才能创建代码的循环数组样式版本?
实验代码:
var currentAccount = [];
var fieldList = ["firstName","lastName","age","gender"];
for (var i = 0; i < fieldList.length; i++) {
JSON.parse(fieldList[i]) = document.getElementById(fieldList[i]).value;
currentAccount.push(JSON.parse(fieldList[i]));
}
工作代码:
var currentAccount = [];
var firstName, lastName, age, gender;
firstName = document.getElementById("firstName").value;
lastName = document.getElementById("lastName").value;
age = document.getElementById("age").value;
gender = document.getElementById("gender").value;
currentAccount = [firstName, lastName, age, gender];
答案 0 :(得分:1)
我该怎么做才能创建代码的循环数组样式版本?
像这样的东西
var fieldIds = [ "firstName", "lastName", "age", "gender" ];
var currentAccount = fieldIds.map( function( fieldId ){
return document.getElementById( fieldId ).value;
})
答案 1 :(得分:0)
无需在实验代码中使用JSON.parse()
:
for (var i = 0; i < fieldList.length; i++) {
var fieldVal = document.getElementById(fieldList[i]).value;
currentAccount.push(fieldVal);
}
答案 2 :(得分:0)
以下是使用 ES6 的快速解决方案以及 document.getElementById 的另一种方式。希望它有所帮助!
var $ = function( id ) { return document.getElementById( id ); };
var fieldIds = [ "firstName", "lastName", "age", "gender" ];
var currentAccount = fieldIds.map((fieldId) =>{
return $(fieldId).value;
});