我试图在我的代码中使用地图函数,但我担心我犯了一些愚蠢的错误。它只是不起作用!
这是我的代码。我有 2 个按钮,标题为“ID”和“文本”。单击它们应显示输入字段的 ID 和文本列表。该程序运行良好,直到地图为止。
各位大师能帮助我理解我的错误吗?
<!DOCTYPE html>
<html>
<head>
<script>
getID = (x) => x.id;
getText = (x) => x.value;
function Click(x) {
input = document.getElementsByTagName("input");
alert(input.map((x.id == "id") ? getID : getText));
}
</script>
</head>
<body>
<input type="input" id="input1"> </input>
<input type="input" id="input2"> </input>
<button id="id" onclick="Click(this)"> ID </button>
<button id="text" onclick="Click(this)"> Text </button>
</body>
</html>
.map()
方法是Array.prototype
的一部分,它允许您在数组上使用它,但是,在您的情况下,input
不是数组,而是一个HTMLCollection(因为这就是getElementsByTagName
返回的内容)。您可以使用扩展语法 HTMLCollection
或使用 const inputArray = [...input];
将 const inputArray = Array.from(input)
转换为数组,并在转换后执行映射,但是,使用 Array.from()
的第二个参数来执行映射会更有效转换时(这可以避免对集合进行两次迭代):
const input = document.getElementsByTagName("input");
alert(Array.from(input, (x.id == "id") ? getID : getText));
附带说明一下,您应该使用
getID
或 getText
来声明 const
和 let
,以将它们的范围限制在当前脚本中并避免使它们成为全局的。同样的想法也适用于 input
,用 const
/let
/var
来声明它,以将其范围限制在声明它的函数中:
const getID = (x) => x.id;
const getText = (x) => x.value;
function Click(x) {
const input = document.getElementsByTagName("input");
alert(Array.from(input, (x.id == "id") ? getID : getText));
}
<input type="input" id="input1"> </input>
<input type="input" id="input2"> </input>
<button id="id" onclick="Click(this)"> ID </button>
<button id="text" onclick="Click(this)"> Text </button>