JS_includes() ์ •๋ฆฌ

jjyu_myยท2025๋…„ 2์›” 6์ผ
0

JAVASCRIPT

๋ชฉ๋ก ๋ณด๊ธฐ
11/15
post-thumbnail

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป indexOf() ๋งŒ ์•Œ๊ณ ์žˆ๋‹ค๊ฐ€ .includes()๋ฅผ ์ƒˆ๋กœ ์•Œ๊ฒŒ๋˜์—ˆ๋‹ค...
๋‚˜๋งŒ ์ง€๊ธˆ ์•Œ๊ฒŒ๋œ๊ฑฐ๋ƒ๊ตฌ...ใ…Žใ…Žใ…Ž ์•Œ๋ฉด ์•Œ์ˆ˜๋ก ์ƒˆ๋กœ์šด๊ฑฐ ํˆฌ์„ฑ์ด๋‹ค!!!


1๏ธโƒฃ ๋ฐฐ์—ด์—์„œ .includes()

โœ” ๋ฐฐ์—ด์— ํŠน์ • ์š”์†Œ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•  ๋•Œ ์‚ฌ์šฉ

const fruits = ["์‚ฌ๊ณผ", "๋ฐ”๋‚˜๋‚˜", "ํฌ๋„"];

console.log(fruits.includes("๋ฐ”๋‚˜๋‚˜")); // true
console.log(fruits.includes("๋ณต์ˆญ์•„")); // false

โœ… ๋Œ€์†Œ๋ฌธ์ž๋ฅผ ๊ตฌ๋ถ„ํ•˜์ง€ ์•Š๋Š”๋‹ค
โœ… true ๋˜๋Š” false๋ฅผ ๋ฐ˜ํ™˜
โœ… ES6(ECMAScript 2016)๋ถ€ํ„ฐ ์‚ฌ์šฉ ๊ฐ€๋Šฅ


2๏ธโƒฃ ๋ฌธ์ž์—ด์—์„œ .includes()

โœ” ๋ฌธ์ž์—ด ์•ˆ์— ํŠน์ • ๋‹จ์–ด๊ฐ€ ํฌํ•จ๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธํ•  ๋•Œ ์‚ฌ์šฉ

const text = "JavaScript๋Š” ์žฌ๋ฏธ์žˆ๋‹ค.";

console.log(text.includes("JavaScript")); // true
console.log(text.includes("Python")); // false

โœ… ๋Œ€์†Œ๋ฌธ์ž๋ฅผ ๊ตฌ๋ถ„ํ•œ๋‹ค ("Hello"์™€ "hello"๋Š” ๋‹ค๋ฅด๊ฒŒ ์ธ์‹๋จ)
โœ… ๊ณต๋ฐฑ๋„ ํฌํ•จํ•ด์„œ ์ฐพ๋Š”๋‹ค
โœ… indexOf()๋ณด๋‹ค ๊ฐ€๋…์„ฑ์ด ์ข‹๋‹ค


3๏ธโƒฃ ๋‘ ๋ฒˆ์งธ ๋งค๊ฐœ๋ณ€์ˆ˜ (๊ฒ€์ƒ‰ ์‹œ์ž‘ ์œ„์น˜)

โœ” .includes(value, startIndex) ํ˜•์‹์œผ๋กœ ํŠน์ • ์œ„์น˜๋ถ€ํ„ฐ ๊ฒ€์ƒ‰ํ•  ์ˆ˜ ์žˆ๋‹ค

const numbers = [10, 20, 30, 40, 50];

console.log(numbers.includes(20, 2)); // false (2๋ฒˆ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์ฐพ์Œ)
console.log(numbers.includes(30, 2)); // true

4๏ธโƒฃ .includes() vs .indexOf()

๋ฉ”์„œ๋“œ๋ฐ˜ํ™˜๊ฐ’์‚ฌ์šฉ๋ฒ•
.includes()true ๋˜๋Š” falsearr.includes(value)
.indexOf()์ฐพ์œผ๋ฉด ์ธ๋ฑ์Šค ๋ฒˆํ˜ธ, ์—†์œผ๋ฉด -1arr.indexOf(value) !== -1

๐Ÿ’ก ์กด์žฌ ์—ฌ๋ถ€๋งŒ ํ™•์ธํ•  ๋• .includes()๊ฐ€ ๋” ์ง๊ด€์ 


5๏ธโƒฃ ํ™œ์šฉ ์˜ˆ์‹œ

โœ” ๋ฐฐ์—ด์—์„œ ์ค‘๋ณต ๊ฐ’ ์ฒดํฌ

const selectedColors = ["red", "yellow", "green"];
const newColor = "blue";

if (!selectedColors.includes(newColor)) {
  selectedColors.push(newColor);
}

console.log(selectedColors); // ["red", "yellow", "green", "blue"]

โœ” ๊ฒ€์ƒ‰ ๊ธฐ๋Šฅ ๊ตฌํ˜„

const products = ["์•„์ดํฐ", "๊ฐค๋Ÿญ์‹œ", "๋งฅ๋ถ", "์•„์ดํŒจ๋“œ"];

const search = "์•„์ดํฐ";
console.log(products.some((p) => p.includes(search))); // true

๐Ÿ”น ์ •๋ฆฌ

โœ” .includes()๋Š” ๋ฐฐ์—ด๊ณผ ๋ฌธ์ž์—ด์—์„œ ํŠน์ • ๊ฐ’์ด ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ฉ”์„œ๋“œ
โœ” true ๋˜๋Š” false๋ฅผ ๋ฐ˜ํ™˜ํ•ด ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์กฐ๊ฑด๋ฌธ์—์„œ ํ™œ์šฉ๊ฐ€๋Šฅ
โœ” ๊ฒ€์ƒ‰, ์ค‘๋ณต ์ฒดํฌ, ํ•„ํ„ฐ๋ง ๋“ฑ์— ์œ ์šฉ


profile

0๊ฐœ์˜ ๋Œ“๊ธ€