JavaScript - 获取满足条件的数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3777200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - get array element fulfilling a condition
提问by Day_Dreamer
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? Maybe something like (in other languages):
除了在 for 循环中的数组元素上运行之外,还有其他方法吗?也许类似(在其他语言中):
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. thanks
同样,我很乐意在更广泛的网站上提供建议以学习 JavaScript。谢谢
采纳答案by Tim Down
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 Networkhas a lot of good JavaScript resources.
Mozilla Developer Network有很多不错的 JavaScript 资源。
回答by Andrey Moiseev
Use ES6 Array.filter()
and arrow functionswith expression body:
将 ES6Array.filter()
和箭头函数与表达式主体结合使用:
myArray.filter(x => x > 5)
A bit more concise than @Beauty's answer.
比@Beauty 的回答简洁一点。
回答by Beauty
Here a short wayto 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 propertycondition.
这里是一个对象数组的过滤器,它检查属性条件。
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' } ]
回答by Nicolas NZ
You can use Array.prototype.find, wich does exactly what you want, returns the first element fullfilling the condition. Example:
您可以使用Array.prototype.find,这正是您想要的,返回满足条件的第一个元素。例子:
> ([4, {a:7}, 7, {a:5, k:'r'}, 8]).find(o => o.a == 5)
{a:5, k:'r'}
回答by jwueller
You can use for ... in
in JavaScript:
您可以for ... in
在 JavaScript 中使用:
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
-loop。
EDIT:You could use a JavaScript framework like jQueryto eliminate these cross-browser problems. Give it a try. Its $.each()
-methoddoes the job.
编辑:您可以使用像jQuery这样的 JavaScript 框架来消除这些跨浏览器问题。试一试。它的$.each()
-method 可以完成这项工作。
回答by Rene Saarsoo
About arrays
关于数组
What you usually want for iterating over array is the forEachmethod:
你通常想要迭代数组的是forEach方法:
arr.forEach(function(el) {
alert(el);
});
In your specific case for incrementing each element of array, I'd recommend the mapmethod:
在您增加数组的每个元素的特定情况下,我建议使用map方法:
arr = arr.map(function(t){ return t+1; });
There are also filter, reduce, and others, which too come in handy.
But like Tim Down already mentioned, these won't work by default in 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):
但是就像 Tim Down 已经提到的那样,这些默认情况下在 IE 中不起作用。但是您也可以轻松地为 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
构造用于数组 - 这是用于对象的。
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. But those references are passed around by value. Let me explain...
在 JavaScript 中,每个变量实际上都是对某个对象的引用。但是这些引用是按值传递的。让我解释...
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
. But variable h
outside the function still contains the old reference and so remains to point at 10
.
在这里,您创建一个全新的对象11
并将其引用分配给变量height
。但是h
函数外的变量仍然包含旧引用,因此仍然指向10
.
回答by hector-j-rivas
Just came across the same problem. Tim Downcame 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!
我希望能回答这个长期存在的问题!
回答by Cybernetic
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:
用法:
returnonly elements containing .logextension:
只返回包含.log扩展名的元素:
array_only(use_array, "e.includes('.log')")
[ 'gogo.log' ]
['gogo.log']
returnonly elements containing .pngextension:
只返回包含.png扩展名的元素:
array_only(use_array, "e.includes('.png')")
[ 'hello.png', 'hoho.png' ]
[ 'hello.png', 'hoho.png' ]
returnonly elements NOT containing.pngextension:
只返回不包含.png扩展名的元素:
array_only(use_array, "!e.includes('.png')")
[ 'hello', 'go_there', 'now', 'go_here', 'gogo.log' ]
['你好','go_there','现在','go_here','gogo.log']
returnelements containing setof 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
您可以轻松地通过多个条件
returnall 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']
回答by Jeferson Souza
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
这是返回布尔值