Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

_.slice(array, [start=0], [end=array.length]) #1

Open
JCHappytime opened this issue Feb 23, 2021 · 0 comments
Open

_.slice(array, [start=0], [end=array.length]) #1

JCHappytime opened this issue Feb 23, 2021 · 0 comments
Labels
数组 数组相关的操作

Comments

@JCHappytime
Copy link
Owner

JCHappytime commented Feb 23, 2021

1. 作用及使用

裁剪数组array,从start位置开始到end结束,但不包括end本身的位置。也就是左闭右开的形式。
这个方法可以替代数组本身的Array.slice()方法来确保数组正确返回。
【参数】

  1. array: 要裁剪的数组
  2. start=0: 开始位置
  3. end=array.length: 结束位置

2. 示例

  1. start和end都传
    slice

  2. start和end都不传
    slice

  3. 只传start

slice-2

3. 源码分析

源码:
function slice(array, start, end) {
  let length = array == null ? 0 : array.length;
  if (!length) {
    return [];
  }
  start = start == null ? 0 : start;    // 边界值设定
  end = end === undefined ? length : end;   // 边界值设定

  if (start < 0) {
    start = -start > length ? 0 : length + start;
  }
  end = end > length ? length : end;
  if (end < 0) {
    end += length;
  }
  length = start > end ? 0 : (end - start) >>> 0;   
  // 这里的>>>表示向右移位,>>>0的意思是无符号移位,该操作符会将第一个操作数向右移动指定的位数。向右被移出的位被 
 // 丢弃,左侧用0填充。因为符号位变成了0,所以结果总是非负的。
  start >>>= 0;

  let index = -1;
  const result = new Array(length);
  while (++index < length) {
    result[index] = array[index + start];
    // 当index + 1的值小于数组长度时,result数组的index位置的值被赋值为array的[index+start位置的值]
  }
  return result;
}
@JCHappytime JCHappytime added the 数组 数组相关的操作 label Feb 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
数组 数组相关的操作
Projects
None yet
Development

No branches or pull requests

1 participant