开发者

Converting PHP code into JS

I have this PHP code -

 <?php
for($i=1; $i<=1000; $i++) {
  $array=array();
  $array[$i]=54*$i;

  $arr=array($array[$i].",");

  foreach ($arr as $value) {
    echo $value;
  }
}
?>

I tried with:

var i;
for(i=1;i<=1000;i++) {
  var array = new Array();
  array[i] = 54*i;
  var arr = new Array();
  arr.push(arra开发者_如何学Goy[i]+",");
}
alert(arr)

But it doesn't work. Where's the mistake?


Wild stab.. because the PHP code while it may produce the expected output, is actually 'wrong' (wrong on the basis that you may expect the array to hold all those values, and it doesn't).

so here's the php (fixed).

<?php
$a = array();
$stringVersion = '';
for($i=1; $i<=1000; $i++) {
  $a[$i] = 54*$i;
  $stringVersion .= $a[$i] . ',';
}
echo $stringVersion;

and here's a JS alternative

var a = [];
var stringVersion = '';
for(var i=1;i<=1000; i++) {
  a[i] = 54*i;
  stringVersion += a[i] + ',';
}
alert(stringVersion);


Something like this:

var array = new Array(1000);
for(var i=1;i<=1000;i++) { 
    array[i] = 54*i; 
} 
alert(array[1000]) ;

Just a few "pointers" (pun unintended);

  1. You sure don't want all 1000 calls to be echoed to messageboxes - I only display the last (1000 * 54) to the user - clicking Ok 1000 times ...
  2. You don't push anything into an array like Php code. In this case I "define" the arraylength to 1000, but creating an array without the lenght does work to. Just "add" items with arrayName[indexToBeCreated] et voila.
  3. Loop variables don't need to be defined before the loop, just define them inside the loop (for (var i blabla...

Hope it helps

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜