JavaScript array problem - javascript

This bit of code doesn't seem to work.
for(var b = 0; b < wallPoints.length-1; b++)
{
wallPoints[b].xPos = wallPoints[b]-1;
}
function Point(x,y)
{
this.xPos = x;
this.yPos = y;
}
wallPoints is an array of Points
The code doesn't return any errors, it just makes all my code stop executing. This is my first time using JavaScript, so this is probably a very stupid mistake.

What are you trying to do -- shift each point by one in the x axis? You need to reference the property on the right hand side of the assignment as well.
for(var b = 0; b < wallPoints.length; b++)
{
wallPoints[b].xPos = wallPoints[b].xPos - 1;
}
or do you want to propagate the x axis from one point to another
for(var b = 1; b < wallPoints.length; b++)
{
wallPoints[b].xPos = wallPoints[b-1].xPos;
}
In the latter case, you'll need to figure out what to do with the first point. Note the change in the termination condition (and start condition in the second case).
EDIT: Here's my test code:
<html>
<head>
<title>Point</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var wallPoints = new Array();
wallPoints[0] = new Point(0,10);
wallPoints[1] = new Point(600,10);
wallPoints[2] = new Point(650,10);
var content = $('#content');
content.append('<h2>Before</h2>');
for(var b = 0; b < wallPoints.length; b++)
{
content.append('<p> x = ' + wallPoints[b].xPos + ', y = ' + wallPoints[b].yPos + '</p>' );
wallPoints[b].xPos = wallPoints[b].xPos-1;
}
content.append('<h2>After</h2>');
for(var b = 0; b < wallPoints.length; b++)
{
content.append('<p> x = ' + wallPoints[b].xPos + ', y = ' + wallPoints[b].yPos + '</p>' );
}
function Point(x,y)
{
this.xPos = x;
this.yPos = y;
}
});
</script>
</head>
<body>
<div id="content">
</div>
</body>
</html>

You're assigning an X variable equal to a point. Not an option:
for(var b = 0; b < wallPoints.length-1; b++)
{
wallPoints[b].xPos = wallPoints[b]-1;
}
instead try this:
for(var b = 0; b < wallPoints.length-1; b++)
{
wallPoints[b].xPos = wallPoints[b].xPos - 1;
}

Related

Why does a tetris piece fall all at once instead of one at a time?

I am making tetris in JS. When making a block fall, it makes the block reach the bottom of the screen in one draw instead of slowly approaching the bottom. I tried creating a variable that stores the changes to be made so that it only looks at the current board, but no luck. After checking whether the output variable is == to the board, it seems like the board is changing after all, as it returns true. What's going on?
EDIT: I have successfully made a shallow copy of the array. It still falls to the bottom immediately, though. What's going on?
var data = [];
function array(x, text) {
var y = [];
for (var i = 0; i < x-1; i++) {y.push(text);}
return y;
}
for (var i=0; i<20; i++){data.push(array(10, "b"));}
function draw(){
var j;
var i;
var dataOut = [...data];
for (i = 0; i < data.length - 1; i++){
for (j = 0; j < data[i].length; j++){
if (data[i][j] == "a" && data[i + 1][j] == "b" && i < data.length - 1) {
dataOut[i][j] = "b";
dataOut[i + 1][j] = "a";
}
}
}
data = dataOut;
}
data[0][4] = 'a';
draw();
console.log(data);
In JavaScript, Arrays and Objects are passed by reference. So when you do this:
var dataOut = data;
Both of these references point to the same Array. You could clone the Array every time:
var dataOut = JSON.parse(JSON.stringify(data));
Or simply revert your loop, to go from the bottom to the top. I took the liberty of renaming the variables to make this more clear. Try it below:
var chars = {empty: '.', block: '#'},
grid = createEmptyGrid(10, 20);
function createEmptyGrid(width, height) {
var result = [], x, y;
for (y = 0; y < height; y++) {
var row = [];
for (x = 0; x < width; x++) {
row.push(chars.empty);
}
result.push(row);
}
return result;
}
function draw() {
var x, y;
for (y = grid.length - 1; y > 0; y--) {
for (x = 0; x < grid[y].length; x++) {
if (grid[y][x] === chars.empty && grid[y - 1][x] === chars.block) {
grid[y][x] = chars.block;
grid[y - 1][x] = chars.empty;
}
}
}
}
// Just for the demo
var t = 0, loop = setInterval(function () {
draw();
if (grid[0].includes(chars.block)) {
clearInterval(loop);
grid[9] = 'GAME OVER!'.split('');
}
document.body.innerHTML = '<pre style="font-size:.6em">'
+ grid.map(row => row.join(' ')).join('\n')
+ '</pre>';
if (t % 20 === 0) {
grid[0][Math.floor(Math.random() * 10)] = chars.block;
}
t++;
}, 20);

How to console.log multiplication table without repeating x*y=z, y*x=z

How to make multiplication table without repeating reverse calculations like this xy=z yx=z? I tried to use if else with !== operator but it shows nothing. My code:
for (var x = 1; x <= 10; x++) {
for (var i = 1; i <= 10; i++) {
var result = x * i;
if (result !== result){
console.log(x + ' * ' + i + ' = ' + result);
}
else {
}
}
}
Pretty simple :
for (var x = 1; x <= 10; x++) {
for (var i = x; i <= 10; i++) {
var result = x * i;
console.log(x + ' * ' + i + ' = ' + result);
}
}
Replace i = 1 by i = x on the second line so that it starts later and ignores all the previous calculations it already did.
E.G.: When you're calculating the table 3, you can start with 3*3 as you already already did 3*1 (1*3) with table 1 and 3*2 (2*3) with table 2
You could keep track of the calculations you've already done in an hash table. If it's already in the table - skip that calculation. Something like this:
var doneCalculations = {};
for (var x = 1; x <= 10; x++) {
for (var i = 1; i <= 10; i++) {;
if (doneCalculations[i+'x'+x]) continue;
doneCalculations[x+'x'+i] = true;
var result = x * i;
console.log(x + ' * ' + i + ' = ' + result);
}
}
start the second loop with first loop variable
for (var x = 1; x <= 10; x++) {
for (var i = x; i <= 10; i++) {
var result = x * i;
console.log(x + ' * ' + i + ' = ' + result);
}
}
You want to print full multiplication table for each values of x, 1 to 10. Use memoization to avoid recalculation
In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
var doneCalculations = {};
var calculations = {};
var doneCalculations = {};
for (var x = 1; x <= 10; x++) {
for (var i = 1; i <= 10; i++) {;
if (doneCalculations[i+'x'+x]) {
result = calculations[i+'x'+x]
}
else {
doneCalculations[x+'x'+i] = true;
var result = x * i;
calculations[x+'x'+i] = result;
}
console.log(x + ' * ' + i + ' = ' + result);
}
}
console.log(calculations)

for loop works fine with console.log but not innerHTML?

hello i'm very new to javascript so forgive me if the answer seems obvious...
this is my code which is executed at the click of a button in the body
function q() {
var A = document.getElementById("time_one").value;
var B = document.getElementById("time_two").value;
var C = document.getElementById("post_number").value;
var D = (B - A) / C;
for ( var x = A; x < B; x = x + D ) {
document.getElementById("q_box").innerHTML = x + "<br />";
}
}
i'm pretty sure the error is in the for loop... the output is supposed to be a list of numbers between A and B. and changing the innerHTML = to innerHTML += hasn't worked either?
function q() {
var A = +document.getElementById("time_one").value;
var B = +document.getElementById("time_two").value;
var C = +document.getElementById("post_number").value;
var D = (B - A) / C;
for ( var x = A; x < B; x = x + D ) {
document.getElementById("q_box").innerHTML += x + "<br />";
}
}
You should convert the values in int and you should use +=
With innerHTML code inside the for loop you are always setting the value with the last time iterated value. Hence, you need to update your code to
for ( var x = A; x < B; x = x + D ) {
document.getElementById("q_box").innerHTML += x + "<br />";
}
OR
var y = "";
for ( var x = A; x < B; x = x + D ) {
y += x + "<br />";
}
document.getElementById("q_box").innerHTML = y;
I will recommend you to go for 2nd option, as it is better to set the updated value at once and not to extract the value and update for each iteration.

Convert array to string while grouping by pairs

I have an array of latitudes and longitudes in javascript, like this:
a = [lat1, lon1, lat2, lon2, lat3, lon3, ...] // assert(a.length % 2 = 0)
and I would like to create a string like this:
s = "lat1,lon1 lat2,lon2 lat3,lon3 ..."
that is, each latlon pair has a comma separating the pair, and the pairs are separated by a space.
I'm a bit stuck here (mostly because I know very little of javascript):
function polylineToKml(p)
{
var s = "";
for (var i = 0; i < p.length; i+=2)
{
var lat = p[i];
var lon = p[i+1]
// now what?
}
}
In a more functional way:
function polylineToKml(p) {
return p.map(function(el, i) {
return el + (i % 2 > 0 ? " " : ",");
}).join("").trim();
}
And if your environment supports ES6:
var polylineToKml = p =>
p.map((el, i) => el + (i % 2 > 0 ? " " : ",")).join("").trim();
One way:
var s = [];
for (var i = 0; i < a.length; i+=2)
{
s.push(a[i] + "," + a[i+1]);
}
s = s.join(" ");
function polylineToKml(p) {
var s = "";
for (var i = 0, l = p.length; i < l; i += 2) {
var lat = p[i];
var lon = p[i + 1];
s += lat + ',' + lon;
// don't add a space at the end
if (i !== l - 2) s += ' ';
}
return s;
}
DEMO
one more way...
function polylineToKml(p){
var s = "";
for (var i = 0; i < p.length - 1; i++){
s += p[i] + ",";
}
s += p[p.length - 1];
return s;
}
You should adopt a proper way to organize your data set, one way is to use JSON array with key-value pairs, e.g.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var a = [1.234, 2.345, 3.456, 5.456, 4.653, 2.567]
var coordinates = [];
for (var i=0; i < a.length; i=i+2){
coordinates[i/2] = {"latitude":a[i], "longitude":a[i+1]}
}
for (var i=0; i < coordinates.length; i++){
document.getElementById("demo").innerHTML +=
coordinates[i].latitude + ", " + coordinates[i].longitude + "<br>";
}
</script>
</body>
</html>
In this way, the coordinates will be represented as such:
coordinates = [
{"latitude":"1.234", "longitude":"2.345"},
{"latitude":"3.456", "longitude":"5.456"},
{"latitude":"4.653", "longitude":"2.567"}
];
Find out more on http://www.w3schools.com/json/default.asp

2-Dimensional Javascript Array unable to fill with duel for loops

I am writing a program that needs to use a Javascript 2-dimensional array, so I built this test rig to experiment adding values into the array.
As you can see if you examine the output, the loop runs the inner loop twice and then stops, the outer loop requirement to run 10 times is not enforced.
Can anyone explain what I am doing wrong?
HTML:
<body>
<input type="button" value="Press me!" id="pressMe" onclick="primaryCommand('textBox')">
<textarea id="textBox"></textarea>
</body>
Javascript:
function primaryCommand(input){
arrayTest(input);
}
function arrayTest(input){
// How large can an array be and still be safe?
var array = new Array(new Array());
var obj = document.getElementById(input);
obj.value="";
var x = 0, y = 0;
for (x = 0; x < 10; x++)
{
for (y = 0; y < 2; y++)
{
array[x][y] = "Hello World, x='" + x + "', y='" + y + "'\n";
obj.value+=array[x][y];
}
}
}
Output:
Hello World, x='0', y='0'
Hello World, x='0', y='1'
Your outer array (indexed by x) only has one member (a single array). Try this:
function arrayTest(input){
var array = [];
var obj = document.getElementById(input);
obj.value="";
var x = 0, y = 0;
for (x = 0; x < 10; x++)
{
array[x] = [];
for (y = 0; y < 2; y++)
{
array[x][y] = "Hello World, x='" + x + "', y='" + y + "'\n";
obj.value+=array[x][y];
}
}
}

Categories