Sunday 20 October 2013

Tutorial JavaScript: Cara untuk convert JavaScript Array & Object kepada JSON Object menggunakan fungsi JSON.stringify()

Ini adalah salah satu soalan lazim yang selalu dikemukakan jika anda ingin memulakan pengaturcaraan web application dan AJAX (Asynchronous JavaScript and XML).

Berikut adalah contoh aturcara yang boleh anda lakukan:-

<!DOCTYPE html>
<!-- Copyright (2013) Muhamad Abdul Hay 
     juruteraperisian@gmail.com 
-->
<HTML>

</HEAD>
<TITLE>Tutorial - JavaScript Array, Object & JSON</TITLE>
</HEAD>
<BODY id="mainBody">
<SCRIPT>
var main = document.getElementById('mainBody');

var myArray = ['a', 'b', 'd', 'h'];
myArray.push('a'); // Add new element 
myArray.push('y'); // Add new element 

var myObject = {a: 'AAAAA', b: 'BBBBBB'};
myObject.z = 'ZZZZZZZZ'; // Add new element

main.innerHTML = 
"<pre>" +
"myArray[0] ==> " + myArray[0] + "<br>" +
"myArray[1] ==> " + myArray[1] + "<br>" +
"myArray[1] ==> " + myArray[2] + "<br>" +
"myArray[1] ==> " + myArray[3] + "<br>" +
"myArray[1] ==> " + myArray[4] + "<br>" +
"myArray[2] ==> " + myArray[5] + "<br><br>" +

"myObject['a'] ==> " + myObject['a'] + "<br>" +
"myObject['b'] ==> " + myObject['b'] + "<br>" +
"myObject['b'] ==> " + myObject['z'] + "<br><br>" +

"myObject.a ==> " + myObject.a + "<br>" +
"myObject.b ==> " + myObject.b + "<br>" +
"myObject.z ==> " + myObject.z + "<br><br>" +

"Converting JavaScript array & object into JSON format...<br>" +
"myArray  ==>  " + JSON.stringify(myArray) + "<br>" +
"myObject ==>  " + JSON.stringify(myObject) + "<br>" +

"<pre>";

</SCRIPT>
</BODY>
</HTML>

Dapatkan Deals Terbaru Di Sini

Related Posts Plugin for WordPress, Blogger...