最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - How to access Javascript variable values outside of the function - Stack Overflow

programmeradmin1浏览0评论

I've been banging my head off a brick wall with this one and another all nighter with no success. What I would like to do is have access to the values set in an array within a function but outside of that function. How could this be done? For example:

function profileloader()
{
    profile = [];
    profile[0] = "Joe";
    profile[1] = "Bloggs";
    profile[2] = "images/joeb/pic.jpg";
    profile[3] = "Web Site Manager";
}

I would then further down the page within a paragraph tag have something like:

document.write("Firstname is: " + profile[0]);

Obviously that would be contained with in the script tag but all i'm getting is an error on the console stating: "profile[0] is not defined".

Anyone got any ideas where I'm going wrong? I just can't seem to figure it out and none of the other solutions I've seen when passing values from either function to function or outside of a function, have worked so far.

Thank you to anyone who can help me with this, its probably something simple I've missed!

I've been banging my head off a brick wall with this one and another all nighter with no success. What I would like to do is have access to the values set in an array within a function but outside of that function. How could this be done? For example:

function profileloader()
{
    profile = [];
    profile[0] = "Joe";
    profile[1] = "Bloggs";
    profile[2] = "images/joeb/pic.jpg";
    profile[3] = "Web Site Manager";
}

I would then further down the page within a paragraph tag have something like:

document.write("Firstname is: " + profile[0]);

Obviously that would be contained with in the script tag but all i'm getting is an error on the console stating: "profile[0] is not defined".

Anyone got any ideas where I'm going wrong? I just can't seem to figure it out and none of the other solutions I've seen when passing values from either function to function or outside of a function, have worked so far.

Thank you to anyone who can help me with this, its probably something simple I've missed!

Share Improve this question asked May 23, 2012 at 5:39 GeordieDave1980GeordieDave1980 5994 gold badges11 silver badges25 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 9

Since you do NOT have a var in front of the profile=[];, it is stored in the global window scope.

What I suspect is that you forgot to call the profileloader() before using it.

It is good practice is to declare your global variables in an obvious manner, as shown in other answers on this page

It is not considered good practice to rely on side effects.

It is also not good practise to use document.write - it will, for example, wipe the page if executed after load.


Commented code to show what is going on, NOTE not recommended method:

This should work. And it does work:

function profileloader() {
  profile = []; // no "var" makes this global in scope
  profile[0] = "Joe";
  profile[1] = "Bloggs";
  profile[2] = "images/joeb/pic.jpg";
  profile[3] = "Web Site Manager";
}
profileloader(); // mandatory
document.write("Firstname is: " + profile[0]);

Preferred:

document.addEventListener('DOMContentLoaded', () => { // when the page loads
  let profiles = []; // now in scope of the load event handler

  const profileLoader = () => {
    // Simulate an Ajax call and populate the profiles array
    profiles.push({
      "First name": "Joe",
      "Last name": "Bloggs",
      "Job title": "Web Site Manager",
      "img": "images/joeb/pic.jpg"
    });
    profiles.push({
      "First name": "Jane",
      "Last name": "Bloggs",
      "Job title": "CIO",
      "img": "images/janeb/pic.jpg"
    });
  };

  profileLoader(); // mandatory

  const profilesContainer = document.getElementById('profiles'); // Assuming <div id="profiles"></div> exists

  profiles.forEach(profile => {
    // Create a div for each profile
    const div = document.createElement('div');
    div.classList.add('profile');
    // Loop through profile keys and dynamically create elements
    Object.entries(profile).forEach(([key, value]) => {
      const isImage = key === 'img';
      const elem = document.createElement(isImage ? 'img' : 'span');
      if (isImage) elem.src = value;
      else elem.textContent = `${key}: ${value}`;
      elem.classList.add(key.replace(/\s+/g,''));
      div.appendChild(elem); 
      if (!isImage) div.appendChild(document.createElement('br')); // Add line breaks for non-image fields
    });
    
    // Append the profile div to the container
    profilesContainer.appendChild(div);
  });
});
.profile { border-bottom: 1px solid black; }
<div id="profiles">
</div>

declare it outside the function so the outside scope can see it (be careful of globals though)

var profile = [];
function profileloader(){
    profile[0] = "Joe";
    profile[1] = "Bloggs";
    profile[2] = "images/joeb/pic.jpg";
    profile[3] = "Web Site Manager";
}

or have the function return it:

function profileloader(){
    var profile = [];
    profile[0] = "Joe";
    profile[1] = "Bloggs";
    profile[2] = "images/joeb/pic.jpg";
    profile[3] = "Web Site Manager";
    return profile;
}

var myprofile = profileloader(); //myprofile === profile
发布评论

评论列表(0)

  1. 暂无评论