This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 6 years ago.
I'm a total newbie in JavaScript. I'm trying to learn it using programming experience in Python...
Let's say there is an array of integers [2,3,4,5]. I want to get sum of all items in it with for loop. In Python this gonna looks like
list_sum = 0
for i in [2,3,4,5]:
list_sum += i
Result is 14
But if I try same in JavaScript:
var listSum = 0;
for (i in [2,3,4,5])
{
listSum += i;
}
This will return 00123. Seems that item indexes concatenated in a string with initial listSum value. How to make code works as intended and to get sum of all array items as integer?
You are doing wrong for loop syntax. check this : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for
var listSum = 0;
var arr = [2,3,4,5];
for (i=0;i<arr.length ; i++)
{
listSum += arr[i];
}
document.write(listSum);
Related
This question already has answers here:
Does return stop a loop?
(7 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
function monkeyCount(n) {
for (i=1; i<=n; ++i){
let monkeyArray=[i];
return monkeyArray[i];
}
}
Another rookie question lol. I need to return the values of an entire array using the return statement and not the console.log. If I pass a number such as 5 to the function I need to return 1,2,3,4,5 your help much appreciated:0)
It looks like you want to append values to the array not reassign the array at every iteration of the loop. Try this:
const monkeyArray = [];
for(let i = 1; i<= n; i++){
monkeyArray.push(i);
}
return monkeyArray;
There are also many ways to do this such as with the lodash library where you can just call _.range(1, 6) to get an array from [1,6)
This is pretty simple, you just have try this on browser console.
function monkeyCount(n) {
let monkeyArray = [];
for (i=1; i<=n; ++i) {
monkeyArray[i-1] = i;
}
return monkeyArray.join(',');
}
This question already has answers here:
Does return stop a loop?
(7 answers)
Closed 1 year ago.
I found this task on "Code Wars"
"Complete the function that takes a non-negative integer n as input, and returns a list of all the powers of 2 with the exponent ranging from 0 to n (inclusive)."
This is what my attempt to solve the problem looks like:
function powersOfTwo(n){
var myArray = [];
for (var i=0; i<=n; i++){
return myArray.push(2**i);
}
return myArray
}
However, it doesn't work, and I don't really understand why. I just started writing code last week to be honest.
You are returning inside of your loop, so it exits the function straight away. Just remove that return as you are returning the array at the end.
function powersOfTwo(n){
var myArray = [];
for (var i=0; i<=n; i++){
myArray.push(2**i);
}
return myArray
}
const result = powersOfTwo(2)
console.log(result)
This question already has answers here:
Generating non-repeating random numbers in JS
(20 answers)
Unique random values from array of unique values javascript
(2 answers)
Closed 2 years ago.
I have been reworking this a few times and thought this would resolve the issue. I am still getting two of the same numbers though. Also, the array amount will fluctuate from 8 values which I have set the array for, but then go to 9 values which I don't quite understand. Any help would be much appreciated.
function totalQuestion(){
let amountOfQuestionTotal = myObj.length // amount of question
var amountOfQuestionsNeeded = [8];// am
let numberNeeded = 8;
for(var i = 0; i < numberNeeded; i++) {
var countNumber = Math.floor(Math.random() * amountOfQuestionTotal)
var n = amountOfQuestionsNeeded.includes(countNumber)
if (countNumber != n) {
amountOfQuestionsNeeded.push(countNumber);
}
}
return amountOfQuestionsNeeded;
}
totalQuestion();
console.log(totalQuestion());
This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 4 years ago.
I have this code, where the point is to read lottery numbers, and the numbers can not be smaller than 0, nor bigger than 49, nor can they repeat themselves. I don't understand how to put that in the while loop. How can I compare each number is inserted with the numbers previously inserted?
var totoloto=new Array(1);
for(var i=0; i<1; i++) {
totoloto[i]=new Array(5);
for(var j=0; j<5; j++) {
do {
totoloto[i][j] = parseInt(readLine("totoloto="));
} while (totoloto[i][j] < 1 || totoloto[i][j] > 49);
}
print(totoloto[i].toString().replaceAll(",", " "));
}
You can use Set instead of Array and just add values into set. If you don't know, Set contains only unique values.
Another way to do this is just using object:
let obj={}
obj.value1 = true // true is just for example. It doesn't make any sense
obj.value2 = true
// After getting all the keys you can
Object.keys(obj) // it returns all the keys in objecti i.e. your values
So, adding values with the same keys has no effect, because object can have only unique keys.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am currently learning to code. I have to create an array and then create a function that prints only the even numbers from the array. Here is what I currently have. I am at a loss on what to do. I am learning from Code Highschool. It is what my class is making us use.
Instructions from codehs:
Write a function called
function onlyEvens(arr)
That takes an array and returns an array with only the even numbers in the original array.
Then, you should print out the new list.
How do I get the code to only print the even numbers that are in the array?
function start(){
var arr = [1,2,3,4,5,6];
var evens = onlyEvens(arr);
println(evens);
}
function onlyEvens(arr){
}
Simply you can use like this
start();
function start(){
var arr = [1,2,3,4,5,6];
var evens = onlyEvens(arr);
console.log(evens);
}
function onlyEvens(arr){
evenArr={};
for (var i = 0,j=0 ;i < arr.length; i++) {
if(arr[i] % 2 === 0) { //
evenArr[j] = arr[i];
j++;
}
}
return evenArr;
}
https://jsfiddle.net/n3jke25n/
The operator you're looking for is the modulus operator.
For any integer variable x, if x % 2 == 1, x is odd. On the other hand, if x % 2 == 0, x is even.
Thus, write an if statement that determines, using the modulus operator, whether the number in question is even; then, if it is, add it to the destination array.
Try using a modulo in onlyEvens whilst cycling the array
for (var i=0;i<arr.length;i++) {
if i%2==0 {
console.log("is even:"+arr[i])
}
}
Something like that, more here: https://en.wikipedia.org/wiki/Modulo_operation