JavaScript Glossary: Array.some()

Publikováno: 8.2.2019

Basics

This method checks if any of the elements contained in an array passes a set test. If at least one of the elements passes this test, true is returned. This method only ...

Celý článek

Basics

This method checks if any of the elements contained in an array passes a set test. If at least one of the elements passes this test, true is returned. This method only returns a Boolean.

const result = [10,20,30,40,3].some(function(number){
    return number < 10
})

https://scotch.io/embed/gist/e3954f8bd1a7e85f44385388b19ce94b

The some() method:

  • Takes a callback function that is called once for each element.
  • Runs each element against the set test.
  • Returns true if any of the elements pass the test and false if none of them do.

Syntax

const result = array.some(callback(element[, index[, array]])[, thisArg])

2 Parameters

callback (function, required) The function that executes each of the elements of the array. The callback function is required and can take three parameters:

  • element: this is the element currently being executed - required.
  • index: the index of the current item - optional.
  • array: the array that is currently being processed - optional.

thisArg This is an argument passed to be used as the this value in the callback - optional

Returns a Boolean

A boolean value of true or false is returned once the test is passed or failed respectively.

// create a string
const names = ['John', 'Peter', 'Mary'];
const firstName = 'John'

const hasMyName = names.some(name => name === firstName);
//Output: 'John'

Common Uses and Snippets

Verify the content of objects in an array

Used when checking if any elements within an array matches a test.

https://scotch.io/embed/gist/3064ddddef4aaf5ae9dbf0a171157ce9

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace