我需要根据数组的长度创建一个字符串值。
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次循环后更改数字
答案 0 :(得分:3)
您可以使用列表项的索引和数组的长度来做到这一点。
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)
});
答案 1 :(得分:0)
使用新的ECMAScript对象(例如(ns another-namespace)
(defmacro def&resolve [a b]
`(do
(def ~a 12)
(def ~b (resolve '~a))))
(macroexpand-1 '(def&resolve foo bar))
#=> (do (def foo 12) (def bar (clojure.core/resolve (quote foo))))
(def&resolve foo bar)
bar
#=> #'another-namespace/foo
和arrow functions
原型方法,以及新的fill
和let
变量类型,您可以这样做:< / p>
const
编辑:我使用了let instructions = ['left', 'right', 'top', 'bottom'];
const ARRAY_LEN = 10;
const DUMMY_ELEM = 0;
let dummyArray = new Array(ARRAY_LEN).fill(DUMMY_ELEM);
dummyArray.map((element, index) => {
const AUX_INDEX = index % instructions.length;
console.log(instructions[AUX_INDEX] + Math.floor(index / instructions.length));
})
,但是您当然可以使用map
,或者根据您的具体问题,甚至可以使用Array.prototype.every方法。
答案 2 :(得分:0)
如果只需要一个值(取决于数组长度)。这可能会帮助您:
var array = ["left", "right", "top", "bottom"];
var list = [1,2,3,4,5,6,7];
var index = (list.length - 1) % array.length;
var postfix = Math.floor(list.length / array.length);
var result = array[index] + postfix;
console.log(result);
如果您需要字符串列表:
var array = ["left", "right", "top", "bottom"];
var list = [1,2,3,4,5,6,7];
var result = list.map((item, index) => array[index % array.length] + Math.floor(index / array.length));
console.log(result);