简体   繁体   English

Javascript无法从一个文件到另一个文件访问数组

[英]Javascript can't access array from one file to another

In my php page, i'm including 2 .js files, and the first one creates and populates a js array which I need to access in the second .js file. 在我的php页面中,我包括2个.js文件,第一个创建并填充一个我需要在第二个.js文件中访问的js数组。 For some reason, I'm getting an error that the array is undefined when I know for a fact that it's being populated. 出于某种原因,当我知道该数组正在被填充时,我得到一个错误,该数组未定义。 Why is this broken? 为什么这坏了?
What am I doing wrong? 我究竟做错了什么?

Error: ReferenceError: sl is not defined

first.js first.js

var sl = [];
for (var i = 0; i < j.length; i++) {
    options += '<option value="' + j[i].value + '">' + j[i].text + '</option>';
    sl[j[i].value] = [];
    sl[j[i].value]['shopping_list'] = j[i].text;
    sl[j[i].value]['is_private']= j[i].is_private;
    console.log('printing SL for ' + j[i].value);
    console.log(sl[j[i].value]['shopping_list']);
}

second.js second.js

$("#shopping_list_name").val(sl[$("#existing_shopping_lists").val()]['shopping_list']);

Is the code that you cited from first.js inside a function (possibly a $(function() {}); )? 您从first.js引用的代码是否在函数内部(可能是$(function() {}); )内? JavaScript has functional scoping making the var sl=[] not global (regardless of order) JavaScript具有功能范围,使var sl=[]不全局(无论顺序如何)

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

相关问题 无法访问另一个javascript文件中的变量 - can't access variables in another javascript file 为什么我不能从另一个文件中的一个文件访问全局范围变量? - Why can't I access global-scope variables from one file in another file? 为什么我无法从另一个.js文件访问.js文件中定义的JavaScript函数? - Why I can't access a JavaScript function defined in a .js file from another .js file? 为什么我的 JavaScript 文件无法从另一个文件访问定义的常量? - Why my JavaScript file can't access defined constant from another file? 如何将一个数组从javascript文件写入另一个新的js文件? - How can i write one array from javascript file to another new js file? 从Javascript文件加载另一个脚本,但无法访问已加载脚本中的函数 - Loading another script from a Javascript file but I can't access functions in the loaded script Node.js 无法访问另一个 javascript 文件中的变量 - Node.js Can't access variable in another javascript file 无法在javascript中访问数组 - Can't access array in javascript Javascript - 无法访问从 csv 文件创建的数组的数组元素 - Javascript - Can not access array elements of an array created from a csv file 你可以在javascript或jquery中从另一个数组中删除一个数组 - can you remove one array from another in javascript or jquery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM