How to use for loop in Javascript to print 1...10 numbers without assignment

时间:2017-08-05 11:53:23

标签: javascript

I have one question, how to use for loop in javascript to print the 1...10 numbers without using assignment operator.

Usually we do for(i=1;i<=10;i++) { console.log(i); } but how we can use same without assign value in i

5 个答案:

答案 0 :(得分:2)

for loop

no assignment

for(var i of [1,2,3,4,5,6,7,8,9,10]) console.log(i);

Done

答案 1 :(得分:2)

另一种方法(在ES6中),但类似于@Nina Scholz的答案...

new Array(10).fill().forEach((e, i) => console.log(++i));

forEach()中函数的第二个参数是索引。这样,就不需要Object.keys()

说明:

  • new Array(10)创建一个包含10个空项的数组(这意味着该数组c'a̲n̲n̲o̲t̲还需要迭代)。
  • .fill()undefined填充数组(这意味着数组c̲a̲n̲现在可以迭代)。
  • .forEach((e, i) => {})遍历数组。它采用具有两个参数的函数,第一个(e)是数组的每个元素,第二个(i)是当前循环的索引。

答案 2 :(得分:1)

You could create an array, fill it, take the keys and slice it. After all display the indices.

Object.keys(Array(11).fill()).slice(1).forEach(i => console.log(i));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)

[1,2,3,4,5,6,7,8,9,10].forEach(function(i) {
  console.log(i);
});

答案 4 :(得分:0)

对于一种for循环而没有赋值运算符..?

for (var i in Array.from(Array(10))) console.log(+i+1);