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

时间:2010-09-23 09:58:06

标签: javascript arrays conditional-statements

我正在使用W3C学习JavaScript,但我找不到这个问题的答案。

我正在尝试对满足某些条件的数组元素进行一些操作。

除了在for循环中运行数组元素之外,还有办法吗? 也许像(在其他语言中):

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

另一件事,有时我想使用元素的值,有时我想用它作为参考。什么是语法上的区别?

同样,我会很高兴在更广泛的网站上推荐学习JavaScript。 感谢

9 个答案:

答案 0 :(得分:29)

在大多数浏览器中(不是IE< = 8),数组都有一个filter方法,它不能满足您的需求但会创建一个满足特定条件的原始数组元素数组:

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

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

Mozilla Developer Network有很多优秀的JavaScript资源。

答案 1 :(得分:8)

将ES6 Array.filter()arrow functions与表达式主体一起使用:

result

比@Beauty的回答更简洁。

答案 2 :(得分:6)

这里有一个简短的方法来编写过滤器。 从一组数字中返回所有大于5的值。

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

用法示例:

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

此处是对象数组的过滤器,用于检查属性条件。

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

用法示例:

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' } ]

答案 3 :(得分:3)

您可以在JavaScript中使用for ... in

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

从JavaScript 1.6开始,您也可以使用它:

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

这些主要用于遍历对象属性。您应该考虑简单地使用for - 循环。

编辑:您可以使用jQuery等JavaScript框架来消除这些跨浏览器问题。试试看。它$.each()-method完成了这项工作。

答案 4 :(得分:1)

关于数组

您通常想要迭代数组的是forEach方法:

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

在您递增数组的每个元素的特定情况下,我建议使用map方法:

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

还有filterreduce和其他内容,它们也派上用场。

但是就像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);
    }
  };
}

但是不要对数组使用for ... in构造 - 这适用于对象。

关于参考文献

  

另一件事,有时我想使用元素的值,有时我想用它作为参考。什么是语法差异?

在JavaScript中,每个变量实际上都是对某个对象的引用。但是那些引用是按值传递的。让我解释一下......

您可以将对象传递给修改对象的函数,并且可以在函数外部看到更改:

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

在此修改person引用指向的值,因此更改将反映在函数外部。

但是这样的事情失败了:

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

在这里,您可以创建一个全新的对象11,并将其引用分配给变量height。但是函数外部的变量h仍包含旧引用,因此仍需指向10

答案 5 :(得分:1)

您可以使用Array.prototype.find,它可以完全按照您的意愿运行,返回满足条件的第一个元素。 例如:

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

{a:5, k:'r'}

答案 6 :(得分:0)

刚遇到同样的问题。 Tim Down接近,他只需要一个包装过滤器阵列的长度:

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

用法:

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

我希望能回答这个长期存在的问题!

答案 7 :(得分:0)

编写接受各种条件的通用函数

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

示例:

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

用法

仅返回包含 .log 扩展名

的元素
array_only(use_array, "e.includes('.log')")

['gogo.log']

仅返回包含 .png 扩展名的元素:

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

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

仅返回元素不包含 .png 扩展名:

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

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

返回元素包含 set 的扩展名和前缀:

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

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

您可以轻松传递多个条件

返回所有长度小于9个字符的png文件:

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

['hoho.png']

答案 8 :(得分:0)

问题:

我需要知道任何PJ客户端是否存在客户端集。

解决方案:

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

返回布尔值

相关问题