JavaScript - get array element fulfilling a condit

2020-02-17 08:56发布

I'm learning JavaScript using W3C and I didn't find an answer to this question.

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):

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

9条回答
放我归山
2楼-- · 2020-02-17 09:12

Use ES6 Array.filter() and arrow functions with expression body:

myArray.filter(x => x > 5)

A bit more concise than @Beauty's answer.

查看更多
劫难
3楼-- · 2020-02-17 09:14

Problem:

I need to know if a client set exists for any PJ client.

Solution:

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

It's return boolean

查看更多
我只想做你的唯一
4楼-- · 2020-02-17 09:20

Here a short way to write a filter. From an array of numbers it returns all values greater than 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' } ]
查看更多
孤傲高冷的网名
5楼-- · 2020-02-17 09:20

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:

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

[ 'gogo.log' ]

return only elements containing .png extension:

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

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

return only elements NOT containing .png extension:

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

[ 'hello', 'go_there', 'now', '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' ]

You can easily pass MULTIPLE CONDITIONS

return all png files that are less than 9 characters long:

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

[ 'hoho.png' ]

查看更多
▲ chillily
6楼-- · 2020-02-17 09:23

You can use for ... in in JavaScript:

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

As of JavaScript 1.6, you can use this, too:

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

These are mainly meant to traverse object properties. You should consider to simply use your for-loop.

EDIT: You could use a JavaScript framework like jQuery to eliminate these cross-browser problems. Give it a try. Its $.each()-method does the job.

查看更多
Root(大扎)
7楼-- · 2020-02-17 09:29

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:

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.

查看更多
登录 后发表回答