【问题标题】:If index is out of bounds of array, set index to closest boundary如果索引超出数组范围,则将索引设置为最近的边界
【发布时间】: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 语句来完成,我正在寻找一种使用某种数学公式的方法,也许

  1. 将任何负数转换为 0;
  2. 保留任何正数;
  3. 使用数组的长度来确定何时返回上限。

更新

我同意 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


【解决方案1】:

这称为钳位值以将其限制在指定范围内。

您可以使用min()max(),例如:

function goToChapter(array, index ){
    myIndex = Math.min(array.length-1, Math.max(0, index));
    return array[ myIndex ];
}

另一种方法是使用嵌套三元运算符,例如

function goToChapter(array, index ){
    myIndex = index < 0 
        ? 0
        : index >= array.length
            ? array.length - 1
            : index;
    return array[ myIndex ];
}

您也可以使用if 语句,如

function goToChapter(array, index ){
    if (index < 0) {
        myIndex = 0;
    } else if (index >= array.length) {
        myIndex = array.length-1;
    } else {
        myIndex = index;
    }

    return array[ myIndex ];
}

或者使用连续的if 语句的变体可能是

function goToChapter(array, index ){
    myIndex = index;

    if (myIndex < 0) {
        myIndex = 0;
    }

    if (myIndex >= array.length) {
        myIndex = array.length-1;
    }

    return array[ myIndex ];
}

【讨论】:

  • 我喜欢这个,你能不能把 myArray 改成数组,包括 Math.在您的最小值和最大值中,以及包含实际数组和返回值。这样,有人可以将您的答案复制粘贴到控制台中并进行测试;我会接受你的回答。
猜你喜欢
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多