从数组一次获取三个元素 [英] Take three elements at a time from array

查看:232
本文介绍了从数组一次获取三个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由九个元素组成的数组:

I have an array composed by nine elements:

var ar = ['a','a','a','a','a','a','a','a','a'];

我需要一次通过返回true或false的函数来控制三个元素。如果第一个返回true,则不必执行其他操作即可仅获得一个真实结果。

I need to control three elements at a time by a function that returns a true or false. If the first returns true, the others do not have to execute in order to obtain just one true result.

var one = fun(ar.slice(0, 3));
if (one != false) document.write(one);

var two = fun(ar.slice(3, 6));
if (two != false) document.write(two);

var three = fun(ar.slice(6, 9));
if (three != false) document.write(three);

如何简化此过程?避免创建多数组。

How can I simplify this process? To avoid the creation of a multiarray.

谢谢!!

推荐答案

您可以使用带有切片参数的数组,并使用 Array#some

You could use an array with the slicing paramters and iterate with Array#some

function fun(array) {
    return array.reduce(function (a, b) { return a + b; }) > 10;
}

var ar = [0, 1, 2, 3, 4, 5, 6, 7, 8];

[0, 3, 6].some(function (a) {
    var result = fun(ar.slice(a, a + 3));
    if (result) {
        console.log(a, result);
        return true;
    }
});

这篇关于从数组一次获取三个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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