So, in this code I have a string of 0's and 1's and the length of the string is 32, which will be split in 6 equal parts but the last part will have the length of 2 so I will add (4) 0's after that which will make its length 6. So I wrote a function that will add the remaining 0's which is padding(num).
And that function will be invoked in side the slicing(str) function.
But the code breaks when I try to do execute.
Any help?
Thanks.
// This code works.
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
let f = padding0s(2);
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");
// But this does not..
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
let f = padding0s(res[temp1].length);
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");
Always define variables before using them
Not doing so can result in undefined behaviour, which is exactly what is happening in your second case. Here is how:
for (i = 0; i < str.length; ) {...}
// ^ Assignment to undefined variable i
In the above for-loop, by using i before you define it, you are declaring it as a global variable. But so far, so good, as it doesn't matter, if not for this second problem. The real problem is the call to padding0s() in your loop. Let's look at padding0s:
function padding0s(num) {
...
for (i = 0; i < 6 - num; i++) {
s += "0";
}
}
This is another loop using i without defining it. But since i was already defined as a global variable in the parent loop, this loop will be setting its value. So in short, the value of i is always equal to 6 - num in the parent loop. Since your exit condition is i < str.length, with a string of length 32 the loop will run forever.
You can get around this in many ways, one of which you've already posted. The other way would be to use let i or var i instead of i in the parent loop. Even better is to write something like this (but beware that padEnd may not work on old browsers):
function slicing(str) {
return str.match(/.{1,6}/g).map((item) => {
return item.padEnd(6, "0");
});
}
console.log(slicing("01000011010011110100010001000101"));
I'm sure this is quite a simple programming question however, I cant seem to understand it...
I'm trying to make the console.log print out numbers like this - 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 - one for each line. I thought modulo could be used to make this happen, however, I cant seem to figure out how to use it.
Here is the code:
iteration = 16;
for (var i = 0; i < iteration; i++) {
if(i == iteration%4 )
console.log(i);
}
Yes, you need a single loop.
No, you do not need the remainder operator %. This would give you
0 1 2 3 0 1 2 3 ...
But instead you could divide the actual value by 4 and take the integer value for console.log.
const iteration = 16;
for (let i = 0; i < iteration; i++) {
console.log(Math.floor(i / 4) + 1); // offset for starting with 1
}
I suggest that you use two nested for loops, one for the rows and another one for the columns.
Here's an example of how i would do it:
const columns = 4;
const rows = 4;
//if you want to just console.log each number on a different line
for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= columns; j++) {
console.log(i);
}
console.log("\n");
}
//if you want to add each number to an array, and then log the array
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
console.log(columnsArray);
}
//if you want to just log the numbers, you can spread the array
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
console.log(...columnsArray);
}
//or you could push the arrays in another one, and get a matrix!
const matrix = [];
for (let i = 1; i <= rows; i++) {
let columnsArray = [];
columnsArray.length = columns;
columnsArray.fill(i);
matrix.push(columnsArray);
}
console.log(matrix);
It was not clear the output that you wanted, so i got a little sidetracked and made an example for the different cases that came to my mind.
I'm learning JavaScript and I came across the following situation:
My code:
alfabetoMadegues = "jngmclqskrzfvbwpxdht"
var listaLetras = Array.from(alfabetoMadegues);
dicionario_Madegues = {};
for (var i = 0 < listaLetras.length; i++;) {
listaLetras.forEach(element => {
dicionario_Madegues[element] = i;
})
};
If "j" is the first element of the array Why "j" is receiving 2 instead 0?. Why am i getting this result?
The expected result should be:
"j" 0
"n" 1
"g" 2
"m" 3
"c" 4
"l" 5
ES6 Soluce aka ECMA2015 - see compatibility table
As second parameter of Array.forEach you can get the position of the element; as example :
const alfabetoMadegues = 'jngmclqskrzfvbwpxdht';
const listaLetras = Array.from(alfabetoMadegues);
const dicionario_Madegues = {};
listaLetras.forEach((x, xi) => {
dicionario_Madegues[x] = xi;
});
console.log(dicionario_Madegues);
Also, the use of Array.reduce is more appropriate; as example
PS: We use of Spread operator ... and dynamic key naming [x].
const alfabetoMadegues = 'jngmclqskrzfvbwpxdht';
const listaLetras = Array.from(alfabetoMadegues);
const dicionario_Madegues = listaLetras.reduce((tmp, x, xi) => ({
...tmp,
[x]: xi,
}), {});
console.log(dicionario_Madegues);
ES5 Soluce
var alfabetoMadegues = 'jngmclqskrzfvbwpxdht';
var listaLetras = Array.from(alfabetoMadegues);
var dicionario_Madegues = {};
for (var i = 0; i < listaLetras.length; i += 1) {
dicionario_Madegues[listaLetras[i]] = i;
}
console.log(dicionario_Madegues);
You don't want that forEach inside the for. For the output you've described, you want to just remove that and replace it with dicionario_Madegues[listaLetras[i]] = i;.
You also have an error in your for loop. You have:
for (var i = 0 < listaLetras.length; i++;) {
...which will run forever. The initialization and test should be separated with ;:
for (var i = 0; i < listaLetras.length; i++) {
// -----------^^^--------------------------^ (no `;` after `i++`)
Live example:
var alfabetoMadegues = "jngmclqskrzfvbwpxdht";
var listaLetras = Array.from(alfabetoMadegues);
var dicionario_Madegues = {};
for (var i = 0; i < listaLetras.length; i++) {
dicionario_Madegues[listaLetras[i]] = i;
}
console.log(dicionario_Madegues);
Also note the various places I've removed and added ;. It's probably worth reviewing the rules for them.
You are looping two times:
for (var i = 0 < listaLetras.length; i++;) { // HERE
listaLetras.forEach(element => { //HERE
dicionario_Madegues[element] = i;
})
};
So you have to use either the for or the forEach:
alfabetoMadegues = "jngmclqskrzfvbwpxdht"
var listaLetras = Array.from(alfabetoMadegues);
var dicionario_Madegues_CON_FOR = {};
var dicionario_Madegues_CON_FOREACH = {};
for (var i = 0 ; i < listaLetras.length ; i++ ) {
dicionario_Madegues_CON_FOR[listaLetras[i]] = i;
};
listaLetras.forEach((letra, indice) => dicionario_Madegues_CON_FOREACH[letra] = indice);
console.log(dicionario_Madegues_CON_FOR);
console.log(dicionario_Madegues_CON_FOREACH);
There are also sintax errors in your for:
for (var i = 0 < listaLetras.length; i++;)
That should be
for(var i = 0 ; i < listaLetras.length ; i++ )
In addition to the provided answers you also can consider the following approach:
alfabetoMadegues = "jngmclqskrzfvbwpxdht"
var obj = {}
alfabetoMadegues.split('').forEach((element, index) => obj[element] = index)
console.log(obj)
There is a mistake on this line
for (var i = 0 < listaLetras.length; i++;) {
The for construct has three sections:
Initilisation
Condition
Afterthought
Each section is separated with a ;
You've smooshed your condition (i < listaLetras.length) and initialisation together. The afterthought is being left blank.
The correct code would be
for (var i = 0; i < listaLetras.length; i++) {
The reason j is 2 is for two reasons;
On the first pass of the loop i is getting set the the value of i < listaLetras.length - this evaluates to true.
Next the loop runs the comparision (to check whether it should run the body of the loop). The comparision here is .... i++ ! i is true so the comparison passes and then i is incremented.
i's value true is getting implicitly cast to a 1 for the increment.
When we hit the body of the loop it is now 2.
You are also looping two times with the foreach function - setting each value to i every iteration of i that occurs.
<!DOCTYPE html>
<html>
<head>
<title>100-Numbers</title>
</head>
<body>
<script>
var points = new Array(100);
var label = points.length;
for (var i = 0; i < label; i++) {
console.log(points[i]);
}
</script>
</body>
</html>
This is my First question in Stackoverflow. As i am an beginner, Please bare me and i need alot of support from you people. I m trying to print 1 to 100 numbers using arrays in javascript only. I'm Facing some errors in the above code. Please correct my mistakes to get the output..Thankyou in advance.
This will print 1-100 without any loops
Array.from({length: 100},(_,x) => console.log(x+1))
he said he wants to print 1-100 from an ARRAY...So the array needs to be populated, first. THEN, you can loop through the array.
var points = new Array(100);
for (var i = 0; i < 100; i++) {
points[i] = i + 1; //This populates the array. +1 is necessary because arrays are 0 index based and you want to store 1-100 in it, NOT 0-99.
}
for (var i = 0; i < points.length; i++) {
console.log(points[i]); //This prints the values that you stored in the array
}
The array values are uninitialized. I'm assuming that you want to print the values 1 to 100 using arrays where the values 1 to 100 are inside the array.
First initialize the array.
var oneToHundredArray = [];
Now populate it with values 1 to 100.
for(var value = 1; value <= 100; value++) {
oneToHundredArray.push(value);
}
Now the contains the values you want. Just loop and print over it now.
for(var index = 0; index < oneToHundredArray.length; index++) {
console.log(oneToHundredArray[index]);
}
Done :)
Array.from(Array(100), (_,i) => console.log(i+1));
The second parameter acts as mapping callback, so you also do this...
const arr = Array.from(Array(100), (_,i) => i+1);
for(num of arr) {
console.log(num);
}
Reference: Array.from
You should start off with an empty array, then run a loop for 1-101, I logged the iterator so you can see the values populate, you then need a binding agent to hold the value of the iteration, then you would need to push those values to your empty array.
var numbersArray = [];
for( var i = 1; i <101; i++){
console.log(i);
var numbers = i;
numbersArray.push(numbers);
}
After that, you then need to run a loop for the length of the numbersArray to output the individual results.
for(var m=0; m<= numbersArray.length -1; m++){
console.log(numbersArray[m]);
}
output console.log logs numbers 1-100 respectively.
var label = new Array(100);
for (var i = 0; i < 100; i++) {
label[i] = i + 1;
}
for (var i = 0; i < label.length; i++) {
console.log(label[i]);
}
It's much more easier with "while"
var i = 1;
while (i < 100) {
document.write(i + "<br/>");
i++;
}
Using a for loop:
function get_array() {
var arr = [];
for(var i=1; i<=100; i++) {
arr.push(i);
}
console.log(arr);
}
get_array()
I am trying to write a jQuery that will find the index of a specific value within a 7x7 2D array.
So if the value I am looking for is 0 then I need the function to search the 2D array and once it finds 0 it stores the index of the two indexes.
This is what I have so far, but it returns "0 0" (the initial values set to the variable.
Here is a jsFiddle and the function I have so far:
http://jsfiddle.net/31pj8ydz/1/
$(document).ready( function() {
var items = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = 0;
var line = 0;
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
$('.text').text(row + ' ' + line);
});
HTML:
<p class="text"></p>
Your if statement is comparing
if (items[i, j] == '0,')
Accessing is wrong, you should use [i][j].
And your array has values:
[1,2,3,4,5,6,7]
....
Your value '0,' is a string, which will not match numeric values inside the array, meaning that your row and line won't change.
First, you are accessing your array wrong. To access a 2D array, you use the format items[i][j].
Second, your array doesn't contain the value '0'. It doesn't contain any strings. So the row and line variables are never changed.
You should change your if statement to look like this:
if(items[i][j] == 0) {
Notice it is searching for the number 0, not the string '0'.
You access your array with the wrong way. Please just try this one:
items[i][j]
When we have a multidimensional array we access the an element of the array, using array[firstDimensionIndex][secondDimensionIndex]...[nthDimensionIndex].
That being said, you should change the condition in your if statement:
if( items[i][j] === 0 )
Please notice that I have removed the , you had after 0. It isn't needed. Also I have removed the ''. We don't need them also.
There are following problems in the code
1) items[i,j] should be items[i][j].
2) You are comparing it with '0,' it should be 0 or '0', if you are not concerned about type.
3) In your inner for loop you should be incrementing j and testing j as exit condition.
Change your for loop like bellow and it will work
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == '0') {
row = i;
line = j;
}
}
}
DEMO
Note:-
1) Better to use === at the place of ==, it checks for type also. As you see with 0=='0' gives true.
2) Better to say i < items.length and j<items[i].length instead of hard-coding it as 7.
var foo;
items.forEach(function(arr, i) {
arr.forEach(function(val, j) {
if (!val) { //0 coerces to false
foo = [i, j];
}
}
}
Here foo will be the last instance of 0 in the 2D array.
You are doing loop wrong
On place of
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
use this
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == 0) {
row = i;
line = j;
}
}
}
Here is the demo
looks like you are still learning how to program. But here is an algorithm I've made. Analyze it and compare to your code ;)
var itens = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = null;
var collumn = null;
for (var i = 0; i < itens.length; i++) {
for (var j = 0; j < itens[i].length; j++) {
if (itens[i][j] == 0) {
row = i;
collumn = j;
}
}
}
console.log(row, collumn);