简体   繁体   English

JavaScript - 获取满足条件的数组元素

[英]JavaScript - get array element fulfilling a condition

I'm learning JavaScript using W3C and I didn't find an answer to this question.我正在使用 W3C 学习 JavaScript,但我没有找到这个问题的答案。

I'm trying to make some manipulations on array elements which fulfill some condition.我正在尝试对满足某些条件的数组元素进行一些操作。

Is there a way to do it other than running on the array elements in for loop?除了在 for 循环中的数组元素上运行之外,还有其他方法吗? Maybe something like (in other languages):也许类似(在其他语言中):

foreach (object t in tArray)
   if (t follows some condition...) t++;

another thing, sometimes I want to use the element's value and sometimes I want to use it as a reference.另一件事,有时我想使用元素的值,有时我想用它作为参考。 what is the syntactical difference?语法上的区别是什么?

As well, I'll be happy for recommendations on more extensive sites to learn JavaScript from.同样,我很乐意在更广泛的网站上提供建议以学习 JavaScript。 thanks谢谢

In most browsers (not IE <= 8) arrays have a filter method, which doesn't do quite what you want but does create you an array of elements of the original array that satisfy a certain condition:在大多数浏览器(不是 IE <= 8)中,数组有一个filter方法,它不能完全满足你的要求,但会为你创建一个满足特定条件的原始数组元素的数组:

function isGreaterThanFive(x) {
     return x > 5;
}

[1, 10, 4, 6].filter(isGreaterThanFive); // Returns [10, 6]

Mozilla Developer Network has a lot of good JavaScript resources. Mozilla Developer Network有很多不错的 JavaScript 资源。

Use ES6 Array.filter() and arrow functions with expression body:使用 ES6 Array.filter()和带有表达式主体的箭头函数

myArray.filter(x => x > 5)

A bit more concise than @Beauty's answer.比@Beauty 的回答简洁一点。

Here a short way to write a filter.这是编写过滤器的简短方法 From an array of numbers it returns all values greater than 5.它从一个数字数组中返回所有大于 5 的值。

myArray.filter((x) => { return x > 5; })

Usage example:用法示例:

var filterResult = [1, 10, 4, 6].filter((x) => { return x > 5; });
console.log(filterResult); // returns [ 10, 6 ]

And here a filter for an array of objects , which checks a property condition.这里是一个对象数组的过滤器,它检查属性条件。

myArray.filter((x) => { return x.myNumber > 5; })

Usage example:用法示例:

var myArray = [{myNumber: 1, name: 'one'}, {myNumber: 3, name: 'tree'}, {myNumber: 6, name: 'six'}, {myNumber: 8, name: 'eight'}];
var result = myArray.filter((x) => { return x.myNumber > 5; });
console.log(result); // returns [ { myNumber: 6, name: 'six' }, { myNumber: 8, name: 'eight' } ]

You can use for ... in in JavaScript:你可以在 JavaScript 中使用for ... in

for (var key in array) {
    if (/* some condition */) {
        // ...
    }
}

As of JavaScript 1.6, you can use this, too:从 JavaScript 1.6 开始,您也可以使用它:

for each (var element in array) {
    // ...
}

These are mainly meant to traverse object properties.这些主要用于遍历对象属性。 You should consider to simply use your for -loop.您应该考虑简单地使用您的for循环。

EDIT: You could use a JavaScript framework like jQuery to eliminate these cross-browser problems.编辑:您可以使用像jQuery这样的 JavaScript 框架来消除这些跨浏览器问题。 Give it a try.试一试。 Its $.each() -method does the job.它的$.each()方法可以完成这项工作。

You can use Array.prototype.find , wich does exactly what you want, returns the first element fullfilling the condition.您可以使用Array.prototype.find ,这正是您想要的,返回满足条件的第一个元素。 Example:示例:

> ([4, {a:7}, 7, {a:5, k:'r'}, 8]).find(o => o.a == 5)

{a:5, k:'r'}

About arrays关于数组

What you usually want for iterating over array is the forEach method:你通常想要遍历数组的是forEach方法:

arr.forEach(function(el) {
  alert(el);
});

In your specific case for incrementing each element of array, I'd recommend the map method:在您增加数组的每个元素的特定情况下,我建议使用map方法:

arr = arr.map(function(t){ return t+1; });

There are also filter , reduce , and others, which too come in handy.还有filterreduce等,它们也派上用场。

But like Tim Down already mentioned, these won't work by default in IE.但是就像 Tim Down 已经提到的那样,这些默认情况下在 IE 中不起作用。 But you can easily add these methods for IE too, like shown in MDC documentation, or actually you can even write simpler versions than the ones in MDC documentation (I don't know why they are so un-JavaScript-y over there):但是您也可以轻松地为 IE 添加这些方法,如 MDC 文档中所示,或者实际上您甚至可以编写比 MDC 文档中的更简单的版本(我不知道为什么它们在那里如此非 JavaScript-y):

if (!Array.prototype.forEach) {
  Array.prototype.forEach = function(func, scope) {
    for (var i = 0, len = this.length; i < len; i++) {
      func.call(scope, this[i], i, this);
    }
  };
}

But don't use the for ... in construct for arrays - this is meant for objects.但是不要for ... in数组中使用for ... in构造 - 这是用于对象的。

About references关于参考

Another thing, sometimes I want to use the element's value and sometimes I want to use it as a reference.另一件事,有时我想使用元素的值,有时我想用它作为参考。 What is the syntactical difference?语法上的区别是什么?

In JavaScript every variable is in fact a reference to some object.在 JavaScript 中,每个变量实际上都是对某个对象的引用。 But those references are passed around by value.但是这些引用是按值传递的。 Let me explain...让我解释一下...

You can pass an object to a function that modifies the object and the changes will be seen outside the function:您可以将一个对象传递给一个修改该对象的函数,而这些更改将在该函数之外被看到:

function incrementHeight(person) {
  person.height = person.height + 1;
}
var p = {height: 10);
alert(p.height); // outputs: 10
incrementHeight(p);
alert(p.height); // outputs: 11

Here you modify the value to which the person reference points to and so the change will be reflected outside the function.在此修改person引用所指向的值,因此更改将反映在函数之外。

But something like this fails:但是这样的事情失败了:

function incrementHeight(height) {
  height = height + 1;
}
var h = 10;
alert(h); // outputs: 10
incrementHeight(h);
alert(h); // outputs: 10

Here you create a completely new object 11 and assign its reference to variable height .在这里,您创建了一个全新的对象11并将其引用分配给变量height But variable h outside the function still contains the old reference and so remains to point at 10 .但是函数外的变量h仍然包含旧引用,因此仍然指向10

Write a generic function that accepts various conditions :编写一个接受各种条件的通用函数:

function array_only(arr, condition) {
    hold_test=[]
    arr.map(function(e, i) {if(eval(condition)){hold_test.push(e)}})
    return(hold_test)
    }

Example:示例:

use_array = ['hello', 'go_there', 'now', 'go_here', 'hello.png', 'gogo.log', 'hoho.png']

Usage :用法

return only elements containing .log extension:返回包含.log扩展名的元素:

array_only(use_array, "e.includes('.log')")

[ 'gogo.log' ] ['gogo.log']

return only elements containing .png extension:返回包含.png扩展名的元素:

array_only(use_array, "e.includes('.png')")

[ 'hello.png', 'hoho.png' ] [ 'hello.png', 'hoho.png' ]

return only elements NOT containing .png extension:返回不包含.png扩展名的元素:

array_only(use_array, "!e.includes('.png')")

[ 'hello', 'go_there', 'now', 'go_here', 'gogo.log' ] ['你好','go_there','现在','go_here','gogo.log']

return elements containing set of extensions and prefixes:返回包含一组扩展和前缀的元素:

array_only(use_array, "['go_', '.png', '.log'].some(el => e.includes(el))")

[ 'go_there', 'go_here', 'hello.png', 'gogo.log', 'hoho.png' ] ['go_there'、'go_here'、'hello.png'、'gogo.log'、'hoho.png']

You can easily pass MULTIPLE CONDITIONS您可以轻松地通过多个条件

return all png files that are less than 9 characters long:返回所有长度小于 9 个字符的 png 文件:

array_only(use_array, "e.includes('.png') && e.length<9")

[ 'hoho.png' ] ['hoho.png']

Just came across the same problem.刚刚遇到同样的问题。 Tim Down came close, he just needed a wrapper to the length of the filtered array: Tim Down接近了,他只需要一个包装到过滤数组的长度:

// count elements fulfilling a condition
Array.prototype.count = function (f) {
  return this.filter(f).length;  
};

Usage:用法:

// get the answer weight from the question's values array
var w = Math.pow(q.values.count(function(v) { return v !== -1; }), -1);

I hope that answers this long standing question!我希望能回答这个长期存在的问题!

Problem:问题:

I need to know if a client set exists for any PJ client.我需要知道是否存在任何 PJ 客户端的客户端集。

Solution:解决方法:

function deveExibirLista(lst: Clientes[]){
    return lst.some(cli => cli.Documento === 14);
}

It's return boolean这是返回布尔值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM