javascript中有没有一种方法可以做与rust中的windows相同的事情?

我想在js中迭代一个数组,每次比较2个值,就像在rust中使用windows()一样,但不确定是否有方法可以实现这一点.

有人知道一种方法或类似的方法来重建它吗?

windows()示例:

let slice = ['r', 'u', 's', 't'];
let mut iter = slice.windows(2);
assert_eq!(iter.next().unwrap(), &['r', 'u']);
assert_eq!(iter.next().unwrap(), &['u', 's']);
assert_eq!(iter.next().unwrap(), &['s', 't']);
assert!(iter.next().is_none());

推荐答案

generator函数非常适合于此

function* windows(array, count=1) {
  if (typeof count !== 'number') {
    throw new Error("paramater must be a number");
  }
  let index = 0;
  while(index < array.length - count + 1) {
    yield array.slice(index, index+count);
    index++;
  }
}
const x = windows(['r', 'u', 's', 't'], 2);
[...x].forEach(v=>console.log(v))

此外,如果您不反对向内置类型添加方法

你可以这样做

Array.prototype.windows = function*(count) {
  if (typeof count !== 'number') {
    throw new Error("paramater must be a number");
  }
  let index = 0;
  while(index < this.length - count + 1) {
    yield this.slice(index, index+count);
    index++;
  }
}
const array = ['r', 'u', 's', 't'];
[...array.windows(2)].forEach(v=>console.log(v))

这样,所有数组的just都有windows方法

此外...下面是一些简单的代码,部分模仿了问题中的代码

Array.prototype.windows = function*(count) {
  if (typeof count !== 'number') {
    throw new Error("paramater must be a number");
  }
  let index = 0;
  while(index < this.length - count + 1) {
    yield this.slice(index, index+count);
    index++;
  }
}
const assert_eq = (a, b) => {
  a = a.toString();
  b = b.toString();
  if (a !== b) {
    throw "fail";
  }
  console.log('ok');
};

const slice = ['r', 'u', 's', 't'];
const iter = slice.windows(2);
assert_eq(iter.next().value, ['r', 'u']);
assert_eq(iter.next().value, ['u', 's']);
assert_eq(iter.next().value, ['s', 't']);
assert_eq(iter.next().done, true);

额外提示:如果你想实现"块"

while(index < this.length) {
    yield this.slice(index, index+count);
    index+=count;
}

Javascript相关问答推荐

如何在不指定宽度和高度的情况下显示来自网址的下一张图像

React redux状态未在React-Router库中呈现

我不明白这个react 组件有什么问题

强制执行useStatego struct 化变量[foo,setFoo]的命名约定?

使用typeof运算符获取对象值类型-接收字符串而不是数组

我试图实现用户验证的reduxstore 和操作中出了什么问题?

我可以使用CSS有效地实现最大宽度=100%和最大高度=100%,而无需父母有明确的/固定的宽度和高度,替代方法吗?

Google maps API通过API返回ZERO_RESULTS,以获得方向请求,但适用于Google maps

构造HTML表单以使用表单数据创建对象数组

如何从网站www.example.com获取表与Cheerio谷歌应用程序脚本

Reaction Native中的范围滑块

material UI按钮组样式props 不反射

Eval vs函数()返回语义

如何在DYGRAPS中更改鼠标事件和键盘输入

未捕获的运行时错误:调度程序为空

我想使用GAS和HTML将从Electron 表格中获得的信息插入到文本字段的初始值中

为什么延迟在我的laravel项目中不起作用?

Phaser3 preFX addGlow不支持zoom

如何在脚本编译后直接将RxJ模块导入浏览器(无需Angel、webpack、LiteServer)

本地损坏的Java脚本