[英]How to push values to array in one function and read it in another function?
Here is my code: 这是我的代码:
var myObject = [];
function something() {
myObject.push("thing");
}
function other() {
console.log(myObject);
}
How can I let other
see the items pushed into myObject
by something
? 如何让other
看到something
推入myObject
的项目?
It's declared globally - so just calling something()
then other()
will ensure that there are elements in the array. 它是全局声明的-因此只需调用something()
然后other()
将确保数组中存在元素。 If you were calling them in the wrong order, then the function was displaying the empty array first, then adding an element to it. 如果您以错误的顺序调用它们,则该函数将首先显示空数组,然后向其添加元素。
var myObject = []; function something() { myObject.push("thing"); } function other() { console.log(myObject); } something(); other();
If you want to log each item on a separate line: 如果要将每个项目记录在单独的行中:
var myObject = []; function something() { myObject.push("thing"); } function other() { myObject.forEach(e => console.log(e)); } something(); something(); something(); other();
Also, you're dealing with an array , not an object. 另外,您要处理的是数组 ,而不是对象。 An object looks like this: 对象看起来像这样:
var anObject = { key1: "value1", key2: true, key3: 42.01 }; console.log(anObject);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.