我知道有很多帖子可以回答我的問題,但是由于某種我無法弄清楚的原因,我永遠不會得到想要的結果。
這是我的代碼:
const NameArray = [];
const IdArray = [];
let Dict = {};
function getName() {
const Input = document.getElementById("input").value;
const list_names = Input.split(", ");
for (let i of list_names) {
NameArray.push(i);
IdArray.push(i);
};
console.log(NameArray, IdArray);
};
function CreateDict() {
NameArray.forEach((key, i) => Dict[key] = IdArray[i]);
console.log(Dict);
};
CreateDict();
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="main.js" charset="utf-8" defer></script>
<title></title>
</head>
<body>
<form id="form" action="#" method="post">
<input type="text" id="input">
<button onclick="getName();">Get Data</button>
</form>
</body>
</html>
我幾乎可以肯定這個簡單的代碼應該可以正常作業,但是在我的控制臺日志中我沒有看到陣列。我正在使用最新版本的 Firefox。
我得到的是以下內容:
Object { }
?
<prototype>: Object { … }
??
__defineGetter__: function __defineGetter__()
??
__defineSetter__: function __defineSetter__()
??
__lookupGetter__: function __lookupGetter__()
??
__lookupSetter__: function __lookupSetter__()
??
__proto__:
??
constructor: function Object()
??
hasOwnProperty: function hasOwnProperty()
??
isPrototypeOf: function isPrototypeOf()
??
propertyIsEnumerable: function propertyIsEnumerable()
??
toLocaleString: function toLocaleString()
??
toString: function toString()
??
valueOf: function valueOf()
??
<get __proto__()>: function __proto__()
??
<set __proto__()>: function __proto__()
這是有問題的,因為我無法除錯,而且我什至不知道如何訪問鍵值對……
uj5u.com熱心網友回復:
正如我所看到的,您已經在 html 檔案中匯入了腳本檔案。這使您的CreateDict()函式甚至在您輸入輸入欄位之前運行。
CreateDict()函式只能在呼叫 getName() 后運行。理想的方式是:
const NameArray = [];
const IdArray = [];
let Dict = {};
function getName() {
const Input = document.getElementById("input").value;
const list_names = Input.split(", ");
for (let i of list_names) {
NameArray.push(i);
IdArray.push(i);
};
console.log(NameArray, IdArray);
CreateDict();
};
function CreateDict() {
NameArray.forEach((key, i) => Dict[key] = IdArray[i]);
console.log(Dict);
};
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="main.js" charset="utf-8" defer></script>
<title></title>
</head>
<body>
<form id="form" action="#" method="post">
<input type="text" id="input">
<button onclick="getName();">Get Data</button>
</form>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358186.html
標籤:javascript 数组 字典
上一篇:從JSON中消除不必要的部分
