简体   繁体   English

我的循环在 Javascript 中不起作用。 我必须遍历循环到数组并乘以 2

[英]Mine loop doesn't work in Javascript. I have to traverse loop to array and multiply by 2

hey guys i have problem with my exercise: "using a while loop, traverse the array and multiply each price by 2" i have this to now嘿伙计们,我的练习有问题:“使用while循环,遍历数组并将每个价格乘以2”我现在有这个

 var prices = [10, 15, 25, 8, 4, 55, 99, 11, 15, 25, 5, 4, 65, 5, 10, 15, 7, 8, 4, 9, 100]; while (prices < 201) { console.log('This item costs', prices); prices * 2 }

I don't know where the error is?我不知道错误在哪里?

Right now you are just doing for one element.现在你只为一个元素做。 In array you have to access element with their index number.在数组中,您必须使用索引号访问元素。 The logic for doing is that you have to loop till the end of the array and for each element have to multiply the price by 2. I have attached the code below with proper logic.这样做的逻辑是,您必须循环到数组的末尾,并且每个元素必须将价格乘以 2。我在下面的代码中附上了正确的逻辑。

 var prices = [10, 15, 25, 8, 4, 55, 99, 11, 15, 25, 5, 4, 65, 5, 10, 15, 7, 8, 4, 9, 100]; var i=0; //loop to double price of each element in the array while (i < prices.length){ prices[i]=prices[i]*2; i++; } console.log(prices);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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