gpt4 book ai didi

javascript - 为什么 object.eval() 有效,方括号返回未定义?

转载 作者:行者123 更新时间:2023-12-02 23:03:48 26 4
gpt4 key购买 nike

我正在尝试编写一个脚本,该脚本从表的第一列中获取方法(以字符串的形式),并在每行的第三列中显示该方法的输出。前任。 html 表的第 1 行第 1 列包含 .getFullYear(),因此在第 3 列中我想运行(我的 Date 对象)now.getFullYear()。在下一行中,我将运行 now.getMonth() 等。

当我运行 eval("now."+method) 时,它运行没有问题,但我试图避免使用 eval()。当我运行 now[method] 时,输出返回未定义。为什么 eval() 可以工作,但现在 [method] 返回不同的东西?

```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] 相同。

最佳答案

如果方法.getFullYear(),那么

method = method.slice(1, -2);
row.cells[2].innerText = now[method]();

应该可以工作。您忘记从 method 中删除 ()

关于javascript - 为什么 object.eval() 有效,方括号返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57683152/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com