【发布时间】:2015-11-08 06:03:13
【问题描述】:
假设我们有一个长度为 1 到 ?? 的数组
我们有一种方法可以通过单击向上或向下导航的按钮来向上或向下导航此数组,该按钮显示在 DOM 中(想想分页)。
我们希望导航在超出下限时停止,或者在导航超出上限时停止。
当我们到达下限时,我们会通过值 -1
知道这一点当我们到达上限时,我们会通过值 ( > array.length - 1 ) 知道这一点。
我们的函数接受如图所示的参数索引
function goToChapter( index ){
// compute value of index to within bounds.
return array[ index ];
}
假设我们要做的就是使用计算范围内的索引从返回的数组中获取一个值。
示例
var array ["chapZero", "chapOne", "chapTwo", "chapThree"];
goToChapter( 2 );
=> "chapTwo;
goToChapter( 4 );
=> "chapThree"; // because four is out of upper bound so index became three.
goToChapter( -1 );
=> "chapZero"; // because -1 is our of lower bound so index became zero.
我意识到这可以用一些 if 语句来完成,我正在寻找一种使用某种数学公式的方法,也许
- 将任何负数转换为 0;
- 保留任何正数;
- 使用数组的长度来确定何时返回上限。
更新
我同意 Andand 的回答。如果您觉得这有帮助并想测试一下,我已经添加了足够多的内容,可以将解决方案复制粘贴到控制台中。
var array = [0,1,2,3,4];
function goToChapter( index, array ){
return array[(Math.min( array.length - 1, Math.max( 0, index )))];
}
goToChapter( -1, array ); => 0;
goToChapter( 3, array ); => 3;
goToChapter( 8, array ); => 4;
谢谢安达。
注意:
我也发现这很有帮助,但没有那么快。
function setWithinArrayBounds( index, array ){
return !!index ? 0 : index > ( array.length - 1 ) ? ( array.length - 1 ) : index;
}
【问题讨论】:
-
对于这样的事情,我总是在一些实用程序类中定义一个静态
clapm(min, max, value)函数。
标签: javascript arrays algorithm math