I have code like this:
$data = array();
for(int $i = 0; $i < 10; $i ++)
$data[$i][] = 5;
I don't know what's name of $data[$i][] = 5; in php and how to write this code in javascript?
or other hands, how can I write code above in javascript?
Thanks
P/s:
I want to write that code on nodeJs
You can try Array#push to add a element for array
var data = [];
for(var i = 0; i < 10; i ++)
if(!data[i]) data[i] = [];
data[i].push(5);
in this case, can understand $data[$i][] = 5; as below
$data[$i] = array();
array_push($data[$i],5);
// ex: [ 0 => [0 => 5]]
in Javascipt:
var data = [];
for (var i = 0; i < 10; i ++){
data[i] = [];
data[i].push(5);
}
Array.push() is a function used to insert a value into an array. But you can also use the C like way data[i] = 'value'.
data = [];
for (var i = 0; i < 10; i++)
data.push([5]);
document.write(JSON.stringify(data))
As an alternative use
data = [];
for(var i = 0; i < 10; i ++)
data[i] = [5];
document.write(JSON.stringify(data));
Use array.push() to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
To do this n times use a for loop.
var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
sample.push(new Object());
Note that you can also substitute new Array() with [] and new Object() with {} so it becomes:
var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({});
JavaScript code:
var data = [];
for (i = 0; i < 10; i++) {
data[i] = [];
data[i][data[i].length] = 5;
}
Related
I have this so far, trying to get it to find the sum of each one of any number of inputted numbers with integers and "-"s.
When I run this,
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for (var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
I have also tried
var howM = prompt("How many cards?")
var arr = [];
for (var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for (var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace(/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
In both cases I get the sum for the first piece in the array and then undefined. How do I get it to run for each piece? I kind of have an idea of what is wrong with it I just don't quite know how to fix it.
You need to use a second counter for the nested for loop, like so:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
var sumpre = [];
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i];
eXt = eXt.replace (/-/g, "");
for (var j = 0; j < eXt.length; j++) {
sum += parseInt(eXt.substr(j, 1));
}
sumpre.push(sum);
}
console.log(sumpre)
Your var sum = 0; inside your for-loop meaning sum variable will not be accessible outside of the loop
I want to initialize and then print the elements of a 2D array using javascript.
I wrote this code but nothing displays as output. How to output this array?
var m = 6;
var n = 3;
var mat = new Array[m][n];
for (i = 0; i < mat.length; i++) {
for (j = 0; j < mat[i].length; j++) {
mat[i][j]) = i * j;
document.writeln(mat[i][j]);
}
document.writeln("<br />");
}
<html>
<body>
</body>
<script>
var m=6;
var n=3;
var mat =new Array(m);
for( var i=0; i < m ; i++){
mat[i] = new Array(n);
for( var j=0;j< n ;j++){
mat[i][j] = i*j;
document.writeln(mat[i][j]);
}
document.writeln("<br />");
}
</script>
</html>
As BenG pointed out, you've got an extra ) but you also aren't initializing your array correctly. Javascript doesn't allow you to declare multi-dimensional arrays like other languages. Instead, you'd have to do something more like this:
var m = 6;
var n = 3;
var mat = new Array(m);
for (var i = 0; i < m; i++) {
mat[i] = new Array(n);
}
Javascript arrays are dynamic. They will grow to the size you require. You can call push() to add a new element to the array. It's also worth noting that you should avoid using the new keyword with objects and arrays. Use their literal notations [] for arrays and {} for objects. So a better solution here would be to push to the arrays as you need them.
var mat = [];
var m = 6;
var n = 3;
for (var i = 0; i < m; i++) {
// Let's add an empty array to our main array
mat.push([]);
for (var j = 0; j < n; j++) {
mat[i].push(i * j);
document.writeln(i * j);
}
document.writeln('<br />');
}
I want to create a multidimensional array like this:
array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]
array[.][....]
How can I do this in Javascript?
I have tried this:
var squares = new Array();
for(var i = 1; i <= 8; i++)
{
for(var j = 1; j <= 20; j++)
{
squares.push(i, j);
}
}
How can I accomplish this?
You can do something like this:
var squares = new Array();
for(var i = 0; i <= 8; i++)
{
squares[i] = new Array();
for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
if (squares[i] == null)
squares[i] = j;
else
squares[i].push(j);
}
Output comes like:
array[0][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
array[1][21,22,23,24,25,26,27....]
var array = []; // Main array
var numArrays = 10, // Number of sub-arrays
numPerArray = 20; // Number of squares per sub-array
for(var i = 0; i < numArrays; i++){
var subArray = [];
// Number to start at
var start = i * numPerArray;
// Count up to start + numPerArray
for(var j = start; j < start + numPerArray; j++){
subArray.push(j);
}
// Add to main array
array.push(subArray);
}
Use modulus operand to limit the inner array's size
var limit = 80
var inner_limit = 20
var square=[]
var inner =[]
for(var i=1;i<=limit;i++){
inner.push(i)
if(i%inner_limit==0){
square.push(inner)
inner = []
}
}
You can do it with two "for" loops. In the first loop you go through the main array and for each element add the elements from the second loop.
var arrayLength = 10; // Main array length
var limit = 20; // Number of squares
var array = [];
for ( var i = 0; i < arrayLength; i++ )
{
array[i] = []; // Create subArray
for( var j = 1; j <= limit; j++ )
{
array[i].push(j);
}
}
I am iterating over a JSON array (rec'd from a webworker AJAX call)
var dataReceived = JSON.parse(xhr.responseText);//JSON verified as ok
//dataReceived.length verified
var dataProcessed = [];
for (var i = 0; i < dataReceived.length; i++) {
for ( var h = 0; h < dataReceived[i].length; h++) {
dataProcessed[i][h][0]=((dataReceived[i][h][0])*30)-30;
dataProcessed[i][h][1]=((dataReceived[i][h][1])*30)-30;
}
}
postMessage(dataProcessed);
But i get the error
dataProcessed[i] is undefined
Does Javascript not create multidimensional arrays on the fly?
Does Javascript not create multidimensional arrays on the fly?
No, you have to create it:
for (var i = 0; i < dataReceived.length; i++) {
dataProcessed[i] = []; // <============= Here
for ( var h = 0; h < dataReceived[i].length; h++) {
dataProcessed[i][h] = []; // <============= And here
Side note: You can make that more efficient by factoring out your repeated lookups; also, you can create and initialize the innermost array simultaneously:
var dataReceived = JSON.parse(xhr.responseText);
var dataProcessed = [];
var recEntry, procEntry;
for (var i = 0; i < dataReceived.length; i++) {
procEntry = dataProcessed[i] = [];
recEntry = dataReceived[i];
for ( var h = 0; h < recEntry.length; h++) {
procEntry[h] = [
((recEntry[h][0])*30)-30,
((recEntry[h][1])*30)-30
];
}
}
postMessage(dataProcessed);
No, javascript does not create multidimensional arrays on the fly.
You will have to look for the edge case .e.g. first iteration of the loop, and
then create an empty array.
Or you can also initialize the array using || operator
for (var i = 0; i < dataReceived.length; i++) {
dataProcessed[i] = []; // array
for ( var h = 0; h < dataReceived[i].length; h++) {
dataProcessed[i][h] = []; // array
dataProcessed[i][h][0]=((dataReceived[i][h][0])*30)-30;
dataProcessed[i][h][1]=((dataReceived[i][h][1])*30)-30;
}
}
postMessage(dataProcessed);
Here's a pseudocode example about what I'm trying to do:
var totalLanguages = XX;
for(var i = 0; i < totalLanguages; i++){
var dynamicArray + i = new Array();
/*.....*/
}
I need to create dynamically many arrays as the value of totalLanguages which can be either number.
This is to be able to do something like this:
for(var i = 0; i < totalLanguages; i++){
var arrayLanguages["es"] = dynamicArray+i;
var arrayLanguages["en"] = dynamicArray+i;
}
Is there any way to do this?
var languageNames = ['en', 'es'];
var languages = {};
for (var i = 0; i < languageNames.length; i++) {
languages[languageNames[i]] = [];
}
You are basically trying to recreate an array with variable names. Just use an Array to start out!
var dynamicArray = [];
for(var i = 0; i < totalLanguages; i++) {
dynamicArray[i] = new Array();
}
You can use multi-dimensional arrays:
var languagesArray = new Array(totalLanguages);
for(var i = 0; i < totalLanguages; i++) {
var innerArray = new Array();
innerArray.push("Hello");
innerArray.push("World");
languagesArray[i] = innerArray;
}
console.log(languagesArray[0][0]);
See: How can I create a two dimensional array in JavaScript?
How about:
for(var i = 0; i < totalLanguages; i++){
window["dynamicvariable " + i] = new Array();
/*.....*/
}