我正在尝试编写一个脚本,该脚本采用表的第一列中的方法(字符串形式),并在每一行的第三列中显示该方法的输出。例如html表的第1行第1列包含.getFullYear(),因此在第3列中,我现在要运行(我的Date对象).getFullYear()。在下一行中,我将立即运行now.getMonth()等等。
当我运行eval(“ now。” + method)时,它没有问题,但是我试图避免使用eval()。当我现在运行[方法]时,输出返回未定义。为什么eval()可以工作,但是现在[方法]返回不同的东西?
```JavaScript`
const now = new Date();
//gets the full table data
const methodTable = document.querySelector("#methods-table");
function tableTimeData(table) {
const tableLength = table.rows.length;
for (let i = 1; i < tableLength; i++) { //iterate through each table row, skipping the header
let row = table.rows[i];
let method = row.cells[0].innerText;
row.cells[2].innerText = eval("now." + method);
//OR
method = method.substr(1);
row.cells[2].innerText = now[method];
}
}
tableTimeData(methodTable);
HTML
<table class="table" id="methods-table">
<tr>
<th>Method Name</th>
<th>Method Description</th>
<th>Method Output</th>
</tr>
<tr>
<td class="text-info font-weight-bold">.getFullYear()</td>
<td>Returns the full 4 digit year.</td>
<td></td>
</tr>
<tr>
<td class="text-info font-weight-bold">.getMonth()</td>
<td>Returns the month as an integer (0-11).</td>
<td></td>
</tr>
<tr>
<td class="text-info font-weight-bold">.getDay()</td>
<td>Returns the day of the week as an integer (0-6).</td>
<td></td>
</tr>
<tr>
<td class="text-info font-weight-bold">.getHours()</td>
<td>Returns the hour as of creation.</td>
<td></td>
</tr>
<tr>
<td class="text-info font-weight-bold">.getMinutes()</td>
<td>Returns minute as of creation</td>
<td></td>
</tr>
<tr>
<td class="text-info font-weight-bold">.getSeconds()</td>
<td>Returns second as of creation</td>
<td></td>
</tr>
<tr>
<td class="text-info font-weight-bold">.getTime()</td>
<td>Returns the number of miliseconds passed since Jan. 1 1970. Used as a baseline to compare 2 dates.</td>
<td></td>
</tr>
<tr>
<td class="text-info font-weight-bold">.toDateString()</td>
<td>Returns a shortened date with day, month, date and year with day and month as names rather than integers.</td>
<td></td>
</tr>
<tr>
<td class="text-info font-weight-bold">.toTimeString()</td>
<td>Returns a shortened time of day with hour, minute second and time zone (always Greenwhich Mean Time as a standard).</td>
<td></td>
</tr>
<tr>
<td class="text-info font-weight-bold">.toLocaleString()</td>
<td>Returns a shortened time of day with hour, minute second and time zone (as your local time zone).</td>
<td></td>
</tr>
</table>
我希望eval(“ now。” + method)的结果与now [method]相同。
答案 0 :(得分:1)
如果method
是.getFullYear()
,则
method = method.slice(1, -2);
row.cells[2].innerText = now[method]();
应该工作。您忘记从()
中删除method