Javascript

[javascript] ๋ฌธ์ž์—ด์—์„œ ํŠน์ • ๋ฌธ์ž ์œ„์น˜ ์ฐพ๊ธฐ indexOf / includes / findIndex

ddon 2021. 6. 8. 00:27
str.indexOf(searchValue[, fromIndex])

searchValue : ์ฐพ์œผ๋ ค๋Š” ๋ฌธ์ž์—ด

fromIndex(Optional) : ๋ฌธ์ž์—ด์—์„œ ์ฐพ๊ธฐ ์‹œ์ž‘ํ•˜๋Š” ์œ„์น˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ธ๋ฑ์Šค ๊ฐ’

const str = 'Hello, world!';
const arr = [0, 1, 2, 3, 4, 5];

// indexOf(์ฐพ์„ ๋ฌธ์ž, n๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์ฐพ๊ธฐ) : ์œ„์น˜ ์ƒ๋žต ๊ฐ€๋Šฅ

str.indexOf('lo')	// 3	(3๋ฒˆ์งธ ์ธ๋ฑ์Šค์— ์žˆ์Œ)
str.indexOf('d!')	// 11	(11๋ฒˆ์งธ ์ธ๋ฑ์Šค์— ์žˆ์Œ)
str.indexOf('d~')	// -1	(์—†์Œ : -1 ๋ฐ˜ํ™˜)
str.indexOf('l', 3)	// 3	(3๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์ฐพ์•„์„œ 3๋ฒˆ์งธ ์ธ๋ฑ์Šค ๋ฐ˜ํ™˜)
str.indexOf('l', 4) 	// 10	(4๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์ฐพ์•„์„œ 10๋ฒˆ์งธ ์ธ๋ฑ์Šค ๋ฐ˜ํ™˜)

arr.indexOf(3)		// 3
arr.indexOf('3')	// -1

 

 

arr.includes(valueToFind[, fromIndex])

valueToFind : ํƒ์ƒ‰ํ•  ์š”์†Œ

fromIndex(Optional) : ๋ฐฐ์—ด์—์„œ ๊ฒ€์ƒ‰์„ ์‹œ์ž‘ํ•  ์œ„์น˜

const arr2 = [1, 2, 3, 'a', 'b', 'c'];

arr2.includes(2);	// true
arr2.includes(2, 1);	// true
arr2.includes(2, 2);	// false
arr2.includes('b');	// true

* includes๋Š” IE์™€ ํ˜ธํ™˜๋˜์ง€ ์•Š๋Š”๋‹ค.

 

 

arr.findIndex(callback(element[, index[, array]])[, thisArg])

element : ๋ฐฐ์—ด์—์„œ ์ฒ˜๋ฆฌ์ค‘์ธ ํ˜„์žฌ ์š”์†Œ

index : ๋ฐฐ์—ด์—์„œ ์ฒ˜๋ฆฌ์ค‘์ธ ํ˜„์žฌ ์š”์†Œ์˜ ์ธ๋ฑ์Šค

array : findIndex ํ•จ์ˆ˜๊ฐ€ ํ˜ธ์ถœ๋œ ๋ฐฐ์—ด

const arr3 = [{num:0, str:'a'}, {num:1, str:'b'}, {num:2, str:'c'}];

arr3.findIndex(ele => ele.str === 'b')	// 1