Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
147
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@i_am_master_yoda

JavaScriptのsomeとeveryがすごく便利

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 とかと比べてパフォーマンス変わるんですか?

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
147
Help us understand the problem. What are the problem?