I know there are many posts out there that answer my question, but for some reason that I cannot figure out, I never end up with the desire result.
Here is my code:
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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
I am almost sure this simple code should work properly, but in my console log I do not see the array. I’m working with Firefox, the latest version.
what I get is the following:
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__()
It is problematic because I cannot debug, and I don’t even know how to access the key value pairs then...
CodePudding user response:
As I can see you have imported script file in your html file.
This makes your CreateDict()
function run even before you type in input field.
CreateDict()
function should only be run only after once getName() is invoked.
Ideal way will be :
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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>