如何在Array方法(例如filter)中使用break语句? [英] How to use break statement in an Array method such as filter?

查看:411
本文介绍了如何在Array方法(例如filter)中使用break语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决所需的算法挑战;

I was trying to solve an algorithm challenge which required;



开头开始,放下数组的元素(第一个参数),直到谓词(第二个参数)返回

Drop the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true.

第二个参数func是用于测试数组的前
个元素以决定是否应将其删除或删除的函数。

The second argument, func, is a function you'll use to test the first elements of the array to decide if you should drop it or not.

返回其余数组,否则返回空数组。

Return the rest of the array, otherwise return an empty array.

尽管我能够通过循环数组提出一个冗长的解决方案,但我想知道是否有一种方法可以在方法内部实现break语句。

Though I have been able to come up with a lengthy solution to this through looping the array I was wondering if there is a way to implement the break statement inside the methods.

是否可以通过重新定义Array.prototype.filter方法来接受break语句来完成?

Could it be accomplish by redefining the Array.prototype.filter method to accept a break statement ?

尽管该解决方案本来很容易,但JavaScript中的数组方法不接受这种方法。您如何绕过呢?

Though the solution could have been easy as such the methods of arrays in JavaScript doesn't accept this. How do you bypass that?

function dropElements(arr, func) {
  return arr.filter(func);
}


推荐答案

您可以只使用 for 循环,当函数返回true时,您可以中断循环并从该索引返回结果。

You can just use for loop and when function returns true you can just break loop and return results from that index.

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

function drop(data, func) {
  var result = [];
  for (var i = 0; i < data.length; i++) {
    var check = func(data[i]);
    if (check) {
      result = data.slice(i);
      break;
    }
  }
  return result;
}

var result = drop(arr, e => e == 4)

console.log(result)

您还可以使用 findIndex(),如果找到匹配项,则可以从该索引中切片数组,否则返回空

You can also use findIndex() and if match is found you can slice array from that index otherwise return empty array.

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

var index = arr.findIndex(e => e == 4)
var result = index != -1 ? arr.slice(index) : []

console.log(result)

这篇关于如何在Array方法(例如filter)中使用break语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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