如何在一个函数中将值推入数组并在另一个函数中读取它?

时间:2019-05-22 21:20:08

标签: javascript arrays function

这是我的代码:

var myObject = [];
function something() {
    myObject.push("thing");
}

function other() {
    console.log(myObject);
}

如何让other看到myObject推送到something中的项目?

1 个答案:

答案 0 :(得分:1)

它是全局声明的-因此仅调用something()然后other()将确保数组中存在元素。如果您以错误的顺序调用它们,则该函数将首先显示空数组,然后向其中添加元素。

var myObject = [];

function something() {
  myObject.push("thing");
}

function other() {
  console.log(myObject);
}

something();
other();

如果要将每个项目记录在单独的行中:

var myObject = [];

function something() {
  myObject.push("thing");
}

function other() {
  myObject.forEach(e => console.log(e));
}

something();
something();
something();
other();

此外,您正在处理的是 array 而不是对象。一个对象看起来像这样:

var anObject = {
  key1: "value1",
  key2: true,
  key3: 42.01
};

console.log(anObject);