javascript - 我需要根据数组的长度创建字符串值

标签 javascript angular typescript

我需要根据数组的长度创建一个字符串值。

var array = ["left", "right", "top", "bottom"];
//list contain array of Object
 list.forEach((po) => {

//for example if the length of the list is 10. i need to generate the string for each loop like this 

// "left0"   for 1 loop i need this value 
// "right0"  for 2 loop i need this value
// "top0"      for 3 loop i need this value
// "bottom0"   for 4 loop i need this value

// "left1"     for 5 loop i need this value
// "right1"   for 6 loop i need this value
// "top1"     for 7 loop i need this value
// "bottom1"     for 8 loop i need this value

// "left2"   for 1 loop i need this value 
// "right2"  for 2 loop i need this value
}

请帮我解决这个问题。我发现很难生成字符串以及最后的数字,左、右、上、下应该按顺序排列,并且数字应该在 5 个循环后发生变化,如图所示

最佳答案

您可以使用列表项的索引和数组的长度来完成此操作。

var array = ["left", "right", "top", "bottom"];

// Dummy list array
var list = new Array(10).fill(0);

list.forEach((po, i) => {
  // based on index of list calculate position in array
  // by using remainder operator
  var j = i % array.length,
    // get repetion count by simple dividing by the length
    c = Math.floor(i / array.length);
  console.log(array[j] + c)
});

关于javascript - 我需要根据数组的长度创建字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52534468/

相关文章:

javascript - Jquery回调函数每次调用都会返回一次

javascript - 在 Javascript if 语句中动态生成多个条件

php - 如何在 php if 语句中进行 JavaScript 重定向

node.js - 如何从 ionic 公开静态 html 页面

typescript - Eslint 不使用 TypeScript 语法

javascript - 当按钮名称为 "submit"时,表单提交按钮将不会提交

angular - 我有一个新项目,但是当执行 ng serve 时,我得到错误

javascript - Angular 2 Material - 路由器动画破坏了 sidenav 内容和滚动

angular - 如何取消/取消订阅 Angular 4+ 中所有待处理的 HTTP 请求

Angular 6 : Passing Observable response to another Observable