313
215

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptのsomeとeveryがすごく便利

Last updated at Posted at 2018-01-29

every someがすごく便利だったのでメモ

every

everyは配列が条件をすべて満たす場合にtrueを返す

  • 間違いがありましたので修正致しました
    @syon さんありがとうございます!
every.js
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

arr.every(value => value > 0)
// return true

arr.every(value => value < 5)
// return false

ただreturnを返すだけでも大丈夫

return.js
const arr = ['hello', true, 1]

arr.every(value => {
  return value //分かりやすいようにあえてreturn
})
// return true

const arr = ['hello', true, 0 /* JSは0をfalseとみなす */]
arr.every(value => {
  return value
})
// return false

some

someは配列が条件を一つでも満たしていればtrueを返す

some.js
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

arr.some(value => value < 10)
// return true

arr.every(value => value > 11)
// return false

先ほどと同じ通り、returnを返すだけでも大丈夫

return.js
const arr = [false, null, 1]

arr.some(value => {
  return value
})
// return true

const false_arr = [false, null, 0]
arr.every(value => {
  return value
})
// return false

使い所

everyはフォーム等の必須条件とかに使えそう
someは各条件、一つでも満たせば良い所とか(コンタクトフォームとか?)

質問

ずっとfor (var i = 0; i < arr.length; i++) とか使ってたのですが map とかと比べてパフォーマンス変わるんですか?

313
215
8

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
313
215

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?