简体   繁体   English

Javascript-根据数量变量循环遍历次数

[英]Javascript - loop through number of times based on qty variable

I have the following javascript object 我有以下javascript对象

[Object { url="http://domain.com/abc", qty="1" }, Object { url="http://myurl.com/cde", qty="2" }]

I want to be able to loop through the object and output the URL using console.log() based on the qty variable. 我希望能够遍历对象并使用基于qty变量的console.log()输出URL。

So in this instance domain.com/abc would display once & the myurl.com/cde would display twice as the qty is set to 2. 因此,在这种情况下,由于数量设置为2,domain.com / abc将显示一次,而myurl.com/cde将显示两次。

I have something like the following but needs some work.. 我有类似以下内容,但需要一些工作。

cart.forEach(function(value) {
   var qty = value.qty;
   var url = value.url;
   var i = 0;

   while ( i < qty ) {
     // logic needed here (i believe)
     i++;
   }
}

That's how one can implement String.repeat in JS: 这就是在JS中实现String.repeat的方式:

var repeatedString = Array(repeatsCount + 1).join(stringToRepeat);

... so in your case it'll be just ... ...所以就您而言...

console.log(Array(+value.qty + 1).join(value.url));

Unary plus is a shortcut for Number(value.qty) : it looks like you got a string there. 一元加号是Number(value.qty)的快捷方式:看起来您那里有一个字符串。


But it looks you actually need to collect all the urls instead. 但看起来您实际上实际上需要收集所有URL。 That's one possible way to do that: 那是做到这一点的一种可能方法:

var arrayOfUrls = [];
cart.forEach(function(value) {
   for (var i = value.qty; i--) {
     arrayOfUrls.push(value.url);
   }
});

Alternative (.reduce-based): 备选方案(基于.reduce):

var arrayOfUrls = cart.reduce(function(arr, value) {
  for (var i = value.qty; i--) {
     arr.push(value.url);
  }
  return arr;
}, []);

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

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