简体   繁体   中英

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(array[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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM