开发者

Access to an array

开发者 https://www.devze.com 2023-03-13 14:12 出处:网络
after a while I need your help again ;-). I found following javascript var global_index = 0; var db = [ \"10000000\", \"01000000\", \"00100000\", \"00010000\", \"00001000\", \"00000100\", \"0000001

after a while I need your help again ;-). I found following javascript

var global_index = 0;
var db = [ "10000000", "01000000", "00100000", "00010000", "00001000", "00000100", "00000010", "00000001" ];

function loadled()
{
    var byte = db[ global_index ];
    if( global_index < 7 ) global_index++; else global_index = 0;
    for( var x = 0; x < byte.lengt开发者_JAVA技巧h; x++ )
    {
        document.getElementById("id_" + x ).src = [ "led_off.gif", "led_on.gif" ][ parseInt( byte[ x ], 10 ) ];
    }
    window.setTimeout( loadled, 100 );
}
window.onload = loadled;

</script></head>  
</html>

I don't understand following line:

document.getElementById("id_" + x ).src = [ "led_off.gif", "led_on.gif" ][ parseInt( byte[ x ], 10 ) ];

Can anyone provide a simple explanation for this or a comparison to common writing?

Thanks.


I belive that the following code : parseInt( byte[ x ], 10 ) will always return 0 or 1 thus selecting eiter "led_off.gif" or "led_on.gif" as the src of the element x :)

HTH :)


document.getElementById("id_" + x ).src = [ "led_off.gif", "led_on.gif" ][ parseInt( byte[ x ], 10 ) ];

document.getElementById("id_" + x)

selects the html element named id_x (where x is the variable in your code)

.src

specifies that you want to change the source of the html element selected above

[ "led_off.gif", "led_on.gif" ][ parseInt( byte[ x ], 10 ) ];

that will either render to "led_off.gif" or "led_on.gif" depending on the value of x.

parseInt(byte[x],10) tries to convert a string to numeral format (and in this case the numeral format based on 10), and will either be 0 or 1.

So the line will become:

document.getElementById("id_[x]").src = "led_off.gif"

or

document.getElementById("id_[x]").src = "led_on.gif"

depending on the value of x. Which means that the source of the image with the id=id_x will change source to the other gif.

0

精彩评论

暂无评论...
验证码 换一张
取 消