如何移动到数组的preV /下一个元素 [英] How to move to prev/next element of an array

查看:127
本文介绍了如何移动到数组的preV /下一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们有一个整数列表:

  VAR斐波纳契= [1,1,2,35,8,13,21];

我希望能够获得下一个和previous元素(只是移动元素的指针,而不修改数组)以下列方式(例如,可以去没有原型重新定义阵列接口,但为什么不)

 斐波纳契preV()。 //返回false
fibonacci.next(); //返回1
fibonacci.next(); //返回1
fibonacci.next(); //返回2
fibonacci.next(); //返回3
fibonacci.next(); //返回5
fibonacci.next(); //返回8斐波纳契preV()。 //返回5fibonacci.next(); //返回8
fibonacci.next(); //返回13
fibonacci.next(); //返回false


解决方案

如果你想保持列表作为阵列,你就必须改变其 [原型]] ,使它看起来像一个迭代系列:

  Array.prototype.next =功能(){
    返回此[++ this.current]
};
Array.prototype。preV =功能(){
    返回此[ - this.current]
};
Array.prototype.current = 0;

现在每个阵列将有方法 $ P $光伏接下来电流属性,它指向当前的元素。一个警告:在电流属性可以被修改,从而导致IM predictable结果

邮政scriptum:我不建议做 $ P $光伏接下来收益当指数超出范围。如果你真的想,你可以改变的方法是这样的:

  Array.prototype.next =功能(){
    如果返回false(((this.current +在这1))!);
    返回此[++ this.current]
};

Let's say we have a list of integers:

var fibonacci = [1,1,2,3,5,8,13,21];

I want to be able to get the next and previous element (just to move the element pointer, without modifying the array) in following manner (example, might go without prototype to redefine the Array interface but why not):

fibonacci.prev(); // returns false
fibonacci.next(); // returns 1
fibonacci.next(); // returns 1
fibonacci.next(); // returns 2
fibonacci.next(); // returns 3
fibonacci.next(); // returns 5
fibonacci.next(); // returns 8

fibonacci.prev(); // returns 5

fibonacci.next(); // returns 8
fibonacci.next(); // returns 13
fibonacci.next(); // returns false

解决方案

If you want to keep the list as an Array, you'll have to change its [[prototype]] to make it look like an iterable collection:

Array.prototype.next = function() {
    return this[++this.current];
};
Array.prototype.prev = function() {
    return this[--this.current];
};
Array.prototype.current = 0;

Now every Array will have the methods prev and next, and the current property, which points to the "current" elements. A caveat: the current property can be modified, thus leading to impredictable results.

Post scriptum: I don't recommend to make prev and next return false when the index is out of range. If you really want to, you can change the methods to something like:

Array.prototype.next = function() {
    if (!((this.current + 1) in this)) return false;
    return this[++this.current];
};

这篇关于如何移动到数组的preV /下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆