简体   繁体   中英

How to add value from one array to another array

edit #3 in the interest of getting better help (THANK YOU for the patience) i want to combine these two scripts:

SCRIPT 1:

//get csv file and set up array
        d3.csv('../mapdata/mapdatatest.csv', function (csv) {

            var rid = [],
                lat = [],
                lon = [],
                pinclr = [],
                name = [],
                str = [],
                citystzip = [],
                phone = [],
            lastinspturl = [],
            lastinspctdt = [];

            csv.map(function (d) {
                rid.push(d.rid).toString();
                lat.push(d.lat).toString();
                lon.push(d.lon).toString();
                pinclr.push(d.pinclr).toString();
                name.push(d.name).toString();
                str.push(d.str).toString();
                citystzip.push(d.citystzip).toString();
                phone.push(d.phone).toString();
                lastinspturl.push(d.lastinspturl).toString();
                lastinspctdt.push(d.lastinspctdt).toString();

               for (i = 0; i < rid.length; i++) {

                   var points = ('"' + lat[i] + "," + lon[i] + '"');

                }

            });
        });

SCRIPT 2:

    deCarta.Core.Configuration.clientName = Config.clientName;
            deCarta.Core.Configuration.clientPassword = Config.clientPassword;

            var center = new deCarta.Core.Position(Config.position);

            var pinOverlay = new deCarta.Core.MapOverlay({
                name: "Pins"
            });

            window.map = new deCarta.Core.Map({
                id: "mapContainer",
                autoResize: true,
                zoom: 11,
                center: center,
                onReady: function (map) {
                    map.addLayer(pinOverlay);

                    postPins();
                }
            });

            function postPins() {

                var points = {
                    "points": [
//i have typed in these values for testing purposes only
                        "47.15211, -97.570039",
    "48.625045, -101.375369",
    "48.39679, -101.052669"]
                };


                for (var i = 0; i < points.points.length;) {

                    pos = new deCarta.Core.Position(points.points[i]);

                    pin = pin = new deCarta.Core.Pin({
                        position: center.clone(),
                        text: 'pin: ' + (points.points[i]),
                        position: pos
                        // imageSrc: 'img/pin.png'
                    });
                    pinOverlay.addObject(pin);
                    i++;
                }

                var view = new deCarta.Core.BoundingBox(points.points);
                var centerAndZoom = view.getIdealCenterAndZoom(window.map);
                map.zoomTo(centerAndZoom.zoom);
                map.centerOn(centerAndZoom.center);

            }

THE RESULT I AM TRYING TO ACHIEVE:

instead of using typed in values as i'm doing in SCRIPT 2 -- i want those values to be fed in from SCRIPT 1.

so

var points = {
                    "points": [
//i have typed in these values for testing purposes only
                        "47.15211, -97.570039",
    "48.625045, -101.375369",
    "48.39679, -101.052669"]
                };

needs to be

var points = {
                    "points": [
THE "point" VALUES FROM THE SCRIPT 1 loop]
                };

i get the concept, can't seem to get the syntax right...tried all the suggestions, the push();, read a lot of articles, samples...i needed this 10 hours ago, any assistance will be greatly appreciated. i'd vote you up if i had enough rep yet :) thank you, thank you, thank you.

I'm having a hard time understanding your questions. Does this help at all:

var points = { 
  "points": [ 
    "47.15211, -97.570039", 
    "48.625045, -101.375369", 
    "48.39679, -101.052669"
  ] 
};

console.log(points.points);

var array = points.points;
var array_len = array.length;

for(var i = 0; i < array_len; ++i)
{
  var str = array[i];
  console.log(str);
}

--output:--

[ '47.15211, -97.570039',
  '48.625045, -101.375369',
  '48.39679, -101.052669' ]
47.15211, -97.570039
48.625045, -101.375369
48.39679, -101.052669

======

i built on another page:

That is troublesome. Are you aware that the web is stateless ? That means that once a user leaves a page, no data is saved on the user's computer. There are some ways around that: you can save small bits of information in cookies, or a page can send the data to a server side script, and then the server side script can save the data in a file or a database.

On the other hand, if by "on another page" you mean another javascript file, then start simpler. Combine both javascript files into one file and get that to work, eg:

func1(a, b) = {
    ....
    return results;
}

func2(x, y, z) = {

   info = func1(x, y) + z

   //do something with info
}

Then it's a just a matter of putting func1 and func2 into separate files and including both of them in an html page:

<script type='text/javascript' src='js2.js'></script>
<script type='text/javascript' src='js1.js'></script>

Just make sure you get the order right: if function in js1.js calls a function defined in js2.js, then js2.js needs to be included first.

====

html.html

<html>
<head>
  <title>Test</title>
  <script type='text/javascript' src='js2.js'></script>
  <script type='text/javascript' src='js.js'></script>

  <style type='text/css'>
    .colorText {
      color: blue; 
    }
    .surprise {
      background: red;
    }
  </style>
</head>

<body>
  <div id="show_results" class="colorText">Hello world</div>

</body>
</html>

js.js

function do_stuff(x, y, z) {
  //send two of this function's arguments to another function
  //defined in another script:
  var results = do_other_stuff(x, y);
  return results + z; 
}

//This function will execute once the html page loads:
window.onload = function() {

  var my_results = do_stuff(10, 20, 30);
  alert("Inserting results in <div>");

  //The following div won't exist until after the page loads:
  var div = document.getElementById('show_results');
  div.innerHTML = my_results;

}

If the window.onload thing is too confusing, just get rid of it and use alert()'s to show the results (or any other info you are interested in).

js2.js

function do_other_stuff(x, y) {
  return x+y;
}

Now, if you want to pass just one thing to the do_other_stuff() function, eg your object (things with braces around them are called 'objects'), you can rewrite your scripts like this:

js.js

function do_stuff() {  

    var points = { 
        "points": [ 
        "47.15211, -97.570039", 
        "48.625045, -101.375369", 
        "48.39679, -101.052669" ] 
    };

    do_other_stuff(points);

}


do_stuff();

Then rewrite do_other_stuff() to look like this:

js2.js

function do_other_stuff(points_obj) {

  //do stuff with points_obj, e.g.
  alert( points_obj.points[0] );

}

In this example, the scripts aren't operating on any of the html elements, so there is no need to wait for the page to load.

====

See if the following comments help:
1) This loop:

for (i = 0; i < rid.length; i++) {

    var points = ('"' + lat[i] + "," + lon[i] + '"');

}

is equivalent to:

var points = '"' + lat[rid.length] + "," + lon[rid.length] + '"';

2) The thing you are doing with the quotes there is really ugly. If you are just trying to turn some numbers into a string, you can do this:

var point = lat[i] + ", " + lon[i];

js can't add a number and a string together, so js makes the assumption that you are trying to create a string, and js converts the number to a string then adds the strings together. Check this out:

var str = 3 + ', ' + 2;
var arr = [str];
console.log(arr);

--output:--
[ '3, 2' ]

3) You probably want to do something like this:

var points = []

for (i = 0; i < rid.length; i++) {

    points.push( lat[i] + ", " + lon[i] );

}

4) Then to pass the points array to your deCarta stuff, you can do this:

var points = []

for (i = 0; i < rid.length; i++) {

    points.push( lat[i] + ", " + lon[i] );

}

do_stuff(points);

And then you would define do_stuff() like this:

function do_stuff(the_points) {

    //Do all your deCarta stuff here

    window.map = new deCarta.Core.Map({
                id: "mapContainer",
                autoResize: true,
                zoom: 11,
                center: center,
                onReady: function (map) {
                    map.addLayer(pinOverlay);

                    postPins();
                }
            });

            function postPins() {
               console.log(the_points); //You have access to the points array
               obj = {"points": the_points};

=======

1) When you call a function, js lines up the function call with the function definition:

         do_stuff(10, 20, 30)  <----function call
function do_stuff( x,  y,  z) {...}  <---function definition

Then javascript does these assignments:

var x = 10;
var y = 20;
var z = 30;

2) Then inside the function, you use the variables x, y, and z to refer to those values.

3) In the code I posted, the function call and function definition look like this:

         do_stuff(points)
function do_stuff(the_points) {...}

So js does this assignment:

 var the_points = points;

And points is just some array like ['10, 20', '100, 200'], so that assignment is equivalent to:

 var the_points = ['10, 20', '100, 200']

And inside the function you use the_points to refer to the array.

You can use something like this to run through each pair in the array:

var points = [ "47.15211, -97.570039", "48.625045, -101.375369", "48.39679, -101.052669"];
points.forEach(function (point) {
  point = point.match(/^"([0-9\.]+)\s*,\s*([0-9\.]+)"$/);
  console.log('"' + point[0] + '", "' + point[1] + '"');
});

Or something like this if you're wanting to put them in their own arrays:

var points = [ "47.15211, -97.570039", "48.625045, -101.375369", "48.39679, -101.052669"],
    lat = [], lon = [];

points.forEach(function (point) {
  point = point.match(/^"([0-9\.]+)\s*,\s*([0-9\.]+)"$/);
  lat.push(point[0]);
  lon.push(point[1]);
});

lat.forEach(function (lat, id) {
  console.log('"' + lat + '", "' + lon[id] + '"');
});

Or even:

lon.forEach(function (lon, id) {
  console.log('"' + lat[id] + '", "' + lon + '"');
});

Also, someone commented on here and said that I shouldn't be using split for this when you're joining it back together. If you're not looking to have them separated like this, you can always use:

points.points = points.points.map(function (point) {
  return point.replace(/^"([0-9\.]+)\s*,\s*([0-9\.]+)"$/, '"$1", "$2"');
});

Maybe this will work but I don't know what your variables rid, lat and long are. Maybe you could post it. To see the variable in Chrome or Firefox you can do:

console.log(JSON.stringify(rid);

Press F12 to see the console.

var points={};
points.points=[];
for (i = 0; i < rid.length; i++) {
   points.points.push('"' + rid[i].lat + "," + rid[i].lon + '"');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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