简体   繁体   English

在JavaScript中循环读取数组值

[英]Read array values in a loop in JavaScript

I have an array in JavaScript that have defined these values: 我在JavaScript中有一个已定义这些值的数组:

var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];

And when I call a function the first time function, I need to get this: 当我第一次调用函数函数时,我需要得到这个:

1
2
3

Calling it again I need to get: 再次打电话给我需要:

4
5
6

Calling it again: 再次打电话:

7
8
9

Calling it again: 再次打电话:

10
1
2

Calling again: 再次打电话:

3
4
5

And so on. 等等。 You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. 你得到了重点,显示了数组中的3个值,如果我们在数组的末尾,请从头开始阅读......我有一个具有远程控制功能的应用程序,并且具有向下和向上键。 When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values). 当用户按下向下按钮从数组中获取这些值时,如上例所示,如果用户按下向上按钮,则需要从示例返回...所以在循环中读取数组(最后,数组从头开始读取,但始终显示三个值)。

I try using this: 我尝试使用这个:

var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
    if (i<(6)) {
       console.log(myStringArray[i]);
    }
}

But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter? 但是下次我调用这段代码时,它会从数组的开头显示,而不是继续读取其他值...我需要第二个计数器吗?

If you are OK with manipulating your original array as you loop through it you could splice and concat similar to below (or you could use a clone of the array if you need to persist the original array): 如果你是操纵你的原始数组OK,你通过它循环,你可以spliceconcat类似下面(或者,如果你需要坚持原有的数组,你可以使用数组的一个克隆):

 var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var loopByX = function(x){ var y = myStringArray.splice(0,x); myStringArray = myStringArray.concat(y); return y; } console.log(loopByX(3)); console.log(loopByX(3)); console.log(loopByX(3)); console.log(loopByX(3)); console.log(loopByX(3)); 

If you want to go bi-directional (is that what you call it?), as mentioned in the comments, you could do it as below which then gives you the ability to go backwards or forward and the flexibility to do so in an arbitrary number: 如果你想要双向(就是你所说的那个?),正如评论中所提到的那样,你可以按照下面的方式进行,然后让你能够向后或向前进行,并且可以灵活地进行任意操作。数:

 var myStringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]; var loopByX = function(x) { var len = myStringArray.length; // Ensure x is always valid but you can add any behaviour here in that case yourself. As an example I return an empty array. if (Math.abs(x) > len) { return []; } var y = x > 0 ? myStringArray.splice(0, x) : myStringArray.splice(len + x, len); myStringArray = x > 0 ? myStringArray.concat(y) : y.concat(myStringArray); return y; } console.log(loopByX(20)); // invalid number console.log(loopByX(-20)); // invalid number console.log(loopByX(-3)); console.log(loopByX(-6)); console.log(loopByX(3)); console.log(loopByX(4)); 

You could take a function which slices three elements and if not possible, it takes the needed first values of the array as well. 你可以采用一个切三个元素的函数,如果不可能,它也需要数组所需的第一个值。

 function take3() { var temp = array.slice(index, index += 3) index %= array.length; console.log(temp.concat(temp.length < 3 ? array.slice(0, index) : []).join(' ')); } var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], index = 0; 
 <button onclick="take3()">take 3</button> 

With a mapping of a dynamic count. 使用动态计数的映射。

 function take(length) { console.log(Array.from({ length }, _ => array[++index, index %= array.length])); } var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], index = -1; 
 <button onclick="take(3)">take 3</button> 

Your variable i is local to the for loop which means it basically resets every time the loop is started. 你的变量ifor循环的本地变量for这意味着它每次循环启动时基本上都会重置。 So first make your variable i global. 因此,首先让你变i全球。

 var i=0; function employeeNames(){ var empList = ["1","2","3","4","5","6","7","8","9","10"]; var output = []; var j=0; while(j<3) { output.push(empList[i]) i=(i+1)%empList.length; j++; } return output; } console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); console.log(employeeNames()); 

If you want the immutable way to achieve your circular looping 如果您希望以不可变的方式实现循环循环

function loopArray(arr, step=3) {
    let i = 0;
    return function inner() {
        for (let j = 0; j < step; j++) {
            console.log(arr[i]);
            i = (i + 1) % arr.length;
        }
    };
 }

const func = loopArray(["1","2","3","4","5","6","7","8","9","10"], 3);
func();
func();
func();
func();
func();

@Igor Petev , JavaScript's closures are a nice concept that you can use to solve your problem. @Igor Petev ,JavaScript的闭包是一个很好的概念,可以用来解决你的问题。

Please read JavaScript's Closures - w3schools article. 请阅读JavaScript的闭包 - w3schools文章。 It's really nice and excellent. 它非常好,非常好。

I have used the concept of closures to solve this problem. 我已经使用闭包的概念来解决这个问题。 Please leave a comment if you don't understand my code or anything else related to this problem. 如果您不理解我的代码或与此问题相关的任何其他内容,请发表评论。

Please have a look at the below code. 请看下面的代码。

var get3items = (function () {

    var index = 0;
    var myStringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
    var len = myStringArray.length

    return function () {
       for(var count = 0; count < 3; count += 1)
       {
           console.log(myStringArray[index]);

           if(index == (len - 1))
           {
               index = 0;
           }
           else {
               index += 1;
           }
       }
    }
})();

get3items (); // First call

console.log()
get3items (); // Second call

console.log()
get3items (); // Third call

console.log()
get3items (); // Fourth call

console.log()
get3items (); // Fifth call

/*
 1
 2
 3

 4
 5
 6

 7
 8
 9

 10
 1
 2

 3
 4
 5
*/

The fancy solution with generator functions: 具有发电机功能的奇特解决方案:

function* cycle(arr) {
    let i=0;
    while (true) {
        yield arr[i++];
        i %= arr.length;
    }
}
function* chunksOf(n, iterable) {
    let chunk = [];
    for (const x of iterable) {
        chunk.push(x)
        if (chunk.length >= n) {
            yield chunk;
            chunk = [];
        }
    }
    if (chunk.length > 0)
        yield chunk;
}
function toFunction(iterator) {
    return () => iterator.next().value;
}
var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];

const f = toFunction(chunksOf(3, cycle(myStringArray)));
console.log(f());
console.log(f());
console.log(f());
// …

How about using a generator: 如何使用发电机:

function* get3() {
  var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
  var index = 0;
  while (true) {
    yield [0, 1, 2].map(i => myStringArray[(index + i) % myStringArray.length])
    index = (index + 3) % myStringArray.length;
  }
}

Calling this function returns an object which you can call .next() on, to get the next set of 3: 调用此函数会返回一个对象,您可以调用.next() ,以获取下一组3:

var getter = get3();
console.log(getter.next().value); // ["1","2","3"]
console.log(getter.next().value); // ["4","5","6"]
console.log(getter.next().value); // ["7","8","9"]
// etc.
function* employeeNames(){
    var empList =  ["1","2","3","4","5","6","7","8","9","10"];

    for(var i =0; i<=empList.length; i++){
        yield empList[i];
    }
}

var emp;
emp = employeeNames();

It uses a generator function... 它使用发电机功能......

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

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