1

How to create dynamic array for example pairs of data using javascript? i want the exact structure as shown in example data pairs in dynamic array. i tried code below but it seems my array is not correct. could any one help me fix it.Thanks

Note: alert(files.join('\n')); shows [object object] Example of pairs of data to be stored in array

files: [

        {'url': 'http://www.somesite.com/1.jpg', 'filename': 'new1.jpg'},
        {'url': 'http://www.somesite.com/2.jpg', 'filename': 'new2.jpg'},
        {'url': 'http://www.somesite.com/2.jpg', 'filename': 'new3.jpg'},
    ],

My array creation function:

<script>
var i=1;
  files = new Array();   
    function addtoArray(a,b){
    alert("URL:"+a+"\nFileName:"+b);

    files[i] = { url: +a, filename: +b };
    i++;
    alert(files.join('\n'));
    };
</script>
<body>
<button onclick="addtoArray('http://www.somesite.com/1.jpg','new1.jpg')">add to array</button>

<button onclick="addtoArray('http://www.somesite.com/2.jpg','new2.jpg')">add to array</button>

2 Answers 2

1

Try this.

function addtoArray(a,b){
files.push({ url: a, filename: b });
};

EDIT: Adding code to display the content

alert(JSON.stringify(files));
2
  • thanks for reply. How to print its content i used alert(files.join('\n')); but i get [ object object] using alert (i want to verify the store data)? Furthermore is it possible to addd single quate around url and filename and its value and use , in between similer to sample data ? Jun 12, 2015 at 1:35
  • Oh, added code to display content of files object. Side note: Generally we use console to debug. Just do console.out(files) and then you can inspect the content.
    – aadarshsg
    Jun 12, 2015 at 1:48
1

This seems to be working in a Codepen. (http://codepen.io/dharshba/pen/YXQvPP)

<script>
files = [];

function addtoArray(a, b) {
  var obj = {
    url: a,
    filename: b
  };
  files.push(obj);
};
</script>

I believe the +a and +b were at least part of the issue. Using the + operator that way attempts to coerce the strings into numbers, which wasn't really what you wanted.

To answer your question about seeing the array in a human-readable form in an alert, you can use:

alert(JSON.stringify(files));
1
  • Thank for replies. Yeah the + operator was part of the problem ! if i want to verify array content how i can print them ? Jun 12, 2015 at 1:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.