JavaScriptオブジェクトリテラル同士の代入

このQ&Aのポイント
  • JavaScriptのオブジェクトリテラル同士の代入について質問があります。具体的には、{p:r, q:s} = {p:"foo", q:"bar"}の構文についての説明を求めています。
  • また、代入後の変数rとsがグローバル変数として定義される理由や、varを付けないと構文エラーになる理由、および代入したオブジェクトのプロパティにアクセスできない理由についても知りたいです。
  • さらに、この構文による代入はshallow copyなのかdeep copyなのかも教えてください。そして、もし左辺のvalueをグローバル変数として定義する意味がある場合、var obj2={a:"dummy"}; var {p:obj2.a}={p:"a"};のようなコードが文法エラーになる理由も知りたいです。
回答を見る
  • ベストアンサー

JavaScriptオブジェクトリテラル同士の代入

他人のソースコードの中に次のような構文を見かけました。 var {p:r, q:s} = {p:"foo", q:"bar"}; 質問ですが、(1)これは何をしているものなのでしょうか。入門レベルのサイトを検索しましたが分かりませんでした。糖衣構文の一種なのでしょうか。動作環境はfirefoxです。 (2)r,sがwindowオブジェクト直下のグローバル変数として定義されるのはなぜですか? (3)varを付けないと構文エラーになるのはなぜですか? {p:r, q:s} = {p:"foo", q:"bar"};// SyntaxError: invalid label (4)また、例えば var obj1={a:"b"}; としたとき、 obj1.a="b"; のようにkeyを指定してvalueにアクセスできますが、上記構文を実行した場合デバッガでp,qが存在しないのはなぜですか? (5)オブジェクト、配列、連想配列の"="によるコピーはshallow copyですが、この構文ではdeep copyになるのですか? // shallw copy var test={p:"hoge",q:"piyo"},test2={p:"miko",q:"nuko"}; test=test2; test2.p="fuga";// test.p is "fuga" test.q is "nuko" // deep copy var test2={p:"miko",q:"nuko"}; var {p:r,q:s}=test2; test2.p="fuga";// window.r is "miko" window.s is "nuko" so r,s is not alias (6)もし、この構文で左辺のvalueをグローバル変数として定義や再定義するような意味があると仮定すると、次のコードを実行すると2行目で文法エラーになるのはなぜですか? var obj2={a:"dummy"}; var {p:obj2.a}={p:"a"}; // SyntaxError: missing variable name 解説しているサイトのご提示でも問題ありませんが、仕様書等の場合はページ内の大まかな記載場所を併記してもらえると幸いです。 よろしくお願いします。

質問者が選んだベストアンサー

  • ベストアンサー
  • think49
  • ベストアンサー率59% (285/482)
回答No.2

Firefox の独自機能「分割代入」のようですね。 https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Grammar_and_types https://developer.mozilla.org/ja/docs/Web/JavaScript/New_in_JavaScript/1.7#.E5.88.86.E5.89.B2.E4.BB.A3.E5.85.A5 MDNの JavaScript から [Mozilla における ECMAScript 6 のサポート] -> [合意や安定性が確立していない機能] と辿っていけば見つかります。 https://developer.mozilla.org/ja/docs/Web/JavaScript # Re: shining330さん

その他の回答 (1)

  • think49
  • ベストアンサー率59% (285/482)
回答No.1

var {p:r, q:s} = {p:"foo", q:"bar"}; を Google Chrome で実行すると SyntaxError になりますが、質問文にある「次のような構文」は有効なコードであることを確認されたものなのでしょうか。 また、そのコードを見かけたサイトのURLはどこでしょう? # Re: shining330さん

shining330
質問者

補足

動作環境はfirefoxです。エラーメッセージの有無や有効性はfirebugにて確認しました。また、オフラインでhtmlファイルを作成し以下のように確認できます。 ~略~ <script> var {p:r, q:s} = {p:"foo", q:"bar"}; alert(r);// foo </script> コードは業務で使っている物ですが、担当者がいないため質問させていただきました。

関連するQ&A

  • Javascriptで数値の和を求める際の処理

    宜しくお願いします。 下記のプログラムの場合、 a,b,c の何れかの値が一つでも未入力の場合、 計算結果が表示されません。 未入力の場合は「0」とみなして、結果を表示させるには、 どの様にしたらよろしいでしょうか。 ご教授ください。 <script> var sum = 0; sum += a; sum += b; sum += c; var result = sum; var x = result; var y = myFormatNumber(x);function myFormatNumber(x) { var s = "" + x; var p = s.indexOf(".");if (p < 0) { p = s.length; } var r = s.substring(p, s.length); for (var i = 0; i < p; i++) { var c = s.substring(p - 1 - i, p - 1 - i + 1); if (c < "0" || c > "9") { r = s.substring(0, p - i) + r; break;}if (i > 0 && i % 3 == 0) { r = "," + r; } r = c + r; } return r; } document.write(y); </script>

  • JavaScriptで自動的に画像に表示されるALT属性を消したい

    以前、こちらでご質問させて頂き、 下記のJavaScript記述を教えて頂いたのですが、 画像にALT属性が自動的に入ってしまい 色々手を入れているうちに混乱してきてしまいました。 複数サムネイル画像をScriptで呼び出し、 オンマウスで拡大画像を表示、 それぞれのサムネイルにもリンクを張るという 少し入り組んだ仕様です。 ALT属性がリンク先ページのURLを表示してしまうため、 どうしても気になって消したいのですが、 もし分かる方がいらっしゃれば教えて頂けないでしょうか・・・ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <title>TEST</title> <style type="text/css"> .smlimg { width:120px; height:80px; } #bigimg { width:600px; height:400px; } #a { width:600px; height:100px; overflow:auto; } </style> <div><img src="" id="bigimg"></div> <div id="a"><div id="b"></div></div> <script type="text/javascript"> //@cc_on var simage = 'p0.jpg p1.jpg p2.jpg p3.jpg p4.jpg p5.jpg'.split(' '); var bimage = 'p0.jpg p1.jpg p2.jpg p3.jpg p4.jpg p5.jpg'.split(' '); var jmpurl = 'htp:/test.xxx0.com htp:/test.xxx1.com htp:/test.xxx2.com htp:/test.xxx3.com htp:/test.xxx4.com htp:/test.xxx5.com '.split(' '); var bufimg = []; addEvent( window, 'load', init); addEvent( 'b', 'mouseover', chgimg ); addEvent( document.body, 'click', chgurl ); function init(){ var w=0; for(var i in simage){ bufimg[i] = new Image; bufimg[i].src = bimage[i]; var image = document.createElement('img'); with( image ){ src = simage[i]; alt = bimage[i];title = jmpurl[i]; className = 'smlimg'; } var p = document.getElementById('b').appendChild( image ); w+=p.offsetWidth; } document.getElementById('b').style.width=w+'px'; var r = Math.random()*i|0; setbimg( bufimg[r].src, jmpurl[r] ); } function chgimg( evt ){ var obj = evt.target || evt.srcElement; if( obj.className && obj.className == 'smlimg') setbimg( obj.alt, obj.title ); } function chgurl( evt ){ var obj = evt.target || evt.srcElement; if( obj.className == 'smlimg' || obj.id == 'bigimg' ) window.open( obj.title ); } function setbimg(s,t){with( document.getElementById('bigimg')){alt=s;title=t}; changeImage('bigimg',s,5,20);} function addEvent(elementId, evt, eventHandler, flag){ var element = ( typeof( elementId ) == 'string' )? document.getElementById( elementId ): elementId; element./*@if(1)attachEvent('on'+ @else @*/addEventListener(/*@end@*/evt, eventHandler, flag); } var ff=0; function changeImage( elementId, imgsrc, step, wtime ){ this.setOpacity = function(n){ this.opacity = n; this.obj.style./*@cc_on @if(1) filter = 'alpha(opacity='+ this.opacity+ ')'; @else @*/ MozOpacity = this.obj.style.opacity = this.opacity / 100;/*@end@*/ } this.go = function(){ var f=0; this.setOpacity( this.opacity += this.step ); if( this.opacity<0 || this.opacity>100 ) { clearInterval( this.tmid ); this.obj.parentNode.removeChild( this.obj ); ff=0; } } if(ff) return; ff=1; var tobj = ( typeof( elementId ) == 'string' )? document.getElementById( elementId ): elementId; tobj.style.position='absolute'; var wrap = document.createElement( 'img' ); wrap.src = tobj.src; wrap.style.top = tobj.offsetTop +'px'; wrap.style.left = tobj.offsetLeft +'px'; wrap.style.width = tobj.offsetWidth +'px'; wrap.style.height = tobj.offsetHeight +'px'; wrap.style.position = 'absolute'; tobj.style.position=''; this.obj = document.body.appendChild( wrap ); tobj.src = imgsrc; this.setOpacity( 100 ); this.step = -step; this.tmid = setInterval((function(f_){ return function(){ f_.go.call(f_);}})(this), wtime); } </script>

  • objectの座標が取れない。

    JavaScriptを利用して、画面に仕込んだタグをポップアップのように 呼び出したいと思っています。 以下、概略ですが <div id ="test1" style="display:none;">テスト</div> <a href="javascript:balOpen(this,number)">呼び出し</a> 以下js function balOpen(obj,number) { document.getElementById('test' + number).style.display = 'block'; var positionX; var positionY; positionX = getLocation(obj, 'X'); positionY = getLocation(obj, 'Y'); } 画面をスクロールした際でも、画面中央に出したいので、座標を見て tes1のleftとtopを調整したいと思っています。 しかし、上記のような書き方をしても、X、Yの座標が取れず困っています。 何か良いやり方があれば教えていただけないでしょうか。 宜しくお願いします。

  • JavaScriptの配列について

    var old_array = Array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '<', '#', '/', '>', '%', '.', '*', '0', '!', '?', ':', '=', '|'); var new_array = Array('b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '<', '#', '/', '>', '%', '.', '*', '0', '!', '?', ':', '=', '|'); のような配列があり、 abcと入力するとbcd DEFと入力するとEFG 012と入力すると!23 というようなものを作りたいのですがどうすればいいでしょうか。

  • IEでF12を押さないとjavascriptが…

    javascript初心者です。 サイトのログインページに、 IDとpasswordを保存する機能をを作りたいと考えています。 プログラムからjavaccriptを呼び出しているのですが、 IEからそのjavascriptが読み込まれなくなってしまいました。 (Chrome,FireFox,Operaでは正しく動作しています。) F12を押してIEの開発者ツールを立ち上げると、正しく動作するようになります。 なぜ、F12を押さないと呼ばれないのかが、 さっぱりわからず、教えていただけないでしょうか。 htmlソースにも記述されています。 呼び出し元は、tclです。 <script language="JavaScript"> var rwAuthInfo = { conf : { kwordId : 'auth_id', kwordPass : 'auth_pass', savePeriod : 120, idElemKey : 'authId', passElemKey : 'authPass', chkElemKey : 'authSave' }, CookieWrite : function(kword, kdata, kday) { if (!navigator.cookieEnabled) { return; } var sday = new Date(); sday.setTime(sday.getTime() + (kday * 1000 * 60 * 60 * 24)); var s2day = sday.toGMTString(); document.cookie = kword + "=" + escape(encodeURIComponent(kdata)) + ";expires=" + s2day + ";path=/"; }, CookieRead : function(kword) { if (typeof(kword) == "undefined") { return ""; } kword = kword + "="; var kdata = ""; var scookie = document.cookie + ";"; var start = scookie.indexOf(kword); if (start != -1) { end = scookie.indexOf(";", start); kdata = decodeURIComponent(unescape(scookie.substring(start + kword.length, end))); } return kdata; }, getAuthInfo : function() { console.log("get auth info"); var myPass = decodeURIComponent(unescape(rwAuthInfo.CookieRead(rwAuthInfo.conf.kwordPass))); var obj1 = document.getElementsByTagName('input'); for(i = 0; i < obj1.length; i++){ if ( obj1[i].id == rwAuthInfo.conf.passElemKey && myPass != "" ) { obj1[i].value = myPass; } } var myId = rwAuthInfo.CookieRead(rwAuthInfo.conf.kwordId); var obj2 = document.getElementsByTagName('input'); for(i = 0; i < obj2.length; i++){ if ( obj2[i].id == rwAuthInfo.conf.idElemKey && myId != "" ) { obj2[i].value = myId; } } console.log("From cookie - id: " + myId + ", password: " + myPass); }, saveAuthInfo : function() { console.log("save authentication info"); var objChk = document.getElementById(rwAuthInfo.conf.chkElemKey); if ( objChk.type == "checkbox" && objChk.checked ) { var obj1 = document.getElementById(rwAuthInfo.conf.passElemKey); if ( obj1.value != null && obj1.value != '' ) { var myPass = escape(encodeURIComponent(obj1.value)); console.log("password: " + obj1.value + ", encoded: " + myPass); rwAuthInfo.CookieWrite(rwAuthInfo.conf.kwordPass, myPass, rwAuthInfo.conf.savePeriod); } var obj2 = document.getElementById(rwAuthInfo.conf.idElemKey); if ( obj2.value != null && obj2.value != '' ) { var myId = escape(encodeURIComponent(obj2.value)); rwAuthInfo.CookieWrite(rwAuthInfo.conf.kwordId, myId, rwAuthInfo.conf.savePeriod); } } }, addSubmitEvent : function() { for ( i=0; i<document.forms.length; i++ ) { var frm = document.forms[i]; try { frm.addEventListener('submit', rwAuthInfo.saveAuthInfo, false); } catch (e) { frm.attachEvent('onsubmit', rwAuthInfo.saveAuthInfo); } } }, addLoadEvent : function() { try { if (window.addEventListener) { window.addEventListener('load', rwAuthInfo.getAuthInfo, false); window.addEventListener('load', rwAuthInfo.addSubmitEvent, false); } else if (window.attachEvent) { var isMSIE = /*@cc_on!@*/0; if (isMSIE) { window.attachEvent('onload', rwAuthInfo.getAuthInfo); window.attachEvent('onload', rwAuthInfo.addSubmitEvent); window.attachEvent('load', rwAuthInfo.getAuthInfo); window.attachEvent('load', rwAuthInfo.addSubmitEvent); } else { window.attachEvent('onload', rwAuthInfo.getAuthInfo); window.attachEvent('onload', rwAuthInfo.addSubmitEvent); } } } catch (e) { console.error("got error in addLoadEvent: " + e); window.attachEvent('onload', rwAuthInfo.getAuthInfo); window.attachEvent('onload', rwAuthInfo.addSubmitEvent); } } } rwAuthInfo.addLoadEvent(); </script>

  • [javascript][DOM]getElementByIdやremoveChildの戻り値と処理の結果

    以前から気になっていたけれど聞かなかったこと。 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"> <head> <title>QFUMEI テストケース1</title> <script type="application/ecmascript"> function init(){ var hoge = document.getElementById("hoge"); var fuga = document.getElementById("fuga"); hoge.removeChild(fuga); alert(fuga); // [object HTMLParagraphElement] ← nullではない fuga = document.getElementById("fuga"); alert(fuga); // null } </script> </head> <body onload="init();"> <div id="hoge"> <p id="fuga">ほげ</p> </div> </body> </html> 結局 fuga = getElementById("fuga")によって 何が代入されているのでしょう? document上のp#fugaへの参照であれば removeChildの直後 fuga = nullとなっていてもよさそうだなと思っているのですが・・・・。 hoge.firstChild.nodeValueをいじるとp要素内の文字列が変化するし・・・・

  • flash javascript php の引数受け渡しで

    http://61.197.170.205/~tobacco/htdocs/test.php があり。戻り値があります。 javascriptに var req_argument = null; function File_Request(data, fileName){ //XMLHttpRequestオブジェクト(ブラウザー対策できてるものとして) var http_obj = new XMLHttpRequest(); http_obj.open("POST", fileName); http_obj.onreadystatechange = function(){ if(http_obj.readyState == 4){ req_argument = http_obj.responseText; } } http_obj.setRequestHeader('Content-Type','text/plain;charset=UTF-8'); http_obj.send(data); } function flash_kick(argument) { File_Request(argument, "http://61.197.170.205/~tobacco/htdocs/test.php"); return req_argument; } を設置したページを用意し、さらにactionscript上に以下と「bt_test」ボタン・「kakunin_text_box」のあるflashを配置しました。 import flash.external.*; bt_test.addEventListener(MouseEvent.MOUSE_UP, test_action); function test_action(e){ var argument:String = "渡したい引数"; var s:String = String(ExternalInterface.call("flash_kick", argument)); kakunin_text_box.text = s; }; うまくいかず、http_obj.readyState == 4を待ってくれないのでnullが戻ってきます。 どのような処理をするとスムーズにphpの返り値をflashへ受け渡せるのか、ご教授いただけると嬉しいです。 質問用書き換え時に文法エラーあったらごめんなさい。

    • ベストアンサー
    • AJAX
  • JavaScriptって何者だ。

    参考までにソースを見ることができました。 HTMLで書かれているのは解りそうな気がしますが、JavaScriptは一生理解できないような気がします。メチャクチャ複雑でゴチャゴチャしています。 これって人間業じゃないような気がします。 マダ、PHPやPerl等も覚えようと思っていますが、JavaScriptはメチャクチャ 難しそうです。 WEBデザイナーの方なんか余程勉強したのでしょうね。 お先真っ暗です。 どうやって勉強するのかアドバイスをください。 宜しくお願い申し上げます。 n[e].exports}if("function"==typeof __nr_require)return __nr_require;for(var o=0;o<e.length;o++)r(e[o]);return r}({1:[function(t,n,e){function r(t){try{s.console&&console.log(t)}catch(n){}}var o,i=t("ee"),a=t(15),s={};try{o=localStorage.getItem("__nr_flags").split(","),console&&"function"==typeof console.log&&(s.console=!0,o.indexOf("dev")!==-1&&(s.dev=!0),o.indexOf("nr_dev")!==-1&&(s.nrDev=!0))}catch(c){}s.nrDev&&i.on("internal-error",function(t){r(t.stack)}),s.dev&&i.on("fn-err",function(t,n,e){r(e.stack)}),s.dev&&(r("NR AGENT IN DEVELOPMENT MODE"),r("flags: "+a(s,function(t,n){return t}).join(", ")))},{}],2:[function(t,n,e){function r(t,n,e,r,o){try{d?d-=1:i("err",[o||new UncaughtException(t,n,e)])}catch(s){try{i("ierr",[s,c.now(),!0])}catch(u){}}return"function"==typeof f&&f.apply(this,a(arguments))}function UncaughtException(t,n,e){this.message=t||"Uncaught error with no additional information",this.sourceURL=n,this.line=e}function o(t){i("err",[t,c.now()])}var i=t("handle"),a=t(16),s=t("ee"),c=t("loader"),f=window.onerror,u=!1,d=0;c.features.err=!0,t(1),window.onerror=r;try{throw new Error}catch(l){"stack"in l&&(t(8),t(7),"addEventListener"in window&&t(5),c.xhrWrappable&&t(9),u=!0)}s.on("fn-start",function(t,n,e){u&&(d+=1)}),s.on("fn-err",function(t,n,e){u&&(this.thrown=!0,o(e))}),s.on("fn-end",function(){u&&!this.thrown&&d>0&&(d-=1)}),s.on("internal-error",function(t){i("ierr",[t,c.now(),!0])})},{}],3:[function(t,n,e){t("loader").features.ins=!0},{}],4:[function(t,n,e){function r(t){}if(window.performance&&window.performance.timing&&window.performance.getEntriesByType){var o=t("ee"),i=t("handle"),a=t(8),s=t(7),c="learResourceTimings",f="addEventListener",u="resourcetimingbufferfull",d="bstResource",l="resource",p="-start",h="-end",m="fn"+p,w="fn"+h,v="bstTimer",y="pushState",g=t("loader");g.features.stn=!0,t(6);var b=NREUM.o.EV;o.on(m,function(t,n){var e=t[0];e instanceof b&&(this.bstStart=g.now())}),o.on(w,function(t,n){var e=t[0];e instanceof b&&i("bst",[e,n,this.bstStart,g.now()])}),a.on(m,function(t,n,e){this.bstStart=g.now(),this.bstType=e}),a.on(w,function(t,n){i(v,[n,this.bstStart,g.now(),this.bstType])}),s.on(m,function(){this.bstStart=g.now()}),s.on(w,function(t,n){i(v,[n,this.bstStart,g.now(),"requestAnimationFrame"])}),o.on(y+p,function(t){this.time=g.now(),this.startPath=location.pathname+location.hash}),o.on(y+h,function(t){i("bstHist",[location.pathname+location.hash,this.startPath,this.time])}),f in window.performance&&(window.performance["c"+c]?window.performance[f](u,function(t){i(d,[window.performance.getEntriesByType(l)]),window.performance["c"+c]()},!1):window.performance[f]("webkit"+u,function(t){i(d,[window.performance.getEntriesByType(l)]),window.performance["webkitC"+c]()},!1)),document[f]("scroll",r,{passive:!0}),document[f]("keypress",r,!1),document[f]("click",r,!1)}},{}],5:[function(t,n,e){function r(t){for(var n=t;n&&!n.hasOwnProperty(u);)n=Object.getPrototypeOf(n);n&&o(n)}function o(t){s.inPlace(t,[u,d],"-",i)}function i(t,n){return t[1]}var a=t("ee").get("events"),s=t(18)(a,!0),c=t("gos"),f=XMLHttpRequest,u="addEventListener",d="removeEventListener";n.exports=a,"getPrototypeOf"in Object?(r(document),r(window),r(f.prototype)):f.prototype.hasOwnProperty(u)&&(o(window),o(f.prototype)),a.on(u+"-start",function(t,n){var e=t[1],r=c(e,"nr@wrapped",function(){function t(){if("function"==typeof e.handleEvent)return e.handleEvent.apply(e,arguments)}var n={object:t,"function":e}[typeof e];return n?s(n,"fn-",null,n.name||"anonymous"):e});this.wrapped=t[1]=r}),a.on(d+"-start",function(t){t[1]=this.wrapped||t[1]})},{}],6:[function(t,n,e){var r=t("ee").get("history"),o=t(18)(r);n.exports=r,o.inPlace(window.history,

  • javascriptについて

    function df(){ document.ad.ad1.value=500; } function df2(a){ var sty=a.ad2.selectedIndex; a.ad3.value=eval(a.ad1.value)*eval(a.ad2.options[sty].value); } function df3(){ var s1=document.ad.ad3.value; var s2=document.ad.ad4.value; var fv=s1+"円\n"+ s2+"様"; var don=confirm(fv); } function df4(){ var p=0; if(document.ad.ad4.value==""){ p=1; } if(p){ alert("記入漏れ"); return false; } else{ return true; } } --> </script> </head> <body> <form action="#" method="POST" name="ad"> <p>ラーメン<input type="text" soze="20" value="500" name="ad1" onChange="df()">円</p> <p><select name="ad2" onChange="df2(this.form)"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> 個 </select> </p> <p>合計<input type="text" size="20" name="ad3">円</p> <p>備考:<input type="text" size="20" name="ad4"></p> <p><button onClick="df3();df4();"><img src="rtp/migi.jpg"></button></p> </form> </body> </html> 内容に間違いがあっても データーを送ってしまいます。 何故なんでしょうか?

  • JavaScriptの文字のエンコードについて

    フォームの入力欄で、「'」(シングルクォート)を入力してサブミットすると、ブラウザ(Firefox3.5)で見ると「'」と表示されていますが、ブラウザのソースを見るとvalueの¥ところには、「'」と表示されています。 これは、PHPでエンコードされているせいなのですが、 PHPでエンコードされた「'」を、JavaScriptを使って、ブラウザからソースを見たときに「'」と表示できるでしょうか? ソースは、こんな感じで書いたのですが、動作しませんでした........。 function chChar(){ var keyValue = document.getElementById("delete_key").value; var ascii = new Array(' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F','G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~'); var htmlChar = new Array(' ', '!', '"', '#', '$', '%', '&', ''', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~'); var re = new RegExp(htmlChar); if(keyValue.match(re)){ for(i=0; i<ascii.length; i++){ keyValue = keyValue.replace(htmlChar[i], ascii[i]); } } return keyValue; }

専門家に質問してみよう