简体   繁体   English

从全局范围内的函数内部访问数据

[英]Access data from inside a function in the global scope

I'm still learning JS and I'm currently struggling with this problem.我还在学习 JS,我目前正在努力解决这个问题。 I want to be able to access the data from ordArray in the global scope.我希望能够在全局范围内访问来自ordArray的数据。 How do I do this ?我该怎么做呢 ? I've tried with returns but struggling to solve it.我已经尝试过退货,但很难解决。

const startOrd = function() {
    const ordArray = [];
    val = document.getElementById("val_ord").value;
    ordArray.push(val)
    console.log(ordArray)
}

Simply create ordArray outside of the function :)只需在函数之外创建 ordArray :)

const ordArray = [];
const startOrd = function () {
  val = document.getElementById("val_ord").value;
  ordArray.push(val)
  console.log(ordArray)

}

Declare/initialize the array outside of the function.在函数外部声明/初始化数组。

const ordArray = [];

const startOrd = function() {
    val = document.getElementById("val_ord").value;
    ordArray.push(val)
    console.log(ordArray)
}

Your code looks correct, Only thing you want is I've tried with returns but struggling to solve it您的代码看起来正确,您唯一想要的就是我尝试过退货但努力解决它

Demo :演示

 const startOrd = function() { const ordArray = []; const val = document.getElementById("val_ord").value; ordArray.push(val) return ordArray; }; console.log(startOrd());
 <input type="text" id="val_ord" value="abcd"/>

Constants are block-scoped , when you create variable in function you dont access to variable out side the function.常量是block-scoped ,当您在函数中创建变量时,您无法访问函数之外的变量。

please follow the link请点击链接

I think, This writing code method is more better:我认为,这种编写代码方法更好:

var ordArray = [];
let startOrd = (elem) => elem?.value;
let targetElem = document.getElementById("val_ord");
ordArray.push(startOrd(targetElem));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM