From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- files/ko/web/javascript/about/index.html | 58 ++ files/ko/web/javascript/data_structures/index.html | 221 +++++ .../index.html | 63 ++ .../index.html | 331 ++++++++ .../equality_comparisons_and_sameness/index.html | 503 +++++++++++ files/ko/web/javascript/eventloop/index.html | 147 ++++ files/ko/web/javascript/guide/closures/index.html | 454 ++++++++++ .../control_flow_and_error_handling/index.html | 433 ++++++++++ .../guide/expressions_and_operators/index.html | 926 +++++++++++++++++++++ files/ko/web/javascript/guide/index.html | 138 +++ .../guide/indexed_collections/index.html | 456 ++++++++++ .../inheritance_and_the_prototype_chain/index.html | 531 ++++++++++++ .../guide/iterators_and_generators/index.html | 193 +++++ .../javascript/guide/keyed_collections/index.html | 149 ++++ .../guide/loops_and_iteration/index.html | 332 ++++++++ files/ko/web/javascript/guide/modules/index.html | 414 +++++++++ .../javascript/guide/numbers_and_dates/index.html | 384 +++++++++ .../core_javascript_1.5_guide/about/index.html | 109 +++ .../index.html | 26 + .../core_javascript_1.5_guide/constants/index.html | 28 + .../creating_a_regular_expression/index.html | 35 + .../defining_getters_and_setters/index.html | 84 ++ .../defining_methods/index.html | 43 + .../index.html | 11 + .../deleting_properties/index.html | 20 + .../creating_new_objects/index.html | 6 + .../indexing_object_properties/index.html | 9 + .../using_a_constructor_function/index.html | 58 ++ .../using_this_for_object_references/index.html | 25 + .../expressions/index.html | 16 + .../javascript_overview/index.html | 44 + .../core_javascript_1.5_guide/literals/index.html | 174 ++++ .../objects_and_properties/index.html | 39 + .../operators/arithmetic_operators/index.html | 44 + .../operators/assignment_operators/index.html | 62 ++ .../operators/bitwise_operators/index.html | 101 +++ .../core_javascript_1.5_guide/operators/index.html | 108 +++ .../operators/logical_operators/index.html | 68 ++ .../operators/special_operators/index.html | 228 +++++ .../operators/string_operators/index.html | 11 + .../array_object/index.html | 133 +++ .../predefined_core_objects/index.html | 20 + .../core_javascript_1.5_guide/unicode/index.html | 109 +++ .../core_javascript_1.5_guide/values/index.html | 39 + .../core_javascript_1.5_guide/variables/index.html | 64 ++ .../javascript/guide/text_formatting/index.html | 275 ++++++ .../web/javascript/guide/using_promises/index.html | 361 ++++++++ .../values,_variables,_and_literals/index.html | 708 ++++++++++++++++ .../guide/working_with_objects/index.html | 500 +++++++++++ .../index.html" | 714 ++++++++++++++++ .../index.html" | 258 ++++++ .../guide/\354\206\214\352\260\234/index.html" | 153 ++++ .../assertions/index.html" | 244 ++++++ .../groups_and_ranges/index.html" | 91 ++ .../index.html" | 666 +++++++++++++++ .../guide/\355\225\250\354\210\230/index.html" | 658 +++++++++++++++ files/ko/web/javascript/index.html | 118 +++ .../index.html | 289 +++++++ .../javascript_technologies_overview/index.html | 83 ++ .../ko/web/javascript/memory_management/index.html | 183 ++++ .../javascript/new_in_javascript/1.5/index.html | 37 + .../javascript/new_in_javascript/1.6/index.html | 85 ++ .../javascript/new_in_javascript/1.8.1/index.html | 26 + .../javascript/new_in_javascript/1.8.5/index.html | 126 +++ .../javascript/new_in_javascript/1.8/index.html | 138 +++ .../ecmascript_5_support_in_mozilla/index.html | 45 + .../ecmascript_6_support_in_mozilla/index.html | 285 +++++++ .../ko/web/javascript/new_in_javascript/index.html | 71 ++ files/ko/web/javascript/reference/about/index.html | 51 ++ .../reference/classes/class_fields/index.html | 396 +++++++++ .../reference/classes/constructor/index.html | 128 +++ .../reference/classes/extends/index.html | 112 +++ .../ko/web/javascript/reference/classes/index.html | 402 +++++++++ .../classes/private_class_fields/index.html | 201 +++++ .../javascript/reference/classes/static/index.html | 136 +++ .../deprecated_and_obsolete_features/index.html | 290 +++++++ .../reference/errors/bad_octal/index.html | 45 + .../reference/errors/bad_radix/index.html | 57 ++ .../reference/errors/bad_regexp_flag/index.html | 107 +++ .../errors/bad_return_or_yield/index.html | 51 ++ .../index.html | 56 ++ .../errors/delete_in_strict_mode/index.html | 71 ++ .../index.html | 70 ++ .../reference/errors/deprecated_octal/index.html | 64 ++ .../errors/identifier_after_number/index.html | 57 ++ .../reference/errors/illegal_character/index.html | 81 ++ .../ko/web/javascript/reference/errors/index.html | 12 + .../errors/invalid_array_length/index.html | 73 ++ .../invalid_assignment_left-hand_side/index.html | 50 ++ .../reference/errors/invalid_date/index.html | 50 ++ .../errors/invalid_for-in_initializer/index.html | 75 ++ .../errors/invalid_for-of_initializer/index.html | 64 ++ .../reference/errors/is_not_iterable/index.html | 106 +++ .../reference/errors/json_bad_parse/index.html | 105 +++ .../errors/malformed_formal_parameter/index.html | 57 ++ .../errors/missing_bracket_after_list/index.html | 56 ++ .../missing_colon_after_property_id/index.html | 78 ++ .../missing_curly_after_property_list/index.html | 47 ++ .../errors/missing_initializer_in_const/index.html | 55 ++ .../missing_name_after_dot_operator/index.html | 63 ++ .../index.html | 38 + .../missing_parenthesis_after_condition/index.html | 65 ++ .../missing_semicolon_before_statement/index.html | 63 ++ .../errors/more_arguments_needed/index.html | 45 + .../errors/negative_repetition_count/index.html | 40 + .../reference/errors/no_variable_name/index.html | 79 ++ .../reference/errors/not_a_codepoint/index.html | 51 ++ .../reference/errors/not_a_constructor/index.html | 91 ++ .../reference/errors/not_defined/index.html | 66 ++ .../reference/errors/precision_range/index.html | 92 ++ .../errors/property_access_denied/index.html | 42 + .../reference/errors/read-only/index.html | 77 ++ .../index.html | 83 ++ .../errors/reserved_identifier/index.html | 80 ++ .../errors/resulting_string_too_large/index.html | 46 + .../errors/strict_non_simple_params/index.html | 107 +++ .../reference/errors/too_much_recursion/index.html | 50 ++ .../reference/errors/undeclared_var/index.html | 62 ++ .../reference/errors/undefined_prop/index.html | 58 ++ .../reference/errors/unexpected_token/index.html | 49 ++ .../reference/errors/unexpected_type/index.html | 67 ++ .../errors/unnamed_function_statement/index.html | 118 +++ .../functions/arguments/@@iterator/index.html | 78 ++ .../functions/arguments/callee/index.html | 203 +++++ .../functions/arguments/caller/index.html | 93 +++ .../reference/functions/arguments/index.html | 189 +++++ .../functions/arguments/length/index.html | 74 ++ .../functions/default_parameters/index.html | 239 ++++++ .../javascript/reference/functions/get/index.html | 179 ++++ .../web/javascript/reference/functions/index.html | 596 +++++++++++++ .../functions/method_definitions/index.html | 230 +++++ .../reference/functions/rest_parameters/index.html | 223 +++++ .../javascript/reference/functions/set/index.html | 208 +++++ .../index.html" | 465 +++++++++++ .../global_objects/aggregateerror/index.html | 87 ++ .../global_objects/array/@@iterator/index.html | 84 ++ .../global_objects/array/@@species/index.html | 75 ++ .../global_objects/array/@@unscopables/index.html | 72 ++ .../global_objects/array/array/index.html | 86 ++ .../global_objects/array/concat/index.html | 138 +++ .../global_objects/array/copywithin/index.html | 183 ++++ .../global_objects/array/entries/index.html | 89 ++ .../global_objects/array/every/index.html | 191 +++++ .../reference/global_objects/array/fill/index.html | 146 ++++ .../global_objects/array/filter/index.html | 231 +++++ .../reference/global_objects/array/find/index.html | 226 +++++ .../global_objects/array/findindex/index.html | 146 ++++ .../reference/global_objects/array/flat/index.html | 160 ++++ .../global_objects/array/flatmap/index.html | 148 ++++ .../global_objects/array/foreach/index.html | 264 ++++++ .../reference/global_objects/array/from/index.html | 244 ++++++ .../global_objects/array/includes/index.html | 173 ++++ .../reference/global_objects/array/index.html | 493 +++++++++++ .../global_objects/array/indexof/index.html | 196 +++++ .../global_objects/array/isarray/index.html | 131 +++ .../reference/global_objects/array/join/index.html | 91 ++ .../reference/global_objects/array/keys/index.html | 69 ++ .../global_objects/array/lastindexof/index.html | 103 +++ .../global_objects/array/length/index.html | 135 +++ .../reference/global_objects/array/map/index.html | 293 +++++++ .../global_objects/array/observe/index.html | 87 ++ .../reference/global_objects/array/of/index.html | 104 +++ .../reference/global_objects/array/pop/index.html | 91 ++ .../reference/global_objects/array/push/index.html | 113 +++ .../global_objects/array/reduce/index.html | 573 +++++++++++++ .../global_objects/array/reduceright/index.html | 283 +++++++ .../global_objects/array/reverse/index.html | 87 ++ .../global_objects/array/shift/index.html | 102 +++ .../global_objects/array/slice/index.html | 155 ++++ .../reference/global_objects/array/some/index.html | 202 +++++ .../reference/global_objects/array/sort/index.html | 245 ++++++ .../global_objects/array/splice/index.html | 153 ++++ .../global_objects/array/tolocalestring/index.html | 195 +++++ .../global_objects/array/tosource/index.html | 71 ++ .../global_objects/array/tostring/index.html | 80 ++ .../global_objects/array/unshift/index.html | 91 ++ .../global_objects/array/values/index.html | 87 ++ .../arraybuffer/arraybuffer/index.html | 70 ++ .../arraybuffer/bytelength/index.html | 57 ++ .../global_objects/arraybuffer/index.html | 97 +++ .../global_objects/arraybuffer/isview/index.html | 76 ++ .../global_objects/arraybuffer/slice/index.html | 77 ++ .../global_objects/asyncfunction/index.html | 125 +++ .../reference/global_objects/atomics/index.html | 162 ++++ .../global_objects/bigint/bigint/index.html | 62 ++ .../reference/global_objects/bigint/index.html | 280 +++++++ .../global_objects/bigint/prototype/index.html | 59 ++ .../global_objects/boolean/boolean/index.html | 55 ++ .../reference/global_objects/boolean/index.html | 108 +++ .../global_objects/boolean/prototype/index.html | 81 ++ .../global_objects/boolean/tostring/index.html | 69 ++ .../global_objects/boolean/valueof/index.html | 67 ++ .../global_objects/dataview/dataview/index.html | 75 ++ .../reference/global_objects/dataview/index.html | 168 ++++ .../global_objects/date/getdate/index.html | 84 ++ .../global_objects/date/getday/index.html | 95 +++ .../global_objects/date/getfullyear/index.html | 88 ++ .../global_objects/date/gethours/index.html | 83 ++ .../global_objects/date/getmilliseconds/index.html | 81 ++ .../global_objects/date/getminutes/index.html | 83 ++ .../global_objects/date/getmonth/index.html | 94 +++ .../global_objects/date/getseconds/index.html | 83 ++ .../global_objects/date/gettime/index.html | 139 ++++ .../date/gettimezoneoffset/index.html | 119 +++ .../global_objects/date/getutcdate/index.html | 118 +++ .../global_objects/date/getutcday/index.html | 118 +++ .../global_objects/date/getutcfullyear/index.html | 121 +++ .../global_objects/date/getutchours/index.html | 117 +++ .../date/getutcmilliseconds/index.html | 117 +++ .../global_objects/date/getutcminutes/index.html | 117 +++ .../global_objects/date/getutcmonth/index.html | 117 +++ .../global_objects/date/getutcseconds/index.html | 117 +++ .../reference/global_objects/date/index.html | 239 ++++++ .../reference/global_objects/date/now/index.html | 119 +++ .../reference/global_objects/date/parse/index.html | 231 +++++ .../global_objects/date/prototype/index.html | 182 ++++ .../global_objects/date/setdate/index.html | 127 +++ .../global_objects/date/setfullyear/index.html | 133 +++ .../global_objects/date/sethours/index.html | 138 +++ .../global_objects/date/setmilliseconds/index.html | 126 +++ .../global_objects/date/setminutes/index.html | 136 +++ .../global_objects/date/setmonth/index.html | 147 ++++ .../global_objects/date/setseconds/index.html | 134 +++ .../global_objects/date/settime/index.html | 127 +++ .../global_objects/date/setutcdate/index.html | 126 +++ .../global_objects/date/setutcfullyear/index.html | 132 +++ .../global_objects/date/setutchours/index.html | 134 +++ .../date/setutcmilliseconds/index.html | 126 +++ .../global_objects/date/setutcminutes/index.html | 132 +++ .../global_objects/date/setutcmonth/index.html | 130 +++ .../global_objects/date/setutcseconds/index.html | 130 +++ .../global_objects/date/todatestring/index.html | 82 ++ .../global_objects/date/toisostring/index.html | 107 +++ .../global_objects/date/tojson/index.html | 81 ++ .../global_objects/date/tostring/index.html | 125 +++ .../reference/global_objects/date/utc/index.html | 139 ++++ .../global_objects/date/valueof/index.html | 79 ++ .../reference/global_objects/decodeuri/index.html | 101 +++ .../global_objects/decodeuricomponent/index.html | 92 ++ .../reference/global_objects/encodeuri/index.html | 111 +++ .../global_objects/encodeuricomponent/index.html | 148 ++++ .../reference/global_objects/error/index.html | 240 ++++++ .../reference/global_objects/error/name/index.html | 72 ++ .../reference/global_objects/eval/index.html | 285 +++++++ .../reference/global_objects/evalerror/index.html | 112 +++ .../global_objects/function/apply/index.html | 236 ++++++ .../global_objects/function/arguments/index.html | 60 ++ .../global_objects/function/bind/index.html | 296 +++++++ .../global_objects/function/call/index.html | 197 +++++ .../reference/global_objects/function/index.html | 167 ++++ .../global_objects/function/length/index.html | 80 ++ .../global_objects/function/name/index.html | 191 +++++ .../global_objects/function/tosource/index.html | 71 ++ .../reference/global_objects/generator/index.html | 186 +++++ .../global_objects/generator/next/index.html | 153 ++++ .../global_objects/generator/return/index.html | 132 +++ .../global_objects/generator/throw/index.html | 99 +++ .../global_objects/generatorfunction/index.html | 112 +++ .../reference/global_objects/globalthis/index.html | 89 ++ .../javascript/reference/global_objects/index.html | 204 +++++ .../reference/global_objects/infinity/index.html | 65 ++ .../global_objects/internalerror/index.html | 120 +++ .../internalerror/prototype/index.html | 100 +++ .../global_objects/intl/datetimeformat/index.html | 303 +++++++ .../intl/datetimeformat/prototype/index.html | 86 ++ .../reference/global_objects/intl/index.html | 134 +++ .../global_objects/intl/locale/index.html | 77 ++ .../global_objects/intl/locale/language/index.html | 62 ++ .../global_objects/intl/numberformat/index.html | 198 +++++ .../intl/numberformat/prototype/index.html | 85 ++ .../reference/global_objects/isfinite/index.html | 84 ++ .../reference/global_objects/isnan/index.html | 190 +++++ .../reference/global_objects/json/index.html | 122 +++ .../reference/global_objects/json/parse/index.html | 123 +++ .../global_objects/json/stringify/index.html | 230 +++++ .../global_objects/map/@@tostringtag/index.html | 51 ++ .../reference/global_objects/map/clear/index.html | 75 ++ .../reference/global_objects/map/delete/index.html | 79 ++ .../global_objects/map/entries/index.html | 78 ++ .../global_objects/map/foreach/index.html | 98 +++ .../reference/global_objects/map/get/index.html | 80 ++ .../reference/global_objects/map/has/index.html | 81 ++ .../reference/global_objects/map/index.html | 244 ++++++ .../reference/global_objects/map/map/index.html | 60 ++ .../global_objects/map/prototype/index.html | 86 ++ .../reference/global_objects/map/set/index.html | 96 +++ .../reference/global_objects/map/size/index.html | 62 ++ .../reference/global_objects/math/abs/index.html | 104 +++ .../reference/global_objects/math/acos/index.html | 103 +++ .../reference/global_objects/math/cbrt/index.html | 98 +++ .../reference/global_objects/math/ceil/index.html | 209 +++++ .../reference/global_objects/math/e/index.html | 84 ++ .../reference/global_objects/math/exp/index.html | 90 ++ .../reference/global_objects/math/floor/index.html | 171 ++++ .../global_objects/math/fround/index.html | 130 +++ .../reference/global_objects/math/imul/index.html | 130 +++ .../reference/global_objects/math/index.html | 155 ++++ .../reference/global_objects/math/ln10/index.html | 84 ++ .../reference/global_objects/math/ln2/index.html | 86 ++ .../reference/global_objects/math/log/index.html | 104 +++ .../global_objects/math/log10e/index.html | 84 ++ .../reference/global_objects/math/log2/index.html | 96 +++ .../reference/global_objects/math/log2e/index.html | 84 ++ .../reference/global_objects/math/max/index.html | 110 +++ .../reference/global_objects/math/min/index.html | 103 +++ .../reference/global_objects/math/pi/index.html | 82 ++ .../global_objects/math/random/index.html | 106 +++ .../reference/global_objects/math/round/index.html | 92 ++ .../reference/global_objects/math/sign/index.html | 112 +++ .../reference/global_objects/math/sin/index.html | 97 +++ .../reference/global_objects/math/sinh/index.html | 96 +++ .../reference/global_objects/math/sqrt/index.html | 90 ++ .../global_objects/math/sqrt1_2/index.html | 59 ++ .../reference/global_objects/math/sqrt2/index.html | 74 ++ .../reference/global_objects/math/tan/index.html | 102 +++ .../reference/global_objects/math/tanh/index.html | 85 ++ .../reference/global_objects/math/trunc/index.html | 96 +++ .../reference/global_objects/nan/index.html | 91 ++ .../reference/global_objects/null/index.html | 69 ++ .../global_objects/number/epsilon/index.html | 61 ++ .../reference/global_objects/number/index.html | 177 ++++ .../global_objects/number/isfinite/index.html | 90 ++ .../global_objects/number/isinteger/index.html | 96 +++ .../global_objects/number/isnan/index.html | 100 +++ .../global_objects/number/issafeinteger/index.html | 100 +++ .../number/max_safe_integer/index.html | 76 ++ .../global_objects/number/max_value/index.html | 81 ++ .../number/min_safe_integer/index.html | 66 ++ .../global_objects/number/min_value/index.html | 84 ++ .../reference/global_objects/number/nan/index.html | 62 ++ .../number/negative_infinity/index.html | 82 ++ .../global_objects/number/parsefloat/index.html | 79 ++ .../global_objects/number/parseint/index.html | 78 ++ .../number/positive_infinity/index.html | 82 ++ .../global_objects/number/prototype/index.html | 90 ++ .../global_objects/number/toexponential/index.html | 108 +++ .../global_objects/number/tofixed/index.html | 109 +++ .../global_objects/number/toprecision/index.html | 110 +++ .../global_objects/number/tostring/index.html | 112 +++ .../global_objects/number/valueof/index.html | 86 ++ .../object/__definegetter__/index.html | 99 +++ .../global_objects/object/assign/index.html | 284 +++++++ .../global_objects/object/constructor/index.html | 155 ++++ .../global_objects/object/create/index.html | 271 ++++++ .../object/defineproperties/index.html | 191 +++++ .../object/defineproperty/index.html | 417 ++++++++++ .../global_objects/object/entries/index.html | 145 ++++ .../global_objects/object/freeze/index.html | 257 ++++++ .../global_objects/object/fromentries/index.html | 98 +++ .../object/getownpropertydescriptor/index.html | 126 +++ .../object/getprototypeof/index.html | 134 +++ .../object/hasownproperty/index.html | 146 ++++ .../reference/global_objects/object/index.html | 177 ++++ .../reference/global_objects/object/is/index.html | 124 +++ .../global_objects/object/isextensible/index.html | 110 +++ .../global_objects/object/isfrozen/index.html | 155 ++++ .../global_objects/object/isprototypeof/index.html | 111 +++ .../global_objects/object/issealed/index.html | 128 +++ .../global_objects/object/observe/index.html | 193 +++++ .../object/preventextensions/index.html | 126 +++ .../object/propertyisenumerable/index.html | 146 ++++ .../global_objects/object/prototype/index.html | 218 +++++ .../global_objects/object/seal/index.html | 135 +++ .../object/setprototypeof/index.html | 242 ++++++ .../object/tolocalestring/index.html | 86 ++ .../global_objects/object/tostring/index.html | 134 +++ .../global_objects/object/valueof/index.html | 118 +++ .../global_objects/object/values/index.html | 98 +++ .../reference/global_objects/parsefloat/index.html | 120 +++ .../reference/global_objects/parseint/index.html | 220 +++++ .../global_objects/promise/all/index.html | 239 ++++++ .../global_objects/promise/allsettled/index.html | 66 ++ .../global_objects/promise/finally/index.html | 100 +++ .../reference/global_objects/promise/index.html | 226 +++++ .../global_objects/promise/promise/index.html | 78 ++ .../global_objects/promise/prototype/index.html | 71 ++ .../global_objects/promise/race/index.html | 187 +++++ .../global_objects/promise/reject/index.html | 81 ++ .../global_objects/promise/resolve/index.html | 162 ++++ .../global_objects/promise/then/index.html | 308 +++++++ .../global_objects/proxy/handler/apply/index.html | 154 ++++ .../global_objects/proxy/handler/index.html | 81 ++ .../reference/global_objects/proxy/index.html | 394 +++++++++ .../reference/global_objects/rangeerror/index.html | 163 ++++ .../global_objects/referenceerror/index.html | 129 +++ .../global_objects/reflect/apply/index.html | 93 +++ .../global_objects/reflect/construct/index.html | 154 ++++ .../reflect/defineproperty/index.html | 100 +++ .../reflect/deleteproperty/index.html | 98 +++ .../global_objects/reflect/get/index.html | 100 +++ .../reflect/getownpropertydescriptor/index.html | 103 +++ .../reflect/getprototypeof/index.html | 104 +++ .../global_objects/reflect/has/index.html | 97 +++ .../reference/global_objects/reflect/index.html | 106 +++ .../global_objects/reflect/isextensible/index.html | 111 +++ .../global_objects/reflect/ownkeys/index.html | 95 +++ .../reflect/preventextensions/index.html | 103 +++ .../global_objects/reflect/set/index.html | 108 +++ .../reflect/setprototypeof/index.html | 88 ++ .../global_objects/regexp/exec/index.html | 188 +++++ .../reference/global_objects/regexp/index.html | 233 ++++++ .../reference/global_objects/regexp/n/index.html | 66 ++ .../global_objects/regexp/regexp/index.html | 114 +++ .../global_objects/regexp/test/index.html | 129 +++ .../reference/global_objects/set/add/index.html | 83 ++ .../reference/global_objects/set/clear/index.html | 76 ++ .../reference/global_objects/set/delete/index.html | 98 +++ .../global_objects/set/foreach/index.html | 117 +++ .../reference/global_objects/set/has/index.html | 93 +++ .../reference/global_objects/set/index.html | 237 ++++++ .../global_objects/set/prototype/index.html | 86 ++ .../reference/global_objects/set/size/index.html | 69 ++ .../reference/global_objects/set/values/index.html | 72 ++ .../global_objects/sharedarraybuffer/index.html | 137 +++ .../sharedarraybuffer/prototype/index.html | 65 ++ .../global_objects/string/charat/index.html | 260 ++++++ .../global_objects/string/charcodeat/index.html | 169 ++++ .../global_objects/string/concat/index.html | 105 +++ .../global_objects/string/endswith/index.html | 142 ++++ .../global_objects/string/fromcharcode/index.html | 101 +++ .../global_objects/string/includes/index.html | 125 +++ .../reference/global_objects/string/index.html | 298 +++++++ .../global_objects/string/indexof/index.html | 159 ++++ .../global_objects/string/lastindexof/index.html | 105 +++ .../global_objects/string/length/index.html | 84 ++ .../global_objects/string/localecompare/index.html | 159 ++++ .../global_objects/string/match/index.html | 156 ++++ .../global_objects/string/normalize/index.html | 163 ++++ .../global_objects/string/padend/index.html | 99 +++ .../global_objects/string/padstart/index.html | 104 +++ .../global_objects/string/prototype/index.html | 218 +++++ .../global_objects/string/repeat/index.html | 113 +++ .../global_objects/string/replace/index.html | 299 +++++++ .../global_objects/string/search/index.html | 100 +++ .../global_objects/string/slice/index.html | 129 +++ .../global_objects/string/split/index.html | 231 +++++ .../global_objects/string/startswith/index.html | 95 +++ .../global_objects/string/substr/index.html | 131 +++ .../global_objects/string/substring/index.html | 190 +++++ .../global_objects/string/tolowercase/index.html | 83 ++ .../global_objects/string/tosource/index.html | 49 ++ .../global_objects/string/tostring/index.html | 59 ++ .../global_objects/string/touppercase/index.html | 105 +++ .../global_objects/string/trim/index.html | 97 +++ .../global_objects/string/valueof/index.html | 83 ++ .../reference/global_objects/symbol/for/index.html | 150 ++++ .../reference/global_objects/symbol/index.html | 233 ++++++ .../global_objects/symbol/iterator/index.html | 95 +++ .../global_objects/syntaxerror/index.html | 123 +++ .../syntaxerror/prototype/index.html | 126 +++ .../typedarray/@@iterator/index.html | 127 +++ .../global_objects/typedarray/buffer/index.html | 111 +++ .../typedarray/bytelength/index.html | 73 ++ .../typedarray/byteoffset/index.html | 69 ++ .../typedarray/bytes_per_element/index.html | 75 ++ .../global_objects/typedarray/fill/index.html | 75 ++ .../reference/global_objects/typedarray/index.html | 342 ++++++++ .../global_objects/typedarray/indexof/index.html | 80 ++ .../global_objects/typedarray/length/index.html | 68 ++ .../global_objects/typedarray/name/index.html | 70 ++ .../global_objects/typedarray/of/index.html | 92 ++ .../global_objects/typedarray/prototype/index.html | 175 ++++ .../global_objects/typedarray/reverse/index.html | 69 ++ .../global_objects/typedarray/set/index.html | 95 +++ .../global_objects/typedarray/slice/index.html | 129 +++ .../global_objects/typedarray/some/index.html | 106 +++ .../global_objects/typedarray/sort/index.html | 119 +++ .../global_objects/typedarray/values/index.html | 127 +++ .../reference/global_objects/typeerror/index.html | 123 +++ .../reference/global_objects/undefined/index.html | 138 +++ .../reference/global_objects/uneval/index.html | 67 ++ .../global_objects/weakmap/delete/index.html | 80 ++ .../reference/global_objects/weakmap/index.html | 283 +++++++ .../global_objects/weakmap/prototype/index.html | 142 ++++ .../reference/global_objects/weakset/index.html | 108 +++ .../global_objects/weakset/prototype/index.html | 141 ++++ .../global_objects/webassembly/compile/index.html | 83 ++ .../webassembly/compileerror/index.html | 114 +++ .../webassembly/compilestreaming/index.html | 79 ++ .../global_objects/webassembly/global/index.html | 116 +++ .../webassembly/global/prototype/index.html | 69 ++ .../global_objects/webassembly/index.html | 100 +++ .../global_objects/webassembly/instance/index.html | 74 ++ .../webassembly/instantiate/index.html | 168 ++++ .../webassembly/instantiatestreaming/index.html | 83 ++ .../webassembly/linkerror/index.html | 113 +++ .../global_objects/webassembly/memory/index.html | 112 +++ .../global_objects/webassembly/module/index.html | 83 ++ .../webassembly/runtimeerror/index.html | 111 +++ .../global_objects/webassembly/table/index.html | 130 +++ .../global_objects/webassembly/validate/index.html | 75 ++ files/ko/web/javascript/reference/index.html | 48 ++ .../reference/iteration_protocols/index.html | 394 +++++++++ .../reference/lexical_grammar/index.html | 657 +++++++++++++++ .../javascript/reference/liveconnect/index.html | 17 + .../reference/operators/addition/index.html | 77 ++ .../operators/arithmetic_operators/index.html | 290 +++++++ .../operators/assignment_operators/index.html | 394 +++++++++ .../reference/operators/async_function/index.html | 96 +++ .../reference/operators/await/index.html | 137 +++ .../operators/bitwise_operators/index.html | 540 ++++++++++++ .../reference/operators/class/index.html | 100 +++ .../reference/operators/comma_operator/index.html | 91 ++ .../operators/comparison_operators/index.html | 215 +++++ .../operators/conditional_operator/index.html | 193 +++++ .../reference/operators/delete/index.html | 282 +++++++ .../operators/destructuring_assignment/index.html | 409 +++++++++ .../reference/operators/equality/index.html | 123 +++ .../operators/expression_closures/index.html | 79 ++ .../reference/operators/function/index.html | 154 ++++ .../reference/operators/function_star_/index.html | 85 ++ .../operators/generator_comprehensions/index.html | 174 ++++ .../reference/operators/grouping/index.html | 92 ++ .../javascript/reference/operators/in/index.html | 188 +++++ .../web/javascript/reference/operators/index.html | 304 +++++++ .../reference/operators/instanceof/index.html | 161 ++++ .../reference/operators/new.target/index.html | 93 +++ .../javascript/reference/operators/new/index.html | 187 +++++ .../nullish_coalescing_operator/index.html | 161 ++++ .../operators/object_initializer/index.html | 302 +++++++ .../operators/optional_chaining/index.html | 187 +++++ .../operators/pipeline_operator/index.html | 76 ++ .../operators/property_accessors/index.html | 153 ++++ .../reference/operators/remainder/index.html | 73 ++ .../reference/operators/spread_syntax/index.html | 255 ++++++ .../reference/operators/super/index.html | 176 ++++ .../javascript/reference/operators/this/index.html | 398 +++++++++ .../reference/operators/typeof/index.html | 227 +++++ .../javascript/reference/operators/void/index.html | 122 +++ .../reference/operators/yield/index.html | 182 ++++ .../reference/operators/yield_star_/index.html | 164 ++++ .../index.html" | 249 ++++++ .../operators/\353\260\260\354\227\264/index.html" | 200 +++++ .../index.html" | 462 ++++++++++ .../reference/statements/async_function/index.html | 243 ++++++ .../reference/statements/block/index.html | 132 +++ .../reference/statements/break/index.html | 119 +++ .../reference/statements/class/index.html | 119 +++ .../reference/statements/const/index.html | 136 +++ .../reference/statements/continue/index.html | 164 ++++ .../reference/statements/debugger/index.html | 79 ++ .../reference/statements/default/index.html | 121 +++ .../reference/statements/do...while/index.html | 78 ++ .../reference/statements/empty/index.html | 102 +++ .../reference/statements/export/index.html | 199 +++++ .../reference/statements/for-await...of/index.html | 144 ++++ .../reference/statements/for...in/index.html | 176 ++++ .../reference/statements/for...of/index.html | 228 +++++ .../javascript/reference/statements/for/index.html | 160 ++++ .../reference/statements/for_each...in/index.html | 85 ++ .../reference/statements/function/index.html | 177 ++++ .../reference/statements/function_star_/index.html | 159 ++++ .../reference/statements/if...else/index.html | 177 ++++ .../reference/statements/import/index.html | 156 ++++ .../web/javascript/reference/statements/index.html | 143 ++++ .../reference/statements/label/index.html | 241 ++++++ .../javascript/reference/statements/let/index.html | 246 ++++++ .../reference/statements/return/index.html | 159 ++++ .../reference/statements/switch/index.html | 306 +++++++ .../reference/statements/throw/index.html | 198 +++++ .../reference/statements/try...catch/index.html | 273 ++++++ .../javascript/reference/statements/var/index.html | 195 +++++ .../reference/statements/while/index.html | 142 ++++ .../reference/statements/with/index.html | 127 +++ .../javascript/reference/strict_mode/index.html | 383 +++++++++ .../transitioning_to_strict_mode/index.html | 137 +++ .../reference/template_literals/index.html | 254 ++++++ .../reference/trailing_commas/index.html | 185 ++++ files/ko/web/javascript/typed_arrays/index.html | 222 +++++ "files/ko/web/javascript/\354\211\230/index.html" | 40 + .../index.html" | 327 ++++++++ .../index.html" | 155 ++++ 572 files changed, 82607 insertions(+) create mode 100644 files/ko/web/javascript/about/index.html create mode 100644 files/ko/web/javascript/data_structures/index.html create mode 100644 files/ko/web/javascript/differential_inheritance_in_javascript/index.html create mode 100644 files/ko/web/javascript/enumerability_and_ownership_of_properties/index.html create mode 100644 files/ko/web/javascript/equality_comparisons_and_sameness/index.html create mode 100644 files/ko/web/javascript/eventloop/index.html create mode 100644 files/ko/web/javascript/guide/closures/index.html create mode 100644 files/ko/web/javascript/guide/control_flow_and_error_handling/index.html create mode 100644 files/ko/web/javascript/guide/expressions_and_operators/index.html create mode 100644 files/ko/web/javascript/guide/index.html create mode 100644 files/ko/web/javascript/guide/indexed_collections/index.html create mode 100644 files/ko/web/javascript/guide/inheritance_and_the_prototype_chain/index.html create mode 100644 files/ko/web/javascript/guide/iterators_and_generators/index.html create mode 100644 files/ko/web/javascript/guide/keyed_collections/index.html create mode 100644 files/ko/web/javascript/guide/loops_and_iteration/index.html create mode 100644 files/ko/web/javascript/guide/modules/index.html create mode 100644 files/ko/web/javascript/guide/numbers_and_dates/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/about/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/class-based_vs._prototype-based_languages/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/constants/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_a_regular_expression/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_getters_and_setters/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_methods/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_properties_for_an_object_type/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/deleting_properties/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/indexing_object_properties/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_a_constructor_function/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_this_for_object_references/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/expressions/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/javascript_overview/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/literals/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/objects_and_properties/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/arithmetic_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/assignment_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/bitwise_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/logical_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/special_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/string_operators/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/array_object/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/unicode/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/values/index.html create mode 100644 files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/variables/index.html create mode 100644 files/ko/web/javascript/guide/text_formatting/index.html create mode 100644 files/ko/web/javascript/guide/using_promises/index.html create mode 100644 files/ko/web/javascript/guide/values,_variables,_and_literals/index.html create mode 100644 files/ko/web/javascript/guide/working_with_objects/index.html create mode 100644 "files/ko/web/javascript/guide/\352\260\235\354\262\264_\353\252\250\353\215\270\354\235\230_\354\204\270\353\266\200\354\202\254\355\225\255/index.html" create mode 100644 "files/ko/web/javascript/guide/\353\251\224\355\203\200_\355\224\204\353\241\234\352\267\270\353\236\230\353\260\215/index.html" create mode 100644 "files/ko/web/javascript/guide/\354\206\214\352\260\234/index.html" create mode 100644 "files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/assertions/index.html" create mode 100644 "files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/groups_and_ranges/index.html" create mode 100644 "files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/index.html" create mode 100644 "files/ko/web/javascript/guide/\355\225\250\354\210\230/index.html" create mode 100644 files/ko/web/javascript/index.html create mode 100644 files/ko/web/javascript/introduction_to_object-oriented_javascript/index.html create mode 100644 files/ko/web/javascript/javascript_technologies_overview/index.html create mode 100644 files/ko/web/javascript/memory_management/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/1.5/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/1.6/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/1.8.1/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/1.8.5/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/1.8/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html create mode 100644 files/ko/web/javascript/new_in_javascript/index.html create mode 100644 files/ko/web/javascript/reference/about/index.html create mode 100644 files/ko/web/javascript/reference/classes/class_fields/index.html create mode 100644 files/ko/web/javascript/reference/classes/constructor/index.html create mode 100644 files/ko/web/javascript/reference/classes/extends/index.html create mode 100644 files/ko/web/javascript/reference/classes/index.html create mode 100644 files/ko/web/javascript/reference/classes/private_class_fields/index.html create mode 100644 files/ko/web/javascript/reference/classes/static/index.html create mode 100644 files/ko/web/javascript/reference/deprecated_and_obsolete_features/index.html create mode 100644 files/ko/web/javascript/reference/errors/bad_octal/index.html create mode 100644 files/ko/web/javascript/reference/errors/bad_radix/index.html create mode 100644 files/ko/web/javascript/reference/errors/bad_regexp_flag/index.html create mode 100644 files/ko/web/javascript/reference/errors/bad_return_or_yield/index.html create mode 100644 files/ko/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html create mode 100644 files/ko/web/javascript/reference/errors/delete_in_strict_mode/index.html create mode 100644 files/ko/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html create mode 100644 files/ko/web/javascript/reference/errors/deprecated_octal/index.html create mode 100644 files/ko/web/javascript/reference/errors/identifier_after_number/index.html create mode 100644 files/ko/web/javascript/reference/errors/illegal_character/index.html create mode 100644 files/ko/web/javascript/reference/errors/index.html create mode 100644 files/ko/web/javascript/reference/errors/invalid_array_length/index.html create mode 100644 files/ko/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html create mode 100644 files/ko/web/javascript/reference/errors/invalid_date/index.html create mode 100644 files/ko/web/javascript/reference/errors/invalid_for-in_initializer/index.html create mode 100644 files/ko/web/javascript/reference/errors/invalid_for-of_initializer/index.html create mode 100644 files/ko/web/javascript/reference/errors/is_not_iterable/index.html create mode 100644 files/ko/web/javascript/reference/errors/json_bad_parse/index.html create mode 100644 files/ko/web/javascript/reference/errors/malformed_formal_parameter/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_bracket_after_list/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_colon_after_property_id/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_curly_after_property_list/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_initializer_in_const/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_name_after_dot_operator/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html create mode 100644 files/ko/web/javascript/reference/errors/missing_semicolon_before_statement/index.html create mode 100644 files/ko/web/javascript/reference/errors/more_arguments_needed/index.html create mode 100644 files/ko/web/javascript/reference/errors/negative_repetition_count/index.html create mode 100644 files/ko/web/javascript/reference/errors/no_variable_name/index.html create mode 100644 files/ko/web/javascript/reference/errors/not_a_codepoint/index.html create mode 100644 files/ko/web/javascript/reference/errors/not_a_constructor/index.html create mode 100644 files/ko/web/javascript/reference/errors/not_defined/index.html create mode 100644 files/ko/web/javascript/reference/errors/precision_range/index.html create mode 100644 files/ko/web/javascript/reference/errors/property_access_denied/index.html create mode 100644 files/ko/web/javascript/reference/errors/read-only/index.html create mode 100644 files/ko/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html create mode 100644 files/ko/web/javascript/reference/errors/reserved_identifier/index.html create mode 100644 files/ko/web/javascript/reference/errors/resulting_string_too_large/index.html create mode 100644 files/ko/web/javascript/reference/errors/strict_non_simple_params/index.html create mode 100644 files/ko/web/javascript/reference/errors/too_much_recursion/index.html create mode 100644 files/ko/web/javascript/reference/errors/undeclared_var/index.html create mode 100644 files/ko/web/javascript/reference/errors/undefined_prop/index.html create mode 100644 files/ko/web/javascript/reference/errors/unexpected_token/index.html create mode 100644 files/ko/web/javascript/reference/errors/unexpected_type/index.html create mode 100644 files/ko/web/javascript/reference/errors/unnamed_function_statement/index.html create mode 100644 files/ko/web/javascript/reference/functions/arguments/@@iterator/index.html create mode 100644 files/ko/web/javascript/reference/functions/arguments/callee/index.html create mode 100644 files/ko/web/javascript/reference/functions/arguments/caller/index.html create mode 100644 files/ko/web/javascript/reference/functions/arguments/index.html create mode 100644 files/ko/web/javascript/reference/functions/arguments/length/index.html create mode 100644 files/ko/web/javascript/reference/functions/default_parameters/index.html create mode 100644 files/ko/web/javascript/reference/functions/get/index.html create mode 100644 files/ko/web/javascript/reference/functions/index.html create mode 100644 files/ko/web/javascript/reference/functions/method_definitions/index.html create mode 100644 files/ko/web/javascript/reference/functions/rest_parameters/index.html create mode 100644 files/ko/web/javascript/reference/functions/set/index.html create mode 100644 "files/ko/web/javascript/reference/functions/\354\225\240\353\241\234\354\232\260_\355\216\221\354\205\230/index.html" create mode 100644 files/ko/web/javascript/reference/global_objects/aggregateerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/@@species/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/array/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/copywithin/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/entries/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/every/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/fill/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/filter/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/findindex/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/flat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/flatmap/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/foreach/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/indexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/keys/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/length/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/observe/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/push/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/reduce/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/reduceright/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/shift/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/some/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/sort/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/tosource/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/array/values/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/arraybuffer/arraybuffer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/arraybuffer/bytelength/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/arraybuffer/isview/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/arraybuffer/slice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/asyncfunction/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/atomics/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/bigint/bigint/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/bigint/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/boolean/boolean/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/boolean/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/boolean/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/boolean/valueof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/dataview/dataview/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/dataview/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getdate/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getday/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getfullyear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/gethours/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getmilliseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getminutes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getmonth/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/gettime/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcdate/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcday/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcfullyear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutchours/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcmilliseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcminutes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcmonth/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/getutcseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/parse/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setdate/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setfullyear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/sethours/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setmilliseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setminutes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setmonth/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/settime/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcdate/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcfullyear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutchours/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcmilliseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcminutes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcmonth/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/setutcseconds/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/todatestring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/toisostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/tojson/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/utc/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/date/valueof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/decodeuri/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/decodeuricomponent/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/encodeuri/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/encodeuricomponent/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/error/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/error/name/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/eval/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/evalerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/arguments/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/bind/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/length/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/name/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/function/tosource/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/generator/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/generator/next/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/generator/return/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/generator/throw/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/generatorfunction/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/globalthis/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/infinity/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/internalerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/datetimeformat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/locale/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/locale/language/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/numberformat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/isfinite/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/isnan/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/json/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/json/parse/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/json/stringify/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/@@tostringtag/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/clear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/delete/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/entries/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/foreach/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/get/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/has/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/map/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/set/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/map/size/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/abs/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/acos/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/cbrt/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/e/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/exp/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/floor/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/fround/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/imul/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/ln10/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/ln2/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/log/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/log10e/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/log2/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/log2e/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/max/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/min/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/pi/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/random/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/round/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sign/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sin/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sinh/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sqrt/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sqrt1_2/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/sqrt2/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/tan/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/tanh/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/math/trunc/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/nan/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/null/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/epsilon/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/isfinite/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/isinteger/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/isnan/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/issafeinteger/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/max_safe_integer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/max_value/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/min_safe_integer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/min_value/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/nan/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/negative_infinity/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/parsefloat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/parseint/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/positive_infinity/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/toexponential/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/tofixed/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/toprecision/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/number/valueof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/__definegetter__/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/constructor/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/create/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/defineproperties/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/defineproperty/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/entries/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/freeze/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/fromentries/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/hasownproperty/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/is/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/isextensible/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/isfrozen/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/isprototypeof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/issealed/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/observe/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/preventextensions/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/propertyisenumerable/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/seal/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/setprototypeof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/tolocalestring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/valueof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/object/values/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/parsefloat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/parseint/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/all/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/allsettled/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/finally/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/promise/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/race/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/reject/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/resolve/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/promise/then/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/proxy/handler/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/proxy/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/rangeerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/referenceerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/apply/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/construct/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/defineproperty/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/deleteproperty/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/get/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/getprototypeof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/has/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/isextensible/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/ownkeys/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/preventextensions/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/set/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/reflect/setprototypeof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/exec/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/n/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/regexp/test/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/add/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/clear/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/delete/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/foreach/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/has/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/size/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/set/values/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/sharedarraybuffer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/charat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/concat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/endswith/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/includes/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/length/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/localecompare/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/match/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/normalize/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/padend/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/padstart/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/repeat/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/replace/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/search/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/slice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/split/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/startswith/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/substr/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/substring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/tosource/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/tostring/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/touppercase/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/trim/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/string/valueof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/symbol/for/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/symbol/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/symbol/iterator/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/syntaxerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/@@iterator/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/buffer/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/bytelength/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/byteoffset/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/bytes_per_element/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/fill/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/indexof/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/length/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/name/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/of/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/reverse/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/set/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/slice/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/some/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/sort/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typedarray/values/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/typeerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/undefined/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/uneval/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/weakmap/delete/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/weakmap/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/weakset/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/compile/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/compileerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/compilestreaming/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/global/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/instance/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/instantiate/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/instantiatestreaming/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/linkerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/memory/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/module/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/runtimeerror/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/table/index.html create mode 100644 files/ko/web/javascript/reference/global_objects/webassembly/validate/index.html create mode 100644 files/ko/web/javascript/reference/index.html create mode 100644 files/ko/web/javascript/reference/iteration_protocols/index.html create mode 100644 files/ko/web/javascript/reference/lexical_grammar/index.html create mode 100644 files/ko/web/javascript/reference/liveconnect/index.html create mode 100644 files/ko/web/javascript/reference/operators/addition/index.html create mode 100644 files/ko/web/javascript/reference/operators/arithmetic_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/assignment_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/async_function/index.html create mode 100644 files/ko/web/javascript/reference/operators/await/index.html create mode 100644 files/ko/web/javascript/reference/operators/bitwise_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/class/index.html create mode 100644 files/ko/web/javascript/reference/operators/comma_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/comparison_operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/conditional_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/delete/index.html create mode 100644 files/ko/web/javascript/reference/operators/destructuring_assignment/index.html create mode 100644 files/ko/web/javascript/reference/operators/equality/index.html create mode 100644 files/ko/web/javascript/reference/operators/expression_closures/index.html create mode 100644 files/ko/web/javascript/reference/operators/function/index.html create mode 100644 files/ko/web/javascript/reference/operators/function_star_/index.html create mode 100644 files/ko/web/javascript/reference/operators/generator_comprehensions/index.html create mode 100644 files/ko/web/javascript/reference/operators/grouping/index.html create mode 100644 files/ko/web/javascript/reference/operators/in/index.html create mode 100644 files/ko/web/javascript/reference/operators/index.html create mode 100644 files/ko/web/javascript/reference/operators/instanceof/index.html create mode 100644 files/ko/web/javascript/reference/operators/new.target/index.html create mode 100644 files/ko/web/javascript/reference/operators/new/index.html create mode 100644 files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/object_initializer/index.html create mode 100644 files/ko/web/javascript/reference/operators/optional_chaining/index.html create mode 100644 files/ko/web/javascript/reference/operators/pipeline_operator/index.html create mode 100644 files/ko/web/javascript/reference/operators/property_accessors/index.html create mode 100644 files/ko/web/javascript/reference/operators/remainder/index.html create mode 100644 files/ko/web/javascript/reference/operators/spread_syntax/index.html create mode 100644 files/ko/web/javascript/reference/operators/super/index.html create mode 100644 files/ko/web/javascript/reference/operators/this/index.html create mode 100644 files/ko/web/javascript/reference/operators/typeof/index.html create mode 100644 files/ko/web/javascript/reference/operators/void/index.html create mode 100644 files/ko/web/javascript/reference/operators/yield/index.html create mode 100644 files/ko/web/javascript/reference/operators/yield_star_/index.html create mode 100644 "files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" create mode 100644 "files/ko/web/javascript/reference/operators/\353\260\260\354\227\264/index.html" create mode 100644 "files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" create mode 100644 files/ko/web/javascript/reference/statements/async_function/index.html create mode 100644 files/ko/web/javascript/reference/statements/block/index.html create mode 100644 files/ko/web/javascript/reference/statements/break/index.html create mode 100644 files/ko/web/javascript/reference/statements/class/index.html create mode 100644 files/ko/web/javascript/reference/statements/const/index.html create mode 100644 files/ko/web/javascript/reference/statements/continue/index.html create mode 100644 files/ko/web/javascript/reference/statements/debugger/index.html create mode 100644 files/ko/web/javascript/reference/statements/default/index.html create mode 100644 files/ko/web/javascript/reference/statements/do...while/index.html create mode 100644 files/ko/web/javascript/reference/statements/empty/index.html create mode 100644 files/ko/web/javascript/reference/statements/export/index.html create mode 100644 files/ko/web/javascript/reference/statements/for-await...of/index.html create mode 100644 files/ko/web/javascript/reference/statements/for...in/index.html create mode 100644 files/ko/web/javascript/reference/statements/for...of/index.html create mode 100644 files/ko/web/javascript/reference/statements/for/index.html create mode 100644 files/ko/web/javascript/reference/statements/for_each...in/index.html create mode 100644 files/ko/web/javascript/reference/statements/function/index.html create mode 100644 files/ko/web/javascript/reference/statements/function_star_/index.html create mode 100644 files/ko/web/javascript/reference/statements/if...else/index.html create mode 100644 files/ko/web/javascript/reference/statements/import/index.html create mode 100644 files/ko/web/javascript/reference/statements/index.html create mode 100644 files/ko/web/javascript/reference/statements/label/index.html create mode 100644 files/ko/web/javascript/reference/statements/let/index.html create mode 100644 files/ko/web/javascript/reference/statements/return/index.html create mode 100644 files/ko/web/javascript/reference/statements/switch/index.html create mode 100644 files/ko/web/javascript/reference/statements/throw/index.html create mode 100644 files/ko/web/javascript/reference/statements/try...catch/index.html create mode 100644 files/ko/web/javascript/reference/statements/var/index.html create mode 100644 files/ko/web/javascript/reference/statements/while/index.html create mode 100644 files/ko/web/javascript/reference/statements/with/index.html create mode 100644 files/ko/web/javascript/reference/strict_mode/index.html create mode 100644 files/ko/web/javascript/reference/strict_mode/transitioning_to_strict_mode/index.html create mode 100644 files/ko/web/javascript/reference/template_literals/index.html create mode 100644 files/ko/web/javascript/reference/trailing_commas/index.html create mode 100644 files/ko/web/javascript/typed_arrays/index.html create mode 100644 "files/ko/web/javascript/\354\211\230/index.html" create mode 100644 "files/ko/web/javascript/\354\213\234\354\236\221\355\225\230\352\270\260/index.html" create mode 100644 "files/ko/web/javascript/\354\226\270\354\226\264_\353\246\254\354\206\214\354\212\244/index.html" (limited to 'files/ko/web/javascript') diff --git a/files/ko/web/javascript/about/index.html b/files/ko/web/javascript/about/index.html new file mode 100644 index 0000000000..c7ec0f9f28 --- /dev/null +++ b/files/ko/web/javascript/about/index.html @@ -0,0 +1,58 @@ +--- +title: JavaScript에 대하여 +slug: Web/JavaScript/About +tags: + - 비기너 + - 소개 + - 자바스크립트 +translation_of: Web/JavaScript/About_JavaScript +--- +

{{JsSidebar}}

+ +

JavaScript란 무엇인가?

+ +

JavaScript® (줄여서 JS)는 일급 함수를 사용하는 가벼운 객체 지향 인터프리터 언어이며 웹페이지의 스크립트 언어로 잘 알려져 있지만, 브라우저가 아닌 환경에서도 많이 사용된다. 프로토타입 기반, 다중 패러다임 스크립트 언어이며, 동적이고 명령어, 객체 지향, 함수 프로그래밍 스타일을 지원한다.

+ +

자바스크립트는 클라이언트 측 웹(브라우저)에서 실행 되고, 웹 페이지가 이벤트 발생시 어떻게 작동하는 지 디자인 / 프로그래밍할 수 있다. 자바스크립트는 쉽게 배울 수 있고 강력한 스크립트 언어로 웹 페이지 동작을 제어하는 데 널리 사용된다.

+ +

대중적인 오해와 달리, Javascript는 인터프리트 형태 자바가 아니다. 간단히 말하면, Javascript는 프로토 타입 기반 객체 생성을 지원하는 동적 스크립트 언어이다.  기본적인 문법은  언어 학습에 필요한 새로운 개념을 줄이기 위해 Java와 C++의 if문, for와 while문, switch문과 try...catch 구문을 사용하는 언어구조를 사용하며, 그와 같은 (거의 가까운) 동작을 한다.

+ +

Javascript는 절차지향 (procedural) 언어와  객체지향 (object oriented) 언어 두가지 형태로 만들수 있다. 자바스크립트에서 객체는 실시간으로 빈 객체를 오버라이딩하여 메소드와 프로퍼티를 연결하는 (프로그래밍)방식으로 생성된다. C++ 및 Java와 같은 컴파일 언어에서 공통적인 구문 클래스 정의와 반대되는 개념이다. 한번 객체가 생성하면, 비슷한 객체를 생성할 때 프로토타입으로 사용할 수 있다.

+ +

JavaScript의 동적인 성질은, 실행시의 오브젝트 구축, 가변 인수 리스트, 함수 변수, (eval 에 의한)동적 스크립트 작성, (for ... in 에 의한) 오브젝트의 내부참조, 또는 소스코드 복원 (JavaScript 의 프로그램은 함수본체를 소스텍스트에 역컴파일할 수 있다.) 을 포함하고 있다.

+ +

자바스크립트 프로그래밍에 대한 더 자세한 설명은 아래의 자바스크립트 리소스 링크를 참조하면 된다.

+ +

어떠한 JavaScript 구현이 유용한가?

+ +

Mozilla 프로젝트는 두 가지 자바스크립트 구현을 제공한다. 최초의 Javascript는 Netscape의 Brendan Eich에 의해 만들었다. 이후 ECMA-262 에디션 5 와 최신 버전을 준수하도록 업데이트되었다. SpiderMonkey 라는 이름의 엔진은 C/C++로 구현되었다. Rhino 엔진은 주로 Norris Boys(또한 Netscape)가 만들었고 Java로 작성된 Javascript 구현체이다. SpiderMonkey와 마찬가지로 Rhino도 ECMA-262 에디션 5를 준거한다.

+ +

TraceMonkey (Firefox 3.5), JägerMonkey (Firefox 4) 그리고 IonMonkey와 같은 몇가지 주요한 실시간 최적화는 차츰 SpiderMonkey 자바스크립트 엔진에 추가되었다. 자바스크립트 실행 성능 향상을 위한 작업은 지금도 진행 중이다.

+ +

위의 구현 이외에도 다음과 같은 다른 인기있는 자바스크립트 엔진이 있다.

+ + + +

mozilla.org의 각 JavaScript 엔진은, 애플리케이션이 JavaScript를 지원하기 위해 부를 수 있는 공개 API를 공개하고 있다. JavaScript 를 지원하는 가장 일반적인 호스트환경은 웹브라우저이다. 웹 브라우저는 일반적으로 공개 API를 사용하여 DOM을 Javascript로 반영하는 호스트 객체를 만든다.

+ +

JavaScript 의 또 다른 일반적인 애플리케이션은 (웹) 서버사이드 스크립팅 언어이다. 자바스크립트 웹 서버는 HTTP 요청 및 응답 객체를 나타내는 호스트 객체를 공개하며 자바 스크립트 프로그램에 의해 조작되어 웹 페이지를 동적으로 생성 할 수 있다. Node.js는 이에 대한 대중적인 예이다.

+ +

JavaScript 자원

+ +
+
SpiderMonkey
+
애플리케이션에 임베드하는 방법을 포함하는, C/C++ 엔진(SpiderMonkey)으로 구현된 Mozilla의 JavaScript 구현체에 관한 정보.
+
Rhino
+
Java(Rhino)로 작성된 자바스크립트 구현체에 관련 정보.
+
Language resources
+
자바스크립트 표준을 출판하기 위한 포인터들.
+
A re-introduction to JavaScript
+
자바스크립트 가이드자바스크립트 레퍼런스.
+
+ +

JavaScript® 는 미국 및 여러 나라의 Oracle 트레이드마크 또는 등록된 트레이드마크입니다.

diff --git a/files/ko/web/javascript/data_structures/index.html b/files/ko/web/javascript/data_structures/index.html new file mode 100644 index 0000000000..14967ae250 --- /dev/null +++ b/files/ko/web/javascript/data_structures/index.html @@ -0,0 +1,221 @@ +--- +title: 자바스크립트의 자료형 +slug: Web/JavaScript/Data_structures +translation_of: Web/JavaScript/Data_structures +--- +
{{jsSidebar("More")}}
+ +

모든 프로그래밍 언어는 내장 자료형이 있지만, 종종 이러한 내장 자료형은 언어마다 다르다. 이 문서에서는 자바스크립트의 내장 자료형과, 내장 자료형에서 사용할 수 있는 속성들에 대해 알아본다. 이로써 내장 자료형들로 더 복잡한 자료형을 만드는데 사용할 수 있을 것이다. 가능하다면 다른 언어와도 비교해보자.

+ +

동적 타이핑

+ +

자바스크립트는 느슨한 타입 (loosely typed) 언어, 혹은 동적 (dynamic) 언어이다. 그 말은, 변수의 타입을 미리 선언할 필요가 없다는 뜻이다. 타입은 프로그램이 처리되는 과정에서 자동으로 파악될 것이다. 또한 그 말은 같은 변수에 여러 타입의 값을 넣을 수 있다는 뜻이다.

+ +
var foo = 42;    // foo 는 이제 Number 임
+var foo = "bar"; // foo 는 이제 String 임
+var foo = true;  // foo 는 이제 Boolean 임
+
+ +

데이터 타입

+ +

최신 ECMAScript 표준은 다음과 같은 7개의 자료형을  정의한다.

+ + + +

다음 장에서 이 여섯개의 자료형을 사용하는 방법과 자료형을 조합하여 더 복잡한 자료형을 만드는 방법에 대해 알아보자.

+ +

기본 타입 (Primitive value)

+ +

오브젝트를 제외한 모든 값은 변경 불가능한 값 (immutable value) 이다. 예를 들자면, 특히 C 언어와는 다르게도, 문자열은 불변값 (immutable) 이다. 이런 값을 "primitive values" 라고 일컫는다. 아래의  {{ anch("Strings") }} 장에서 더 자세히 설명할 것이다.

+ +

Boolean 타입

+ +

Boolean 은 논리적인 요소를 나타내고, truefalse 의 두 가지 값을 가질 수 있다.

+ +

Null 타입

+ +

Null 타입은 딱 한 가지 값, null 을 가질 수 있다. 더 알아보려면 {{jsxref("null")}} 와 {{Glossary("Null")}} 을 보라.

+ +

Undefined 타입

+ +

값을 할당하지 않은 변수는 undefined 값을 가진다. 더 알아보려면 {{jsxref("undefined")}} 와 {{Glossary("Undefined")}} 을 보라.

+ +

Number 타입

+ +

ECMAScript 표준에 따르면, 숫자의 자료형은 배정밀도 64비트 형식 IEEE 754 값 (-(253 -1) 와 253 -1 사이의 숫자값) 단 하나만 존재한다. 정수만을 표현하기 위한 특별한 자료형은 없다. 부동 소수점을 표현할 수 있는 것 말고도, Number 타입은 세 가지 의미있는 몇가지 상징적인 값들도 표현할 수 있다. 이 값에는 +무한대, -무한대, and NaN (숫자가 아님)이 있다.

+ +

+/-Infinity 보다 크거나 작은지 확인하는 용도로 상수값인 {{jsxref("Number.MAX_VALUE")}} 나 {{jsxref("Number.MIN_VALUE")}} 을 사용할 수 있다. 또한, ECMAScript 6 부터는 숫자가 배정밀도 부동소수점 숫자인지 확인하는 용도로 {{jsxref("Number.isSafeInteger()")}} 과 {{jsxref("Number.MAX_SAFE_INTEGER")}}, {{jsxref("Number.MIN_SAFE_INTEGER")}} 을 사용할 수 있다. 이 범위를 넘어서면, 자바스크립트의 숫자는 더 이상 안전하지 않다.

+ +

Number 타입의 값 중에는 두 가지 방식으로 표현할 수 있는 유일한 값이 있는데, 0 이다. 0 은 -0 이나 +0 으로 표시할 수 있다. ("0" 은 물론 +0 이다.) 실제로는 이러한 사실은 거의 효력이 없다. 그 예로, +0 === -0true 이다. 하지만 0으로 나누는 경우 그 차이가 눈에 띌 것이다.

+ +
> 42 / +0
+Infinity
+> 42 / -0
+-Infinity
+ +

숫자가 보통 값만으로 표현되긴 하지만, 자바스크립트는 몇 가지 이진 연산자도 제공한다. 이러한 이진 연산자들은 비트 마스킹(bit masking) 기법으로 한 숫자 안에 여러 Boolean 값을 저장하는데도 쓸 수 있다. 일반적으로 이런 방법은 나쁜 방법이지만, 자바스크립트에서는 (Boolean 값의 배열이나 Boolean 값들을 이름있는 속성들로 가지는 객체 같은) Boolean 덩어리를 나타낼 다른 방법이 없다. 비트 마스킹은 또한 코드를 이해하고, 읽고, 유지보수하는데에 있어서 좀 더 어렵게 만드는 경향이 있다. 하지만 이러한 기법은 local storage 의 저장공간이 부족해서 절약하려고 하거나, 네트워크 상에서 각각의 비트를 전송하는 등의 극단적인 상황 같은 굉장히 제한적인 환경에서 필요할 수도 있다. 그래서 비트 마스킹 기법은 크기를 최대한 줄여야하는 상황에서만 사용을 고려해야 한다.

+ +

String 타입

+ +

자바스크립트의 {{jsxref("Global_Objects/String", "String")}} 타입은 텍스트 데이터를 나타내는데 사용한다. 이는 16비트 부호없는 정수 값 요소들의 집합이다. String의 각 요소는 String의 위치를 차지한다. 첫 번째 요소는 0번 인덱스에 있고, 다음 요소는 1번, 그 다음 요소는 2번... 같은 방식이다. String 의 길이는 String이 가지고있는 요소의 갯수이다.

+ +

C 같은 언어와는 다르게, 자바스크립트의 문자열은 변경 불가능 (immutable) 하다. 이것은 한 번 문자열이 생성되면, 그 문자열을 수정할 수 없다는걸 의미한다. 그러나 원래 문자열에서 일부가 수정된 다른 문자열을 만드는건 가능하다. 예를 들자면 이렇다.

+ + + +

"문자열의 자료형화"를 조심하라!

+ +

문자열을 복잡한 자료형을 표현하는 용도로 쓰는 방법이 꽤나 매력적일 수 있다. 단기적으로 이런 장점들이 있다.

+ + + +

규칙만 잘 정의해놓는다면, 어떤 자료구조가 되던 문자열로 표시할 수 있다. 그렇다고 해서 이게 좋은 방법이 되는 건 아니다. 예를 들자면, 구분자로 리스트 자료형을 흉내낼 수 있을 것이다 (하지만 자바스크립트의 배열을 사용하는게 더 알맞을 것이다). 불행하게도, 리스트의 요소중에 구분자가 들어있는 요소가 있다면 리스트는 엉망진창이 될 것이다. 물론 탈출 문자 (escape character) 등을 사용하거나 할 수도 있을 것이다. 하지만 이런 것들은 모두 미리 정해놓은 규칙을 필요로 하고, 덕분에 불필요한 관리 부담을 낳는다.

+ +

문자열은 텍스트 데이터에만 사용하자. 복잡한 데이터를 나타낼때는, 문자열을 분석해서 적합한 추상화를 선택해 사용하자.

+ +

Symbol 타입

+ +

Symbol 은 ECMAScript 6 에서 추가되었다. Symbol은 유일하고 변경 불가능한 (immutable) 기본값 (primitive value) 이다. 또한, 객체 속성의 key 값으로도 사용될 수 있다 (아래를 볼 것). 몇몇 프로그래밍 언어에서는 Symbol을 atom 이라고 부른다. 또, C 언어의 이름있는 열거형 (enum) 과도 비슷하다. 좀 더 자세히 알아보려면, 자바스크립트의  {{Glossary("Symbol")}} 와 {{jsxref("Symbol")}} 객체 래퍼 (wrapper) 를 보라.

+ +

객체 (Objects)

+ +

컴퓨터 과학에서, 객체는 {{Glossary("Identifier", "식별자 (Identifier)")}} 로 참조할 수 있는, 메모리에 있는 값이다.

+ +

속성 (Properties)

+ +

자바스크립트에서, 객체는 속성들을 담고있는 가방 (collection) 으로 볼 수 있다. 객체 리터럴 문법 (object literal syntax) 으로 제한적으로 몇 가지 속성을 초기화할 수 있고, 그러고 나서 속성들을 추가하거나 제거할 수도 있다. 속성 값은 객체를 포함해 어떠한 자료형도 될 수 있고, 그 덕분에  복잡한 데이터 구조를 형성하는게 가능해진다. 속성은 키 (key) 값으로 식별된다. 키 값은 String 이거나 Symbol 값이다.

+ +

두 종류의 객체 속성이 있는데, 이들은 종류에 따라 특성값들을 가질 수 있다. 데이터 (data) 속성과 접근자 (accessor) 속성이 그것이다.

+ +

데이터 속성 (Data property)

+ +

키에 값을 연결하고, 아래와 같은 특성들 (attribute) 이 있다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
데이터 속성의 특성들
특성 (Attribute)자료형설명기본값
[[Value]]JavaScript 타입 모두 가능이 속성에 대한 get 접근으로 반환되는 값.undefined
[[Writable]]Booleanfalse 라면, 이 속성의 [[Value]] 을 바꿀 수 없다.false
[[Enumerable]]Booleantrue 라면, 이 속성은 for...in 루프에서 열거될 수 있다.false
[[Configurable]]Booleanfalse 라면, 이 속성은 제거될 수 없고, [[Value]]와 [[Writable]] 외에는 수정될 수 없다.false
+ +

접근자 속성 (Accessor property)

+ +

값을 가져오거나 값을 저장하기 위해 키에 하나 혹은 두 개의 접근자 함수 (get, set) 연결짓는다. 아래와 같은 특성이 있다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
접근자 속성
특성 (Attribute)자료형설명기본값
[[Get]]Function 객체 혹은 undefined이 속성의 값에 접근할 때마다, 인자 목록 없이 함수가 호출되고, 함수의 반환된 값으로 속성값을 가져온다. get 을 볼 것undefined
[[Set]]Function 객체 혹은 undefined +

이 속성의 값이 바뀌려고 할 때마다, 할당된 값을 인자로 함수가 호출된다. set 을 볼 것

+
undefined
[[Enumerable]]Booleantrue 라면, 이 속성은 for...in 루프에서 열거될 수 있다.false
[[Configurable]]Booleanfalse 라면, 이 속성은 제거될 수 없고, 데이터 속성을 수정할 수 없다.false
+ +

"Normal" objects, and functions

+ +

자바스크립트 오브젝트는 키와 값의 매핑이다. 키는 문자열이고 값은 다른 어떤 값도 될 수 있다. 오브젝트는 hashmaps을 표현하는데 적합하다. 표준이 아닌 __proto__  슈도 프로퍼티를 사용할 때는 주의하자. 이것을 지원하는 환경에서는 '__proto__'는 오브젝트의 프로토타입을 의미하므로 이 이름을 키로 사용할 수 없다.   속성을 사용할 수 없다. 문자열의 출처가 분명하지 않을 때(입력 필드의 입력값 등)주의가 필요하다. 이런 일이 생길 수도 있다. 이 때는  StringMap abstraction 같은 대안을 사용해보자.함수는 일반 오브젝트에서 호출 가능한 특성을 추가한 오브젝트이다.

+ +

Dates

+ +

시간을 나타내려면 Date utility를 사용하자. 최고의 선택이다.

+ +

Arrays

+ +

배열(Arrays) 는 정수키를 가지는 일련의 값들을 표현하기 위한 오브젝트이다. 배열 오브젝트에는 길이를 나타내는 'length'란 속성도 있다. 배열은 Array.prototype을 상속받으므로 배열을 다룰 때 편한 indexOf (배열에서 값 검색)와 push (새로운 값 추가) 같은 함수를 사용할 수 있다. 배열은 리스트나 집합을 표현하는데 적합하다.

+ +

WeakMaps, Maps, Sets

+ +

표준이 아니지만 ECMAScript 6에서 표준이 될 것 같다.

+ +

이 자료형들에서는 키가 문자열 뿐만 아니라 오브젝트도 될 수 있다. Set은 오브젝트의 집합을 나타내는 반면에 WeakMaps와 Maps는 오브젝트에 값을 연관시킬 수 있다. Map과 WeakMap의 차이는 전자는 오브젝트 키를 열거할 수 있다는 것이다. 이것은 가비지 콜렉션에서 이점을 준다.

+ +

ECMAScript 5를 이용해서 Map과 Set을 구현할 수 있을 것이다. 그러나 오브젝트는 크기 비교가 안된다는 점 때문에(예를들어 어떤 오브젝트는 다른 오브젝트보다 '작다'라고 할 수 없다) look-up에 소요되는 시간이 선형 시간이지 않을 것이다. 네이티브 구현은(WeakMaps를 포함해서) look-up 시간이 거의 로그 시간에서 상수 시간이다.

+ +

DOM 노드에 데이터를 지정하기 위해서 직접 속성을 지정할 수도 있지만 data-* 속성을 사용할 수도 있다. 여기에는 다른 스크립트도 모두 그 속성에 접근할 수 있다는 나쁜 점이 있다. Map과 WeakMap은 오브젝트만 사용할 수 있는 개인 데이터를 쉽게 만들 수 있게 해준다.

+ +

TypedArrays

+ +

표준이 아니지만 ECMAScript 6에서 표준이 될 것 같다.

+ +

더 보기

+ + diff --git a/files/ko/web/javascript/differential_inheritance_in_javascript/index.html b/files/ko/web/javascript/differential_inheritance_in_javascript/index.html new file mode 100644 index 0000000000..70fd4256c3 --- /dev/null +++ b/files/ko/web/javascript/differential_inheritance_in_javascript/index.html @@ -0,0 +1,63 @@ +--- +title: Differential inheritance in JavaScript +slug: Web/JavaScript/Differential_inheritance_in_JavaScript +translation_of: Web/JavaScript/Differential_inheritance_in_JavaScript +--- +

Introduction

+ +

차등 상속(Differential Inheritance)은 자바 스크립트와 같은 프로토 타입 기반 프로그래밍 언어에서 사용되는 일반적인 상속 모델입니다. 대부분의 객체는 다른 일반적인 객체에서 파생되고 몇 가지 작은 측면에서만 차이가 있다는 원칙에 따라 동작합니다. 일반적으로 객체가 다른 다른 객체에 대한 포인터 목록을 내부적으로 유지합니다.

+ +

Example

+ + + +

다음 코드는 개체를 "상속"하는 간단한 메서드 예제입니다.

+ +
Object.prototype.inherit = function(){
+  // Create a new object with this as its prototype
+  var p = Object.create(this);
+
+  /* actually not necessary:
+  // Apply the constructor on the new object
+  this.constructor.apply(p, arguments);
+  */
+
+  return p;
+};
+
+ +

상속(inherit)을 사용하면 일반 프로토 타입에서보다 구체적인 개체를 간단히 파생시킬 수 있습니다. 다음은 상속 방법 및 차등 상속을 사용하여 점점 더 구체적인 객체를 구성하는 간단한 예입니다.

+ +
var root = {}; // Could be any object with any prototype object
+
+var record = root.inherit();
+record.toString = function(){ return "a Record"; };
+
+var person = root.inherit();
+person.firstName = false;
+person.lastName = false;
+person.toString = function(){
+    if (this.firstName) {
+        if (this.lastName) {
+            return this.firstName + " " + this.lastName;
+        } else {
+            return this.firstName;
+        }
+    } else if (this.lastName) {
+        return this.lastName;
+    } else {
+        return "a Person";
+    }
+};
+
+JoePerson = person.inherit();
+JoePerson.firstName = "Joe";
+alert( JoePerson.toString() );
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/enumerability_and_ownership_of_properties/index.html b/files/ko/web/javascript/enumerability_and_ownership_of_properties/index.html new file mode 100644 index 0000000000..41252c39d1 --- /dev/null +++ b/files/ko/web/javascript/enumerability_and_ownership_of_properties/index.html @@ -0,0 +1,331 @@ +--- +title: Enumerability and ownership of properties +slug: Web/JavaScript/Enumerability_and_ownership_of_properties +translation_of: Web/JavaScript/Enumerability_and_ownership_of_properties +--- +
{{JsSidebar("More")}}
+ + + +

'Enumerable properties'(열거 가능한 속성)는 내부 열거 형 플래그가 true로 설정된 property로, 이는 간단한 할당 또는 property initializer (Object.defineProperty를 통해 정의 된 특성 및 이러한 기본 열거 형을 false로 정의한 특성)를 통해 작성된 property의 기본값입니다. 등록 정보의 키가 Symbol이 아니면 열거 가능한 등록 정보가 for...in 루프에 표시됩니다. 'Ownership of properties' (속성의 소유권)은 속성이 프로토 타입 체인이 아닌 개체에 직접 속하는지 여부에 따라 결정됩니다. 객체의 속성도 전체적으로 검색 할 수 있습니다. 개체 속성을 감지, 반복 / 열거 및 검색하는 여러 가지 기본 제공 방법이 있으며 아래 표와 같이 사용할 수 있습니다. 누락 된 범주를 얻는 방법을 보여주는 샘플 코드는 다음과 같습니다.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property enumerability and ownership - built-in methods of detection, retrieval, and iteration
FunctionalityOwn objectOwn object and its prototype chainPrototype chain only
Detection + + + + + + + + + + + + + + + +
EnumerableNonenumerableEnumerable and Nonenumerable
+

propertyIsEnumerable

+ +

hasOwnProperty

+
+

hasOwnProperty – filtered to exclude enumerables using propertyIsEnumerable

+
hasOwnProperty
+
+ + + + + + + + + + + + + + + +
EnumerableNonenumerableEnumerable and Nonenumerable
Not available without extra codeNot available without extra codein
+
Not available without extra code
Retrieval + + + + + + + + + + + + + + + +
EnumerableNonenumerableEnumerable and Nonenumerable
+

Object.keys

+ +

getOwnPropertyNames 

+ +

getOwnPropertySymbols

+
getOwnPropertyNames, getOwnPropertySymbols – filtered to exclude enumerables using propertyIsEnumerable +

getOwnPropertyNames

+ +

getOwnPropertySymbols

+
+
Not available without extra codeNot available without extra code
Iterable + + + + + + + + + + + + + + + +
EnumerableNonenumerableEnumerable and Nonenumerable
+

Object.keys

+ +

getOwnPropertyNames 

+ +

getOwnPropertySymbols

+
getOwnPropertyNames, getOwnPropertySymbols – filtered to exclude enumerables using propertyIsEnumerable +

getOwnPropertyNames

+ +

getOwnPropertySymbols

+
+
+ + + + + + + + + + + + + + + +
EnumerableNonenumerableEnumerable and Nonenumerable
+

for..in

+ +

(excluding symbols)

+
Not available without extra codeNot available without extra code
+
Not available without extra code
+
+ +

Obtaining properties by enumerability/ownership

+ + + +

아래는 모든 경우에 가장 효율적인 알고리즘은 아니지만 빠르게 코드를 작성하여 확인하기 좋습니다.

+ + + +
var SimplePropertyRetriever = {
+    getOwnEnumerables: function(obj) {
+        return this._getPropertyNames(obj, true, false, this._enumerable);
+         // Or could use for..in filtered with hasOwnProperty or just this: return Object.keys(obj);
+    },
+    getOwnNonenumerables: function(obj) {
+        return this._getPropertyNames(obj, true, false, this._notEnumerable);
+    },
+    getOwnEnumerablesAndNonenumerables: function(obj) {
+        return this._getPropertyNames(obj, true, false, this._enumerableAndNotEnumerable);
+        // Or just use: return Object.getOwnPropertyNames(obj);
+    },
+    getPrototypeEnumerables: function(obj) {
+        return this._getPropertyNames(obj, false, true, this._enumerable);
+    },
+    getPrototypeNonenumerables: function(obj) {
+        return this._getPropertyNames(obj, false, true, this._notEnumerable);
+    },
+    getPrototypeEnumerablesAndNonenumerables: function(obj) {
+        return this._getPropertyNames(obj, false, true, this._enumerableAndNotEnumerable);
+    },
+    getOwnAndPrototypeEnumerables: function(obj) {
+        return this._getPropertyNames(obj, true, true, this._enumerable);
+        // Or could use unfiltered for..in
+    },
+    getOwnAndPrototypeNonenumerables: function(obj) {
+        return this._getPropertyNames(obj, true, true, this._notEnumerable);
+    },
+    getOwnAndPrototypeEnumerablesAndNonenumerables: function(obj) {
+        return this._getPropertyNames(obj, true, true, this._enumerableAndNotEnumerable);
+    },
+    // Private static property checker callbacks
+    _enumerable: function(obj, prop) {
+        return obj.propertyIsEnumerable(prop);
+    },
+    _notEnumerable: function(obj, prop) {
+        return !obj.propertyIsEnumerable(prop);
+    },
+    _enumerableAndNotEnumerable: function(obj, prop) {
+        return true;
+    },
+    // Inspired by http://stackoverflow.com/a/8024294/271577
+    _getPropertyNames: function getAllPropertyNames(obj, iterateSelfBool, iteratePrototypeBool, includePropCb) {
+        var props = [];
+
+        do {
+            if (iterateSelfBool) {
+                Object.getOwnPropertyNames(obj).forEach(function(prop) {
+                    if (props.indexOf(prop) === -1 && includePropCb(obj, prop)) {
+                        props.push(prop);
+                    }
+                });
+            }
+            if (!iteratePrototypeBool) {
+                break;
+            }
+            iterateSelfBool = true;
+        } while (obj = Object.getPrototypeOf(obj));
+
+        return props;
+    }
+};
+ +

Detection Table

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
infor..inobj.hasOwnPropertyobj.propertyIsEnumerableObject.keysObject.getOwnPropertyNamesObject.getOwnPropertyDescriptorsReflect.ownKeys()
Enumerabletruetruetruetruetruetruetruetrue
Nonenumerabletruefalsetruefalsefalsetruetruetrue
Symbols keystruefalsetruetruefalsefalsetruetrue
Inherited Enumerabletruetruefalsefalsefalsefalsefalsefalse
Inherited Nonenumerabletruefalsefalsefalsefalsefalsefalsefalse
Inherited Symbols keystruefalsefalsefalsefalsefalsefalsefalse
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/equality_comparisons_and_sameness/index.html b/files/ko/web/javascript/equality_comparisons_and_sameness/index.html new file mode 100644 index 0000000000..31d1778d5d --- /dev/null +++ b/files/ko/web/javascript/equality_comparisons_and_sameness/index.html @@ -0,0 +1,503 @@ +--- +title: 동치 비교 및 동일성 +slug: Web/JavaScript/Equality_comparisons_and_sameness +tags: + - Comparison + - Equality + - Intermediate + - JavaScript + - SameValue + - SameValueZero + - Sameness +translation_of: Web/JavaScript/Equality_comparisons_and_sameness +--- +
{{jsSidebar("Intermediate")}}
+ +
+

ES2015에는 4가지 같음(equality) 알고리즘이 있습니다:

+ + + +

JavaScript는 3가지 서로 다른 값 비교 연산을 제공합니다:

+ + + +

어느 연산을 쓸 지 그 선택은 당신이 어떤 종류의 비교를 수행하기 위해 찾고 있는 지에 달렸습니다.

+ +

 

+ + + +

 

+
+ +

이들 사이의 구분은 모두 원시형(primitive) 처리와 관련이 있습니다. 매개 변수가 구조적, 개념적으로 유사한 지 비교하는 것이 없습니다. 같은 구조를 가지지만 개체 자체가 각각인 비원시형(non-primitive) 개체 x 및 y의 경우 위의 모든 형태(form)는 false로 평가됩니다.

+ +

===를 사용하는 엄격한 같음

+ +

엄격한 같음(strict equality)은 두 값이 같은 지 비교합니다. 어느 값도 비교되기 전에 어떤 다른 값으로 남몰래 변환되지 않습니다. 둘이 서로 다른 형이면, 둘은 같지 않다고 여깁니다. 그렇지 않고 둘이 같은 형이고 숫자가 아닌 경우, 같은 값이면 같다고 여깁니다. 끝으로, 둘이 숫자인 경우, 둘 다 NaN이 아닌 같은 값이거나 하나는 +0 또 하나는 -0인 경우 같다고 여깁니다.

+ +
var num = 0;
+var obj = new String("0");
+var str = "0";
+var b = false;
+
+console.log(num === num); // true
+console.log(obj === obj); // true
+console.log(str === str); // true
+
+console.log(num === obj); // false
+console.log(num === str); // false
+console.log(obj === str); // false
+console.log(null === undefined); // false
+console.log(obj === null); // false
+console.log(obj === undefined); // false
+
+ +

엄격한 같음은 거의 항상 사용하는 올바른 비교 연산입니다. 숫자를 뺀 모든 값에 대해, 분명한 의미(semantics)를 사용합니다: 값은 그 자체와만 같습니다(/ 단지 그 자체입니다). 숫자는 서로 다른 두 극단 상황(edge case)을 얼버무리기(gloss over) 위해 약간 다른 의미를 사용합니다. 첫째는 부동 소수점 0은 양이든 음이든 하나의 부호를 지닙니다. 이는 특정 수학상의 해결책을 나타내는 데 유용하지만, 대부분의 상황에 +0-0의 차이에 신경쓰지 않기에, 엄격한 같음은 둘을 같은 값으로 다룹니다. 둘째는 부동 소수점은 not-a-number 값(NaN) 개념을 포함합니다, 특정 잘못 정의된(ill-defined) 수학 문제의 해결책을 보여주기 위해: 예를 들어, 양의 무한대(infinity)에 추가된 음의 무한대. 엄격한 같음은 NaN을 다른 모든 값과 같지 않게 다룹니다 -- 자신 포함. ((x !== x)true인 유일한 경우는 xNaN일 때입니다.)

+ +

==를 사용하는 느슨한 같음

+ +

느슨한 같음(loose equality)은 두 값이 같은 지 비교합니다, 두 값을 공통(common) 형으로 변환한 에. 변환 후 (하나 또는 양쪽이 변환을 거칠 수 있음), 최종 같음 비교는 꼭 ===처럼 수행됩니다. 느슨한 같음은 대칭(symmetric)입니다: A == BAB가 어떤 값이든 항상 B == A와 같은 의미를 갖습니다 (적용된 변환의 순서 말고는).

+ +

같음 비교는 다양한 형의 피연산자에 대해 다음과 같이 수행됩니다:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 피연산자 B
  UndefinedNullNumberStringBooleanObject
피연산자 AUndefinedtruetruefalsefalsefalsefalse
Nulltruetruefalsefalsefalsefalse
NumberfalsefalseA === BA === ToNumber(B)A === ToNumber(B)A == ToPrimitive(B)
StringfalsefalseToNumber(A) === BA === BToNumber(A) === ToNumber(B)A == ToPrimitive(B)
BooleanfalsefalseToNumber(A) === BToNumber(A) === ToNumber(B)A === BToNumber(A) == ToPrimitive(B)
ObjectfalsefalseToPrimitive(A) == BToPrimitive(A) == BToPrimitive(A) == ToNumber(B)A === B
+ +

위 표에서, ToNumber(A)는 비교 전에 그 인수를 숫자로 변환하려고 시도합니다. 그 동작(behavior)은 +A(단항 + 연산자)에 해당합니다. ToPrimitive(A)는 그 객체 인수를 원시형 값으로 변환하려고 시도합니다, 다양한 순서로 AA.toStringA.valueOf 메서드 호출을 시도하여.

+ +

전통 및 ECMAScript에 따르면, 모든 객체는 undefinednull과 느슨하게 같지 않습니다. 그러나 대부분의 브라우저는 일부 문맥(context)에서 undefined값을 모방하는(emulate) 것처럼 행동하기 위해 매우 좁은 부류의 객체(특히, 모든 페이지에 대한 document.all 객체)에 허용합니다. 느슨한 같음이 그러한 문맥 중 하나입니다: null == Aundefined == A는 A가 undefined모방하는 객체인 경우, 그리고 그 경우에만 true로 평가합니다. 다른 모든 경우에 객체는 결코 undefined 또는 null과 느슨하게 같지 않습니다.

+ +

 

+ +

전통적으로 ECMAScript에 따르면 모든 객체는 undefinednull과 느슨하게 같지 않습니다. 그러나 대부분의 브라우저는 일부 문맥(context)에서 정의되지 않은 값(undefined)을 모방하는(emulate) 것처럼 동작하는 매우 좁은 개체 클래스 (특히 모든 페이지의 document.all 개체)를 허용합니다. Loose equality는 다음과 같은 컨텍스트 중 하나입니다. null == Aundefined == Aundefined를 에뮬레이트하는 객체 인 경우에만 true로 평가됩니다. 다른 모든 경우에는 객체가 undefined거나 null이 될 수 없습니다.

+ +
var num = 0;
+var obj = new String("0");
+var str = "0";
+var b = false;
+
+console.log(num == num); // true
+console.log(obj == obj); // true
+console.log(str == str); // true
+
+console.log(num == obj); // true
+console.log(num == str); // true
+console.log(obj == str); // true
+console.log(null == undefined); // true
+
+// 둘 다 false, 드문 경우를 제외하고는
+console.log(obj == null);
+console.log(obj == undefined);
+
+ +

대부분의 경우 느슨한 같음을 사용하는 것은 바람직하지 않습니다. strict equality를 사용한 비교의 결과는 예측하기가 쉽고 형 강제(coercion) 변환이 일어나지 않기에 평가가 빠를 수 있습니다.

+ +

 

+ +

Same-value equality

+ +

등가(same-value) 같음은 최종 사용 사례(use case)를 다룹니다: 두 값이 모든 문맥에서 기능상 같은지 여부를 결정하는. (이 사용 사례는 리스코프 치환 원칙의 실례를 보입니다.) 다음은 불변 속성(property)을 변화시키려 시도할 때 일어나는 한 사례입니다:

+ +
// 불변(immutable) NEGATIVE_ZERO 속성을 Number 생성자에 추가.
+Object.defineProperty(Number, "NEGATIVE_ZERO",
+                      { value: -0, writable: false, configurable: false, enumerable: false });
+
+function attemptMutation(v)
+{
+  Object.defineProperty(Number, "NEGATIVE_ZERO", { value: v });
+}
+
+ +

Object.defineProperty는 변경 불가능한 속성을 변경하려고 시도 할 때 예외를 throw하지만 실제 변경이 요청되지 않으면 아무 것도 수행하지 않습니다. v-0이면, 변경 사항이 요청되지 않고 오류가 발생하지 않습니다. 내부적으로, 불변의 property가 재정의 (redefined)되었을 때, 새롭게 지정된 값은 같은 값의 동등성을 사용해 현재의 값과 비교됩니다.

+ +

Same-value equality는 {{jsxref("Object.is")}} 메서드로 제공됩니다.

+ +

Same-value-zero equality

+ +

등가 같음과 비슷하지만 +0과 -0이 같다고 여깁니다.

+ +

스펙 내 추상적 같음, 엄격한 같음 및 등가

+ +

In ES5, the comparison performed by == is described in Section 11.9.3, The Abstract Equality Algorithm. The === comparison is 11.9.6, The Strict Equality Algorithm. (Go look at these. They're brief and readable. Hint: read the strict equality algorithm first.) ES5 also describes, in Section 9.12, The SameValue Algorithm for use internally by the JS engine. It's largely the same as the Strict Equality Algorithm, except that 11.9.6.4 and 9.12.4 differ in handling {{jsxref("Number")}}s. ES2015 simply proposes to expose this algorithm through {{jsxref("Object.is")}}.

+ +

We can see that with double and triple equals, with the exception of doing a type check upfront in 11.9.6.1, the Strict Equality Algorithm is a subset of the Abstract Equality Algorithm, because 11.9.6.2–7 correspond to 11.9.3.1.a–f.

+ +

같음 비교를 이해하기 위한 모델은?

+ +

ES2015 이전에, 이중 등호 및 삼중 등호에 대해 하나가 다른 하나의 "확장"판이라고 (말)했을 지 모릅니다. 예를 들어, 누군가는 이중 등호는 삼중 등호의 확장판이라고 합니다, 전자는 후자가 하는 모든 것을 하지만 그 피연산자에 형 변환을 하기에. 가령, 6 == "6". (대신에, 이중 등호는 기준선이고 삼중 등호는 향상판이라고 하는 이도 있습니다, 두 피연산자가 같은 형이길 요구하고 그래서 별도 제약을 추가하기에. 어느 게 더 이해하기 좋은 모델인지는 당신이 상태(things)를 보기 위해 선택한 방법에 달렸습니다.)

+ +

However, this way of thinking about the built-in sameness operators is not a model that can be stretched to allow a place for ES2015's {{jsxref("Object.is")}} on this "spectrum". {{jsxref("Object.is")}} isn't simply "looser" than double equals or "stricter" than triple equals, nor does it fit somewhere in between (i.e., being both stricter than double equals, but looser than triple equals). We can see from the sameness comparisons table below that this is due to the way that {{jsxref("Object.is")}} handles {{jsxref("NaN")}}. Notice that if Object.is(NaN, NaN)evaluated to false, we could say that it fits on the loose/strict spectrum as an even stricter form of triple equals, one that distinguishes between -0 and +0. The {{jsxref("NaN")}} handling means this is untrue, however. Unfortunately, {{jsxref("Object.is")}} simply has to be thought of in terms of its specific characteristics, rather than its looseness or strictness with regard to the equality operators.

+ +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Sameness Comparisons
xy=====Object.isSameValueZero
undefinedundefinedtruetruetruetrue
nullnulltruetruetruetrue
truetruetruetruetruetrue
falsefalsetruetruetruetrue
'foo''foo'truetruetruetrue
00truetruetruetrue
+0-0truetruefalsetrue
+00truetruetruetrue
-00truetruefalsetrue
0falsetruefalsefalsefalse
""falsetruefalsefalsefalse
""0truefalsefalsefalse
'0'0truefalsefalsefalse
'17'17truefalsefalsefalse
[1, 2]'1,2'truefalsefalsefalse
new String('foo')'foo'truefalsefalsefalse
nullundefinedtruefalsefalsefalse
nullfalsefalsefalsefalsefalse
undefinedfalsefalsefalsefalsefalse
{ foo: 'bar' }{ foo: 'bar' }falsefalsefalsefalse
new String('foo')new String('foo')falsefalsefalsefalse
0nullfalsefalsefalsefalse
0NaNfalsefalsefalsefalse
'foo'NaNfalsefalsefalsefalse
NaNNaNfalsefalsetruetrue
+ +

 

+ +

{{jsxref("Object.is")}} 대신 삼중 등호를 사용하는 경우

+ +

In general, the only time {{jsxref("Object.is")}}'s special behavior towards zeros is likely to be of interest is in the pursuit of certain meta-programming schemes, especially regarding property descriptors, when it is desirable for your work to mirror some of the characteristics of {{jsxref("Object.defineProperty")}}. If your use case does not require this, it is suggested to avoid {{jsxref("Object.is")}} and use === instead. Even if your requirements involve having comparisons between two {{jsxref("NaN")}} values evaluate to true, generally it is easier to special-case the {{jsxref("NaN")}} checks (using the {{jsxref("isNaN")}} method available from previous versions of ECMAScript) than it is to work out how surrounding computations might affect the sign of any zeros you encounter in your comparison.

+ +

여기 당신 코드에서 그 자체를 드러내기 위해 -0+0 사이의 구별을 일으킬 수도 있는 철저하지 않은(in-exhaustive) 내장 메서드 및 연산자 목록이 있습니다:

+ +
+
- (unary negation) 
+
+ +
let stoppingForce = obj.mass * -obj.velocity
+ +
+
+

obj.velocity0인 (또는 0으로 계산하는) 경우, -0이 그 자리에 소개되고 stoppingForce로 전해집니다. 

+
+
{{jsxref("Math.atan2")}}
+
{{jsxref("Math.ceil")}}
+
{{jsxref("Math.pow")}}
+
{{jsxref("Math.round")}} 
+
In some cases,it's possible for a -0 to be introduced into an expression as a return value of these methods even when no -0 exists as one of the parameters. For example, using {{jsxref("Math.pow")}} to raise {{jsxref("Infinity", "-Infinity")}} to the power of any negative, odd exponent evaluates to -0. Refer to the documentation for the individual methods. 
+
+ +
+
{jsxref("Math.floor")}}
+
{{jsxref("Math.max")}}
+
{{jsxref("Math.min")}}
+
{{jsxref("Math.sin")}}
+
{{jsxref("Math.sqrt")}}
+
{{jsxref("Math.tan")}} 
+
It's possible to get a -0 return value out of these methods in some cases where a -0 exists as one of the parameters. E.g., Math.min(-0, +0) evaluates to -0. Refer to the documentation for the individual methods.
+
+ +
+
~
+
<<
+
>>
+
이러한 연산자 각각은 내부에서 ToInt32 알고리즘을 사용합니다. 내부 32-bit 정수형에는 0에 대해 한 표현만 있기에, -0은 역(inverse) 연산 후 왕복 여행(round trip, 이중 역 연산)에 살아남지 못합니다. 가령, Object.is(~~(-0), -0)Object.is(-0 << 2 >> 2, -0)false로 평가합니다.
+
+ +

Relying on {{jsxref("Object.is")}} when the signedness of zeros is not taken into account can be hazardous. Of course, when the intent is to distinguish between -0 and +0, it does exactly what's desired.

+ +

Caveat: {{jsxref("Object.is")}} and NaN

+ +

The {{jsxref("Object.is")}} specification treats all instances of {{jsxref("NaN")}} as the same object. However, since typed arrays are available, we can have distinct instances, which don't behave identically in all contexts. For example:

+ +
var f2b = x => new Uint8Array(new Float64Array([x]).buffer);
+var b2f = x => new Float64Array(x.buffer)[0];
+var n = f2b(NaN);
+n[0] = 1;
+var nan2 = b2f(n);
+nan2;
+// > NaN
+Object.is(nan2, NaN);
+// > true
+f2b(NaN);
+// > Uint8Array(8) [0, 0, 0, 0, 0, 0, 248,127)
+f2b(nan2);
+// > Uint8Array(8) [1, 0, 0, 0, 0, 0, 248,127)
+ +

참조

+ + diff --git a/files/ko/web/javascript/eventloop/index.html b/files/ko/web/javascript/eventloop/index.html new file mode 100644 index 0000000000..bc4330700d --- /dev/null +++ b/files/ko/web/javascript/eventloop/index.html @@ -0,0 +1,147 @@ +--- +title: 동시성 모델과 이벤트 루프 +slug: Web/JavaScript/EventLoop +tags: + - 이벤트 루프 +translation_of: Web/JavaScript/EventLoop +--- +
{{JsSidebar("Advanced")}}
+ +

자바스크립트는 코드 실행, 이벤트 수집과 처리, 큐에 놓인 하위 작업들을 담당하는 이벤트 루프에 기반한 동시성(concurrency) 모델을 가지고 있습니다. 이 모델은 C 또는 Java와 같은 언어와 완전히 다릅니다.

+ +

런타임 개념

+ +

이어지는 섹션에서는 이론적 모델을 설명합니다. 모던 자바스크립트 엔진들은 아래 묘사된 개념들을 구현하고 최적화 합니다.

+ +

시각적 표현

+ +

Stack, heap, queue

+ +

Stack

+ +

함수 호출은 프레임들의 스택을 형성합니다.

+ +
function foo(b) {
+  var a = 10;
+  return a + b + 11;
+}
+
+function bar(x) {
+  var y = 3;
+  return foo(x * y);
+}
+
+console.log(bar(7)); //returns 42
+ +

bar를 호출할 때, bar의 인자와 지역 변수를 포함하는 첫 번째 프레임이 생성됩니다. barfoo를 호출하면 두 번째 프레임이 만들어져 foo의 인수와 지역 변수가 들어있는 첫 번째 프레임의 맨 위에 푸시됩니다. foo가 반환되면, 최상위 프레임 요소는 bar의 호출 프레임만을 남겨둔 채로 스택 밖으로 빠져나옵니다. bar가 반환되면, 스택은 비워집니다.

+ +

Heap

+ +

객체들은 힙 안에 할당됩니다. 힙은 구조화되지 않은 넓은 메모리 영역을 지칭합니다.

+ +

Queue

+ +

JavaScript 런타임은 처리 할 메시지 목록 인 메시지 대기열을 사용합니다. 각 메시지에는 메시지를 처리하기 위해 호출되는 관련 함수가 있습니다.

+ +

{{anch("Event loop", "event loop")}} 중 어떤 시점에서 런타임은 대기열에서 가장 오래된 메시지부터 처리하기 시작합니다. 그렇게하기 위해, 메시지는 큐에서 제거되고 해당 기능이 메시지를 입력 매개 변수로 호출됩니다. 언제나 그렇듯이, 함수를 호출하면 그 함수의 사용을위한 새로운 스택 프레임이 생성됩니다.

+ +

함수의 처리는 스택이 다시 비워 질 때까지 계속됩니다. 이벤트 루프는 큐의 다음 메시지를 처리합니다(존재할 경우).

+ +

Event loop

+ +

Event loop는 그 구현 방식 때문에 붙은 이름이며 보통 다음과 유사합니다 :

+ +
while(queue.waitForMessage()){
+  queue.processNextMessage();
+}
+ +

queue.waitForMessage() 함수는 현재 아무 메시지도 없다면 새로운 메시지 도착을 동기적으로 기다립니다.

+ +

"Run-to-completion"

+ +

각 메시지는 다른 메시지가 처리되기 전에 완전히 처리됩니다.

+ +

이것은 함수가 실행될 때마다 미리 비워질 수 없고 다른 코드가 실행되기 전에 완전히 실행되며 함수가 조작하는 데이터를 수정할 수 있다는 사실을 포함하여 프로그램에 대한 추론을 할 때 좋은 속성을 제공합니다. 이것은 C와는 다릅니다. 예를 들어 함수가 쓰레드에서 실행된다면 런타임 시스템이 다른 쓰레드에서 다른 코드를 실행하기 위해 어느 시점에서 멈출 수 있습니다.

+ +

이 모델의 부정적인 면은 어떤 메시지가 완료되기 까지 지나치게 오래 걸린다면 웹 어플리케이션은 클릭이나 스크롤과 같은 사용자 인터랙션을 처리할 수 없게 됩니다. 브라우저는 이러한 상황을 "a script is taking too long to run"과 같은 대화상자로 완화 합니다. 추천되는 좋은 방법은 메시지 처리를 짧도록 만드는 것과 하나의 메시지를 여러개의 메시지로 나누는 것 입니다.

+ +

메시지 추가하기

+ +

웹 브라우저에서 이벤트 리스너가 부착된 이벤트가 발생할 때마다 메시지가 추가됩니다. 리스너가 없으면 이벤트는 손실됩니다. 클릭 이벤트 핸들러가 있는 요소를 클릭하면 다른 이벤트와 마찬가지로 메시지가 추가됩니다.

+ +

setTimeout 함수는 2 개의 인수, 대기열에 추가 할 메시지와 시간값(선택사항, 기본값은 0)으로 호출됩니다. 시간 값은 메시지가 실제로 큐에 푸시 될 때까지의 (최소) 지연을 나타냅니다. 대기열에 다른 메시지가 없으면 지연 직후에 메시지가 처리됩니다. 그러나 메시지가있는 경우 setTimeout 메시지는 다른 메시지가 처리 될 때까지 기다려야합니다. 따라서 두 번째 인수는 최소 시간을 나타내지 만 보장 된 시간은 아닙니다.

+ +

다음은 이 개념에 대한 예제입니다 (setTimeout은 타이머 만료 직후에 실행되지 않습니다).

+ +
const s = new Date().getSeconds();
+
+setTimeout(function() {
+  // prints out "2", meaning that the callback is not called immediately after 500 milliseconds.
+  console.log("Ran after " + (new Date().getSeconds() - s) + " seconds");
+}, 500);
+
+while(true) {
+  if(new Date().getSeconds() - s >= 2) {
+    console.log("Good, looped for 2 seconds");
+    break;
+  }
+}
+ +

Zero delays

+ +

Zero delay는 실제로 0ms 후에 콜백이 시작된다는 의미는 아닙니다. 0ms 지연된 {{domxref("WindowTimers.setTimeout", "setTimeout")}}은 주어진 간격 후에 콜백 함수를 실행하지 않습니다.

+ +

실행은 큐에 대기중인 작업 수에 따라 다릅니다. 아래 예에서, 콜백의 메시지가 처리되기 전에 콘솔에 "this is just message"메시지가 기록됩니다. 왜냐하면 지연(delay)은 보장된 시간이 아니라 요청을 처리하기 위해 필요한 최소의 시간이기 때문입니다.

+ +

기본적으로 setTimeout은 setTimeout에 대한 특정 시간 제한을 지정 했더라도 대기중인 메시지의 모든 코드가 완료 될 때까지 대기해야합니다.

+ +
(function() {
+
+  console.log('this is the start');
+
+  setTimeout(function cb() {
+    console.log('this is a msg from call back');
+  });
+
+  console.log('this is just a message');
+
+  setTimeout(function cb1() {
+    console.log('this is a msg from call back1');
+  }, 0);
+
+  console.log('this is the end');
+
+})();
+
+// "this is the start"
+// "this is just a message"
+// "this is the end"
+// note that function return, which is undefined, happens here
+// "this is a msg from call back"
+// "this is a msg from call back1"
+ +

몇가지 런타임 통신

+ +

웹워커 또는 크로스 오리진 iframe은 자신의 스택, 힙, 메시지 큐를 가지고 있습니다. 두 별개의 런타임들은 postMessage method를 통해서만 서로 통신할 수 있습니다. 이 메서드는 다른 런타임이 message 이벤트 핸들러를 등록하고 있다면 해당 런타임의 큐에 메시지를 추가합니다.

+ +

Never blocking

+ +

이벤트 루프 모델의 무척 재밌는 부분은 다른 언어와 달리 자바스크립트는 결코 Block하지 않는다는 것입니다. I/O 처리는 흔히 이벤트와 콜백으로 처리 됩니다. 그래서 응용프로그램이 IndexedDB query 반환을 기다리고 있거나 XHR 요청 반환을 기다릴 때에도 여전히 사용자 입력과 같은 다른 것을을 처리할 수 있습니다.

+ +

alert 또는 synchronous XHR과 같은 구현 예외가 존재 합니다. 그러나 그것들은 사용되지 않는 것이 좋다라고 여겨집니다. 예외를 위한 예외를 조심하세요 (그러나 보통 구현 버그일뿐 그이상 아무것도 아닙니다).

+ +

명세

+ + + + + + + + + + + + + +
명세
{{SpecName('HTML WHATWG', 'webappapis.html#event-loops', 'Event loops')}}
Node.js Event Loop
diff --git a/files/ko/web/javascript/guide/closures/index.html b/files/ko/web/javascript/guide/closures/index.html new file mode 100644 index 0000000000..b56d843b2b --- /dev/null +++ b/files/ko/web/javascript/guide/closures/index.html @@ -0,0 +1,454 @@ +--- +title: 클로저 +slug: Web/JavaScript/Guide/Closures +tags: + - Closure + - ES5 + - Intermediate + - JavaScript + - Reference +translation_of: Web/JavaScript/Closures +--- +
{{jsSidebar("Intermediate")}}
+ +

클로저는 함수와 함수가 선언된 어휘적 환경의 조합이다. 클로저를 이해하려면 자바스크립트가 어떻게 변수의 유효범위를 지정하는지(Lexical scoping)를 먼저 이해해야 한다.

+ +

어휘적 범위 지정(Lexical scoping)

+ +

다음을 보자:

+ +
function init() {
+  var name = "Mozilla"; // name은 init에 의해 생성된 지역 변수이다.
+  function displayName() { // displayName() 은 내부 함수이며, 클로저다.
+    alert(name); // 부모 함수에서 선언된 변수를 사용한다.
+  }
+  displayName();
+}
+init();
+ +

init()은 지역 변수 name과 함수 displayName()을 생성한다. displayName()init() 안에 정의된 내부 함수이며 init() 함수 본문에서만 사용할 수 있다. 여기서 주의할 점은 displayName() 내부엔 자신만의 지역 변수가 없다는 점이다. 그런데 함수 내부에서 외부 함수의 변수에 접근할 수 있기 때문에 displayName() 역시 부모 함수 init()에서 선언된 변수 name에 접근할 수 있다. 만약 displayName()가 자신만의 name변수를 가지고 있었다면, name대신 this.name을 사용했을 것이다.

+ +

{{JSFiddleEmbed("https://jsfiddle.net/78dg25ax/", "js,result", 250)}}

+ +

위 코드를 실행하면 displayName() 함수 내의 alert()문이 부모 함수에서 정의한 변수 name의 값을 성공적으로 출력한다. 이 예시를 통해 함수가 중첩된 상황에서 파서가 어떻게 변수를 처리하는지 알 수 있다. 이는 어휘적 범위 지정(lexical scoping)의 한 예이다. 여기서 "lexical"이란, 어휘적 범위 지정(lexical scoping) 과정에서 변수가 어디에서 사용 가능한지 알기 위해 그 변수가 소스코드 내 어디에서 선언되었는지 고려한다는 것을 의미한다. 단어 "lexical"은 이런 사실을 나타낸다. 중첩된 함수는 외부 범위(scope)에서 선언한 변수에도 접근할 수 있다.

+ +

클로저(Closure)

+ +

이제 다음 예제를 보자:

+ +
function makeFunc() {
+  var name = "Mozilla";
+  function displayName() {
+    alert(name);
+  }
+  return displayName;
+}
+
+var myFunc = makeFunc();
+//myFunc변수에 displayName을 리턴함
+//유효범위의 어휘적 환경을 유지
+myFunc();
+//리턴된 displayName 함수를 실행(name 변수에 접근)
+ +

이 코드는 바로 전의 예제와 완전히 동일한 결과가 실행된다. 하지만 흥미로운 차이는 displayName()함수가 실행되기 전에 외부함수인 makeFunc()로부터 리턴되어 myFunc 변수에 저장된다는 것이다.

+ +

한 눈에 봐서는 이 코드가 여전히 작동하는 것이 직관적으로 보이지 않을 수 있다. 몇몇 프로그래밍 언어에서, 함수 안의 지역 변수들은 그 함수가 처리되는 동안에만 존재한다. makeFunc() 실행이 끝나면(displayName함수가 리턴되고 나면) name 변수에 더 이상 접근할 수 없게 될 것으로 예상하는 것이 일반적이다.

+ +

하지만 위의 예시와 자바스크립트의 경우는 다르다. 그 이유는 자바스크립트는 함수를 리턴하고, 리턴하는 함수가 클로저를 형성하기 때문이다. 클로저는 함수와 함수가 선언된 어휘적 환경의 조합이다. 이 환경은 클로저가 생성된 시점의 유효 범위 내에 있는 모든 지역 변수로 구성된다. 첫 번째 예시의 경우, myFuncmakeFunc이 실행될 때 생성된 displayName 함수의 인스턴스에 대한 참조다. displayName의 인스턴스는 변수 name 이 있는 어휘적 환경에 대한 참조를 유지한다. 이런 이유로 myFunc가 호출될 때 변수 name은 사용할 수 있는 상태로 남게 되고 "Mozilla" 가 alert 에 전달된다.

+ +

다음은 조금 더 흥미로운 예제인 makeAdder 함수이다:

+ +
function makeAdder(x) {
+  var y = 1;
+  return function(z) {
+    y = 100;
+    return x + y + z;
+  };
+}
+
+var add5 = makeAdder(5);
+var add10 = makeAdder(10);
+//클로저에 x와 y의 환경이 저장됨
+
+console.log(add5(2));  // 107 (x:5 + y:100 + z:2)
+console.log(add10(2)); // 112 (x:10 + y:100 + z:2)
+//함수 실행 시 클로저에 저장된 x, y값에 접근하여 값을 계산
+
+
+ +

이 예제에서 단일 인자 x를 받아서 새 함수를 반환하는 함수 makeAdder(x)를 정의했다. 반환되는 함수는 단일 인자 z를 받아서 x와 y와 z의 합을 반환한다.

+ +

본질적으로 makeAdder는 함수를 만들어내는 공장이다. 이는 makeAdder함수가 특정한 값을 인자로 가질 수 있는 함수들을 리턴한다는 것을 의미한다. 위의 예제에서 add5, add10 두 개의 새로운 함수들을 만들기 위해 makeAdder함수 공장을 사용했다. 하나는 매개변수 x에 5를 더하고 다른 하나는 매개변수 x에 10을 더한다.

+ +

add5add10은 둘 다 클로저이다. 이들은 같은 함수 본문 정의를 공유하지만 서로 다른 맥락(어휘)적 환경을 저장한다. 함수 실행 시 add5의 맥락적 환경에서 클로저 내부의 x는 5 이지만 add10의 맥락적 환경에서 x는 10이다. 또한 리턴되는 함수에서 초기값이 1로 할당된 y에 접근하여 y값을 100으로 변경한 것을 볼 수 있다. (물론 x값도 동일하게 변경 가능하다.) 이는 클로저가 리턴된 후에도 외부함수의 변수들에 접근 가능하다는 것을 보여주는 포인트이며 클로저에 단순히 값 형태로 전달되는 것이 아니라는 것을 의미한다.

+ +

실용적인 클로저

+ +

클로저는 어떤 데이터(어휘적 환경)와 그 데이터를 조작하는 함수를 연관시켜주기 때문에 유용하다. 이것은 객체가 어떤 데이터와(그 객체의 속성) 하나 혹은 그 이상의 메소드들을 연관시킨다는 점에서 객체지향 프로그래밍과 분명히 같은 맥락에 있다.

+ +

결론적으로 오직 하나의 메소드를 가지고 있는 객체를 일반적으로 사용하는 모든 곳에 클로저를 사용할 수 있다.

+ +

이렇게 할 수 있는 상황은 특히 웹에서 일반적이다. 프론트 엔드 자바스크립트에서 우리가 쓰는 많은 코드가 이벤트 기반이다. 우리는 몇 가지 동작을 정의한 다음 사용자에 의한 이벤트에(클릭 혹은 키 누르기 같은) 연결한다. 우리의 코드는 일반적으로 콜백으로 첨부된다: 이벤트에 응답하여 실행되는 단일 함수다.

+ +

예를 들면 페이지의 글자 크기를 조정하는 몇 개의 버튼을 추가한다고 가정하자. 이 작업을 수행하는 한 가지 방법은 body 요소의 font-size를 픽셀 단위로 지정하고 상대적인 em 단위를 사용하여 페이지의 다른 요소들의 (예: 헤더) 크기를 설정하는 것이다.

+ +
body {
+  font-family: Helvetica, Arial, sans-serif;
+  font-size: 12px;
+}
+
+h1 {
+  font-size: 1.5em;
+}
+
+h2 {
+  font-size: 1.2em;
+}
+
+ +

우리의 대화식 글자 크기 버튼들은 body 요소의 font-size 속성을 변경할 수 있고 이런 조정은 상대적 단위들 덕분에 페이지의 다른 요소에 의해 선택된다.

+ +

여기 자바스크립트 코드가 있다.

+ +
function makeSizer(size) {
+  return function() {
+    document.body.style.fontSize = size + 'px';
+  };
+}
+
+var size12 = makeSizer(12);
+var size14 = makeSizer(14);
+var size16 = makeSizer(16);
+
+ +

size12, size14, size16은 body 요소의 글자 크기를 각각 12, 14, 16 픽셀로 바꾸는 함수이다. 이 함수들을 아래처럼 버튼들에(이 경우에는 링크) 연결할 수 있다.

+ +
document.getElementById('size-12').onclick = size12;
+document.getElementById('size-14').onclick = size14;
+document.getElementById('size-16').onclick = size16;
+
+ +
<a href="#" id="size-12">12</a>
+<a href="#" id="size-14">14</a>
+<a href="#" id="size-16">16</a>
+
+ +

{{JSFiddleEmbed("https://jsfiddle.net/vnkuZ/","","200")}}

+ +

클로저를 이용해서 프라이빗 메소드 (private method) 흉내내기

+ +

자바와 같은 몇몇 언어들은 메소드를 프라이빗으로 선언할 수 있는 기능을 제공한다. 이는 같은 클래스 내부의 다른 메소드에서만 그 메소드들을 호출할 수 있다는 의미이다.

+ +

자바스크립트는 태생적으로는 이런 방법을 제공하지 않지만 클로저를 이용하여 프라이빗 메소드를 흉내내는 것이 가능하다. 프라이빗 메소드는 코드에 제한적인 접근만을 허용한다는 점 뿐만 아니라 전역 네임 스페이스를 관리하는 강력한 방법을 제공하여 불필요한 메소드가 공용 인터페이스를 혼란스럽게 만들지 않도록 한다.

+ +

아래 코드는 프라이빗 함수와 변수에 접근하는 퍼블릭 함수를 정의하기 위해 클로저를 사용하는 방법을 보여준다. 이렇게 클로저를 사용하는 것을 모듈 패턴이라 한다.

+ +
var counter = (function() {
+  var privateCounter = 0;
+  function changeBy(val) {
+    privateCounter += val;
+  }
+  return {
+    increment: function() {
+      changeBy(1);
+    },
+    decrement: function() {
+      changeBy(-1);
+    },
+    value: function() {
+      return privateCounter;
+    }
+  };
+})();
+
+console.log(counter.value()); // logs 0
+counter.increment();
+counter.increment();
+console.log(counter.value()); // logs 2
+counter.decrement();
+console.log(counter.value()); // logs 1
+
+ +

이전 예제에서 각 클로저들이 고유한 문법적 환경을 가졌지만 여기서 우리는 counter.increment, counter.decrement, counter.value 세 함수에 의해 공유되는 하나의 어휘적 환경을 만든다.

+ +

공유되는 어휘적 환경은 실행되는 익명 함수 안에서 만들어진다. 이 익명 함수는 정의되는 즉시 실행된다. 이 어휘적 환경은 두 개의 프라이빗 아이템을 포함한다. 하나는 privateCounter라는 변수이고 나머지 하나는 changeBy라는 함수이다. 둘 다 익명 함수 외부에서 접근될 수 없다. 대신에 익명 래퍼에서 반환된 세 개의 퍼블릭 함수를 통해서만 접근되어야만 한다.

+ +

위의 세 가지 퍼블릭 함수는 같은 환경을 공유하는 클로저다. 자바스크립트의 어휘적 유효 범위 덕분에 세 함수 각각 privateCounter 변수와 changeBy 함수에 접근할 수 있다.

+ +

카운터를 생성하는 익명 함수를 정의하고 그 함수를 즉시 호출하고 결과를 counter 변수에 할당하는 것을 알아차렸을 것이다. 이 함수를 별도의 변수 makeCounter 저장하고 이 변수를 이용해 여러 개의 카운터를 만들 수 있다.

+ +
var makeCounter = function() {
+  var privateCounter = 0;
+  function changeBy(val) {
+    privateCounter += val;
+  }
+  return {
+    increment: function() {
+      changeBy(1);
+    },
+    decrement: function() {
+      changeBy(-1);
+    },
+    value: function() {
+      return privateCounter;
+    }
+  }
+};
+
+var counter1 = makeCounter();
+var counter2 = makeCounter();
+alert(counter1.value()); /* 0 */
+counter1.increment();
+counter1.increment();
+alert(counter1.value()); /* 2 */
+counter1.decrement();
+alert(counter1.value()); /* 1 */
+alert(counter2.value()); /* 0 */
+
+ +

두 개의 카운터가 어떻게 다른 카운터와 독립성을 유지하는지 주목해보자. 각 클로저는 그들 고유의 클로저를 통한 privateCounter 변수의 다른 버전을 참조한다. 각 카운터가 호출될 때마다; 하나의 클로저에서 변수 값을 변경해도 다른 클로저의 값에는 영향을 주지 않는다.

+ +

이런 방식으로 클로저를 사용하여 객체지향 프로그래밍의 정보 은닉과 캡슐화 같은 이점들을 얻을 수 있다.

+ +

클로저 스코프 체인

+ +

모든 클로저에는 세가지 스코프(범위)가 있다:-

+ + + +

따라서, 우리는 클로저에 대해 세가지 범위 모두 접근할 수 있지만, 중첩된 내부 함수가 있는 경우 종종 실수를 저지른다. 아래 예제를 확인해보자:

+ +
// 전역 범위 (global scope)
+var e = 10;
+function sum(a){
+  return function(b){
+    return function(c){
+      // 외부 함수 범위 (outer functions scope)
+      return function(d){
+        // 지역 범위 (local scope)
+        return a + b + c + d + e;
+      }
+    }
+  }
+}
+
+console.log(sum(1)(2)(3)(4)); // log 20
+
+// 익명 함수 없이 작성할 수도 있다.
+
+// 전역 범위 (global scope)
+var e = 10;
+function sum(a){
+  return function sum2(b){
+    return function sum3(c){
+      // 외부 함수 범위 (outer functions scope)
+      return function sum4(d){
+        // 지역 범위 (local scope)
+        return a + b + c + d + e;
+      }
+    }
+  }
+}
+
+var s = sum(1);
+var s1 = s(2);
+var s2 = s1(3);
+var s3 = s2(4);
+console.log(s3) //log 20
+ +

위의 예제를 보면 일련의 중첩된 함수들을 확인할 수 있다. 이 함수들은 전부 외부 함수의 스코프에 접근할 수 있다. 그런데 문제는 즉각적인 외부 함수의 스코프만을 추측한다는 것이다. 이 문맥에서는 모든 클로저가 선언된 외부 함수의 스코프에 접근한다라고 말할 수 있다.

+ +

루프에서 클로저 생성하기: 일반적인 실수

+ +

ECMAScript 2015의 let 키워드 소개 전에는 클로저와 관련된 일반적인 문제는 루프 안에서 클로저가 생성되었을 때 발생한다.다음 예제를 보자.

+ +
<p id="help">Helpful notes will appear here</p>
+<p>E-mail: <input type="text" id="email" name="email"></p>
+<p>Name: <input type="text" id="name" name="name"></p>
+<p>Age: <input type="text" id="age" name="age"></p>
+
+ +
function showHelp(help) {
+  document.getElementById('help').innerHTML = help;
+}
+
+function setupHelp() {
+  var helpText = [
+      {'id': 'email', 'help': 'Your e-mail address'},
+      {'id': 'name', 'help': 'Your full name'},
+      {'id': 'age', 'help': 'Your age (you must be over 16)'}
+    ];
+
+  for (var i = 0; i < helpText.length; i++) {
+    var item = helpText[i];
+    document.getElementById(item.id).onfocus = function() {
+      showHelp(item.help);
+    }
+  }
+}
+
+setupHelp();
+
+ +

{{JSFiddleEmbed("https://jsfiddle.net/v7gjv/", "", 200)}}

+ +

helpText 배열은 세 개의 도움말 힌트를 정의한다. 각 도움말은 문서의 입력 필드의 ID와 연관된다. 루프를 돌면서 각 입력 필드 ID에 해당하는 엘리먼트의 onfocus 이벤트에 관련된 도움말을 보여주는 메소드에 연결한다.

+ +

이 코드를 사용하면 제대로 동작하지 않는 것을 알게 된다. 어떤 필드에 포커스를 주더라도 나이에 관한 도움말이 표시된다.

+ +

onfocus 이벤트에 연결된 함수가 클로저이기 때문이다. 이 클로저는 함수 정의와 setupHelp 함수 범위에서 캡처된 환경으로 구성된다. 루프에서 세 개의 클로저가 만들어졌지만 각 클로저는 값이 변하는 변수가 (item.help) 있는 같은 단일 환경을 공유한다. onfocus 콜백이 실행될 때 콜백의 환경에서 item 변수는 (세개의 클로저가 공유한다) helpText 리스트의 마지막 요소를 가리키고 있을 것이다.

+ +

이 경우 한 가지 해결책은 더 많은 클로저를 사용하는 것이다: 특히 앞에서 설명한 함수 팩토리를 사용하는 것이다.

+ +
function showHelp(help) {
+  document.getElementById('help').innerHTML = help;
+}
+
+function makeHelpCallback(help) {
+  return function() {
+    showHelp(help);
+  };
+}
+
+function setupHelp() {
+  var helpText = [
+      {'id': 'email', 'help': 'Your e-mail address'},
+      {'id': 'name', 'help': 'Your full name'},
+      {'id': 'age', 'help': 'Your age (you must be over 16)'}
+    ];
+
+  for (var i = 0; i < helpText.length; i++) {
+    var item = helpText[i];
+    document.getElementById(item.id).onfocus = makeHelpCallback(item.help);
+  }
+}
+
+setupHelp();
+
+ +

{{JSFiddleEmbed("https://jsfiddle.net/v7gjv/1/", "", 300)}}

+ +

이것은 예상대로 동작한다. 모두 단일 환경을 공유하는 콜백대신, makeHelpCallback 함수는 각각의 콜백에 새로운 어휘적 환경을 생성한다. 여기서 help는 helpText 배열의 해당 문자열을 나타낸다.

+ +

익명 클로저를 사용하여 위 코드를 작성하는 또 다른 방법은 다음과 같다.

+ +
function showHelp(help) {
+  document.getElementById('help').innerHTML = help;
+}
+
+function setupHelp() {
+  var helpText = [
+      {'id': 'email', 'help': 'Your e-mail address'},
+      {'id': 'name', 'help': 'Your full name'},
+      {'id': 'age', 'help': 'Your age (you must be over 16)'}
+    ];
+
+  for (var i = 0; i < helpText.length; i++) {
+    (function() {
+       var item = helpText[i];
+       document.getElementById(item.id).onfocus = function() {
+         showHelp(item.help);
+       }
+    })(); // Immediate event listener attachment with the current value of item (preserved until iteration).
+  }
+}
+
+setupHelp();
+ +

더 많은 클로저를 사용하는 것이 싫다면 ES2015의 let 키워드를 사용할 수 있다.

+ +
function showHelp(help) {
+  document.getElementById('help').innerHTML = help;
+}
+
+function setupHelp() {
+  var helpText = [
+      {'id': 'email', 'help': 'Your e-mail address'},
+      {'id': 'name', 'help': 'Your full name'},
+      {'id': 'age', 'help': 'Your age (you must be over 16)'}
+    ];
+
+  for (var i = 0; i < helpText.length; i++) {
+    let item = helpText[i];
+    document.getElementById(item.id).onfocus = function() {
+      showHelp(item.help);
+    }
+  }
+}
+
+setupHelp();
+ +

위의 경우 var 대신 let을 사용하여 모든 클로저가 블록 범위 변수를 바인딩할 것이므로 추가적인 클로저를 사용하지 않아도 완벽하게 동작할 것이다.

+ +

성능 관련 고려 사항

+ +

특정 작업에 클로저가 필요하지 않는데 다른 함수 내에서 함수를 불필요하게 작성하는 것은 현명하지 않다. 이것은 처리 속도와 메모리 소비 측면에서 스크립트 성능에 부정적인 영향을 미칠 것이다.

+ +

예를 들어, 새로운 객체/클래스를 생성 할 때, 메소드는 일반적으로 객체 생성자에 정의되기보다는 객체의 프로토타입에 연결되어야 한다. 그 이유는 생성자가 호출 될 때마다 메서드가 다시 할당되기 때문이다 (즉, 모든 개체가 생성 될 때마다).

+ +

비실용적이지만 시범적인 다음 예를 고려하라:

+ +
function MyObject(name, message) {
+  this.name = name.toString();
+  this.message = message.toString();
+  this.getName = function() {
+    return this.name;
+  };
+
+  this.getMessage = function() {
+    return this.message;
+  };
+}
+
+ +

앞의 코드는 클로저의 이점을 이용하지 않음으로 다음과 같이 다시 쓸 수 있다.

+ +
function MyObject(name, message) {
+  this.name = name.toString();
+  this.message = message.toString();
+}
+MyObject.prototype = {
+  getName: function() {
+    return this.name;
+  },
+  getMessage: function() {
+    return this.message;
+  }
+};
+
+ +

그러나 프로토타입을 다시 정의하는 것은 권장되지 않음으로 기존 프로토타입에 추가하는 다음 예제가 더 좋다.

+ +
function MyObject(name, message) {
+  this.name = name.toString();
+  this.message = message.toString();
+}
+MyObject.prototype.getName = function() {
+  return this.name;
+};
+MyObject.prototype.getMessage = function() {
+  return this.message;
+};
+
+ +

위의 코드는 같은 결과를 가진 더 깨끗한 방법으로 작성할 수도 있다:

+ +
function MyObject(name, message) {
+    this.name = name.toString();
+    this.message = message.toString();
+}
+(function() {
+    this.getName = function() {
+        return this.name;
+    };
+    this.getMessage = function() {
+        return this.message;
+    };
+}).call(MyObject.prototype);
+
+ +

앞의 두 가지 예제에서 상속된 프로토타입은 모든 객체에서 공유될 수 있으며 메소드 정의는 모든 객체 생성시 발생할 필요가 없다. 객체 모델의 세부 사항을 참고하라.

diff --git a/files/ko/web/javascript/guide/control_flow_and_error_handling/index.html b/files/ko/web/javascript/guide/control_flow_and_error_handling/index.html new file mode 100644 index 0000000000..fa007d6997 --- /dev/null +++ b/files/ko/web/javascript/guide/control_flow_and_error_handling/index.html @@ -0,0 +1,433 @@ +--- +title: 제어 흐름과 에러 처리 +slug: Web/JavaScript/Guide/Control_flow_and_error_handling +tags: + - 가이드 + - 자바 스크립트 + - 초보자 +translation_of: Web/JavaScript/Guide/Control_flow_and_error_handling +--- +

{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}

+ +

JavaScript는 어플리케이션 상의 상호작용을 통합하는데 사용할 수 있는 일련의 문법, 특히 제어흐름 문을 지원합니다. 이 장에서는 이러한 문법의 개요를 제공합니다.

+ +

JavaScript reference는 이 장의 문법에 대한 철저하고 자세한 내용은 포함하고 있습니다. 세미콜론 (;) 은 JavaScript 코드 상에서 문장을 나누는데 사용됩니다. 

+ +

 JavaScript 표현식도 문법입니다. 표현식에 대한 자세한 내용은 Expressions and operators를 참조하세요.

+ +

Block 문

+ +

Block 문은 코드를 묶는 가장 기본적인 문법입니다. Block 문은 중괄호 ( { } )에 의해 범위가 결정됩니다.

+ +
{
+  statement_1;
+  statement_2;
+  .
+  .
+  .
+  statement_n;
+}
+
+ +

예시

+ +

Block 문은 일반적으로 제어 흐름 문(if, for, while)과 함께  사용됩니다.

+ +
while (x < 10) {
+  x++;
+}
+
+ +

여기서, { x++; }는 block 문입니다.

+ +

중요: ECMAScript2015 이전의 JavaScript는 블록 범위를 가지고 있지 않습니다. Block 내에서 선언한 변수는 블록을 넘어 변수가 위치한 함수 혹은 스크립트에 영향을 끼치게 됩니다.즉, block 문은 변수의 범위를 정의하지 않습니다. 자바스크립트의 "독립" block 은 C 혹은 Java의 그것과 완전히 다른 결과를 가집니다. 예를 들어:

+ +
var x = 1;
+{
+  var x = 2;
+}
+console.log(x); // outputs 2
+
+ +

블록 내에 var x 문이 블록 전에 var x 문과 같은 범위에 있기 때문에 2를 출력합니다. C 나 Java에서 해당 코드는 1을 출력합니다.

+ +

ECMAScript2015부터, let 그리고 const 변수 선언으로 변수의 블록 범위를 제한할 수 있습니다. 자세한 내용은 {{jsxref("Statements/let", "let")}}와 {{jsxref("Statements/const", "const")}} 참조 페이지를 참조하세요.

+ +

조건문

+ +

조건문은 특정 조건이 참인 경우에 실행하는 명령의 집합입니다. JavaScript는 두 가지 조건문을 지원합니다: if...else and switch.

+ +

if...else

+ +

특정 조건이 참인 경우 문장을 실행하기 위해 if 문을 사용합니다. 또한 선택적으로 조건이 거짓인 경우 문장을 실행하기 위해서는 else 절을 사용합니다. 다음과 같은 경우 :

+ +
if (condition) {
+  statement_1;
+} else {
+  statement_2;
+}
+ +

조건의 참과 거짓에 따라 수행문이 정해질 때 사용할 수 있습니다.. 무엇이 참과 거짓으로 평가되는 지에 대한 설명은 Boolean을 참조하세요. 조건이 참으로 평가되면, statement_1은 실행됩니다. 그렇지 않으면, statement_2가 실행됩니다. statement_1과 statement_2는 if문이 더 중첩 된 경우를 포함한 문장이 될 수도 있습니다.

+ +

다음과 같은 순서대로 나열된 여러 조건을 가지고 else if를 사용하여 문장을 복잡하게 할 수 있습니다:

+ +
if (condition_1) {
+  statement_1;
+} else if (condition_2) {
+  statement_2;
+} else if (condition_n) {
+  statement_n;
+} else {
+  statement_last;
+}
+
+ +

여러 줄의 문장을 실행하기 위해, block 문({ ... })안에 코드들을 작성합니다. 일반적으로, 특히 코드가 중첩할 때, 항상 block 문을 사용하는 것이 좋은 습관입니다:

+ +
if (condition) {
+  statement_1_runs_if_condition_is_true;
+  statement_2_runs_if_condition_is_true;
+} else {
+  statement_3_runs_if_condition_is_false;
+  statement_4_runs_if_condition_is_false;
+}
+
+ +
조건문 안에서의 변수값 할당은 사용하지 않는 것이 좋습니다. 왜냐하면 그것은 코드를 자세히 보지 않는 경우, 동등비교연산자로 오해할 수 있기 때문입니다. 예를 들어, 다음 코드는 사용하지 마세요.
+ +
+

if (x = y) {
+      /* statements here */
+ }

+
+ +

만약 조건식에 할당을 사용해야하는 경우, 일반적인 관행은 할당 주위에 추가 괄호를 넣는 것입니다. 예를 들어:

+ +
if ((x = y)) {
+  /* statements here */
+}
+
+ +

거짓으로 취급하는 값

+ +

다음과 같은 값은 거짓으로 평가됩니다:

+ + + +

조건문에 전달되었을 때 모든 개체를 포함하여 다른 모든 값은 참으로 평가합니다.

+ +

{{jsxref("Boolean")}} 개체의 참과 거짓 값으로 원시 boolean 값 true와 false를 혼동하지 마세요. 예를 들어:

+ +
var b = new Boolean(false);
+if (b) // this condition evaluates to true
+
+ +

예시

+ +

다음 예에서, 텍스트 개체의 문자 수가 3인 경우 함수 checkDatatrue를 반환합니다; 그렇지 않으면 경고를 표시하고 false를 반환합니다.

+ +
function checkData() {
+  if (document.form1.threeChar.value.length == 3) {
+    return true;
+  } else {
+    alert("Enter exactly three characters. " +
+    document.form1.threeChar.value + " is not valid.");
+    return false;
+  }
+}
+
+ +

switch

+ +

Switch문은 프로그램이 표현식을 평가하고  값을 조건과 비교합니다. 만약 값이 일치한다면,  프로그램은 각 조건의 하위 문장을 실행합니다. Switch문은 아래와 같이 사용합니다.:

+ +
switch (expression) {
+  case label_1:
+    statements_1
+    [break;]
+  case label_2:
+    statements_2
+    [break;]
+    ...
+  default:
+    statements_def
+    [break;]
+}
+
+ +

프로그램은 주어진 값과 일치하는 case 라벨을 찾습니다. 그리고나서 관련된 구문을 수행합니다. 만약 매치되는 라벨이 없다면 그 default 절을 찾습니다. 찾게되면, 관련된 구문을 수행합니다.  default 절을 못 찾게 된다면 프로그램의 switch문은 종료됩니다. 관례상, default 절은 마지막절입니다. 하지만 꼭 그럴 필요는 없습니다.

+ +

한번 일치된 문장이 수행되고 switch문을 따라서 계속 수행한다면 각각의 조건절로 연결된 선택적인 break문은 그 프로그램이 switch문을 벗어나게 합니다. 만약 break문이 생략된다면, 그 프로그램은 switch문안에서 다음 문장을 계속 수행합니다.

+ +

예시

+ +

아래 예에서, 만약 "fruittype"가 "Bananas"라면, 프로그램은 case "Bananas"와 값이 일치합니다. 그리고 관련된 문장을 실행합니다. 프로그램의 switch문은 break문을 만났을 때 종료됩니다. 그리고 switch문 다음에 나오는 문장을 실행합니다. 만약 break문이 생략되면, 조건문 "Cherries" 와 관련된 문장도 실행됩니다.

+ +
switch (fruittype) {
+  case "Oranges":
+    console.log("Oranges are $0.59 a pound.");
+    break;
+  case "Apples":
+    console.log("Apples are $0.32 a pound.");
+    break;
+  case "Bananas":
+    console.log("Bananas are $0.48 a pound.");
+    break;
+  case "Cherries":
+    console.log("Cherries are $3.00 a pound.");
+    break;
+  case "Mangoes":
+    console.log("Mangoes are $0.56 a pound.");
+    break;
+  case "Papayas":
+    console.log("Mangoes and papayas are $2.79 a pound.");
+    break;
+  default:
+   console.log("Sorry, we are out of " + fruittype + ".");
+}
+console.log("Is there anything else you'd like?");
+ +

 

+ +

예외처리문

+ +

여러분은 throw문을 사용하는 예외들을 사용 할 수 있고 try...catch문을 사용하는 예외들 또한 다룰 수 있습니다.

+ + + +

예외 유형

+ +

대부분 자바스크립트안에서 사용될 수 있습니다. 그럼에도 불구하고, 반드시 사용되는 객체들이 같은 것으로 만들어 지지는 않습니다. 이것들은 에러같은 숫자들이나 문자열들을 사용하는데 흔한 일이지만 특히 이런 목적으로 만들어진 예외 유형중 하나를 사용하는데 더 효과적입니다:

+ + + +

throw 문

+ +

예외를 사용할 때 throw 문을 사용합니다. 여러분이 예외를 사용할 때, 사용되는 값을 포함하는 표현을 명시해야합니다:

+ +
throw expression;
+
+ +

여러분은 구체적 유형의 표현이 아니라도 어떤 표현이든지 사용할 것입니다. 다음 코드는 다양한 유형중의 여러 예외들을 사용합니다:

+ +
throw "Error2";   // String type
+throw 42;         // Number type
+throw true;       // Boolean type
+throw {toString: function() { return "I'm an object!"; } };
+
+ +
Note: 여러분은  예외를 사용할때 객체를 명시할 수 있습니다. 그리고나서  catch 문안에서 객체의 특성들을 참조 할 수 있습니다. 다음 예시는 myUserException of type UserException객체를 만듭니다 그리고 throw문에서 사용합니다.
+ +
// Create an object type UserException
+function UserException (message){
+  this.message=message;
+  this.name="UserException";
+}
+
+// Make the exception convert to a pretty string when used as a string
+// (e.g. by the error console)
+UserException.prototype.toString = function () {
+  return this.name + ': "' + this.message + '"';
+}
+
+// Create an instance of the object type and throw it
+throw new UserException("Value too high");
+ +

try...catch 문법

+ +

try...catch 문법은 시도할 블록을 표시하고, 예외가 발생하였을때, 하나 이상의 반응을 명시합니다. 만약 예외가 발생하였을때, try...catch 문법은 예외를 잡아냅니다.

+ +

try...catch 문법은 하나 이상의 문장을 포함한 try 블록과, try 블록 에서 예외가 발생하였을때, 어떤 것을 할 것인지 명시된 문장을 포함한 0개 이상의 catch 블록으로 구성됩니다. try 블록이 성공하길 원하고, try 블록이 성공하지 않았다면, 제어를 catch 블록으로 넘기고 싶을 것입니다. 만약 try 블록(또는 try 블록에서 호출하는 함수) 의 문장이 예외를 발생시켰을때, 제어는 즉시 catch 블록으로 이동합니다. 만약 try 블록에서 예외가 발생하지 않았을 때, catch 블록을 건너뜁니다. finally 블록은 try 블록과 catch 블록의 시행이 끝나고 try...catch 문법 다음의 문장이 시행 되기 전에 시행됩니다.

+ +

다음의 예제는 try...catch 문법을 사용합니다. 예제는 함수에 전해진 값을 토대로 달의 이름을 검색하는 함수를 호출합니다. 만약 값이 달 숫자값(1-12) 에 일치하지 않으면,"InvalidMonthNo" 라는 값과 함께 예외가 발생하고 catch 블록의 문장들이 monthName 변수를 unknown 값으로 설정합니다.

+ +
function getMonthName (mo) {
+  mo = mo-1; // Adjust month number for array index (1=Jan, 12=Dec)
+  var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul",
+                "Aug","Sep","Oct","Nov","Dec"];
+  if (months[mo] != null) {
+    return months[mo];
+  } else {
+    throw "InvalidMonthNo"; //throw keyword is used here
+  }
+}
+
+try { // statements to try
+  monthName = getMonthName(myMonth); // function could throw exception
+}
+catch (e) {
+  monthName = "unknown";
+  logMyErrors(e); // pass exception object to error handler
+}
+
+ +

catch 블록

+ +

try 블록에서 발생할수 있는 모든 예외를 처리하기 위해 catch 블록을 사용할 수 있습니다.

+ +
catch (catchID) {
+  statements
+}
+
+ +

catch 블록은 throw문장에 의해 명시된 값을 가지고 있는 식별자(앞 구문의 catchID)를 명시합니다; 이 식별자를 발생된 예외에 대한 정보를 얻기 위하여 사용할 수 있습니다. 자바스크립트는 catch 블록에 진입했을때 식별자를 생성합니다; 식별자는 catch 블록에 있는 동안만 유지됩니다; catch 블록의 시행이 끝난 후, 식별자는 더이상 사용하실 수 없습니다.

+ +

예를 들어, 다음의 코드는 예외를 발생시킵니다. 예외가 발생하였을때, 제어는 catch 블록으로 넘어갑니다.

+ +
try {
+  throw "myException" // generates an exception
+}
+catch (e) {
+  // statements to handle any exceptions
+  logMyErrors(e) // pass exception object to error handler
+}
+
+ +

finally 블록

+ +

finally 블록은 try 블록과 catch 블록이 시행되고, try...catch 문법 다음 문장이 시행되기 전에 시행되는 문장들을 포함하고 있습니다. finally 블록은 예외가 발생하든 안하든 수행됩니다. 만약 예외가 발생하였을때, finally 블록 안의 문장들은 어떤 catch 블록도 예외를 처리하지 않더라도 시행됩니다.

+ +

finally 블록을 예외가 발생하였을때 여러분의 스크립트가 우아하게 실패하도록 만들기 위하여 사용할 수 있습니다. 예를 들어, 여러분의 스크립트가 묶어둔 자원들을 풀어줄 필요가 있습니다. 다음의 예제는 파일을 열고, 파일을 사용하는 문장(서버 측 자바스크립트는 파일에 접근하는 것을 허가합니다)을 시행합니다. 만약 파일이 열린 동안 예외가 발생했다면, finally 블록은 스크립트가 실패하기 전에 파일을 닫아줍니다.

+ +
openMyFile();
+try {
+  writeMyFile(theData); //This may throw a error
+} catch(e) {
+  handleError(e); // If we got a error we handle it
+} finally {
+  closeMyFile(); // always close the resource
+}
+
+ +

만약 finally 블록이 값을 반환하였을 경우, try 블록과 catch블록의 return 문장과 상관없이 전체 try-catch-finally 생산물의 반환값이 됩니다:

+ +
function f() {
+  try {
+    console.log(0);
+    throw "bogus";
+  } catch(e) {
+    console.log(1);
+    return true; // this return statement is suspended
+                 // until finally block has completed
+    console.log(2); // not reachable
+  } finally {
+    console.log(3);
+    return false; // overwrites the previous "return"
+    console.log(4); // not reachable
+  }
+  // "return false" is executed now
+  console.log(5); // not reachable
+}
+f(); // alerts 0, 1, 3; returns false
+
+ +

finally 블록에 의한 반환값 덮어쓰기는 예외가 발생하거나 다시 예외가 발생했을때 또한 적용됩니다.

+ +
function f() {
+  try {
+    throw "bogus";
+  } catch(e) {
+    console.log('caught inner "bogus"');
+    throw e; // this throw statement is suspended until
+             // finally block has completed
+  } finally {
+    return false; // overwrites the previous "throw"
+  }
+  // "return false" is executed now
+}
+
+try {
+  f();
+} catch(e) {
+  // this is never reached because the throw inside
+  // the catch is overwritten
+  // by the return in finally
+  console.log('caught outer "bogus"');
+}
+
+// OUTPUT
+// caught inner "bogus"
+ +

try...catch 문법 중첩하기

+ +

 

+ +

하나 이상의 try ... catch 문을 중첩 할 수 있습니다. 중첩된 안쪽 try ... catch 문에 catch 블록이 없으면 finally 블록이 있어야하고 try ... catch 문의 catch 블록에 일치하는 항목이 있는지 확인해야합니다. 자세한 내용은 try...catch 참조 페이지의 nested try-blocks을 참조하십시오.

+ +

Error 객체를 도구화 하기

+ +

오류의 종류에 따라, 더 정제된 메세지를 얻기 위하여 'name'속성과 'message'속성을 사용할수도 있습니다. 'name'속성은 오류의 일반 클래스(e.g., 'DOMException' 또는 'Error')를 제공하고, 'message' 속성이 error 객체를 문자열로 바꿀수 있는 것 보다 더 간결한 메세지를 제공합니다.

+ +

만약 이 속성들에 대하여 이득을 얻기 위해(여러분의 catch 블록이 시스템의 예외와 여러분의 예외를 구분하지 않을 때와 같은 것) 여러분만의 예외를 발생시킨다면, 여러분은 Error 생성자를 사용할 수 있습니다. 예를 들어:

+ +
function doSomethingErrorProne () {
+  if (ourCodeMakesAMistake()) {
+    throw (new Error('The message'));
+  } else {
+    doSomethingToGetAJavascriptError();
+  }
+}
+....
+try {
+  doSomethingErrorProne();
+}
+catch (e) {
+  console.log(e.name); // logs 'Error'
+  console.log(e.message); // logs 'The message' or a JavaScript error message)
+}
+ +

Promises

+ +

ECMAScript2015를 시작하면서, 자바스크립트는 지연된 흐름과 비동기식의 연산을 제어할 수 있게 하는 {{jsxref("Promise")}} 객체에 대한 지원을 얻게 되었습니다.

+ +

Promise 는 다음의 상태중 하나입니다:

+ + + +

+ +

XHR 를 통해 이미지 불러오기

+ +

이미지를 불러오기 위해 PromiseXMLHttpRequest 를 사용한 간단한 예제는 MDN GitHub promise-test repository 에 있습니다. 이 예제 가 동작하는 것을 보실 수 있습니다. 각 단계는 설명되어있고 Promise 와 XHR 구조를 친밀하게 이해할수 있게 합니다. 여기 Promise 흐름을 보여줘서 아이디어를 얻을 수 있는 설명되지 않은 버전이 있습니다:

+ +
function imgLoad(url) {
+  return new Promise(function(resolve, reject) {
+    var request = new XMLHttpRequest();
+    request.open('GET', url);
+    request.responseType = 'blob';
+    request.onload = function() {
+      if (request.status === 200) {
+        resolve(request.response);
+      } else {
+        reject(Error('Image didn\'t load successfully; error code:'
+                     + request.statusText));
+      }
+    };
+    request.onerror = function() {
+      reject(Error('There was a network error.'));
+    };
+    request.send();
+  });
+}
+ +

더 자세한 정보를 얻기 위해선, {{jsxref("Promise")}} 참고 페이지를 보세요.

+ +
{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
diff --git a/files/ko/web/javascript/guide/expressions_and_operators/index.html b/files/ko/web/javascript/guide/expressions_and_operators/index.html new file mode 100644 index 0000000000..f5e711304f --- /dev/null +++ b/files/ko/web/javascript/guide/expressions_and_operators/index.html @@ -0,0 +1,926 @@ +--- +title: 표현식과 연산자 +slug: Web/JavaScript/Guide/Expressions_and_Operators +tags: + - Beginner + - Expressions + - Guide + - JavaScript + - Operators + - 'l10n:priority' + - 연산자 +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}
+ +

이 장은 JavaScript의 표현식과 할당, 비교, 산술, 비트 계산, 논리, 문자열, 삼항 등 여러 가지 연산자를 설명합니다.

+ +

연산자와 표현식의 완전하고 구체적인 목록도 참고서에서 확인할 수 있습니다.

+ +

연산자

+ +

JavaScript는 다음과 같은 형태의 연산자가 있습니다. 이 절은 연산자에 대하여 설명하고, 연산자 우선순위에 관한 정보를 포함하고 있습니다.

+ + + +

JavaScript는 이항 연산자와 단항연산자, 조건연산자인 단 하나 존재하는 삼항 연산자를 가지고 있습니다. 이항 연산자는 하나는 좌변에 다른 하나는 우변에 두개의 피연산자가 필요합니다:

+ +
피연산자1 연산자 피연산자2
+
+ +

예를 들면 3+4 또는 x*y와 같습니다.

+ +

단항 연산자는 연산자 뒤에든 앞에든 하나의 피연산자를 필요로 합니다.:

+ +
연산자 피연산자
+
+ +

또는

+ +
피연산자 연산자
+
+ +

x++ 또는 ++x를 예시로 들 수 있습니다.

+ +

할당 연산자

+ +

할당 연산자는 오른쪽 피연산자의 값을 왼쪽 피연산자에 할당합니다. 기본적인 할당 연산자는 오른쪽의 피연산자 값을 왼쪽 피연산자 값에 할당하는 등호(=) 입니다. 즉 x = yy 값을 x에 할당합니다.

+ +

다음의 표에 나열된 연산의 약칭인 복합 할당 연산자도 존재합니다:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
복합 할당 연산자
이름복합 할당 연산자
할당x = yx = y
덧셈 할당x += yx = x + y
뺄셈 할당x -= yx = x - y
곱셈 할당x *= yx = x * y
나눗셈 할당x /= yx = x / y
나머지 연산 할당x %= yx = x % y
지수 연산 할당 {{experimental_inline}}x **= yx = x ** y
왼쪽 이동 연산 할당x <<= yx = x << y
오른쪽 이동 연산 할당x >>= yx = x >> y
부호 없는 오른쪽 이동 연산 할당x >>>= yx = x >>> y
비트 AND 할당x &= yx = x & y
비트 XOR 할당x ^= yx = x ^ y
비트 OR 할당x |= yx = x | y
+ +

구조 분해

+ +

복잡한 할당 연산에서, 구조 분해 할당 구문은 배열이나 객체의 구조를 반영하여 배열이나 객체에서 데이터를 추출할 수 있게 해주는 JavaScript 표현식입니다.

+ +
var foo = ['one', 'two', 'three'];
+
+// 구조 분해를 활용하지 않은 경우
+var one   = foo[0];
+var two   = foo[1];
+var three = foo[2];
+
+// 구조 분해를 활용한 경우
+var [one, two, three] = foo;
+ +

비교 연산자

+ +

비교 연산자는 피연산자들을 비교하고 비교에 따라 논리 값을 반환합니다. 피연산자들은 숫자, 문자열, 논리형, 객체 를 사용할 수 있습니다. 문자열은 유니코드 값을 사용하여 표준 사전순서를 기반으로 비교합니다. 만약 두 피연산자가 다른 형태일 경우, JavaScript는 대부분 비교를 위해 피연산자를 적절한 타입으로 변환합니다. 이런 행동은 보통 숫자로 피연산자를 숫자로 비교하는 형태로 나타납니다. 형태를 바꾸기의 유일한 예외는 엄격한 비교를 수행하는 ===!== 연산이 관련되는 경우입니다. 이런 연산자는 비교를 위해 피연산자의 형태를 적절히 바꾸려고 시도하지 않습니다. 다음 표는 샘플 코드를 통해 비교 연산자에 대하여 설명합니다:

+ +
var var1 = 3;
+var var2 = 4;
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
비교 연산자
연산자설명참을 반환하는 예제
동등 (==)피연산자들이 같으면 참을 반환합니다.3 == var1 +

"3" == var1

+ 3 == '3'
부등 (!=)피연산자들이 다르면 참을 반환합니다.var1 != 4
+ var2 != "3"
일치 (===)피연산자들이 같고 피연산자들의 같은 형태인 경우 참을 반환합니다. {{jsxref("Object.is")}} 와 JavaScript에서의 같음을 참고하세요.3 === var1
불일치 (!==)피연산자들이 다르거나 형태가 다른 경우 참을 반환합니다.var1 !== "3"
+ 3 !== '3'
~보다 큰 (>)좌변의 피연산자 보다 우변의 피연산자가 크면 참을 반환합니다.var2 > var1
+ "12" > 2
~보다 크거나 같음 (>=)좌변의 피연산자 보다 우변의 피연산자가 크거나 같으면 참을 반환합니다.var2 >= var1
+ var1 >= 3
~보다 작음 (<)좌변의 피연산자 보다 우변의 피연산자가 작으면 참을 반환합니다.var1 < var2
+ "2" < 12
~보다 작거나 같음 (<=)좌변의 피연산자 보다 우변의 피연산자가 작거나 같으면 참을 반환합니다. +

var1 <= var2
+ var2 <= 5

+
+ +
+

참고: (=>) 은 연산자가 아니고, 화살표 함수(Arrow functions)를 나타내는 기호입니다.

+
+ +

산술 연산자

+ +

산술 연산자는 숫자값(리터럴 또는 변수)을 피연산자로 갖고, 하나의 숫자 값을 반환합니다. 기본적인 산술 연산자는 덧셈(+), 뺄셈 (-), 곱셈 (*), 나눗셈 (/)입니다. 이 연산자들은 대부분의 다른 프로그래밍 언어들이 부동소수점 값을 연산하는것처럼 동작합니다. (0 으로 나누는 것은 {{jsxref("Infinity")}} 을 발생시키는 것을 기억하세요) 예를 들면:

+ +
1 / 2; // 0.5
+1 / 2 == 1.0 / 2.0; // this is true
+
+ +

또한, 표준 산술 연산자 (+, -, *, /) 에 대해 JavaScript는 다음의 표에 나와 있는 산술 연산자를 제공합니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
산술 연산자
연산자설명예제
나머지 연산자 (%)이항 연산자입니다. 두 피연산자를 나눈후 나머지를 반환합니다.12 % 5 는 2를 반환합니다.
증가 연산자 (++)단항 연산자입니다. 피연산자에 1을 더합니다. 만약 연산자를 피연산자 앞(++x)에 사용하면, 피연산자에 1을 더한 값을 반환합니다.; 만약 연산자를 피연산자 뒤(x++)에 사용하면, 피연산자에 1을 더하기 전 값을 반환합니다.x 가 3이면 ++xx 를 4로 만들고 4를 반환합니다. 반면 x++ 는 3을 반환하고 x 를 4로 만듭니다.
감소 연산자 (--)단항 연산자입니다. 피연산자로 부터 1을 뺍니다. 반환값은 증가 연산자와 유사합니다.x 가 3이면 --xx 를 2로 만들고2를 반환합니다. 반면 x-- 는 3을 반환하고 x 를 2로 만듭니다.
단항 부정 연산자 (-)단항 연산자 입니다. 피연산자의 반대값(부호 바뀐값)을 반환합니다. x 가 3이면 -x 는 -3을 반환합니다.
숫자화 연산자 (+)단항연산자 입니다. 피연산자가 숫자값이 아니라면 피연산자를 숫자로 변환하기를 시도합니다.+"3"3을 반환합니다.
+ +true1. 을 반환합니다.
+ +

비트 연산자

+ +

비트 연산자는 피연산자를 10진수, 16진수, 8진수처럼 취급하지 않고 32비트의 집합으로 취급합니다. 예를 들면, 10진수의 9는 2진수의 1001로 나타낼 수 있습니다. 비트 단위 연산자는 이진법으로 연산을 수행하지만, JavaScript의 표준 숫자값을 반환합니다..

+ +

다음의 표는 JavaScript의 비트단위 연산자의 요약입니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
비트 연산자
연산자사용법설명
비트단위 논리곱a & b두 피연산자의 각 자리 비트의 값이 둘다 1일 경우 해당하는 자리에 1을 반환합니다.
비트단위 논리합a | b두 피연산자의 각 자리 비트의 값이 둘다 0일 경우 해당하는 자리에 0을 반환합니다.
비트단위 배타적 논리합a ^ b두 피연산자의 각 자리 비트의 값이 같을 경우 해당하는 자리에 0을 반환합니다.
+ [두 피연산자의 각 자리 비트의 값이 다를 경우 해당하는 자리에 1을 반환합니다.]
비트단위 부정~ a피연산자의 각 자리의 비트를 뒤집습니다.
왼쪽 시프트a << b오른쪽에서 0들을 이동시키면서, a의 이진수의 각 비트를 b비트 만큼 왼쪽으로 이동시킨 값을 반환합니다.
부호 전파 오른쪽 시프트a >> b사라지는 비트를 버리면서, a의 이진수의 각 비트를 b비트만큼 이동시킨값을 반환합니다.
부호 없는 오른쪽 시프트a >>> b사라지는 비트를 버리고 왼쪽에서 0을 이동시키면서, a의 이진수의 각 비트를 b비트 만큼 이동시킨 값을 반환합니다.
+ +

비트 논리 연산자

+ +

개념상으로, 비트단위 논리 연산자는 다음과 같이 동작합니다:

+ + + +

예를 들면, 9의 이진표현은 1001이고, 15의 이진표현은 1111입니다. 따라서, 비트단위 연산자가 이 값들에 적용될때, 결과는 다음과 같습니다:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
비트 연산자 예제
표현결과이진법 설명
15 & 991111 & 1001 = 1001
15 | 9151111 | 1001 = 1111
15 ^ 961111 ^ 1001 = 0110
~15-16~00000000...00001111 = 11111111...11110000
~9-10~00000000...00001001 = 11111111...11110110
+ +

모든 32비트가 비트단위 부정연산자를 통해 뒤집히고, 가장 의미있는(가장 왼쪽의) 비트가 1인 값들이 음수(2의 보수 표기법)로 표현되는것에 주목하세요 . ~x 의 평가 값은 -x -1의 평가값과 동일합니다.

+ +

비트 시프트 연산자

+ +

비트 단위 연산자는 2개의 피연산자를 가집니다: 첫번째는 이동될 수치이고, 두번째는 첫번째 피연산자가 이동될 비트 자리수를 명시합니다. 비트 이동 연산의 방향은 연산자의 사용에 의해 조종됩니다.

+ +

이동 연산자는 피연산자를 32비트의 정수로 변환하고, 왼쪽의 피연산자와 같은 형태를 반환합니다.

+ +

이동 연산자는 다음의 표에 나열되었습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
비트 시프트 연산자
연산자설명예제
왼쪽 시프트
+ (<<)
이 연산자는 첫번째 피연산자를 특정한 수의 비트를 왼쪽으로 이동시킵니다. 왼쪽으로 초과되어 이동되는 비트들은 버려집니다. 오른쪽으로부터 0이 이동됩니다.9<<2 yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
부호 전파 오른쪽 시프트(>>)이 연산자는 첫번째 피연산자를 특정한 수의 비트를 오른쪽으로 이동시킵니다. 오른쪽으로 초과되어 이동되는 비트들은 버려집니다. 왼쪽으로부터 제일 왼쪽의 비트 값이 이동됩니다.9>>2 yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, -9>>2 yields -3, because the sign is preserved.
부호 없는 오른쪽 시프트(>>>)이 연산자는 첫번째 피연산자를 특정한 수의 비트를 오른쪽으로 이동시킵니다. 오른쪽으로 초과되어 이동되는 비트들은 버려집니다. 왼쪽으로부터 0이 이동됩니다 .19>>>2 yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.
+ +

논리 연산자

+ +

논리 연산자는 보통 부울 값과 사용됩니다; 부울 값들과 사용될때, 연산자는 부울값을 반환합니다. 그러나,&& 과 || 연산자는 실제로 명시된 피연자들 중 하나를 반환합니다. 따라서, 만약 이 연산자들이 부울 값이 아닌 값들과 함께 쓰였을때, 그들은 부울 값이 아닌 값을 반환할지도 모릅니다. 논리 연산자들은 다음의 표에서 설명됩니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + +
논리 연산자
연산자구문설명
논리 AND (&&)expr1 && expr2expr1true로 변환할 수 있는 경우 expr2을 반환하고, 그렇지 않으면 expr1을 반환합니다.
논리 OR (||)expr1 || expr2 +

expr1true로 변환할 수 있으면 expr1을 반환하고, 그렇지 않으면 expr2를 반환합니다.

+
논리 NOT (!)!expr단일 피연산자를 true로 변환할 수 있으면 false를 반환합니다. 그렇지 않으면 true를 반환합니다.
+ +

false로 변환될 수 있는 표현 예제들은 null, 0, NaN, 빈 문자열 (""), 또는 정의되지 않음 으로 평가될 수 있습니다.

+ +

다음의 코드는 && (논리 곱) 연산자의 예제를 보여주고 있습니다.

+ +
var a1 =  true && true;     // t && t returns true
+var a2 =  true && false;    // t && f returns false
+var a3 = false && true;     // f && t returns false
+var a4 = false && (3 == 4); // f && f returns false
+var a5 = "Cat" && "Dog";    // t && t returns Dog
+var a6 = false && "Cat";    // f && t returns false
+var a7 = "Cat" && false;    // t && f returns false
+
+ +

다음의 코드는 || (논리 합) 연산자의 예제를 보여주고 있습니다.

+ +
var o1 =  true || true;     // t || t returns true
+var o2 = false || true;     // f || t returns true
+var o3 =  true || false;    // t || f returns true
+var o4 = false || (3 == 4); // f || f returns false
+var o5 = "Cat" || "Dog";    // t || t returns Cat
+var o6 = false || "Cat";    // f || t returns Cat
+var o7 = "Cat" || false;    // t || f returns Cat
+
+ +

다음의 코드는 ! (논리 부정) 연산자의 예제를 보여주고 있습니다.

+ +
var n1 = !true;  // !t returns false
+var n2 = !false; // !f returns true
+var n3 = !"Cat"; // !t returns false
+
+ +

단락 평가

+ +

논리 연산자가 왼쪽에서 오른쪽으로 평가될때, 논리연산자는 다음의 규칙을 따라서 "단축 계산"으로 검사됩니다:

+ + + +

이 논리 규칙들은 이러한 평가가 언제나 정확하다고 보증합니다. 위에서 anything 부분은 평가되지 않았고, 어떤 부작용도 아무런 효과를 미치지 못한다는 것에 주목하세요.

+ +

문자열 연산자

+ +

문자열 값으로 사용될 수 있는 비교 연산자에 덧붙여서, 연결 연산자 (+)는 두 문자열 값을 연결하고,두 문자열이 합쳐진 새로운 문자열을 반환합니다.

+ +

예를 들어,

+ +
console.log("my " + "string"); // console logs the string "my string".
+ +

복합 할당 연산자인 += 또한 문자열을 연결하는데 사용할 수 있습니다.

+ +

예를 들어,

+ +
var mystring = "alpha";
+mystring += "bet"; // evaluates to "alphabet" and assigns this value to mystring.
+ +

조건 (삼항) 연산자

+ +

조건 연산자 는 JavaScript에서 3개의 항을 사용하는 유일한 연산자 입니다. 조건 연산자는 조건에 따라 2개의 값중 하나를 가질 수 있습니다. 문법은 다음과 같습니다:

+ +
조건 ? 값1 : 값2
+
+ +

만약 조건이 참이라면, 조건 연산자는 값1을 값으로 갖습니다. 그렇지 않은 경우 조건 연산자는 값2을 값으로 갖습니다. 표준 연산자를 사용하는 어디든 조건연산자를 사용할 수 있습니다.

+ +

에들 들어,

+ +
var status = (age >= 18) ? "adult" : "minor";
+
+ +

이 구문은 age 변수가 18보다 같거나 클때 "adult" 값을 status 변수에 할당합니다. 그렇지 않은 경우, 이 구문은 "minor"값을 status변수에 할당합니다.

+ +

쉼표 연산자

+ +

쉼표 연산자 (,)는 두 피연산자를 평가하고, 마지막 피연산자의 값을 반환합니다. 이 연산자는 주로 for 반복문 안에서 각각의 시간에 복수의 변수들을 갱신하기 위하여 사용합니다.

+ +

예를 들어, a는 각 변에 10개의 원소가 있는 2차원 배열일때, 다음의 코드는 콤마 연산자를 두 변수를 한번에 증가 시키기 위하여 사용하였습니다. 이 코드는 배열의 대각선에 위치한 원소를 출력합니다:

+ +
var x = [0,1,2,3,4,5,6,7,8,9]
+var a = [x, x, x, x, x];
+
+for (var i = 0, j = 9; i <= j; i++, j--)
+  console.log('a[' + i + '][' + j + ']= ' + a[i][j]);
+ +

단항 연산자

+ +

단항 연산자는 오직 하나의 피연산자를 가지고 연산을합니다.

+ +

delete

+ +

delete연산자는 객체, 객체의 속성 또는 배열의 특정한 위치에 있는 객체를 삭제합니다. 문법은 다음과 같습니다:

+ +
delete objectName;
+delete objectName.property;
+delete objectName[index];
+delete property; // legal only within a with statement
+
+ +

objectName은 객체의 이름이고, property는 객체에 존재하는 속성이고,index는 배열의 위치를 나타내는 정수입니다.

+ +

네번째 형태의 경우,객체의 속성을 삭제하기 위하여 with 구문이 있어야만 동작합니다.

+ +

delete 연산자를 var 구문을 사용하지 않고 묵시적으로 만들어진 변수를 삭제할 때 사용할 수 있습니다.

+ +

만약 delete연산자의 동작이 성공했다면, delete 연산자는 속성이나, 원소를 undefined 로 설정합니다. delete 연산자는 연산이 수행 가능할때 true값을 반환합니다; 수행이 불가능 할 경우 false 값을 반환합니다.

+ +
x = 42;
+var y = 43;
+myobj = new Number();
+myobj.h = 4;    // create property h
+delete x;       // returns true (can delete if declared implicitly)
+delete y;       // returns false (cannot delete if declared with var)
+delete Math.PI; // returns false (cannot delete predefined properties)
+delete myobj.h; // returns true (can delete user-defined properties)
+delete myobj;   // returns true (can delete if declared implicitly)
+
+ +
배열의 원소를 삭제하기
+ +

배열의 원소를 삭제할때, 배열의 길이에는 영향을 주지 못합니다. 예를 들어, 만약 a[3], a[4]를 삭제 했다면 a[4]a[3]는 undefined(정의되지 않음)상태로 되어 있습니다.

+ +

delete 연산자가 배열의 한 원소를 삭제하였을때, 그 원소는 배열에 존재하지 않습니다. 다음의 예제에서, trees[3]delete 연산자에 의해 제거되었습니다.그러나, trees[3] 는 아직도 다룰수 있고 undefined(정의 되지 않음) 을 반환합니다.

+ +
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
+delete trees[3];
+if (3 in trees) {
+  // this does not get executed
+}
+
+ +

만약 배열의 원소가 존재하지만 undefined(정의 되지 않음)값을 가지고 싶으면, delete 연산자 대신 undefined 키워드를 사용하세요. 다음의 예제에서, trees[3]undefined값을 할당받습니다,그러나 배열의 원소는 아직도 존재합니다:

+ +
var trees = ["redwood", "bay", "cedar", "oak", "maple"];
+trees[3] = undefined;
+if (3 in trees) {
+  // this gets executed
+}
+
+ +

typeof

+ +

typeof 연산자는 다음과 같은 방법으로 사용됩니다:

+ +
typeof 피연산자
+typeof (피연산자)
+
+ +

typeof 연산자 피연산자의 타입을 나타내는 문자열을 반환합니다. 피연산자 는 어떤 타입인지 반환될 문자열, 변수, 키워드,또는 객체입니다 . 괄호 표현은 선택사항입니다.

+ +

다음의 변수를 정의했다고 가정하세요:

+ +
var myFun = new Function("5 + 2");
+var shape = "round";
+var size = 1;
+var foo = ['Apple', 'Mango', 'Orange'];
+var today = new Date();
+
+ +

typeof 연산자는 이 변수들에 대하여 다음과 같은 값을 반환합니다:

+ +
typeof myFun;     // returns "function"
+typeof shape;     // returns "string"
+typeof size;      // returns "number"
+typeof foo;       // returns "object"
+typeof today;     // returns "object"
+typeof dontExist; // returns "undefined"
+
+ +

typeof 연산자는 키워드truenull에 대하여 다음과 같은 결과를 반환합니다:

+ +
typeof true; // returns "boolean"
+typeof null; // returns "object"
+
+ +

typeof 연산자는 숫자와 문자열에 대하여 다음과 같은 결과를 반환합니다:

+ +
typeof 62;            // returns "number"
+typeof 'Hello world'; // returns "string"
+
+ +

typeof 연산자는 객체의 속성에 대하여 속성이 갖고있는 타입의 값을 반환합니다.

+ +
typeof document.lastModified; // returns "string"
+typeof window.length;         // returns "number"
+typeof Math.LN2;              // returns "number"
+
+ +

typeof 연산자는 메소드와 함수들에 대하여 다음과 같은 결과를 반환합니다:

+ +
typeof blur;        // returns "function"
+typeof eval;        // returns "function"
+typeof parseInt;    // returns "function"
+typeof shape.split; // returns "function"
+
+ +

typeof 연산자는 미리 정의된 객체에 대하여 다음과 같은 결과를 반환합니다:

+ +
typeof Date;     // returns "function"
+typeof Function; // returns "function"
+typeof Math;     // returns "object"
+typeof Option;   // returns "function"
+typeof String;   // returns "function"
+
+ +

void

+ +

void 연산자 는 다음과 같은 방법들로 사용됩니다:

+ +
void (식)
+void 식
+
+ +

void 연산자는 값을 반환하지 않고 평가되도록 명시합니다. 은 JavaScript의 평가될 표현 입니다. 괄호 로 둘러싸는것은 선택사항이지만, 괄호로 둘러싸는게 좋은 사용방법입니다.

+ +

void 연산자를 표현을 하이퍼링크 에서 명시할때 사용할 수 있습니다 . 구문은 실행이 되나, 현재의 문서에는 로드되지 않습니다.

+ +

다음의 코드는 사용자가 클릭을 하였을때 아무 일도 안하는 하이퍼링크를 생성합니다. 사용자가 클릭을 했을때, void(0) JavaScript에서 아무런 영향을 줄 수 없는 undefined(정의 되지않음)으로 평가됩니다.

+ +
<a href="javascript:void(0)">Click here to do nothing</a>
+
+ +

다음의 코드는 사용자가 클릭을 하였을때, 폼을 제출하는 하이퍼링크를 생성합니다.

+ +
<a href="javascript:void(document.form.submit())">
+Click here to submit</a>
+ +

관계 연산자

+ +

관계 연산자는 피연산자들을 비교하고 ,비교의 참 여부에 기반하여 부울 값을 반환합니다.

+ +

in

+ +

in 연산자는 객체에 특정한 속성이 있는경우 true를 반환합니다. 구문은 다음과 같습니다:

+ +
propNameOrNumber in objectName
+
+ +

propNameOrNumber는 속성의 이름을 나타내는 문자열 또는 배열의 인덱스를 나타내는 숫자이고, objectName은 객체의 이름입니다.

+ +

다음의 예제는 in 연산자의 사용 예를 보여줍니다.

+ +
// Arrays
+var trees = ["redwood", "bay", "cedar", "oak", "maple"];
+0 in trees;        // returns true
+3 in trees;        // returns true
+6 in trees;        // returns false
+"bay" in trees;    // returns false (you must specify the index number,
+                   // not the value at that index)
+"length" in trees; // returns true (length is an Array property)
+
+// built-in objects
+"PI" in Math;          // returns true
+var myString = new String("coral");
+"length" in myString;  // returns true
+
+// Custom objects
+var mycar = { make: "Honda", model: "Accord", year: 1998 };
+"make" in mycar;  // returns true
+"model" in mycar; // returns true
+
+ +

instanceof

+ +

instanceof 연산자는 명시된 객체가 명시된 객체형인 경우 true를 반환합니다. 구문은 다음과 같습니다:

+ +
objectName instanceof objectType
+
+ +

objectName은 objectType 과 비교할 객체의 이름이고, objectType 은 {{jsxref("Date")}} 또는 {{jsxref("Array")}}과 같은 객체형 입니다.

+ +

instanceof 연산자를 동작시간에 객체의 형태를 확인할 필요가 있을때 사용하세요. 예를 들어, 예외가 발생하였을때, 던저진 예외의 형태에 따라 예외를 처리하는 코드로 나뉘게 할 수 있습니다.

+ +

예를 들어, 다음의 코드는instanceof 연산자를theDay 객체가 Date 형의 객체인지 알아내는 코드입니다. theDay객체는 Date 형의 객체이기 때문에, if 문 안의 명령문들은 실행됩니다.

+ +
var theDay = new Date(1995, 12, 17);
+if (theDay instanceof Date) {
+  // statements to execute
+}
+
+ +

연산자 우선순위

+ +

연산자의 우선순위는 구문을 수행할 때 수행될 순서를 결정합니다. 괄호를 통하여 우선순위를 재정의 할 수 있습니다.

+ +

다음의 표는 우선순위가 높은 순서부터 낮은 순서까지, 연산자의 우선순위에 대하여 설명하고 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
연산자 우선순위
Operator typeIndividual operators
맴버 연산자. []
객체 호출/생성 연산자() new
부정/증가 연산자! ~ - + ++ -- typeof void delete
곱셈/나눗셈 연산자* / %
덧셈/뺄셈 연산자+ -
비트단위 시프트 연산자<< >> >>>
관계 연산자< <= > >= in instanceof
같음 비교 연산자== != === !==
비트 단위 논리곱 연산자&
비트단위 배타적 논리합 연산자^
비트단위 논리합 연산자|
논리 곱 연산자&&
논리 합 연산자||
조건 연산자?:
할당 연산자= += -= *= /= %= <<= >>= >>>= &= ^= |=
콤마 연산자,
+ +

각 각의 연산자에 대한 추가적인 상세사항에 대해 연결된, 더 자세한 표를 보고 싶으면, JavaScript Reference에서 보실 수 있습니다.

+ +

표현식

+ +

코드 값으로 확인된 표현은 그 어떤 타당한 단위입니다.

+ +

개념적으로, 2가지의 유형이 있습니다. 첫번째는, 변수에 값을 할당시키는 것, 두번째는 단순히 값을 갖는것이 있습니다.

+ +

x = 7이란 표현은 첫번째 유형입니다. 이 표현은 x에다가 7을 할당시키기위해 =연산자를 사용합니다. 그 표현자체 7로 계산됩니다.

+ +

3 + 4란 코드는 두번째 표현방식의 예입니다. 이 표현은 7이라는 결과로 할당하는것없이 3과 4를 더하기위해 +연산자를 사용합니다.

+ +

JavaScript는 아래 표현범주를 따릅니다.

+ + + +

중요한 표현식

+ +

JavaScript에서의 기본적인 키워드와 일반적인 표현식입니다.

+ +

this

+ +

현재 객체를 참조하는 데 this 키워드를 사용합니다. 일반적으로, this는 메소드에서 호출하는 객체를 참조합니다. 점(.)이나 괄호([])로 접근할 수 있습니다.

+ +
this["propertyName"]
+this.propertyName
+
+ +

어떤 객체의 최솟값 최댓값에 대하여, value 프로퍼티가 유효범위에 속하는지를 평가하는 validate 함수를 호출했다고 가정해봅시다.

+ +
function validate(obj, lowval, hival){
+  if ((obj.value < lowval) || (obj.value > hival))
+    console.log("Invalid Value!");
+}
+
+ +

다음과 같이 각 form 요소의 onChange 이벤트 처리기에서 validate 함수를 호출할 수 있습니다. this 일차식을 사용하여 form 요소(element)를 전달할 수 있습니다:

+ +
<p>Enter a number between 18 and 99:</p>
+<input type="text" name="age" size=3 onChange="validate(this, 18, 99);">
+
+ +

그룹 연산자

+ +

그룹연산자 ()는 표현식 평가의 우선순위를 조절합니다. 예를 들어, 곱셈과 나눗셈 연산을 무시하고, 우선 덧셈 뺄셈 연산을 먼저 수행할 수도 있습니다.

+ +
var a = 1;
+var b = 2;
+var c = 3;
+
+// default precedence
+a + b * c     // 7
+// evaluated by default like this
+a + (b * c)   // 7
+
+// now overriding precedence
+// addition before multiplication
+(a + b) * c   // 9
+
+// which is equivalent to
+a * c + b * c // 9
+
+ +

좌변식

+ +

좌측값들이 좌변식의 목적입니다.

+ +

new

+ +

당신은 사용자 정의 객체 형식 또는 한 내장된 객체 형식의 인스턴스를 만드는 데는 new 연산자사용할 수 있습니다. new는 아래와 같이 사용할 수 있습니다:

+ +
var objectName = new objectType([param1, param2, ..., paramN]);
+
+ +

super

+ +

Super 키워드개체의 부모에 함수를 호출하는 데 사용됩니다. 예를 들어 이것은 부모생성자를 부르는 클래스들과 함께 유용합니다

+ +
super([arguments]); // calls the parent constructor.
+super.functionOnParent([arguments]);
+
+ +

확산연산자

+ +

확산연산자는 다중인수(함수호출)또는 다중요소(문자배열)들이 예상되는 곳에서 확장될 수 있는 표현을 하게합니다.

+ +

Example: 만약 하나의 배열에 다른 하나의 배열을 추가하고 싶을 때에는 Array 리터럴 구문이 더이상 충분하지않으므로 push, splice, concat과 같은 함수를 사용하는 것이 좋습니다. 하지만 확산연산자를 사용할 경우 좀 더 간결한 구문으로 구현할 수 있습니다. 

+ +
var parts = ['shoulder', 'knees'];
+var lyrics = ['head', ...parts, 'and', 'toes'];
+
+//[ 'head', 'shoulders', 'knees', 'and', 'toes' ]
+
+ +

위와 같이, 확산연산자의 함수 호출은 다음과 같이 사용합니다.

+ +
function f(x, y, z) { }
+var args = [0, 1, 2];
+f(...args);
+ +
{{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}
diff --git a/files/ko/web/javascript/guide/index.html b/files/ko/web/javascript/guide/index.html new file mode 100644 index 0000000000..7ae4ac0fcf --- /dev/null +++ b/files/ko/web/javascript/guide/index.html @@ -0,0 +1,138 @@ +--- +title: JavaScript 안내서 +slug: Web/JavaScript/Guide +tags: + - Guide + - JavaScript + - 'l10n:priority' + - 자바스크립트 +translation_of: Web/JavaScript/Guide +--- +
{{jsSidebar("JavaScript Guide")}}
+ +

JavaScript 안내서에서 JavaScript 언어 개요와 사용법을 알아보세요. 언어 기능에 대해 상세한 정보가 필요하면 JavaScript 참고서를 방문하세요.

+ +

목차

+ +

본 안내서는 여러 장으로 구성되어 있습니다.

+ + + + + + + + + +

{{Next("Web/JavaScript/Guide/Introduction")}}

diff --git a/files/ko/web/javascript/guide/indexed_collections/index.html b/files/ko/web/javascript/guide/indexed_collections/index.html new file mode 100644 index 0000000000..f048ddc752 --- /dev/null +++ b/files/ko/web/javascript/guide/indexed_collections/index.html @@ -0,0 +1,456 @@ +--- +title: Indexed collections +slug: Web/JavaScript/Guide/Indexed_collections +translation_of: Web/JavaScript/Guide/Indexed_collections +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Keyed_Collections")}}
+ +

이번장에서는 인덱스값에 의해 정렬이 되는 데이터 자료구조에 대해 소개합니다.  배열과 유사 배열 생성자인 {{jsxref("Array")}} 객체와 {{jsxref("TypedArray")}} 객체 같은 생성자들을 포함합니다. 

+ +

배열 객체

+ +

배열은 이름과 인덱스로 참조되는 정렬된 값들의 집합입니다. 예를 들면, 숫자로 된 사원번호를 index로하여 사원명을 가지고 있는 emp라는 배열을 가질 수 있습니다. 그래서 emp[1]은 사원번호 1번, emp[2]는 사원번호 2번, 이런식으로 사원번호를 인덱스 값으로 가질 수 있는 것입니다.

+ +

자바스크립트는 명시적인 배열 데이터 형식을 가지고 있지 않습니다. 그러나 미리 정의된 배열 객체를 사용할 수 있고 배열 객체의 메서드를 개발하는 어플리케이션에서 사용되는 배열에 사용할 수 있습니다. 배열 객체는 합치기(joining), 순서 뒤집기(reversing) 그리고 정렬(sorting)과 같은 다양한 방법으로 배열을 조작하는 메서드들을 제공합니다. 정규 표현식과 함께 사용할 배열 길이와 기타 속성을 결정하는 속성이 있습니다.

+ +

배열 생성

+ +

아래의 구문들은 동일한 요소를 가지는 배열을 생성하는 방법들입니다. 

+ +
var arr = new Array(element0, element1, ..., elementN);
+var arr = Array(element0, element1, ..., elementN);
+var arr = [element0, element1, ..., elementN];
+
+ +

요소0, 요소1, ..., 요소N은 배열내에 포함된 요소의 값 목록 입니다. 해당 값들이 명시되어 있을 경우, 해당 배열은 주어진 요소들을 포함하도록 초기화 됩니다. 해당 배열의 길이는 주어진 요소들의 갯수가 됩니다. 

+ +

대괄호 문법은 일명 "배열  문자" 혹은 "배열 초기화"라고 합니다. 대괄호 문법은 다른 배열 생성 표기법 보다 짧고 일반적으로 선호하는 문법입니다. 보다 상세한 내용은 Array literals를 참조하세요.

+ +

 길이가 0보다 크지만 아무런 요소를 가지고 있지 않은 배열을 생성하기 위한 방법은 아래와 같습니다. 

+ +
var arr = new Array(arrayLength);
+var arr = Array(arrayLength);
+
+// This has exactly the same effect
+var arr = [];
+arr.length = arrayLength;
+
+ +
+

Note : 위의 예제 코드에서, arrayLength는 반드시 숫자여야 합니다. 그렇지 않으면 하나의 요소(주어진 값)을 가지는 배열이 생성 됩니다. arr.length를 호출하면 arrayLength가 반환이 되지만 해당 배열은 실제로 아무런 요소를 가지고 있지 않습니다. {{jsxref("Statements/for...in","for...in")}} 반복문을 실행하면 해당 배열은 아무런 요소를 반환하지 않습니다.

+
+ +

추가로 아래의 예제에서 볼 수 있듯이, 새로이 정의된 혹은 이미 존재하는 객체 변수의 속성으로 배열을 할당 할 수 있습니다.

+ +
var obj = {};
+// ...
+obj.prop = [element0, element1, ..., elementN];
+
+// OR
+var obj = {prop: [element0, element1, ...., elementN]}
+
+ +

값이 숫자인 하나의 요소만을 가지는 배열을 생성하고자 할 경우, 반드시 대괄호 문법을 사용해야 합니다. 하나의 숫자 값을 Array() 생성자에게 전달할 경우, 그 숫자 값은 해당 배열의 요소가 아니라 arrayLength(배열의 길이)로 해석됩니다. 

+ +
var arr = [42];
+var arr = Array(42); // Creates an array with no element,
+                     // but with arr.length set to 42
+
+// The above code is equivalent to
+var arr = [];
+arr.length = 42;
+
+ +

만약 숫자이지만 0이 아닌 소수점을 가지는 숫자를 Array()생성자에게 인자로 줄 경우, 범위 에러(RangeError)가 발생하게 됩니다. 아래의 예제는 범위 에러가 발생되는 상황을 보여 줍니다. 

+ +
var arr = Array(9.3);  // RangeError: Invalid array length
+
+ +

만약 임의의 데이터 형식인 하나의 요소를 가지는 배열을 생성하고자 할 경우, 배열 표기법을 사용하는 것이 안전합니다. 혹은 빈 배열을 먼저 선언한 후 임의의 데이터 값을 해당 배열에 추가하는 것도 방법이 됩니다. 

+ +

ES2015에서 요소가 하나인 배열을 만들기 위해  Array.of 정적 메소드를 사용할 수 있습니다.

+ +
let wisenArray = Array.of(9.3) // wisenArray contains only one element 9.3
+ +

배열에 값 저장

+ +

배열의 요소에 값을 할당하여 배열에 값을 저장할 수 있습니다. 예를 들면, 

+ +
var emp = [];
+emp[0] = 'Casey Jones';
+emp[1] = 'Phil Lesh';
+emp[2] = 'August West';
+
+ +
+

참고: 위의 코드 예제 처럼 배열 연산자에 양의 정수가 아닌 값을 줄 경우, 배열의 요소가 대신 배열로 대변되는 객체의 속성이 생성이 됩니다. 

+
+ +
var arr = [];
+arr[3.4] = 'Oranges';
+console.log(arr.length);                // 0
+console.log(arr.hasOwnProperty(3.4));   // true
+
+ +

배열을 생성함과 동시에 배열에 값을 저장할 수 있습니다. 

+ +
var myArray = new Array('Hello', myVar, 3.14159);
+var myArray = ['Mango', 'Apple', 'Orange'];
+
+ +

배열 요소의 참조

+ +

배열의 요소를 참조하기 위해서 해당 요소의 인덱스(요소의 순서를 나타내는 )를 사용할 수 있습니다. 예를 들어, 아래와 같이 배열을 선언 하였다면

+ +
var myArray = ['Wind', 'Rain', 'Fire'];
+
+ +

배열의 첫번째 요소는 myArray[0]로 참조할 수 있고 두번째 요소는 myArray[1]로 참조할 수 있습니다. 배열의 인덱스 값은 0부터 시작합니다.

+ +
+

참고: 배열 연산자(대괄호)는 배열의 속성에 접근하기 위해서도 사용될 수 있습니다.(배열 또한 객체이기 때문입니다.) 예를 들면 아래와 같습니다.

+
+ +
var arr = ['one', 'two', 'three'];
+arr[2];  // three
+arr["length"];  // 3
+
+ +

배열 길이에 대한 이해

+ +

실제 구현에서, 자바스트립트의 배열은 배열에 포함된 요소들을 배열의 인덱스 값을 속성 이름으로 사용하여 표준 객체의 속성처럼 저장을 합니다. 길이 속성은 좀 특별합니다. 배열의 길이는 항상 마지막 요소의 인덱스에 1을 더한 값을 반환합니다.(다음 예제에서 Dusty는 인덱스 30번째에 위치하기때문에 cats배열의 길이는 31이 됩니다.) 기억하실 것은 자바스크립트 배열의 인덱스는 항상 1부터가 아닌 0부터 시작합니다. 이것이 의미하는 바는 배열의 길이 속성은 배열에 저장되어 있는 가장 큰 인덱스보다 1만큼 큰 값이 된다는 것입니다. 

+ +
var cats = [];
+cats[30] = ['Dusty'];
+console.log(cats.length); // 31
+
+
+ +

배열의 길이(length) 속성을 지정하는 것 또한 가능합니다. 만약 배열에 저장되어 있는 요소의 갯수보다 작은 값을 배열 길이로 지정하게 되면, 지정된 배열 길이보다 큰 인덱스 값을 가지는 요소는 배열에서 삭제됩니다. 0을 배열 길이로 지정하게 되면 해당 배열은 요소를 가지지 않는 빈 배열이 되는 것입니다.

+ +
var cats = ['Dusty', 'Misty', 'Twiggy'];
+console.log(cats.length); // 3
+
+cats.length = 2;
+console.log(cats); // logs "Dusty,Misty" - Twiggy has been removed
+
+cats.length = 0;
+console.log(cats); // logs []; the cats array is empty
+
+cats.length = 3;
+console.log(cats); // logs [ <3 empty items ]
+
+ +

배열의 요소를 반복처리하기

+ +

배열을 가지고 처리하는 주된 작업은 배열의 요소를 반복적으로 접근해서 읽어오는 작업입니다. 가장 간단한 방법은 아래와 같습니다. 

+ +
var colors = ['red', 'green', 'blue'];
+for (var i = 0; i < colors.length; i++) {
+  console.log(colors[i]);
+}
+
+ +

배열이 아무런 요소를 포함하고 있지 않다면  반복문 조건에서 false로 평가됩니다. 배열의 요소가 DOM node들을 포함한다면 보다 효율적인 코드 관용구를 사용할 수 있습니다. 

+ +
var divs = document.getElementsByTagName('div');
+for (var i = 0, div; div = divs[i]; i++) {
+  /* Process div in some way */
+}
+
+ +

위의 예제 코드의 for반복문 조건은 배열의 길이을 확인하는 작업을 피할 수 있고, div변수가 매 반복마다 현재의 요소를 가지게 됩니다. 

+ +

{{jsxref("Array.forEach", "forEach()")}} 메서드는 배열의 요소를 반복처리할 수 있는 또 다른 방법입니다:

+ +
var colors = ['red', 'green', 'blue'];
+colors.forEach(function(color) {
+  console.log(color);
+});
+// red
+// green
+// blue
+
+ +

ES2015 Arrow Function으로 다음과 같이 더 짧게 코드를 짤 수 있습니다.

+ +
var colors = ['red', 'green', 'blue'];
+color.forEach(color => console.log(color));
+// red
+// green
+// blue
+
+ +

forEach에 인자로 주어진 함수는 배열의 각 요소에 대해 한번씩 실행이 되고 배열의 각 요소는 인자로 주어진 함수의 인자로 주어지게 됩니다. 할당 되지 않은 요소 값은 forEach 반복문에서 처리 되지 않습니다. 

+ +

forEach반복문으로 배열의 요소를 반복처리할때, 배열을 정의할 때 생략된 요소는 처리대상이 되지 않는 것에 유의 하세요. 하지만 undefined을 생략된 요소에 할당하게 되면 undefined로 처리됩니다.  

+ +

 

+ +
var array = ['first', 'second', , 'fourth'];
+
+array.forEach(function(element) {
+  console.log(element);
+})
+// first
+// second
+// fourth
+
+if(array[2] === undefined) {
+   console.log('array[2] is undefined'); // true
+}
+
+var array = ['first', 'second', undefined, 'fourth'];
+
+array.forEach(function(element) {
+  console.log(element);
+});
+// first
+// second
+// undefined
+// fourth
+
+ +

JavaScript 요소는 표준 객체 속성으로 저장되므로 {{jsxref ( "Statements / for ... in", "for ... in")}} 루프를 사용하여 JavaScript 배열을 반복하는 것은 바람직하지 않습니다. 왜냐면 일반 요소들과 그리고 모든 열거할 수 있는 속성들이 나열이 되기 때문입니다.

+ +

배열 객체의 메서드

+ +

{{jsxref("Array")}} 객체는 다음과 같은 메서드들을 가지고 있습니다:

+ +

{{jsxref("Array.concat", "concat()")}} 메서드는 두개의 배열을 합쳐 새로운 배열을 반환합니다.

+ +
var myArray = new Array('1', '2', '3');
+myArray = myArray.concat('a', 'b', 'c');
+// myArray is now ["1", "2", "3", "a", "b", "c"]
+ +

{{jsxref("Array.join", "join(delimiter = ',')")}} 메서드는 배열의 모든 요소를 주어진 구분자로 연결된 하나의 문자열을 반환 합니다. 

+ +
var myArray = new Array('Wind', 'Rain', 'Fire');
+var list = myArray.join(' - '); // list is "Wind - Rain - Fire"
+ +

{{jsxref("Array.push", "push()")}}메서드는 하나 혹은 그 이상의 요소를 배열의 마지막에 추가하고 추가된 요소를 포함한 길이를 반환합니다.

+ +
var myArray = new Array('1', '2');
+myArray.push('3'); // myArray is now ["1", "2", "3"]
+ +

{{jsxref("Array.pop", "pop()")}} 메서드는 배열의 마지막 요소를 제거 하고 그 제거된 요소를 반환합니다.

+ +
var myArray = new Array('1', '2', '3');
+var last = myArray.pop();
+// myArray is now ["1", "2"], last = "3"
+ +

{{jsxref("Array.shift", "shift()")}}메서드는 배열의 첫번째 요소를 제거하고 그 제거된 요소를 반환합니다.

+ +
var myArray = new Array('1', '2', '3');
+var first = myArray.shift();
+// myArray is now ["2", "3"], first is "1"
+ +

{{jsxref("Array.shift", "unshift()")}}메서드는 하나 혹은 그 이상의 요소를 배열의 앞쪽에 추가하고 추가한 요소를 포함한 길이를 반환 합니다.

+ +
var myArray = new Array('1', '2', '3');
+myArray.unshift('4', '5');
+// myArray becomes ["4", "5", "1", "2", "3"]
+ +

{{jsxref("Array.slice", "slice(start_index, upto_index)")}}메서드는 배열의 특정 부분을 추출하여 그 추출된 부분을 포함하는 새로운 배열을 반환 합니다. upto_index에 해당하는 요소는 포함되지 않습니다. 

+ +
var myArray = new Array('a', 'b', 'c', 'd', 'e');
+myArray = myArray.slice(1, 4); // starts at index 1 and extracts all elements
+                               // until index 3, returning [ "b", "c", "d"]
+ +

{{jsxref("Array.splice", "splice(index, count_to_remove, addElement1, addElement2, ...)")}} 메세드는 주어진 인덱스 요소를 포함하여 count_to_remove 갯수만큼 삭제 하고 주어진 요소로 바꿔 줍니다. 

+ +
var myArray = new Array('1', '2', '3', '4', '5');
+myArray.splice(1, 3, 'a', 'b', 'c', 'd');
+// myArray is now ["1", "a", "b", "c", "d", "5"]
+// This code started at index one (or where the "2" was),
+// removed 3 elements there, and then inserted all consecutive
+// elements in its place.
+ +

 

+ +

{{jsxref ( "Array.reverse", "reverse ()")}} 배열의 요소를 제자리에 배치합니다. 첫 번째 배열 요소가 마지막 요소가되고 마지막 요소가 첫 번째 요소가됩니다. 배열에 대한 참조를 반환합니다.

+ +
var myArray = new Array('1', '2', '3');
+myArray.reverse();
+// transposes the array so that myArray = ["3", "2", "1"]
+ +

 

+ +

{{jsxref ( "Array.sort", "sort ()")}} 배열의 요소를 제자리에 정렬하고 배열에 대한 참조를 반환합니다.

+ +
var myArray = new Array('Wind', 'Rain', 'Fire');
+myArray.sort();
+// sorts the array so that myArray = [ "Fire", "Rain", "Wind" ]
+
+ +

sort() 메서드에 어떻게 해당 배열의 요소를 정렬할 지 결정하는 콜백 함수를 인자로 줄 수 있습니다.

+ +

콜백을 사용하는 sort 메소드 및 다른 메소드는 반복 메소드로 알려져 있습니다. 일부 메소드에서는 전체 배열을 반복하기 때문입니다. 각각은 thisObject라는 선택적인 두 번째 인수를 취합니다. 제공되면 thisObject는 콜백 함수의 본문에있는 this 키워드의 값이됩니다.

+ +

제공되지 않으면 함수가 명시 적 객체 컨텍스트 외부에서 호출되는 다른 경우와 마찬가지로이 함수는 콜백으로 화살표 함수를 사용할 때 전역 객체 ({{domxref ( "window")}})를 참조합니다. 정상적인 기능은 콜백입니다.

+ +

콜백 함수는 배열의 요소 인 두 개의 인수로 호출됩니다.

+ +

아래 함수는 두 값을 비교하여 세 값 중 하나를 반환합니다.

+ +

예를 들어, 다음은 문자열의 마지막 문자로 정렬합니다.

+ +
var sortFn = function(a, b){
+  if (a[a.length - 1] < b[b.length - 1]) return -1;
+  if (a[a.length - 1] > b[b.length - 1]) return 1;
+  if (a[a.length - 1] == b[b.length - 1]) return 0;
+}
+myArray.sort(sortFn);
+// sorts the array so that myArray = ["Wind","Fire","Rain"]
+
+ + + +

{{jsxref ( "Array.indexOf", "indexOf (searchElement [, fromIndex])")}}는 배열에서 searchElement를 검색하고 첫 번째 일치 항목의 인덱스를 반환합니다.

+ +
var a = ['a', 'b', 'a', 'b', 'a'];
+console.log(a.indexOf('b')); // logs 1
+// Now try again, starting from after the last match
+console.log(a.indexOf('b', 2)); // logs 3
+console.log(a.indexOf('z')); // logs -1, because 'z' was not found
+
+ +

{{jsxref("Array.lastIndexOf", "lastIndexOf(searchElement[, fromIndex])")}}메서드는 indexOf메서드와 유사하게 작동하지만 배열의 뒤쪽에서부터 요소를 찾습니다.

+ +
var a = ['a', 'b', 'c', 'd', 'a', 'b'];
+console.log(a.lastIndexOf('b')); // logs 5
+// Now try again, starting from before the last match
+console.log(a.lastIndexOf('b', 4)); // logs 1
+console.log(a.lastIndexOf('z')); // logs -1
+
+ +

{{jsxref("Array.forEach", "forEach(callback[, thisObject])")}}메서드는 배열의 모든 요소에 대해 반복적으로 주어진 callback 함수를 실행합니다. 

+ +
var a = ['a', 'b', 'c'];
+a.forEach(function(element) { console.log(element);} );
+// logs each item in turn
+
+ +

{{jsxref("Array.map", "map(callback[, thisObject])")}}메서드는 배열의 모든 요소에 대해 콜백함수를 실행하고 콜백함수의 실행결과를 새로운 배열에 담아 반환합니다.

+ +
var a1 = ['a', 'b', 'c'];
+var a2 = a1.map(function(item) { return item.toUpperCase(); });
+console.log(a2); // logs ['A', 'B', 'C']
+
+ +

{{jsxref("Array.filter", "filter(callback[, thisObject])")}}메서드는 배열의 모든 요소에 대해 콜백 함수가 true를 반환하는 요소를 새로운 배열에 담아 반환 합니다. 

+ +
var a1 = ['a', 10, 'b', 20, 'c', 30];
+var a2 = a1.filter(function(item) { return typeof item == 'number'; });
+console.log(a2); // logs ['10', '20', '30']
+
+ +

 

+ +

{{jsxref ( "Array.every", "every (callback [, thisObject])")}}는 콜백이 배열의 모든 항목에 대해 true를 반환하면 true를 반환합니다.

+ +
function isNumber(value){
+  return typeof value == 'number';
+}
+var a1 = [1, 2, 3];
+console.log(a1.every(isNumber)); // logs true
+var a2 = [1, '2', 3];
+console.log(a2.every(isNumber)); // logs false
+
+ +

{{jsxref("Array.some", "some(callback[, thisObject])")}}메서드는 배열의 모든 요소에 대해 콜백 함수를 실행하고 하나의 요소라도 콜백 함수의 결과가 true이면 some()메서드의 결과는 true가 됩니다.

+ +
function isNumber(value){
+  return typeof value == 'number';
+}
+var a1 = [1, 2, 3];
+console.log(a1.some(isNumber)); // logs true
+var a2 = [1, '2', 3];
+console.log(a2.some(isNumber)); // logs true
+var a3 = ['1', '2', '3'];
+console.log(a3.some(isNumber)); // logs false
+
+ +

{{jsxref("Array.reduce", "reduce(callback[, initialValue])")}}메서드는 배열내의 요소를 하나의 요소로 줄이기 위해 firstValue, secondValue를 인자로 받는 콜백 함수를 실행합니다.

+ +
var a = [10, 20, 30];
+var total = a.reduce(function(first, second) { return first + second; }, 0);
+console.log(total) // Prints 60
+
+ +

{{jsxref("Array.reduceRight", "reduceRight(callback[, initalvalue])")}}메서드는 reduce()와 유사하게 작동하지만 배열의 마지막 요소부터 시작합니다.

+ +

reduce와 reduceRight 메서드는 반복적인 배열 메서드 중 가장 명백합니다. 두 메서드는 재귀적으로 하나의 시퀀스를 하나의 값으로 줄이기 위해 두개의 값을 합치는 알고리즘을 위해 사용되어야 합니다. 

+ +

다차원 배열

+ +

배열은 중첩될 수 있습니다. 즉, 하나의 배열은 또 다른 배열을 요소로 포함할 수 있습니다. 자바스크립트 배열의 이런 특성을 사용하여, 다차원 배열을 생성할 수 있습니다.

+ +

아래의 예제는 2차원 배열을 생성하는 예제입니다.

+ +
var a = new Array(4);
+for (i = 0; i < 4; i++) {
+  a[i] = new Array(4);
+  for (j = 0; j < 4; j++) {
+    a[i][j] = '[' + i + ', ' + j + ']';
+  }
+}
+ +

이 예제는 다음과 같은 열을 포함하는 배열을 생성합니다.

+ +
Row 0: [0,0] [0,1] [0,2] [0,3]
+Row 1: [1,0] [1,1] [1,2] [1,3]
+Row 2: [2,0] [2,1] [2,2] [2,3]
+Row 3: [3,0] [3,1] [3,2] [3,3]
+
+ +

배열과 정규표현식

+ +

문자열내에 정규 표현식에 일치하는 결과가 배열일 경우, 해당 배열은 정규 표현식에 일치하는 문자열들의 정보를 제공해 주는 속성들과 요소들을 반환합니다. {{jsxref ( "Global_Objects / RegExp / exec", "RegExp.exec ()")}}, {{jsxref("Global_Objects/String/match","String.match()")}}, 와 {{jsxref("Global_Objects/String/split","String.split()")}}메서드는 결과를 배열로 반환합니다. 정규식과 함께 배열을 어떻게 사용하는지에 대한 정보는 정규표현식을 참조하시면 됩니다. 

+ +

배열과 유사한 객체 사용

+ +

{{domxref ( "document.getElementsByTagName ()")}} 또는 {{jsxref ( "Functions / arguments", "arguments")}}에서 반환하는 {{domxref("NodeList")}}  객체는 함수 본문 내에서 사용할 수 있게 만들어졌으며 겉으로는 배열처럼 보이고 작동하지만 모든 메서드를 공유하지는 않습니다. arguments 객체는 {{jsxref ( "Global_Objects / Function / length", "length")}} 속성을 제공하지만 {{jsxref ( "Array.forEach", "forEach ()")}} 메소드는 구현하지 않습니다.

+ +

배열 프로토 타입 메소드는 다른 배열과 유사한 객체에 대해 호출 될 수 있습니다.

+ +
function printArguments() {
+  Array.prototype.forEach.call(arguments, function(item) {
+    console.log(item);
+  });
+}
+
+ +

배열 프로토 타입 메서드는 배열과 비슷한 방식으로 문자에 순차적으로 액세스 할 수 있으므로 문자열에서도 사용할 수 있습니다.

+ +
Array.prototype.forEach.call('a string', function(chr) {
+  console.log(chr);
+});
+ +

타입 배열

+ +

자바스크립트 타입 배열은 배열과 유사한 객체이며 원시 이진 데이터 접근에 대한 메카니즘을 제공합니다. 이미 알고 있듯이, {{jsxref("Array")}}객체는 동적으로 크기가 커지고 작아 질 수 있으며 어떤 자바스크립트 값이라도 가질 수 있습니다. 자바스크립트 엔진은 그런 배열을 빠르게 만들기 위해 최적화를 수행합니다. 그러나 웹 어플케이션이 보다 강력해지고, 음성, 영상 조작, 웹소켓을 사용하여 원시 데이터에 접근하는 등의 기능들이 추가 되면서 자바스크립트 코드가 타입배열을 가지고 빠르고 쉽게 원시 이진 데이터를 조작할 수 있는 것이 가능한 시점이 되었다는 것은 보다 명백해졌습니다.

+ +

버퍼와 뷰: 타입 배열 구조

+ +

유연성과 효율성을 극대화 하기 위해, 자바스크립트 타입 배열을 버퍼라는 구조로 구현되어 있습니다. 하나의 버퍼({{jsxref("ArrayBuffer")}}객체로 구현되어 있습니다.)는 하나의 데이터 덩어리를 의미하는 객체입니다. 버퍼는 구체적으로 언급할 형식이 없고, 버퍼가 담고 있는 내용에 접근할 메카니즘을 제공하지 않습니다. 버퍼에 담겨져 있는 메모리에 접근하기 위해선, 뷰를 사용해야 합니다. 하나의 뷰는 컨덱스트를 제공하는데, 컨텍스트는 데이터 형, 시작 오프셋 그리고 실제 타입배열로 변경되는 요소의 갯수를 제공합니다. 

+ +

Typed arrays in an ArrayBuffer

+ +

배열버퍼

+ +

{{jsxref("ArrayBuffer")}}는 일반적이고, 고정길이의 이진 데이터 버퍼를 표현하기 위해 사용되는 데이터 타입입니다. ArrayBuffer의 내용을 직접 수정할 수는 없는 대신 타입 배열 뷰 혹은 특정 형식 그리고 해당 버퍼의 내용을 읽고 쓸수 있게 해주는 {{jsxref("DataView")}}를 생성할 수 있습니다.

+ +

타입 배열 뷰

+ +

타입 배열 뷰들은 스스로를 나타낼 수 있는 이름과 Int8, Uint32, Float64등의 일반적인 숫자 형들을 위한 뷰를 제공합니다.Uint8ClampedArray라는 특별한 타입 배열 뷰가 있습니다. 0부터 255까지의 값을 가질수 있습니다. 예를 들며, Uint8ClampedArray는 Canvas data processing에 유용합니다. 

+ +

{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects")}}

+ +

JavaScript typed arrays를 참조하시면 보다 많은 정보를 보실 수 있습니다. 

+ +

{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Keyed_Collections")}}

diff --git a/files/ko/web/javascript/guide/inheritance_and_the_prototype_chain/index.html b/files/ko/web/javascript/guide/inheritance_and_the_prototype_chain/index.html new file mode 100644 index 0000000000..e05bab3102 --- /dev/null +++ b/files/ko/web/javascript/guide/inheritance_and_the_prototype_chain/index.html @@ -0,0 +1,531 @@ +--- +title: 상속과 프로토타입 +slug: Web/JavaScript/Guide/Inheritance_and_the_prototype_chain +tags: + - JavaScript + - 객체지향 + - 상속 + - 중급 +translation_of: Web/JavaScript/Inheritance_and_the_prototype_chain +--- +

{{jsSidebar("Advanced")}}

+ +

Java 나 C++ 같이 클래스 기반의 언어를 사용하던 프로그래머는 자바스크립트가 동적인 언어라는 점과 클래스가 없다는 것에서 혼란스러워 한다. (ES2015부터 class 키워드를 지원하기 시작했으나, 문법적인 양념일 뿐이며 자바스크립트는 여전히 프로토타입 기반의 언어다.)

+ +

상속 관점에서 자바스크립트의 유일한 생성자는 객체뿐이다. 각각의 객체는 [[Prototype]]이라는 은닉(private) 속성을 가지는데 자신의 프로토타입이 되는 다른 객체를 가리킨다. 그 객체의 프로토타입 또한 프로토타입을 가지고 있고 이것이 반복되다, 결국 null을 프로토타입으로 가지는 오브젝트에서 끝난다. null은 더 이상의 프로토타입이 없다고 정의되며, 프로토타입 체인의 종점 역할을 한다.

+ +

종종 이러한 점이 자바스크립트의 약점이라고 지적되지만, 프로토타입적 상속 모델은 사실 고전적인 방법보다 좀 더 강력한 방법이다. 그 말은, 예를 들자면, 프로토타입적 모델에서 고전적인 방식을 구현하는 건 꽤나 사소한 일이지만, 그 반대는 훨씬 더 어려운 일이기 때문이다.

+ +

프로토타입 체인을 이용한 상속

+ +

속성 상속

+ +

자바스크립트 객체는 속성을 저장하는 동적인 "가방"과 (자기만의 속성이라고 부른다) 프로토타입 객체에 대한 링크를 가진다. 객체의 어떤 속성에 접근하려할 때 그 객체 자체 속성 뿐만 아니라 객체의 프로토타입, 그 프로토타입의 프로토타입 등 프로토타입 체인의 종단에 이를 때까지 그 속성을 탐색한다.

+ +
ECMAScript 표준은 someObject.[[Prototype]]을 객체 someObject의 프로토타입을 지시하도록 명시하였다. ECMAScript 2015부터 [[Prototype]]에 조상 {{jsxref("Object.getPrototypeOf()")}}과 {{jsxref("Object.setPrototypeOf()")}}을 이용하여 접근하기 때문이다. 이것은 자바스크립트의 표준은 아니나 많은 브라우저에 구현되어 사실상의 표준이 된 속성 __proto__과 동일하다.
+ +

아래 코드에는 어떤 속성에 접근 하려할 때 일어나는 상황이다.

+ +
// o라는 객체가 있고, 속성 'a' 와 'b'를 갖고 있다고 하자.
+let f = function () {
+    this.a = 1;
+    this.b = 2;
+}
+let o = new f(); // {a: 1, b: 2}
+
+// f 함수의 prototype 속성 값들을 추가 하자.
+f.prototype.b = 3;
+f.prototype.c = 4;
+
+// f.prototype = {b: 3, c: 4}; 라고 하지 마라, 해당 코드는 prototype chain 을 망가뜨린다.
+// o.[[Prototype]]은 속성 'b'와 'c'를 가지고 있다.
+// o.[[Prototype]].[[Prototype]] 은 Object.prototype 이다.
+// 마지막으로 o.[[Prototype]].[[Prototype]].[[Prototype]]은 null이다.
+// null은 프로토타입의 종단을 말하며 정의에 의해서 추가 [[Prototype]]은 없다.
+// {a: 1, b: 2} ---> {b: 3, c: 4} ---> Object.prototype ---> null
+
+console.log(o.a); // 1
+// o는 'a'라는 속성을 가지는가? 그렇다. 속성의 값은 1이다.
+
+console.log(o.b); // 2
+// o는 'b'라는 속성을 가지는가? 그렇다. 속성의 값은 2이다.
+// 프로토타입 역시 'b'라는 속성을 가지지만 이 값은 쓰이지 않는다. 이것을 "속성의 가려짐(property shadowing)" 이라고 부른다.
+
+console.log(o.c); // 4
+// o는 'c'라는 속성을 가지는가? 아니다. 프로토타입을 확인해보자.
+// o.[[Prototype]]은 'c'라는 속성을 가지는가? 가지고 값은 4이다.
+
+console.log(o.d); // undefined
+// o는 'd'라는 속성을 가지는가? 아니다. 프로토타입을 확인해보자.
+// o.[[Prototype]]은 'd'라는 속성을 가지는가? 아니다. 다시 프로토타입을 확인해보자.
+// o.[[Prototype]].[[Prototype]]은 null이다. 찾는 것을 그만두자.
+// 속성이 발견되지 않았기 때문에 undefined를 반환한다.
+
+ +

객체의 속성에 값을 지정하면 "자기만의 속성"이 생긴다.  단, getter or a setter가 적용되는 속성이 상속되는 경우 예외적인 규칙이 적용된다.

+ +

메소드 상속

+ +

자바스크립트에 "메소드"라는건 없다. 하지만 자바스크립트는 객체의 속성으로 함수를 지정할 수 있고 속성 값을 사용하듯 쓸 수 있다. 속성 값으로 지정한 함수의 상속 역시 위에서 본 속성의 상속과 동일하다. (단 위에서 언급한 "속성의 가려짐" 대신 "메소드 오버라이딩, method overriding" 라는 용어를 사용한다)

+ +

상속된 함수가 실행 될 때,  this 라는 변수는 상속된 오브젝트를 가르킨다. 그 함수가 프로토타입의 속성으로 지정되었다고 해도 말이다.

+ +
var o = {
+  a: 2,
+  m: function(b){
+    return this.a + 1;
+  }
+};
+
+console.log(o.m()); // 3
+// o.m을 호출하면 'this' 는 o를 가리킨다.
+
+var p = Object.create(o);
+// p 는 프로토타입을 o로 가지는 오브젝트이다.
+
+p.a = 12; // p 에 'a'라는 새로운 속성을 만들었다.
+console.log(p.m()); // 13
+// p.m이 호출 될 때 'this' 는 'p'를 가리킨다.
+// 따라서 o의 함수 m을 상속 받으며,
+// 'this.a'는 p.a를 나타내며 p의 개인 속성 'a'가 된다.
+
+ +

Javascript 에서 프로토타입을 사용하는 방법

+ +

뒤에서 일어나는 일을 좀 더 자세히 파헤쳐보자.

+ +

위에서 언급했듯이, 자바스크립트에서 함수는 속성을 가질 수 있다. 모든 함수에는 prototype이라는 특수한 속성이 있다. 아래의 예제 코드는 독립적이라는 것에 유의하자. (아래의 코드 이외에는 웹페이지에 다른 자바스크립트가 없다고 가정하는 것이 좋다.)

+ +

최적의 실습을 위해서 콘솔을 열고 "Console" 탭으로 이동하여 아래의 JavaScript 코드를 복사하여 붙여넣은 다음 , 엔터키를 눌러 실행할 것을 적극 권한다. (콘솔은 대부분 웹 브라우저의 Developer Tools에 포함되어있다. 자세한 내용은 Firefox Developer ToolsChrome DevTools, Edge DevTools 에서 확인할 수 있다. )

+ +
+ +
function doSomething(){}
+console.log( doSomething.prototype );
+// It does not matter how you declare the function, a
+//  function in JavaScript will always have a default
+//  prototype property.
+var doSomething = function(){};
+console.log( doSomething.prototype );
+ +

위 내용을 토대로, 콘솔을 보면  doSomething() 은 기본 prototype 속성을 가진다. 코드를 실행한 뒤에 콘솔에서는 다음과 유사한 형태의 객체가 표시되어야한다.

+ +
{
+    constructor: ƒ doSomething(),
+    __proto__: {
+        constructor: ƒ Object(),
+        hasOwnProperty: ƒ hasOwnProperty(),
+        isPrototypeOf: ƒ isPrototypeOf(),
+        propertyIsEnumerable: ƒ propertyIsEnumerable(),
+        toLocaleString: ƒ toLocaleString(),
+        toString: ƒ toString(),
+        valueOf: ƒ valueOf()
+    }
+}
+ +

우리는 아래에 보이는 것과 같이 doSomething() 프로토타입에 속성을 추가할 수 있다.

+ +
function doSomething(){}
+doSomething.prototype.foo = "bar";
+console.log( doSomething.prototype );
+ +

결과:

+ +
{
+    foo: "bar",
+    constructor: ƒ doSomething(),
+    __proto__: {
+        constructor: ƒ Object(),
+        hasOwnProperty: ƒ hasOwnProperty(),
+        isPrototypeOf: ƒ isPrototypeOf(),
+        propertyIsEnumerable: ƒ propertyIsEnumerable(),
+        toLocaleString: ƒ toLocaleString(),
+        toString: ƒ toString(),
+        valueOf: ƒ valueOf()
+    }
+}
+
+ +

이제 new 연산자를 사용해서 프로토타입 기반의 doSomething() 인스턴스를 생성할 수 있다. new 연산자를 사용하려면 함수 호출 형식에 new 접두사를 붙이기만하면 된다. new 연산자로 함수를 호출하면 해당 함수의 인스턴스 객체를 반환받는다. 그러면 속성들을 이 객체에 추가할 수 있다.

+ +

다음의 코드를 실행해보자.

+ +
function doSomething(){}
+doSomething.prototype.foo = "bar"; // add a property onto the prototype
+var doSomeInstancing = new doSomething();
+doSomeInstancing.prop = "some value"; // add a property onto the object
+console.log( doSomeInstancing );
+ +

실행하고나면 결과는 다음과 비슷할 것이다.

+ +
{
+    prop: "some value",
+    __proto__: {
+        foo: "bar",
+        constructor: ƒ doSomething(),
+        __proto__: {
+            constructor: ƒ Object(),
+            hasOwnProperty: ƒ hasOwnProperty(),
+            isPrototypeOf: ƒ isPrototypeOf(),
+            propertyIsEnumerable: ƒ propertyIsEnumerable(),
+            toLocaleString: ƒ toLocaleString(),
+            toString: ƒ toString(),
+            valueOf: ƒ valueOf()
+        }
+    }
+}
+
+ +

위에서 본 것과 같이, doSomeInstancing 객체의 __proto__ 는 doSomething.prototype 이다.
+ 그래서 도대체 __proto__는 무엇을 하는것인지 알아보자.
+ 우리가 doSomeInstancing의 속성에 접근할때 브라우저는 우선 doSomeInstancing이 그 속성을 갖고있는지 확인한다.
+ 만약 doSomeInstancing이 속성을 갖고있지 않다면, 브라우저는 doSomeInstancing의 __proto__(doSomething.prototype)가 그 속성을 갖고있는지 확인한다.
+ 만약 doSomeInstancing의 __proto__가 브라우저가 찾던 속성을 갖고 있다면, doSomething의 __proto__가 갖고있는 그 속성을 사용한다.

+ +

그렇지 않고, doSomeInstancing의 __proto__가 그 속성을 갖고있지 않을때에는
+ doSomeInstancing의 __proto__의 __proto__가 그 속성을 갖는지 확인한다.
+ 기본적으로, 어떠한 함수던지 그 함수의 prototype 속성의 __proto__는 window.Object.prototype이다.
+ 그러므로 브라우저는 doSomeInstancing의 __proto__의 __proto__(doSomething.prototype의 __proto__(다시말해, Object.prototype))  에서 그 속성을 찾아본다.
+ 만약 그 속성을 doSomeInstancing의 __proto__의 __proto__에서 찾을 수 없다면 그다음엔 doSomeInstancing의 __proto__의 __proto__의 __proto__에서 찾을것이다.
+ 하지만 여기서 문제가 발생한다.
+ doSomeInstancing의 __proto__의 __proto__의 __proto__는 존재할 수 없다(window.Object.prototype의 __proto__는 null이기 때문).
+ 그제서야, 오직 모든 프로토타입 체인이 검사 되고 브라우저가 더이상  검사할 __proto__가 없을때에서야 브라우저는 우리가 찾던 값이 undefined라고 결론짓는다.

+ +

콘솔에 코드를 조금 더 추가해보자.

+ +
function doSomething(){}
+doSomething.prototype.foo = "bar";
+var doSomeInstancing = new doSomething();
+doSomeInstancing.prop = "some value";
+console.log("doSomeInstancing.prop:      " + doSomeInstancing.prop);
+console.log("doSomeInstancing.foo:       " + doSomeInstancing.foo);
+console.log("doSomething.prop:           " + doSomething.prop);
+console.log("doSomething.foo:            " + doSomething.foo);
+console.log("doSomething.prototype.prop: " + doSomething.prototype.prop);
+console.log("doSomething.prototype.foo:  " + doSomething.prototype.foo);
+
+ +

이 코드의 결과는 아래와 같다.

+ +
doSomeInstancing.prop:      some value
+doSomeInstancing.foo:       bar
+doSomething.prop:           undefined
+doSomething.foo:            undefined
+doSomething.prototype.prop: undefined
+doSomething.prototype.foo:  bar
+
+ +

객체를 생성하는 여러 방법과 프로토타입 체인 결과

+ +

문법 생성자로 객체 생성

+ +
var o = {a: 1};
+
+// o 객체는 프로토타입으로 Object.prototype 을 가진다.
+// 이로 인해 o.hasOwnProperty('a') 같은 코드를 사용할 수 있다.
+// hasOwnProperty 라는 속성은 Object.prototype 의 속성이다.
+// Object.prototype 의 프로토타입은 null 이다.
+// o ---> Object.prototype ---> null
+
+var a = ["yo", "whadup", "?"];
+
+// Array.prototype을 상속받은 배열도 마찬가지다.
+// (이번에는 indexOf, forEach 등의 메소드를 가진다)
+// 프로토타입 체인은 다음과 같다.
+// a ---> Array.prototype ---> Object.prototype ---> null
+
+function f(){
+  return 2;
+}
+
+// 함수는 Function.prototype 을 상속받는다.
+// (이 프로토타입은 call, bind 같은 메소드를 가진다)
+// f ---> Function.prototype ---> Object.prototype ---> null
+
+ +

생성자를 이용

+ +

자바스크립트에서 생성자는 단지 new 연산자를  사용해 함수를 호출하면 된다.

+ +
function Graph() {
+  this.vertexes = [];
+  this.edges = [];
+}
+
+Graph.prototype = {
+  addVertex: function(v){
+    this.vertexes.push(v);
+  }
+};
+
+var g = new Graph();
+// g 'vertexes' 와 'edges'를 속성으로 가지는 객체이다.
+// 생성시 g.[[Prototype]]은 Graph.prototype의 값과 같은 값을 가진다.
+
+ +

Object.create 이용

+ +

ECMAScript 5는 새로운 방법을 도입했다. Object.create라는 메소드를 호출하여 새로운 객체를 만들 수 있다. 생성된 객체의 프로토타입은 이 메소드의 첫 번째 인수로 지정된다.

+ +
var a = {a: 1};
+// a ---> Object.prototype ---> null
+
+var b = Object.create(a);
+// b ---> a ---> Object.prototype ---> null
+console.log(b.a); // 1 (상속됨)
+
+var c = Object.create(b);
+// c ---> b ---> a ---> Object.prototype ---> null
+
+var d = Object.create(null);
+// d ---> null
+console.log(d.hasOwnProperty); // undefined이다. 왜냐하면 d는 Object.prototype을 상속받지 않기 때문이다.
+
+ +
+

class 키워드 이용

+ +

ECMAScript2015에는 몇 가지 키워드가 도입되어 class를 구현하였다. 이런 생성 방식은 클래서 기반 언어의 개발자들에게 친숙하게 다가오나 동작 방식이 같지는 않다. 자바스크립트는 여전히 프로토타입 기반으로 남아있다. 새로 도입된 키워드는 {{jsxref("Statements/class", "class")}}, {{jsxref("Classes/constructor", "constructor")}}, {{jsxref("Classes/static", "static")}}, {{jsxref("Classes/extends", "extends")}}, 그리고 {{jsxref("Operators/super", "super")}}가 있다.

+ +
'use strict';
+
+class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+
+class Square extends Polygon {
+  constructor(sideLength) {
+    super(sideLength, sideLength);
+  }
+  get area() {
+    return this.height * this.width;
+  }
+  set sideLength(newLength) {
+    this.height = newLength;
+    this.width = newLength;
+  }
+}
+
+var square = new Square(2);
+
+ +

성능

+ +

프로토타입 체인에 걸친 속성 검색으로 성능에 나쁜 영향을 줄 수 있으며, 때때로 치명적일 수 있다. 또한 존재하지도 않는 속성에 접근하려는 시도는 항상 모든 프로토타입 체인인 전체를 탐색해서 확인하게 만든다.

+ +

객체의 속성에 걸쳐 루프를 수행 하는 경우 프로토타입 체인 전체의 모든 열거자 속성에 대하여 적용된다. 객체 개인 속성인지 프로토타입 체인상 어딘가에 있는지 확인하기 위해서는 Object.prototype에서 모든 오브젝트로 상속된 hasOwnProperty 메소드를 이용할 필요가 있다. 다음 코드를 통하여 구체적인 예를 확인하여 보자.

+ +
console.log(g.hasOwnProperty('vertices'));
+// true
+
+console.log(g.hasOwnProperty('nope'));
+// false
+
+console.log(g.hasOwnProperty('addVertex'));
+// false
+
+console.log(g.__proto__.hasOwnProperty('addVertex'));
+// true
+
+ +

hasOwnProperty 메소드만이 속성을 확인하고 프로토타입 체인 전체를 훑지 않게 할 수 있다.

+ +

참고: undefined인지 여부만 확인하는 것으로는 충분하지 않다. 여전히 속성이 존재할 수도 있는데 단지 그 값에 undefined가 할당되어 있을 수도 있기 때문이다.

+ +

좋지 않은 사례: 기본 프로타입의 확장 변형

+ +

Object.prototype 혹은 빌트인 프로토타입의 확장은 종종 이용되지만 오용이다.

+ +

이 기법은 Monkey patching으로 불리며 캡슐화를 망가뜨린다. Prototype.js와 같은 유명한 프레임워크에서도 사용되지만, 빌트인 타입에 비표준 기능을 추가하는 것은 좋은 생각이 아니다.

+ +

유일하게 좋은 사용 예라면, 새로운 자바스크립트 엔진에 Array.forEach등의 새로운 기능을 추가하면서 빌트인 프로토타입을 확장하는 것 정도다. 

+ +

+ +

B는 A를 상속한다:

+ +
function A(a) {
+  this.varA = a;
+}
+
+// A의 정의에서 this.varA는 항상 A.prototype.varA가 가려버리는데
+// prototype에 varA를 다시 넣는 이유는 무엇인가?
+A.prototype = {
+  varA: null,  // 아무것도 안하면서 varA를 쓰는 이유가 있을까?
+      // 아마도 숨겨진 클래스의 할당 구조를 최적화 하려는 것인가?
+      // https://developers.google.com/speed/articles/optimizing-javascript#Initializing-instance-variables
+      // 모든 객체의 varA가 동일하게 초기화 되어야 상기 링크 내용이 유효할 수 있다.
+  doSomething: function() {
+    // ...
+  }
+};
+
+function B(a, b) {
+  A.call(this, a);
+  this.varB = b;
+}
+B.prototype = Object.create(A.prototype, {
+  varB: {
+    value: null,
+    enumerable: true,
+    configurable: true,
+    writable: true
+  },
+  doSomething: {
+    value: function() { // override
+      A.prototype.doSomething.apply(this, arguments); // call super
+      // ...
+    },
+    enumerable: true,
+    configurable: true,
+    writable: true
+  }
+});
+B.prototype.constructor = B;
+
+var b = new B();
+b.doSomething();
+
+ +

중요한 점은:

+ + + +

prototype 그리고 Object.getPrototypeOf

+ +

Java나 C++에 익숙한 개발자는 클래스라는 것도 없고, 모든 것이 동적이고 실행 시 결정되는 자바스크립트의 특징 때문에 어려움을 겪을 수도 있다. 모든 것은 객체이고, 심지의 "class"를 흉내내는 방식도 단지 함수 오브젝트를 이용하는 것 뿐이다.

+ +

이미 알아챘겠지만 우리의 함수 A도 특별한 속성 prototype를 가지고 있다. 이 특별한 속성은 자바스크립트의 new 연산자와 함께 쓰인다. 프로토타입 객체는 새로 만들어진 인스턴스의 내부 [[Prototype]] 속성에 복사되어 참조된다. 가령, var a1 = new A()를 수행할 때, this를 포함하고 있는 함수을 수행하기 전, 메모리에 새로 생성된 객체를 생성한 직후 자바스크립트는 a1.[[Prototype]] = A.prototype를 수행한다. 그 인스턴스의 속성에 접근하려 할 때 자바스크립트는 그 객체의 개인 속성인지 우선 확인하고 그렇지 않은 경우에 [[Prototype]]에서 찾는다. 이것은 prototype에 정의한 모든 것은 모든 인스턴스가 효과적으로 공유한다는 뜻이며, 심지어 프로토타입의 일부를 나중에 변경하다고 해도 이미 생성되어 있는 인스턴스는 필요한 경우 그 변경 사항에 접근할 수 있다.

+ +

위의 예에서, 만일 var a1 = new A(); var a2 = new A(); 그 후 a1.doSomethingObject.getPrototypeOf(a1).doSomething를 가리키게 되는 것은A.prototype.doSomething으로 정의한 것과 같게 된다. 즉, Object.getPrototypeOf(a1).doSomething == Object.getPrototypeOf(a2).doSomething == A.prototype.doSomething.

+ +

요약 하자면, prototype은 타입 정의를 위한 것이고, Object.getPrototypeOf()는 모든 인스턴스가 공유한다.

+ +

[[Prototype]]은 재귀적으로 탐색된다. 즉, a1.doSomething, Object.getPrototypeOf(a1).doSomething,Object.getPrototypeOf(Object.getPrototypeOf(a1)).doSomething 등등, 이미 발견했거나 Object.getPrototypeOfnull을 반환할 때까지 반복된다.

+ +

따라서 다음 호출에 대하여

+ +
var o = new Foo();
+ +

자바스크립트는 실제로 다음 작업을 수행한다.

+ +
var o = new Object();
+o.[[Prototype]] = Foo.prototype;
+Foo.call(o);
+ +

(혹은 그런 비슷한 작업, 내부 구현은 다를 수 있다) 그리고 나중에 다음을 수행하면

+ +
o.someProp;
+ +

자바스크립트는 o가 속성 someProp을 가졌는지 확인하고, 아니면 Object.getPrototypeOf(o).someProp, 또 아니면 Object.getPrototypeOf(Object.getPrototypeOf(o)).someProp 등으로 계속 된다.

+ +

프로토타입 상속의 종류

+ +

프로토타입 상속에는 3가지 종류가 있다 : 위임형 상속, 연결형 상속, 함수형 상속.

+ +

위임형 상속(Delegation inheritance)

+ +

위임형 상속에서 프로토타입 객체는 다른 객체의 기반이 된다. 위임 프로토타입을 상속받을 경우 새 객체는 해당 프로토타입에 대한 참조를 가지고 있다.

+ +

새 객체의 속성에 접근할 때, 해당 객체가 직접적으로 속성을 소유하고 있는지 먼저 체크한다. 없다면 다음 순서로 [[Prototype]]을 체크한다. 이 과정은 프로토타입 체인을 따라서 모든 객체의 프로토타입 체인의 최상위에 있는 객체인 Object.prototype에 도달할 때 까지 반복된다.

+ +

메소드를 위임 상속할 경우 모든 객체가 각 메소드에에 대해 하나의 코드를 공유하므로 메모리를 절약할 수 있다.

+ +

Javascript에서 이를 구현하는 방법은 여러가지가 있는데 ES6에서는 아래와 같은 방식이 흔하다:

+ +
class Greeter {
+  constructor (name) {
+    this.name = name || 'John Doe';
+  }
+  hello () {
+    return `Hello, my name is ${ this.name }`;
+  }
+}
+
+const george = new Greeter('George');
+const msg = george.hello();
+console.log(msg); // Hello, my name is George
+
+ +

Object.create(null). 을 통해 프로토타입을 {{jsxref("null")}}로 지정하여 속성 위임 없이 객체를 생성할 수 있다..

+ +

이 방법의 큰 단점 중 하나는 상태를 저장하는데 그리 좋은 방법이 아니라는 것이다. 객체나 배열의 상태를 변경하게 되면 같은 프로토타입을 공유하는 모든 객체의 상태가 변경된다.

+ +

상태 변경이 전파되는 것을 막으려면 각 객체마다 상태 값의 복사본을 만들어야 한다.

+ +

연결형 상속(Concatenative inheritance)

+ +

연결형 상속은 한 객체의 속성을 다른 객체에 모두 복사함으로써 상속을 구현하는 방법이다.

+ +

이 상속법은 Javascript 객체의 동적 확장성을 이용한 방법이다. 객체 복사는 속성의 초기값을 저장하기 위한 좋은 방법이다: 이 방식은 {{jsxref("Object.assign()")}}을 통해 구현하는 것이 보통이며 ES6 이전에 Lodash, Underscore, jQuery등의 라이브러리들이 .extend() 와 비슷한 메소드로 제공한 방법이다.

+ +
const proto = {
+  hello: function hello() {
+    return `Hello, my name is ${ this.name }`;
+  }
+};
+
+const george = Object.assign({}, proto, {name: 'George'});
+const msg = george.hello();
+console.log(msg); // Hello, my name is George
+
+ +

연결형 상속은 매우 좋은 방법이며 클로져와 같이 사용한다면 훨씬 효과적인 상속 방식입니다..

+ +

함수형 상속(Functional inheritance)

+ +

함수형 상속(Functional inheritance)이라는 단어는 Douglas Crockford가 자신의 저서 “JavaScript: The Good Parts”에서 창조한 단어이다. 이 방법은 새 속성들을 연결형 상속으로 쌓되 상속 기능을 Factory 함수로 만들어 사용하는 방식이다.

+ +

기존의 객체를 확장하는데 쓰이는 함수를 일반적으로 믹스인 함수라 칭한다. 객체 확장에 함수를 사용하는 가장 큰 이점은 Private Data를 클로져를 통해 캡슐화 시킬 수 있다는 점이다.

+ +

다르게 말하자면 Private 상태를 지정할 수 있다는 의미이다.

+ +

특정 함수를 통할 필요 없이 public 접근이 가능한 속성에 대해 접근 제한을 거는 것은 문제가 있다. 따라서 private 클로져에 속성 값을 숨겨야 하며 이는 아래와 같이 구현한다:

+ +
// import Events from 'eventemitter3';
+
+const rawMixin = function () {
+  const attrs = {};
+  return Object.assign(this, {
+    set (name, value) {
+      attrs[name] = value;
+      this.emit('change', {
+        prop: name,
+        value: value
+      });
+    },
+    get (name) {
+      return attrs[name];
+    }
+  }, Events.prototype);
+};
+
+const mixinModel = (target) => rawMixin.call(target);
+const george = { name: 'george' };
+const model = mixinModel(george);
+model.on('change', data => console.log(data));
+model.set('name', 'Sam');
+/*
+{
+  prop: 'name',
+  value: 'Sam'
+}
+*/
+
+ +

attrs 을 public 속성에서 private 영역으로 옮겨서 public API를 통한 접근을 차단할 수 있다. // 접근할 수 있는 유일한 방법은 Privileged 메소드 뿐이다. Privileged 메소드는 클로져 영역에 정의된 함수로 private data에 접근 가능한 함수들을 일컫는다.

+ +

위 예제를 보면 믹스인 함수 rawMixin().에 대한 래퍼로 mixinModel() 을 선언한 것을 알 수 있다. 이는 예제에서 {{jsxref("Function.prototype.call()")}} 을 사용했듯이 함수 내에서 this의 값을 설정해야 하기 때문이다. Wrapper를 생략하고 호출자가 알아서 하도록 놔둘 수 있지만 그럴 경우 혼동될 가능성이 있다.

+ +
+

결론

+ +

복잡한 코드를 작성하여 이용하기 전에 프로토타입 기반의 상속 모델을 이해하는 것이 중요하다. 또한 프로토타입 체인의 길이는 성능을 저해하지 않도록 줄이는 방법을 고안해야 한다. 또한 빌트인 프로토타입은 새로운 자바스크립트 기능과 호환성을 갖기 위한 이유가 아닌 이상 절대 확장해서는 안된다.

+
+
diff --git a/files/ko/web/javascript/guide/iterators_and_generators/index.html b/files/ko/web/javascript/guide/iterators_and_generators/index.html new file mode 100644 index 0000000000..648b898504 --- /dev/null +++ b/files/ko/web/javascript/guide/iterators_and_generators/index.html @@ -0,0 +1,193 @@ +--- +title: 반복기 및 생성기 +slug: Web/JavaScript/Guide/Iterators_and_Generators +tags: + - Guide + - Intermediate + - JavaScript +translation_of: Web/JavaScript/Guide/Iterators_and_Generators +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Using_promises", "Web/JavaScript/Guide/Meta_programming")}}
+ +

컬렉션 내 각 항목 처리는 매우 흔한 연산입니다. JavaScript는 간단한 {{jsxref("Statements/for","for")}} 루프에서 {{jsxref("Global_Objects/Array/map","map()")}} 및 {{jsxref("Global_Objects/Array/filter","filter()")}}에 이르기까지, 컬렉션을 반복하는 많은 방법을 제공합니다. 반복기(iterator) 및 생성기(generator)는 반복 개념을 핵심 언어 내로 바로 가져와 {{jsxref("Statements/for...of","for...of")}} 루프의 동작(behavior)을 사용자 정의하는 메커니즘을 제공합니다.

+ +

자세한 내용은, 다음을 참조하세요:

+ + + +

반복자

+ +

자바스크립트에서 반복자(Iterator)는 시퀀스를 정의하고  종료시의 반환값을 잠재적으로 정의하는 객체입니다.  더 구체적으로 말하자면, 반복자는 두 개의 속성( value, done)을 반환하는 next() 메소드 사용하여  객체의 Iterator protocol을 구현합니다. 시퀀스의 마지막 값이 이미 산출되었다면 done 값은 true 가 됩니다. 만약 value값이 done 과 함께 존재한다면, 그것은 반복자의 반환값이 됩니다.

+ +

반복자를 생성하면 next() 메소드를 반복적으로 호출하여 명시적으로 반복시킬 수 있습니다.  반복자를 반복시키는 것은 일반적으로 한 번씩만 할 수 있기 때문에, 반복자를 소모시키는 것이라고 할 수 있습니다. 마지막 값을 산출하고나서  next()를 추가적으로 호출하면 {done: true}. 가 반환됩니다.

+ +

자바스크립트에서 가장 일반적인 반복자는 배열 반복자로, 배열의 각 값을 순서대로 반환합니다. 모든 반복자가 배열로 표현될수 있다고 상상할 수 있지만 , 이것은 사실은 아닙니다. 배열은 완전히 할당되어야 하지만,  반복자는 필요한만큼만 소모되므로  무제한 시퀀스로 표현할 수 있습니다. 이를 테면 0부터 무한대사이의 정수범위처럼 말이죠.

+ +

여기에 실습할 수 있는 예제가 있습니다.  start에서 end까지 step 수 만큼 띄어진  정수 시퀀스를 정의하는 간단한 범위 반복자를 만들 수 있습니다. 최종적으로 시퀀스의 크기가 반환됩니다.

+ +
function makeRangeIterator(start = 0, end = Infinity, step = 1) {
+    var nextIndex = start;
+    var n = 0;
+
+    var rangeIterator = {
+       next: function() {
+           var result;
+           if (nextIndex < end) {
+               result = { value: nextIndex, done: false }
+           } else if (nextIndex == end) {
+               result = { value: n, done: true }
+           } else {
+               result = { done: true };
+           }
+           nextIndex += step;
+           n++;
+           return result;
+       }
+    };
+    return rangeIterator;
+}
+
+ +

위의 반복자를 사용하면 아래와 같습니다:

+ +
var it = makeRangeIterator(1, 4);
+
+var result = it.next();
+while (!result.done) {
+ console.log(result.value); // 1 2 3
+ result = it.next();
+}
+
+console.log("Iterated over sequence of size: ", result.value);
+
+ +
+

It is not possible to know reflectively whether a particular object is an iterator. If you need to do this, use Iterables.

+
+ +

Generator functions

+ +

잘 만들어진 반복자(Iterator)는 유용한 도구인 반면, 이것을 생성할 때는 주의해서 프로그래밍을 해야 하는데, 반복자 내부에 명시적으로 상태를 유지할 필요가 있기 때문입니다. 생성자(Generator) 함수는 이에 대한 강력한 대안을 제공합니다: 실행이 연속적이지 않은 하나의 함수를 작성함으로서 개발자가 iterative algorithm을 정의할 수 있게 해줍니다. 생성자 함수는 {{jsxref("Statements/function*","function*")}} 문법을 사용하여 작성됩니다. 생성자 함수가 최초로 호출될 때, 함수 내부의 어떠한 코드도 실행되지 않고, 대신 생성자라고 불리는 반복자 타입을 반환합니다. 생성자의 next 메소드를 호출함으로서 어떤 값이 소비되면, 생성자 함수는 yield 키워드를 만날 때까지 실행됩니다. 

+ +

생성자 함수는 원하는 만큼 호출될 수 있고, 매번 새로운 생성자를 반환합니다다. 하지만, 각 생성자는 단 한 번만 순회될 수 있을 것입니다.

+ +

위의 예제 코드에 생성자를 적용한 것입니다. 두 코드의 행위는 동일하지만, 생성자를 사용한 쪽이 쓰거나 읽기가 훨씬 쉽습니다. 

+ +
function* makeRangeIterator(start = 0, end = Infinity, step = 1) {
+    let n = 0;
+    for (let i = start; i < end; i += step) {
+        n++;
+        yield i;
+    }
+    return n;
+}
+ +

Iterables

+ +

객체는 값이 {{jsxref("Statements/for...of", "for..of")}} 구조 내에서 반복되는 것 같은 그 반복 동작을 정의하는 경우 반복이 가능(iterable)합니다. {{jsxref("Array")}} 또는 {{jsxref("Map")}}과 같은 일부 내장 형은 기본 반복 동작이 있지만 다른 형(가령 {{jsxref("Object")}})은 없습니다.

+ +

반복가능하기 위해서, 객체는 @@iterator 메서드를 구현해야 합니다. 즉, 객체( 혹은 그 프로토타입 체인에 등장하는 객체 중 하나)가 {{jsxref("Symbol.iterator")}} 키를 갖는 속성이 있어야 함을 뜻합니다.

+ +

하나의 iterable은 단 한 번, 혹은 여러번 반복가능합니다. 어떤 순간에 어떻게 사용할 지는 프로그래머에게 달려있습니다. 단 한 번 반복가능한 iterable(e.g. Generator)은 관습적으로 자신의 @@iterator 메소드로부터 this를 반환합니다. 반면, 여러 번 반복 가능한 iterables은 @@iterator 메소드가 호출되는 매 회 새로운 iterator를 반드시 반환해야합니다. 

+ +

사용자 정의 iterable

+ +

이와 같이 자신의 반복가능 객체를 만들 수 있습니다:

+ +
var myIterable = {
+    *[Symbol.iterator]() {
+        yield 1;
+        yield 2;
+        yield 3;
+    }
+}
+
+for (let value of myIterable) {
+    console.log(value);
+}
+// 1
+// 2
+// 3
+
+or
+
+[...myIterable]; // [1, 2, 3]
+ +

내장 iterable

+ +

{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}} 및 {{jsxref("Set")}}은 모두 내장 반복가능 객체입니다, 그들의 프로토타입 객체가 모두 {{jsxref("Symbol.iterator")}} 메서드가 있기 때문입니다.

+ +

iterable을 기대하는 구문

+ +

일부 문(statement) 및 식(expression)은 iterable합니다, 가령 {{jsxref("Statements/for...of","for-of")}} 루프, {{jsxref("Operators/Spread_operator","spread syntax","","true")}}, {{jsxref("Operators/yield*","yield*")}} 및 {{jsxref("Operators/Destructuring_assignment","해체 할당","","true")}}.

+ +
for(let value of ['a', 'b', 'c']){
+    console.log(value)
+}
+// "a"
+// "b"
+// "c"
+
+[...'abc'] // ["a", "b", "c"]
+
+function* gen(){
+  yield* ['a', 'b', 'c']
+}
+
+gen().next() // { value:"a", done:false }
+
+[a, b, c] = new Set(['a', 'b', 'c'])
+a // "a"
+
+
+
+ +

Generator 심화

+ +

 생성자 함수는 요청에 따라 그 산출된(yielded, yield 식으로 산출된) 값을 계산하고, 계산하기 비싼(힘든) 수열 또는 위에 설명한 대로 무한 수열이라도 효율적으로 나타내게 합니다.

+ +

{{jsxref("Global_Objects/Generator/next","next()")}} 메서드는 또한 생성기의 내부 상태를 수정하는 데 쓰일 수 있는 값을 받습니다. next()에 전달되는 값은 생성기가 중단된 마지막 yield 식의 결과로 처리됩니다.

+ +

여기 sequence(수열)을 재시작하기 위해 next(x)를 사용하는 피보나치 생성기가 있습니다:

+ +
function* fibonacci(){
+  var fn1 = 0;
+  var fn2 = 1;
+  while (true){
+    var current = fn1;
+    fn1 = fn2;
+    fn2 = current + fn1;
+    var reset = yield current;
+    if (reset){
+        fn1 = 0;
+        fn2 = 1;
+    }
+  }
+}
+
+var sequence = fibonacci();
+console.log(sequence.next().value);     // 0
+console.log(sequence.next().value);     // 1
+console.log(sequence.next().value);     // 1
+console.log(sequence.next().value);     // 2
+console.log(sequence.next().value);     // 3
+console.log(sequence.next().value);     // 5
+console.log(sequence.next().value);     // 8
+console.log(sequence.next(true).value); // 0
+console.log(sequence.next().value);     // 1
+console.log(sequence.next().value);     // 1
+console.log(sequence.next().value);     // 2
+
+ +

You can force a generator to throw an exception by calling its {{jsxref("Global_Objects/Generator/throw","throw()")}} method and passing the exception value it should throw. This exception will be thrown from the current suspended context of the generator, as if the yield that is currently suspended were instead a throwvalue statement.

+ +

If the exception is not caught from within the generator,  it will propagate up through the call to throw(), and subsequent calls to next() will result in the done property being true.

+ +

Generators have a {{jsxref("Global_Objects/Generator/return","return(value)")}} method that returns the given value and finishes the generator itself.

+ +

{{PreviousNext("Web/JavaScript/Guide/Using_promises", "Web/JavaScript/Guide/Meta_programming")}}

diff --git a/files/ko/web/javascript/guide/keyed_collections/index.html b/files/ko/web/javascript/guide/keyed_collections/index.html new file mode 100644 index 0000000000..a206b6556d --- /dev/null +++ b/files/ko/web/javascript/guide/keyed_collections/index.html @@ -0,0 +1,149 @@ +--- +title: 키기반의 컬렉션 +slug: Web/JavaScript/Guide/Keyed_collections +translation_of: Web/JavaScript/Guide/Keyed_collections +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Indexed_Collections", "Web/JavaScript/Guide/Working_with_Objects")}}
+ +

이번 장에서는 입력된 키값을 기준으로 정렬되는 데이터의 집합(자료 구조)에 대해 소개 할 것이다. Map과 Set은 입력된 순서대로 반복적으로 접근 가능한 요소들을 포함하고 있다. 

+ +

Maps

+ +

Map 객체

+ +

ECMAScript 6에서 값들을 매핑하기 위한 새로운 데이터 구조를 소개 하고 있다.  그중 하나인 Map객체는 간단한 키와 값을 서로 연결(매핑)시켜 저장하며 저장된 순서대로 각 요소들을 반복적으로 접근할 수 있도록 한다. 

+ +

다음 코드는 Map이 제공하는 기본적인 기능들을 보여 주고 있다. 더 많은 예제와 모든 기능에 대한 API를 볼려면 {{jsxref("Map")}} 페이지를 참고하면 된다. Map객체에 저장되어 있는 각 요소들을 [키, 값] 형태의 배열로 반복적으로 반환해주는 for...of 를 사용할 수 있다.

+ +
var sayings = new Map();
+sayings.set("dog", "woof");
+sayings.set("cat", "meow");
+sayings.set("elephant", "toot");
+sayings.size; // 3
+sayings.get("fox"); // undefined
+sayings.has("bird"); // false
+sayings.delete("dog");
+
+for (var [key, value] of sayings) {
+  console.log(key + " goes " + value);
+}
+// "cat goes meow"
+// "elephant goes toot"
+
+ +

Object와 Map 비교

+ +

전통적으로 {{jsxref("Object", "objects", "", 1)}} 는 문자열을 값에 매핑하는 데 사용되었다. Object는 키를 값으로 설정하고, 값을 검색하고, 키를 삭제하고, 키에 저장된 내용을 검색 할 수 있게 만들어준다. 그러나 Map 객체는 더 나은 맵이 되도록 하는 몇 가지 장점을 가지고 있다.

+ + + +

Object 혹은 Map중에 어느 것을 사용할지를 결정하는데 도움을 줄 두가지 팁이 있다:

+ + + +

WeakMap object

+ +

{{jsxref("WeakMap")}}객체는  object만을 키로 허용하고 값은 임의의 값을 허용하는  키/값 형태의 요소의 집합이다. 키가 가지고 있는 객체에 대한 참조는 객체에 대한 참조가 더이상 존재하지 않을 경우 garbage collection(GC)의 수거 대상이 되는 약한 참조를 의미한다. WeakMap API는 Map API와 동일하다. 

+ +

단 한가지  Map객체와 다른 점은 WeakMap의 키들은 열거형이 아니라는 점이다. (즉, 키 목록을 제공해 주는 메서드가 없다는 것이다.) 만약에 키 목록을 제공한다면 garbage collection의 상태, 결과에 따라 키 목록이 변하게 될 것이다. 이는 비 결정성을 야기한다. 

+ +

WeakMap에 대한 더 많은 정보와 예제 코드 그리고 "왜 WeakMap을 사용하지?"를 보고 싶다면 {{jsxref("WeakMap")}} 페이지를 참고하면 된다. 

+ +

WeakMap를 사용하는 한가지 경우는 객체의 사적인 정보를 저장하기 위해서 이거나 상세 구현 내용을 숨기기 위한 것이다. 다음의 예제는 Nick Fitzgerald의 블로그 글- "Hiding Implementation Details with ECMAScript 6 WeakMaps"-에서 가져온 것이다. 객체가 가지고 있는 그렇지만 외부에 공개되지 않는(private) 데이터와 메서드들은 WeakMap객체인 privates에 저장이 된다. 인스턴스를 통해 접근 가능한 모든 것들과 prototype은 public이고 다른 것들은 외부에서는 접근이 불가하다 그 이유는 privates는 모듈로부터 내보내기(export)가 되지 않기 때문이다.

+ +
const privates = new WeakMap();
+
+function Public() {
+  const me = {
+    // Private data goes here
+  };
+  privates.set(this, me);
+}
+
+Public.prototype.method = function () {
+  const me = privates.get(this);
+  // Do stuff with private data in `me`...
+};
+
+module.exports = Public;
+
+ +

Sets

+ +

Set object

+ +

{{jsxref("Set")}}객체는 값들의 집합이다. 입력된 순서에따라 저장된 요소를 반복처리할 수 있다. Set은 중복된 값을 허용하지 않는다. 따라서 특정 값은 Set내에서 하나만 존재 하게 된다. 

+ +

아래의 코드는 Set의 기본적인 동작들을 보여 준다. 더 많은 예제와 모든 API는 {{jsxref("Set")}} 참조 페이지를 보면 된다. 

+ +
var mySet = new Set();
+mySet.add(1);
+mySet.add("some text");
+mySet.add("foo");
+
+mySet.has(1); // true
+mySet.delete("foo");
+mySet.size; // 2
+
+for (let item of mySet) console.log(item);
+// 1
+// "some text"
+
+ +

배열과 Set의 상호 변환

+ +

{{jsxref("Array.from")}} 혹은 spread operator를 통해 Set객체를 가지고 {{jsxref("Array")}}을 생성할 수 있다. 또한 Set 생성자는 배열을 인자로 받을 수 있고 해당 배열을 Set객체의 요소로 저장한다. 한번 더 상기시키면 Set객체는 중복된 값을 저장하지 않기때문에 주어진 배열내의 중복된 요소들을 제거되어 Set으로 변환된다. 

+ +
Array.from(mySet);
+[...mySet2];
+
+mySet2 = new Set([1,2,3,4]);
+
+ +

배열과 Set비교

+ +

일반적으로 Javascript에선 배열에 특정 요소의 집합을 저장한다. 하지만 Set객체는 몇가지 이점을 제공한다. 

+ + + +

WeakSet 객체

+ +

{{jsxref("WeakSet")}} objects are collections of objects. An object in the WeakSet may only occur once; it is unique in the WeakSet's collection and objects are not enumerable.

+ +

{{jsxref("WeakSet")}}객체는 객체를 저장하는 일종의 집합이다. WeakSet내의 중복된 객체는 없으며 WeakSet내의 요소를 열거할 수는 없다.  

+ +

{{jsxref("Set")}}과 가장 큰 차이점은 다음과 같다.

+ + + +

WeakSet객체의 사용 사례는 제한되어 있다. 메모리 누수가 발생되지 않기때문에 안전하게 DOM요소를 키로 저장할 수 있고 예를 들면 추적을 위해 DOM요소들을 WeakSet에 저장할 수 있다. 

+ +

 

+ +

Map과 Set의 키와 값의 동치성

+ +

Map객체의 key에 대한 동치성 비교와 Set객체의  값에 대한 동치성 비교 모두 "same-value-zero algorithm"에 근거한다. 

+ + + +

{{PreviousNext("Web/JavaScript/Guide/Indexed_Collections", "Web/JavaScript/Guide/Working_with_Objects")}}

diff --git a/files/ko/web/javascript/guide/loops_and_iteration/index.html b/files/ko/web/javascript/guide/loops_and_iteration/index.html new file mode 100644 index 0000000000..4b0ac738b6 --- /dev/null +++ b/files/ko/web/javascript/guide/loops_and_iteration/index.html @@ -0,0 +1,332 @@ +--- +title: 루프와 반복 +slug: Web/JavaScript/Guide/Loops_and_iteration +translation_of: Web/JavaScript/Guide/Loops_and_iteration +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}
+ +

루프는 어떤 것을 반복적으로 시행할때 빠르고 간편한 방법을 제공합니다. JavaScript Guide의 이 항목은 JavaScript 에서 사용이 가능한 서로 다른 여러가지 반복문을 소개합니다.

+ +

반복문을 게임의 컴퓨터화된 버전이라고 생각해 보세요. 누군가에게 한 방향으로 X만큼 가게 시키고 다른 방향으로 Y만큼 더 가게 한다고 생각해 보십시오. 예를들어, "동쪽으로 5만큼 가세요"는 다음과 같이 반복문으로 표현 될 수 있습니다.

+ +
var step;
+for (step = 0; step < 5; step++) {
+  // Runs 5 times, with values of step 0 through 4.
+  console.log('Walking east one step');
+}
+
+ +

반복문은 매우 다양한 종류가 있습니다. 하지만 반복문이 기본적으로 하는일은 모두 같습니다. 반복문은 한 동작을 여러 번 반복합니다. (사실 0회 반복하는 것도 가능합니다.) 다양한 반복문 메커니즘은 다양한 방법으로 반복문의 시작점과 끝나는 점을 정할 수 있습니다.

+ +

자바스크립트가 지원하는 반복문은 다음과 같습니다:

+ + + +

for

+ +

for 반복문은 어떤 특정한 조건이 거짓으로 판별될 때까지 반복합니다. 자바스크립트의 반복문은 C의 반복문과 비슷합니다. for 반복문은 다음과 같습니다.

+ +
for ([초기문]; [조건문]; [증감문])
+  문장
+
+ +

for문이 실행될 때, 다음과 같이 실행됩니다.:

+ +
    +
  1. 초기화 구문인 초기문이 존재한다면 초기문이 실행됩니다. 이 표현은 보통 1이나 반복문 카운터로 초기 설정이 됩니다. 그러나 복잡한 구문으로 표현 될 때도 있습니다. 또한 변수로 선언 되기도 합니다.
  2. +
  3. 조건문은 조건을 검사합니다. 만약 조건문이 참이라면, 그 반복문은 실행됩니다. 만약 조건문이 거짓이라면, 그 for문은 종결됩니다. 만약 그 조건문이 생략된다면, 그 조건문은 참으로 추정됩니다.
  4. +
  5. 문장이 실행됩니다. 많은 문장을 실행할 경우엔, { } 를 써서 문장들을 묶어 줍니다.
  6. +
  7. 갱신 구문인 증감문이 존재한다면 실행되고 2번째 단계로 돌아갑니다.
  8. +
+ +

예시

+ +

다음 함수는 스크롤링 목록(다중 선택을 허용하는 요소 {{HTMLElement("select")}}). 에서 선택된 옵션들을 세는 for문 입니다. 이 for문은 변수 i 를 선언하고 0으로 초기화 시킵니다. 이것은 i 가  <select> 요소 안의 옵션 수가 i 보다 작은지 확인 합니다. 다음의 if문을 수행하고 각 루프를 빠져나간 뒤 i 를 1 증가시킵니다.

+ +
<form name="selectForm">
+  <p>
+    <label for="musicTypes">Choose some music types, then click the button below:</label>
+    <select id="musicTypes" name="musicTypes" multiple="multiple">
+      <option selected="selected">R&B</option>
+      <option>Jazz</option>
+      <option>Blues</option>
+      <option>New Age</option>
+      <option>Classical</option>
+      <option>Opera</option>
+    </select>
+  </p>
+  <p><input id="btn" type="button" value="How many are selected?" /></p>
+</form>
+
+<script>
+function howMany(selectObject) {
+  var numberSelected = 0;
+  for (var i = 0; i < selectObject.options.length; i++) {
+    if (selectObject.options[i].selected) {
+      numberSelected++;
+    }
+  }
+  return numberSelected;
+}
+
+var btn = document.getElementById("btn");
+btn.addEventListener("click", function(){
+  alert('Number of options selected: ' + howMany(document.selectForm.musicTypes))
+});
+</script>
+
+
+ +

do...while

+ +

do...while 문은 특정한 조건이 거짓으로 판별될 때까지 반복합니다. do...while 문은 다음과 같습니다.

+ +
do
+  문장
+while (조건문);
+
+ +

조건문을 확인하기 전에 문장은 한번 실행됩니다. 많은 문장을 실행하기 위해선 { }를 써서 문장들을 묶어줍니다. 만약 조건이 참이라면, 그 문장은 다시 실행됩니다. 매 실행 마지막마다 조건문이 확인됩니다. 만약 조건문이 거짓일 경우, 실행을 멈추고 do...while 문 바로 아래에 있는 문장으로 넘어가게 합니다.

+ +

예시

+ +

다음 예제에서, do 반복문은 최소 한번은 반복됩니다. 그리고 i 가 5보다 작지 않을 때까지 계속 반복됩니다.

+ +
do {
+  i += 1;
+  console.log(i);
+} while (i < 5);
+ +

while

+ +

while 문은 어떤 조건문이 참이기만 하면 문장을 계속해서 수행합니다. while 문은 다음과 같습니다.

+ +
while (조건문)
+  문장
+
+ +

만약 조건문이 거짓이 된다면, 그 반복문 안의 문장은 실행을 멈추고 반복문 바로 다음의 문장으로 넘어갑니다.

+ +

조건문은 반복문 안의 문장이 실행되기 전에 확인 됩니다. 만약 조건문이 참으로 리턴된다면, 문장은 실행되고 그 조건문은 다시 판별됩니다. 만약 조건문이 거짓으로 리턴된다면, 실행을 멈추고 while문 바로 다음의 문장으로 넘어가게 됩니다.

+ +

많은 문장들을 실행하기 위해선, { }를 써서 문장들을 묶어줍니다.

+ +

예시 1

+ +

다음 while 반복문은 n이 3보다 작은 한, 계속 반복됩니다.

+ +
n = 0;
+x = 0;
+while (n < 3) {
+  n++;
+  x += n;
+}
+
+ +

매 반복과 함께, n이 증가하고 x에 더해집니다. 그러므로, x와 n은 다음과 같은 값을 갖습니다.

+ + + +

세번째 경과 후에, n < 3 은 더이상 참이 아니므로, 반복문은 종결됩니다.

+ +

예시 2

+ +

조건문은 항상 거짓이 될지라도 무한 루프는 피해야 합니다. 그렇지 않으면 그 반복문은 영원히 끝나지 않을 것입니다. 아래의 while 문은 조건문이 절대 거짓이 될 수 없으므로 영원히 반복될 것입니다.

+ +
// 다음과 같은 코드는 피하세요.
+while (true) {
+  console.log("Hello, world");
+}
+ +

레이블 문

+ +

레이블은 여러분이 프로그램에서 다른 곳으로 참조할 수 있도록 식별자로 문을 제공합니다. 예를 들어, 여러분은 루프를 식별하기 위해 레이블을 사용하고, 프로그램이 루프를 방해하거나 실행을 계속할지 여부를 나타내기 위해 break나 continue 문을 사용할 수 있습니다.

+ +

레이블 문의 구문은 다음과 같습니다:

+ +
label :
+   statement
+
+ +

레이블  값은 예약어가 아닌 임의의 JavaScript 식별자일 수 있습니다. 여러분이 레이블을 가지고 식별하는 은 어떠한 문이 될 수 있습니다.

+ +

예시

+ +

이 예에서, 레이블 markLoop는 while 루프를 식별합니다.

+ +
markLoop:
+while (theMark == true) {
+   doSomething();
+}
+ +

break

+ +

break문은 반복문, switch문, 레이블 문과 결합한 문장을 빠져나올  때 사용합니다.

+ + + +

break문의 문법은 다음과 같습니다.

+ +
    +
  1. break;
  2. +
  3. break [레이블];
  4. +
+ +

break문의 첫번째 형식은 가장 안쪽의 반복문이나 switch문을 빠져나옵니다. 두번째 형식는 특정한 레이블 문을 빠져나옵니다.

+ +

예시 1

+ +

다음 예

+ +
for (i = 0; i < a.length; i++) {
+  if (a[i] == theValue) {
+    break;
+  }
+}
+ +

예시 2: Breaking to a label

+ +
var x = 0;
+var z = 0
+labelCancelLoops: while (true) {
+  console.log("Outer loops: " + x);
+  x += 1;
+  z = 1;
+  while (true) {
+    console.log("Inner loops: " + z);
+    z += 1;
+    if (z === 10 && x === 10) {
+      break labelCancelLoops;
+    } else if (z === 10) {
+      break;
+    }
+  }
+}
+
+ +

continue 문

+ +

continue 문은 while, do-while, for, 레이블 문을 다시 시작하기 위해 사용될 수 있습니다.

+ + + +

continue 문의 구문은 다음과 같습니다:

+ +
    +
  1. continue;
  2. +
  3. continue label;
  4. +
+ +

예시 1

+ +

다음의 예는 i 값이 3일 때 실행하는 continue 문과 함께 while 루프를 보여줍니다. 따라서, n은 값 1, 3, 7, 12를 취합니다.

+ +
i = 0;
+n = 0;
+while (i < 5) {
+  i++;
+  if (i == 3) {
+    continue;
+  }
+  n += i;
+}
+
+ +

예시 2

+ +

checkiandj 레이블 문은 checkj 레이블 문을 포함합니다. continue가 발생하는 경우, 프로그램은 checkj의 현재 반복을 종료하고, 다음 반복을 시작합니다. 그 조건이 false를 반환 할 때까지 continue가 발생할 때마다, checkj는 반복합니다. false가 반환될 때, checkiandj 문의 나머지 부분은 완료되고, 그 조건이 false를 반환 할 때까지 checkiandj는 반복합니다. false가 반환될 때, 이 프로그램은 다음 checkiandj 문에서 계속됩니다.

+ +

continue가 checkiandj의 레이블을 가지고 있다면, 프로그램은 checkiandj 문 상단에서 계속될 것입니다.

+ +
checkiandj:
+  while (i < 4) {
+    console.log(i);
+    i += 1;
+    checkj:
+      while (j > 4) {
+        console.log(j);
+        j -= 1;
+        if ((j % 2) == 0) {
+          continue checkj;
+        }
+        console.log(j + " is odd.");
+      }
+      console.log("i = " + i);
+      console.log("j = " + j);
+  }
+ +

for...in

+ +

for...in  문은 객체의 열거 속성을 통해 지정된 변수를 반복합니다. 각각의 고유한 속성에 대해, JavaScript는 지정된 문을 실행합니다. for...in 문은 다음과 같습니다:

+ +
for (variable in object) {
+  statements
+}
+
+ +

예시

+ +

다음 함수는 객체와 객체의 이름을 함수의 인수로 취합니다. 그런 다음 모든 객체의 속성을 반복하고 속성 이름과 값을 나열하는 문자열을 반환합니다.

+ +
function dump_props(obj, obj_name) {
+  var result = "";
+  for (var i in obj) {
+    result += obj_name + "." + i + " = " + obj[i] + "<br>";
+  }
+  result += "<hr>";
+  return result;
+}
+
+ +

속성 make와 model을 가진 객체 car의 경우, 결과는 다음과 같습니다:

+ +
car.make = Ford
+car.model = Mustang
+
+ +

배열

+ +

{{jsxref("배열")}} 요소를 반복하는 방법으로 이를 사용하도록 유도될 수 있지만, for...in 문은 숫자 인덱스에 추가하여 사용자 정의 속성의 이름을 반환합니다. 따라서 만약 여러분이 사용자 정의 속성 또는 메서드를 추가하는 등 Array 객체를 수정한다면, 배열 요소 이외에도 사용자 정의 속성을 통해 for...in 문을 반복하기 때문에, 배열을 통해 반복할 때 숫자 인덱스와 전통적인 for 루프를 사용하는 것이 좋습니다.

+ +

for...of

+ +

for...of 문은 각각의 고유한 특성의 값을 실행할 명령과 함께 사용자 지정 반복 후크를 호출하여, 반복 가능한 객체({{jsxref("배열")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, 인수 객체 등을 포함)를 통해 반복하는 루프를 만듭니다.

+ +
for (variable of object) {
+  statement
+}
+ +

다음 예는 for...of 루프와 for...in 루프의 차이를 보여줍니다. 속성 이름을 통해 for...in이 반복하는 동안, for...of은 속성 값을 통해 반복합니다:

+ +
let arr = [3, 5, 7];
+arr.foo = "hello";
+
+for (let i in arr) {
+   console.log(i); // logs "0", "1", "2", "foo"
+}
+
+for (let i of arr) {
+   console.log(i); // logs "3", "5", "7"
+}
+
+ +

{{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}

diff --git a/files/ko/web/javascript/guide/modules/index.html b/files/ko/web/javascript/guide/modules/index.html new file mode 100644 index 0000000000..b52283a0fc --- /dev/null +++ b/files/ko/web/javascript/guide/modules/index.html @@ -0,0 +1,414 @@ +--- +title: JavaScript modules +slug: Web/JavaScript/Guide/Modules +translation_of: Web/JavaScript/Guide/Modules +--- +
{{jsSidebar("JavaScript Guide")}}{{Previous("Web/JavaScript/Guide/Meta_programming")}}
+ +

이 가이드는 자바스크립트 모듈 구문을 시작하는데 필요한 모든 것을 제공합니다.

+ +

A background on modules

+ +

자바스크립트 프로그램은 꽤 작게 시작되었습니다. 초기에 사용 된 대부분의 스크립트는 독립적인 작업을 수행하여, 필요한 경우 웹 페이지에 약간의 상호 작용을 제공하므로 일반적으로 큰 스크립트가 필요하지 않았습니다. 몇년 후 자바스크립트는 많은 브라우저에서 실행되고 있는 완전한 애플리케이션을 실행할 수 있을 뿐 아니라,  다른 컨텍스트에서 (예를들면 Node.js) 자바스크립트를 사용하게 됩니다.

+ +

따라서 최근 몇 년 동안 자바스크립트 프로그램을 필요에 따라 가져올 수 있는, 별도의 모듈로 분할하기 위한 매커니즘을 제공하는 것에 대해 생각하기 시작했습니다.  node.js는 오랫동안 이러한 능력을 가지고 있었고, 모듈 사용을 가능하게하는 많은 자바스크립트 라이브러리와 프레임워크가 있습니다. (예를들어 RequireJS와 같은 CommonJS 와 AMD기반 모듈 시스템, 더 최근에는 Webpack과 Babel 같은 모듈 기반 시스템이 있습니다.)

+ +

좋은 소식은 최신 브라우저가 기본적으로 모듈 기능을 지원하기 시작했으며, 이것이 이 기사의 전부입니다. 브라우저는 모듈의 로딩을 최적화 할 수 있기 때문에 라이브러리를 사용하는 것보다 더 효율적이며, 클라이언트 측에서의 추가 처리와 여분의 왕복을 모두 해야하는 것 보다 효율적입니다.

+ +

Browser support

+ +

네이티브 자바스크립트 모듈은 import와 export 문(statement)에 의존적이며, 호환성은 다음과 같습니다.

+ +

import

+ +

{{Compat("javascript.statements.import")}}

+ +

export

+ +

{{Compat("javascript.statements.export")}}

+ +

Introducing an example

+ +

모듈 사용법을 설명하기 위해 Github에 간단한 예제 모음을 만들었습니다. 이 예제들은 웹 페이지에 {{htmlelement("canvas")}} 요소(element)를 만들고, 캔버스에 다양한 도형을 그리고, 그린것에 대한 정보를 보고하는 간단한 모듈 집합입니다.

+ +

이것들은 매우 사소한 것이지만, 모듈을 명확하게 설명하기 의해 의도적으로 단순하게 유지중입니다.

+ +
+

주의: 예제를 다운로드하여 로컬에서 실행하려면, 로컬 웹 서버를 통해 예제를 실행해야 합니다.

+
+ +

Basic example structure

+ +

첫 번째 예제(basic-modules)를 보면 다음과 같은 파일 구조가 있습니다.

+ +
index.html
+main.js
+modules/
+    canvas.js
+    square.js
+ +
+

주의: 이 가이드의 모든 예제는 기본적으로 동일한 구조를 가집니다. 위의 내용에 익숙해지시는게 좋습니다.

+
+ +

modules 디렉토리의 두 모듈은 다음과 같습니다.

+ + + +

Exporting module features

+ +

모듈 기능을 사용하려면 먼저 함수를 export 해야 합니다. 이 작업은 export 문(statement)을 사용하여 수행합니다.

+ +

이를 사용하는 가장 쉬운 방법은 모듈 밖으로 내보내려는 항목 앞에 (export를) 배치하는 것입니다. 예를들면 다음과 같습니다.

+ +
export const name = 'square';
+
+export function draw(ctx, length, x, y, color) {
+  ctx.fillStyle = color;
+  ctx.fillRect(x, y, length, length);
+
+  return {
+    length: length,
+    x: x,
+    y: y,
+    color: color
+  };
+}
+ +

functions, var, let, const, class를 내보낼 수 있지만, 최상위 항목이어야 합니다. 예를들어, 함수 안에서 export를 사용할 수 없습니다.

+ +

여러 항목을 내보내는 더 편리한 방법은 모듈 파일 끝에 하나의 export 문을 사용하는 것입니다. 그 다음에 내보내려는 기능들을 쉼표로 구분하여 나열하고 중괄호로 묶습니다.

+ +
export { name, draw, reportArea, reportPerimeter };
+ +

Importing features into your script

+ +

모듈에서 일부 기능을 내보낸 후에는, 이를 사용할 수 있도록 우리가 사용할 스크립트로 가져와야 합니다. 가장 간단한 방법은 다음과 같습니다.

+ +
import { name, draw, reportArea, reportPerimeter } from './modules/square.js';
+ +

import 문(statement)을 사용하고, 가져올 목록을 쉼표로 구분하여 나열한 뒤 괄호로 묶습니다. 그 뒤에는 from을 쓰고 모듈 파일의 경로를 작성합니다. (사이트 루트에 연관된 경로로, 우리의 basic-modules 예제는 /js-examples/modules/basic-modules 입니다) main.js에서 이러한 코드를 볼 수 있습니다.

+ +

그러나 우리는 경로를 조금 다르게 작성했습니다. 우리는 "현재 위치"를 의미하는 점(.) 구문을 사용하고 있으며, 그 다음에 찾고자하는 파일의 경로를 뒤에 써 줍니다. 이것은 상대적으로 전체 상대 경로를 작성하는 것보다 훨씬 빠르며, URL이 더 짧아 지므로 사이트 계층 구조의 다른 위치로 이동하더라도 이 예제가 계속 작동합니다.

+ +

예를들면,

+ +
/js-examples/modules/basic-modules/modules/square.js
+ +

이렇게 쓸 수 있습니다.

+ +
./modules/square.js
+ +

main.js에서 이러한 코드를 볼 수 있습니다.

+ +
+

주의: 일부 모듈 시스템에서는 파일 확장명을 생략할 수 있습니다. (예: '/modules/square'). 이것은 네이티브 자바스크립트에서는 작동하지 않습니다. 또한 앞에 슬래시를 포함해야 합니다.

+
+ +

우리의 스크립트에 기능을 가져오면 동일한 파일 내에 정의한 것처럼 기능을 사용할 수 있습니다. 다음은 main.js 의 import 행 아래에 있습니다.

+ +
let myCanvas = create('myCanvas', document.body, 480, 320);
+let reportList = createReportList(myCanvas.id);
+
+let square1 = draw(myCanvas.ctx, 50, 50, 100, 'blue');
+reportArea(square1.length, reportList);
+reportPerimeter(square1.length, reportList);
+
+ +

Applying the module to your HTML

+ +

이제 main.js 모듈을 HTML 페이지에 적용하면 됩니다. 이는 몇 가지 주목할만한 차이점을 제외하면 HTML페이지에 일반 스크립트를 적용하는것과 매우 유사합니다.

+ +

이 스크립트를 모듈로 선언하려면 {{htmlelement("script")}} 요소(element)에 type="module" 을 포함시켜야 합니다.

+ +
<script type="module" src="main.js"></script>
+ +

기본적으로 모듈 기능을 가져오는 스크립트는 최상위 모듈로 작동합니다. 이를 생략하면 파이어폭스로 예를들면, "SyntaxError: import declarations may only appear at top level of a module"라는 오류를 줍니다.

+ +

import 와 export 문(statement)은 모듈 내에서만 사용할 수 있습니다. 정규 스크립트가 아닙니다.

+ +
+

주의: type="module"을 포함하면 인터널 스크립트에서도 import 모듈을 사용할 수 있습니다. 예: <script type="module"> /* 여기에 코드를 작성하세요 */ </script>.

+
+ +

Other differences between modules and standard scripts

+ + + +

Default exports versus named exports

+ +

지금까지 우리가 export 한 기능은 named exports 로 구성되었습니다. 각 항목(function, const 등)은 export 할 때 이름으로 참조되었으며, import 할 때에 이 이름을 참조하여 사용합니다.

+ +

그 외에도 default export 라고 부르는 export 도 있습니다. 이것은 모듈이 제공하는 기본 기능을 쉽게 만들 수 있도록 설계되었습니다. 또한 자바스크립트 모듈을 기존의 CommonJS 와 AMD 모듈 시스템과 함께 사용(interpolate)하는데도 도움이 됩니다. (Jason Orendorff에 의해 작성된 ES6 In Depth: Modules 에 설명되어있습니다. "Default exports"를 검색해보세요)

+ +

예제를 가지고 어떻게 작동하는지 살펴보겠습니다. 예제 중 basic-modules 프로젝트의 square.js 파일에서 임의의 색상, 크기, 위치로 갖는 사각형을 만드는 randomSquare() 라는 함수를 찾을 수 있습니다. 이것을 기본값으로 export하려고 하므로, 파일의 맨 아래에 다음과 같이 씁니다.

+ +
export default randomSquare;
+ +

중괄호가 없음에 주의하세요.

+ +

대신 함수 앞에 export default 를 추가하고, 다음과 같이 익명함수로 선언할 수 있습니다.

+ +
export default function(ctx) {
+  ...
+}
+ +

main.js 파일에서 다음 코드처럼 사용하면, default function이 import 됩니다.

+ +
import randomSquare from './modules/square.js';
+ +

다시 말하지만, 중괄호가 없다는 점에 유의하세요. 하나의 모듈은 하나의 default export만 허용하기 때문에 우리는 randomSquare 가 해당 모듈임을 알 수 있습니다. 위의 코드는 아래의 코드를 단축하여 사용한 것입니다.

+ +
import {default as randomSquare} from './modules/square.js';
+ +
+

주의: export한 항목의 이름을 바꾸는 구문은 {{anch("Renaming imports and exports")}} 섹션에서 설명합니다.

+
+ +

Avoiding naming conflicts

+ +

지금까지 우리의 캔버스 도형 그리기 모듈은 제대로 작동하는 것 같습니다. 원이나 삼각형처럼 다른 도형을 그리는 모듈을 추가하려고 하면 어떻게 될까요? 이 도형(shape)에는 아마도 draw(), reportArea() 등과 같은 관련 함수가 있을 것입니다. 동일한 이름의 여러 함수를 동일한 최상위 모듈로 가져오려고 하면, 충돌과 에러가 발생합니다.

+ +

다행스럽게도 이 문제를 해결할 수 있는 여러가지 방법이 있습니다. 다음 섹션에서 이 내용을 살펴보겠습니다.

+ +

Renaming imports and exports

+ +

import 와 export 문(statement)의 중괄호 안에 as 키워드를 새 함수의 이름으로 함께 사용하여, 최상위 모듈 내부의 함수들을 식별 가능한 이름으로 변경할 수 있습니다.

+ +

예를들어 다음 두 가지 방법은 약간의 차이가 있지만, 두 방법 모두 동일한 작업을 수행하고 있습니다.

+ +
// inside module.js
+export {
+  function1 as newFunctionName,
+  function2 as anotherNewFunctionName
+};
+
+// inside main.js
+import { newFunctionName, anotherNewFunctionName } from './modules/module.js';
+ +
// inside module.js
+export { function1, function2 };
+
+// inside main.js
+import { function1 as newFunctionName,
+         function2 as anotherNewFunctionName } from './modules/module.js';
+ +

실제 사례를 살펴보겠습니다. renaming 디렉토리에서 원과 삼각형을 그리고 보고하기 위해 circle.js 와 triangle.js 모듈을 추가한다는 점만 제외하면, 앞의 예와 동일한 모듈 시스템을 볼 수 있습니다.

+ +

이 모듈듈 각각에는 내부적으로 동일한 이름의 기능이 있습니다. 따라서 각각 하단에 동일한 export 문(statement)이 있습니다.

+ +
export { name, draw, reportArea, reportPerimeter };
+ +

이것들을 main.js에 가져올 때 우리는 다음과 같이 시도할 수 있습니다.

+ +
import { name, draw, reportArea, reportPerimeter } from './modules/square.js';
+import { name, draw, reportArea, reportPerimeter } from './modules/circle.js';
+import { name, draw, reportArea, reportPerimeter } from './modules/triangle.js';
+ +

위와같이 적으면 브라우저에서 "SyntaxError: redeclaration of import name"과 같은 오류가 발생합니다. (Firefox).

+ +

대신 import가 고유하도록(식별 가능하도록) 이름을 변경해야 합니다.

+ +
import { name as squareName,
+         draw as drawSquare,
+         reportArea as reportSquareArea,
+         reportPerimeter as reportSquarePerimeter } from './modules/square.js';
+
+import { name as circleName,
+         draw as drawCircle,
+         reportArea as reportCircleArea,
+         reportPerimeter as reportCirclePerimeter } from './modules/circle.js';
+
+import { name as triangleName,
+        draw as drawTriangle,
+        reportArea as reportTriangleArea,
+        reportPerimeter as reportTrianglePerimeter } from './modules/triangle.js';
+ +

다음과 같이 import하는 파일 대신 모듈 파일에서 문제를 해결할 수도 있습니다.

+ +
// in square.js
+export { name as squareName,
+         draw as drawSquare,
+         reportArea as reportSquareArea,
+         reportPerimeter as reportSquarePerimeter };
+ +
// in main.js
+import { squareName, drawSquare, reportSquareArea, reportSquarePerimeter } from './modules/square.js';
+ +

그리고 이것은 똑같이 작동 할 것입니다. 사용하는 스타일은 개인의 취향이지만, 모듈 코드를 그대로 두고 import 를 변경하는 것이 더 합리적입니다. 특히 제어 권한이 없는 써드 파티 모듈에서 import를 사용하는 경우에 특히 유용합니다.

+ +

Creating a module object

+ +

위의 방법은 정상적으로 작동하지만, 다소 지저분하고 길어질 수 있습니다. 보다 나은 해결책은 각 모듈의 기능을 모듈 객체 내부로 가져오는 것입니다. 다음과 같은 구문을 사용합니다.

+ +
import * as Module from './modules/module.js';
+ +

이 모듈은 module.js 내에서 사용할 수 있는 모든 export를 가져옵니다. 그리고 그것들을 객체 Module 의 멤버로 만들고 우리 임의의 효과적인 네임스페이스를 제공합니다.

+ +
Module.function1()
+Module.function2()
+etc.
+ +

다시 한 번 실제 사례를 살펴보겠습니다. module-objects 디렉토리로 가면 같은 예제를 볼 수 있지만, 새로운 구문을 이용하기 위해 다시 작성합니다. 모듈에서 export는 모두 다음과 같은 간단한 형식으로 이루어집니다.

+ +
export { name, draw, reportArea, reportPerimeter };
+ +

반면에 import는 다음과 같습니다.

+ +
import * as Canvas from './modules/canvas.js';
+
+import * as Square from './modules/square.js';
+import * as Circle from './modules/circle.js';
+import * as Triangle from './modules/triangle.js';
+ +

각각의 경우에, 지정한 객체 이름 아래에 있는 모듈의 import에 접근할 수 있습니다. 다음은 그 예시입니다.

+ +
let square1 = Square.draw(myCanvas.ctx, 50, 50, 100, 'blue');
+Square.reportArea(square1.length, reportList);
+Square.reportPerimeter(square1.length, reportList);
+ +

따라서 이제는 이전과 똑같은 코드를 작성할 수 있습니다. (필요한 경우 객체 이름을 포함해야 합니다) import는 보다 깔끔해졌습니다.

+ +

Modules and classes

+ +

이전에 암시 했듯이 class를 export하거나 import 할 수도 있습니다. 이것은 코드에서 충돌을 피하기 위한 또 다른 옵션으로, 모듈 코드가 이미 객체 지향 스타일로 작성된 경우에 특히 유용합니다.

+ +

우리의 classes 디렉토리에서 ES 클래스로 다시 작성된 도형 그리기 모듈의 예를 볼 수 있습니다. 예를들어 square.js 파일에는 모든 기능이 단일 클래스에 포함되어 있습니다.

+ +
class Square {
+  constructor(ctx, listId, length, x, y, color) {
+    ...
+  }
+
+  draw() {
+    ...
+  }
+
+  ...
+}
+ +

우리는 다음과 같이 export 합니다.

+ +
export { Square };
+ +

main.js 에서 우리는 다음과 같이 import 합니다.

+ +
import { Square } from './modules/square.js';
+ +

그런다음 클래스를 이용하여 사각형을 그립니다.

+ +
let square1 = new Square(myCanvas.ctx, myCanvas.listId, 50, 50, 100, 'blue');
+square1.draw();
+square1.reportArea();
+square1.reportPerimeter();
+ +

Aggregating modules

+ +

모듈을 모아야 할 때가 있을 것입니다. 여러 서브 모듈을 하나의 부모 모듈로 결합하여 여러 단계의 종속성을 가질 수 있습니다. 상위 모듈에서 다음 양식의 export 구문을 사용하할 수 있습니다.

+ +
export * from 'x.js'
+export { name } from 'x.js'
+ +
+

주의: 이것은 실제로 import 의 줄임말이고, 그 뒤에 export가 옵니다. 예를들면, "나는 모듈 x.js를 가져온 다음, 일부 또는 전부를 export 하겠다" 라는 뜻입니다.

+
+ +

예를들어 module-aggregation 디렉토리를 참조하겠습니다. 이 예제에서는 이전 클래스 예제를 기반으로 circle.js, square.js, triangle.js 의 모든 기능을 함께 모으는 shapes.js라는 추가 모듈이 있습니다. 또한 우리는 shapes 모듈 디렉토리 안에 있는 서브 디렉토리 내에서 서브 모듈을 이동 시켰습니다. 이제 모듈 구조는 다음과 같습니다.

+ +
modules/
+  canvas.js
+  shapes.js
+  shapes/
+    circle.js
+    square.js
+    triangle.js
+ +

각 하위 모듈에서 export 형태는 같습니다. 예)

+ +
export { Square };
+ +

다음은 집합(aggregation) 부분입니다. shapes.js 안에는 다음과 같은 내용이 포함되어 있습니다.

+ +
export { Square } from './shapes/square.js';
+export { Triangle } from './shapes/triangle.js';
+export { Circle } from './shapes/circle.js';
+ +

이 모듈은 각각의 서브 모듈의 export를 가져와서 shapes.js 모듈에서 효과적으로 사용할 수 있도록 합니다.

+ +
+

주의: shapes.js 에서 참조되는 export는 기본적으로 파일을 통해 리다이렉트 되고 실제로는 존재하지 않으므로, 같은 파일 내에 유용한 코드를 쓸 수 없습니다.

+
+ +

이제 main.js 파일에서 우리는 세 개의 모듈 클래스를 모두 대체할 수 있습니다.

+ +
import { Square } from './modules/square.js';
+import { Circle } from './modules/circle.js';
+import { Triangle } from './modules/triangle.js';
+ +

다음과 같은 한 줄로 작성할 수 있습니다.

+ +
import { Square, Circle, Triangle } from '/js-examples/modules/module-aggregation/modules/shapes.js';
+ +

Dynamic module loading

+ +

브라우저에서 사용할 수 있는 자바스크립트 모듈 기능의 최신 부분은 동적 모듈 로딩 입니다. 이렇게 하면 모든 것을 최상위에서 불러오지 않고, 필요할 때만 모듈을 동적으로 불러올 수 있습니다. 이것은 몇 가지 분명한 성능 이점이 있습니다. 계속 읽어보고 어떻게 작동하는지 살펴봅시다.

+ +

이 새로운 기능을 통해 import() 를 함수로 호출하여 모듈 경로를 매개 변수(parameter)로 전달할 수 있습니다. 모듈 객체({{anch("Creating a module object")}} 참조)를 사용하여 promise를 반환하면 해당 객체의 export에 접근할 수 있습니다. 

+ +
import('/modules/myModule.js')
+  .then((module) => {
+    // Do something with the module.
+  });
+ +

예제를 보겠습니다. In the dynamic-module-imports 디렉토리에는 classes 예제를 기반으로 한 또 다른 예제가 있습니다. 이번에는 예제가 로딩될 때 캔버스에 아무것도 그리지 않습니다. 대신 우리는 세 개의 버튼("Circle", "Square", "Triangle")이 포함되어 있습니다. 이 버튼을 누르면 필요한 모듈을 동적으로 불러온 다음, 이를 사용하여 연관된 도형을 그립니다.

+ +

이 예제에서 우리는 index.html 파일과 main.js 파일만 변경했습니다. 모듈 export는 이전과 동일하게 유지됩니다.

+ +

main.js 에서 document.querySelector() 를 사용하여 각 버튼에 대한 참조를 가져왔습니다. 예를들면 다음과 같습니다.

+ +
let squareBtn = document.querySelector('.square');
+ +

그런 다음 각 버튼에 이벤트 리스너를 연결하여 해당 모듈을 누르면, 동적으로 로드되어 도형을 그리는데 사용됩니다.

+ +
squareBtn.addEventListener('click', () => {
+  import('/js-examples/modules/dynamic-module-imports/modules/square.js').then((Module) => {
+    let square1 = new Module.Square(myCanvas.ctx, myCanvas.listId, 50, 50, 100, 'blue');
+    square1.draw();
+    square1.reportArea();
+    square1.reportPerimeter();
+  })
+});
+ +

Note that, promise fulfillment 가 모듈 객체를 반환하기 때문에 클래스는 객체의 하위 기능으로 만들어집니다. 따라서 이제 Module 을 사용하여 생성자(contructor)에 접근해야 합니다. 예를들어 Module.Square( ... ) 와 같이 앞에 Module이 붙습니다.

+ +

See also

+ + + +

{{Previous("Web/JavaScript/Guide/Meta_programming")}}

diff --git a/files/ko/web/javascript/guide/numbers_and_dates/index.html b/files/ko/web/javascript/guide/numbers_and_dates/index.html new file mode 100644 index 0000000000..6a45e1ef7f --- /dev/null +++ b/files/ko/web/javascript/guide/numbers_and_dates/index.html @@ -0,0 +1,384 @@ +--- +title: 숫자와 날짜 +slug: Web/JavaScript/Guide/Numbers_and_dates +tags: + - JavaScript +translation_of: Web/JavaScript/Guide/Numbers_and_dates +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}
+ +

이 장에서는 JavaScript에서 숫자와 날짜를 사용하기 위한 개념과 객체, 함수에 대해 소개합니다. 그리고 숫자를 10진법, 2진법, 16진법 등의 다양한 형태로 표현하는 방법과 더불어 {{jsxref("Math")}} 객체를 사용해 다양한 수학 연산을 수행하는 방법을 알 수 있습니다.

+ +

숫자

+ +

JavaScript에서 모든 숫자는 double-precision 64-bit binary format IEEE 754 (즉, ±2−1022 과 ±2+1023 또는 대략 ±10−308 to ±10+308 사이의 숫자이며 53bits의 수치정밀도 )로 구현되어 있습니다. ± 253 - 1까지의 정수 값을 정확하게 나타낼 수 있습니다.

+ +

여기 부동 소수점 숫자를 나타낼 수 있으며, 숫자 형식은 세 개의 상징적인 값: +{{jsxref("Infinity")}}, -{{jsxref("Infinity")}}, and {{jsxref("NaN")}} (숫자가 아닌 값)을 갖습니다.

+ +

JavaScript에 최근 추가 된 것은 {{jsxref ( "BigInt")}}로, 매우 큰 정수를 나타낼 수 있습니다. BigInt를사용할땐 다음을 주의해야 합니다. 예를 들면, BigInt와 {{jsxref ( "Number")}} 값을 같은 연산으로 혼합하고 일치시킬 수는 없으며 {{jsxref ( "Math")}} 객체를 BigInt값과 함께 사용할 수 없습니다.

+ +

JavaScript에서 다른 기본형과 문맥에 대한 내용은 JavaScript data types and structures를 참조하세요.

+ +

여러분은 숫자 리터럴의 네 가지 유형을 사용할 수 있습니다: 10진수, 2진수, 8진수, 16진수

+ +

10진수

+ +
1234567890
+42
+
+// 앞에 0이 붙은 숫자를 조심하세요:
+
+0888 // 10진수 888로 해석됩니다.
+0777 // non-strict mode에서 10진수 511로 해석됩니다.
+
+ +

10진수 리터럴도 영(0)으로 시작될 수 있다는 점에 유의하세요. 그러나 만약 영0 다음 숫자가 8보다 작으면, 그 숫자는 8진법으로 해석됩니다.

+ +

2진수

+ +

2진수 구문은 앞에 오는 0과 소문자 또는 대문자 라틴 문자 "B"(0B 또는 0b)를 사용합니다. 0b 다음의 숫자가 0 또는 1이 아니면 다음의 SyntaxError가 발생합니다. "0b 이후에 누락 된 2 진수"("Missing binary digits after 0b")입니다.

+ +
var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
+var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
+var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
+ +

8진수

+ +

8 진수 구문은 앞에 0을 사용합니다. 0 이후의 숫자가 0에서 7까지 범위 밖에 있는 경우, 숫자는 10진수로 해석됩니다.

+ +
var n = 0755; // 493
+var m = 0644; // 420
+
+ +

ECMAScript 5의 Strict 모드는 8 진수 구문을 금지합니다. 8 진수 구문은 ECMAScript 5의 일부가 아니지만, 0644 === 420"\ 045"=== "%"의 8 진수에 접두사를 붙이면 모든 브라우저에서 지원됩니다. ECMAScript 2015에서는 접두어가 0o인 경우 8 진수가 지원됩니다 (예 :

+ +
var a = 0o10; // ES2015: 8
+ +

16진수

+ +

16진수 구문은 앞에 0 다음에 소문자나 대문자 라틴어 문자 "X"(0x 또는 0X)를 사용합니다. 0X 이후 숫자가 범위(0123456789ABCDEF) 밖에 있는 경우, 다음 SyntaxError가 발생합니다: "식별자는 숫자 리터럴 후 즉시 시작됩니다".

+ +
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
+0x123456789ABCDEF   // 81985529216486900
+0XA                 // 10
+
+ +

지수 계산

+ +
1E3   // 1000
+2e6   // 2000000
+0.1e2 // 10
+
+ +

Number 객체

+ +

{{jsxref("Number")}} 내장객체는 최대값, not-a-number, 무한대와 같은 숫자 상수를 위한 속성들이 있습니다. 여러분은 이러한 속성의 값을 변경 할 수 없고 다음과 같이 사용합니다:

+ +
var biggestNum = Number.MAX_VALUE;
+var smallestNum = Number.MIN_VALUE;
+var infiniteNum = Number.POSITIVE_INFINITY;
+var negInfiniteNum = Number.NEGATIVE_INFINITY;
+var notANum = Number.NaN;
+
+ +

여러분은 직접 생성한 Number 객체의 속성이 아닌, 위와같이 항상 미리 정의된 Number 객체의 속성을 참조해야합니다.

+ +

다음 표에서는 Number 객체의 속성이 요약되어 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Number 속성들
특성묘사
{{jsxref("Number.MAX_VALUE")}}표현가능한 가장 큰 수 (±1.7976931348623157e+308)
{{jsxref("Number.MIN_VALUE")}}표현가능한 가장 작은 수(±5e-324)
{{jsxref("Number.NaN")}}"숫자가 아닌" 특수값
{{jsxref("Number.NEGATIVE_INFINITY")}}음의 무한대값; 오버 플로로 반환됨.
{{jsxref("Number.POSITIVE_INFINITY")}}양의 무한대 값; 오버 플로로 반환됨.
{{jsxref("Number.EPSILON")}}표현가능한 매우 작은 값{{jsxref("Number")}}.(2.220446049250313e-16)
{{jsxref("Number.MIN_SAFE_INTEGER")}}자바스크립트에서 안전한 최소의 정수.(−253 + 1, or −9007199254740991)
{{jsxref("Number.MAX_SAFE_INTEGER")}}자바스크립트에서 안전한 최대의 정수.(+253 − 1, or +9007199254740991)
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Number 메소드들
방법묘사
{{jsxref("Number.parseFloat()")}} +

문자열 인수를 파싱하고 부동 소수점 숫자를 반환합니다. 전역 {{jsxref("parseFloat", "parseFloat()")}} 함수와 동일합니다.

+
{{jsxref("Number.parseInt()")}}문자열 라인 인수를 파싱해, 지정된 기수 또는 밑줄의 정수를 돌려줍니다. 전역 {{jsxref("parseInt", "parseInt()")}}함수와 동일합니다.
{{jsxref("Number.isFinite()")}}전달된 값이 유한한 수인지 판정합니다.
{{jsxref("Number.isInteger()")}}전달된 값이 정수인지 판정합니다.
{{jsxref("Number.isNaN()")}}이 전달된 값 {{jsxref("Global_Objects/NaN", "Not-a-Number")}}여부를 확인합니다. 원본 글로벌 {{jsxref("Global_Objects/isNaN", "(isNaN)")}}의 더욱 강력한 버전입니다.
{{jsxref("Number.isSafeInteger()")}}제공된 값이 안전한 정수인지 여부를 확인합니다.
+ +

Number 프로토 타입은 다양한 형식의 Number 객체에서 정보를 검색하는 메소드를 제공합니다. 다음 표는 Number.prototype의 메소드를 요약 한 것입니다.

+ + + + + + + + + + + + + + + + + + + + + + + +
Number.prototype의 방법
방법Description
{{jsxref("Number.toExponential", "toExponential()")}}지수표기법 안에서 번호를 나타내는 문자열을 반환합니다.
{{jsxref("Number.toFixed", "toFixed()")}}문자열 고정 소수 점 표기법의 수를 나타내는 문자열을 반환합니다.
{{jsxref("Number.toPrecision", "toPrecision()")}}지정된 정밀에 고정 소수 점 표기법의 수를 나타내는 문자열을 반환합니다.
+ +

Math 객체

+ +

내장 {{jsxref ( "Math")}} 객체는 수학 상수 및 함수에 대한 속성 및 메서드를 포함합니다. 예를 들어, Math 객체의 PI 속성에는 pi (3.141 ...) 값이 있습니다.이 값은 응용 프로그램에서 다음과 같이 사용합니다.

+ +
Math.PI
+
+ +

마찬가지로 표준 수학 함수도 Math의 함수입니다. 여기에는 삼각 함수, 로그 함수, 지수 함수 및 기타 함수가 포함됩니다. 예를 들어 삼각 함수 sine을 사용하려면 다음과 같이 작성합니다.

+ +
Math.sin(1.56)
+
+ +

Math의 모든 삼각 함수에는 라디안으로 매게변수를 입력해야 합니다.

+ +

다음 표에서는 Math 개체의 방법을 요약하였습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Math의 메소드들
방법묘사
{{jsxref("Math.abs", "abs()")}}절대 값
{{jsxref("Math.sin", "sin()")}}, {{jsxref("Math.cos", "cos()")}}, {{jsxref("Math.tan", "tan()")}}표준 삼각 함수; 라디안에서의 인수
{{jsxref("Math.asin", "asin()")}}, {{jsxref("Math.acos", "acos()")}}, {{jsxref("Math.atan", "atan()")}}, {{jsxref("Math.atan2", "atan2()")}}역삼각 함수; 라디안에 반환 값
{{jsxref("Math.sinh", "sinh()")}}, {{jsxref("Math.cosh", "cosh()")}}, {{jsxref("Math.tanh", "tanh()")}}쌍곡삼각함수; 라디안에 반환 값.
{{jsxref("Math.asinh", "asinh()")}}, {{jsxref("Math.acosh", "acosh()")}}, {{jsxref("Math.atanh", "atanh()")}}역쌍곡삼각함수; 라디안에 반환 값.
+

{{jsxref("Math.pow", "pow()")}}, {{jsxref("Math.exp", "exp()")}}, {{jsxref("Math.expm1", "expm1()")}}, {{jsxref("Math.log10", "log10()")}}, {{jsxref("Math.log1p", "log1p()")}}, {{jsxref("Math.log2", "log2()")}}

+
지수와 로그 기능.
{{jsxref("Math.floor", "floor()")}}, {{jsxref("Math.ceil", "ceil()")}} 가장큰/가장작은 정수 보다 적은/많은 또는 그와 동등한 원칙으로 반환해라.
{{jsxref("Math.min", "min()")}}, {{jsxref("Math.max", "max()")}}더적거나 더많은 쉼표의 (각각) 숫자 인수의 나뉜목록으로 반환해라.
{{jsxref("Math.random", "random()")}}0과 1사이의 난수를 반환해라.
{{jsxref("Math.round", "round()")}}, {{jsxref("Math.fround", "fround()")}}, {{jsxref("Math.trunc", "trunc()")}},반올림과 절단 기능들.
{{jsxref("Math.sqrt", "sqrt()")}}, {{jsxref("Math.cbrt", "cbrt()")}}, {{jsxref("Math.hypot", "hypot()")}}제곱 근, 세 제곱 근, 평방 인수의 합의 제곱 근.
{{jsxref("Math.sign", "sign()")}}그 수가 양수인지 음수인지 0인지를 가르키는 숫자의 표시.
{{jsxref("Math.clz32", "clz32()")}},
+ {{jsxref("Math.imul", "imul()")}}
32비트 이진 표시의 주요 제로 비트 수.
+ 그 두 인수의 C-like 32비트 곱셈의 결과.
+ +

다른 많은 객체와 달리 자신의 Math 개체를 만들필요가 없습니다. 언제든 내장 된 Math 객체 바로 사용할 수 있습니다.

+ +

Date 객체

+ +

자바스크립트에는 날짜 데이터 타입이 없습니다. 그러나, {{jsxref ( "Date")}} 객체와 그 메소드를 사용하여 응용 프로그램에서 날짜와 시간을 처리 할 수 ​​있습니다. Date 객체에는 날짜 설정, 가져 오기 및 조작을위한 많은 메소드가 있습니다. 속성(properties)이 없습니다.

+ +

자바스크립트는 자바와 비슷하게 날짜를 처리합니다. 두 언어에는 동일한 날짜 메소드가 많으며 두 언어 모두 1970 년 1 월 1 일 00:00:00 이후의 밀리 초 수로 날짜를 저장합니다. 유닉스 타임 스탬프는 1970 년 1 월 1 일 00:00:00 이후의 초 수입니다.

+ +

Date 개체 범위는 UTC 1970 년 1 월 1 일을 기준으로 -100,000,000 일에서 100,000,000 일입니다.

+ +

Date 객체를 만들려면 :

+ +
var dateObjectName = new Date([parameters]);
+
+ +

여기서 dateObjectName은 만들려는 Date 객체의 이름입니다. 새로운 객체 또는 기존 객체의 속성 일 수 있습니다.

+ +

new 키워드없이 Date를 호출하면 현재 날짜와 시간을 나타내는 문자열이 반환됩니다.

+ +

앞 구문에서 parameters는 아래 규칙을 따릅니다.

+ + + +

Data 개체의 표현 방법

+ +

날짜와 시간을 조절하는 Date객체표현 방법은 아래 종류로 나뉩니다:

+ + + +

"get"및 "set"메소드를 사용하여 초, 분,시, 일, 요일, 월 및 연도를 별도로 가져 와서 설정할 수 있습니다. 요일이 자동적으로 설정되기 (위해) 때문에, 요일을 돌려주는 getDay 메소드가 있습니다만, 대응하는 setDay 메소드는 없습니다. 이러한 메서드는 정수를 사용하여 다음과 같이 값을 나타냅니다.

+ + + +

예를 들어, 아래와 같이 값들을 정의해봅시다 :

+ +
var Xmas95 = new Date("December 25, 1995");
+
+ +

그러면 Xmas95.getMonth()는 11을 반환합니다, 그리고 Xmas95.getFullYear()는 1995를 반환합니다.

+ +

getTimesetTime방법들은 날짜를 나눌때 유용합니다. getTime함수는 Date객체에 대해 1970년 1월 1일 00:00시부터 밀리초단위로 리턴합니다.

+ +

예를 들어, 다음 코드는 현재 년도에 남아 수를 표시합니다:

+ +
var today = new Date();
+var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month
+endYear.setFullYear(today.getFullYear()); // Set year to this year
+var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
+var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
+var daysLeft = Math.round(daysLeft); //returns days left in the year
+
+ +

이 예제에는 오늘 날짜가 포함된 today라는 명칭을 가진 Date객체를 만듭니다. 그리고 나서 endYear라는 Date객체를 만들고 현재연도를 설정합니다. 그런 다음 하루에 밀리 초 수를 사용하여 getTime을 사용하고 전체 일 수를 반올림하여 todayendYear 사이의 일 수를 계산합니다.

+ +

Parse 함수는 날짜문자열부터 기존의 Date객체까지의 값을 할당하기에 유용합니다. 예를 들어, 다음 코드는 그 IPOdate 객체에 날짜값을 할당하기위해 parsesetTime을 사용합니다;

+ +
var IPOdate = new Date();
+IPOdate.setTime(Date.parse("Aug 9, 1995"));
+
+ +

예제

+ +

다음 예제 에서 JSClock()는 digital 시계형식의 시간을 반환합니다.

+ +
function JSClock() {
+  var time = new Date();
+  var hour = time.getHours();
+  var minute = time.getMinutes();
+  var second = time.getSeconds();
+  var temp = "" + ((hour > 12) ? hour - 12 : hour);
+  if (hour == 0)
+    temp = "12";
+  temp += ((minute < 10) ? ":0" : ":") + minute;
+  temp += ((second < 10) ? ":0" : ":") + second;
+  temp += (hour >= 12) ? " P.M." : " A.M.";
+  return temp;
+}
+
+ +

JSClock 함수는 먼저 time이라는 새 Date 객체를 만듭니다. 인수가 없으므로 현재 날짜와 시간으로 시간이 생성됩니다. 그런 다음 getHours, getMinutesgetSeconds 메소드를 호출하면 현재 시간, 분 및 초 값이hour, minute, second로 할당됩니다.

+ +

다음 네 문장은 시간을 기준으로 문자열 값을 만듭니다. 첫 번째 명령문은 변수 temp를 작성하고 조건식을 사용하여 값을 할당합니다. hour가 12보다 큰 경우 (hour - 12), 그렇지 않은 경우 시간이 0이 아닌 경우 시간이 12 일 경우 시간이 12가됩니다.

+ +

다음 명령문은 temp 값에 minute 값을 추가합니다. 분(minute)의 값이 10보다 작 으면 조건식은 앞에 0이 있는 문자열을 추가합니다. 그렇지 않으면 콜론을 구분하는 문자열을 추가합니다. 그런 다음 같은 방법으로 temp에 초 값을 추가합니다.

+ +

마지막으로 조건부 표현식에 "P.M."이 추가됩니다. 시간(hour)이 12 시간 이상이면 임시(temp)로; 그렇지 않으면 "A.M."을 temp에 추가합니다.

+ +

{{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/about/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/about/index.html new file mode 100644 index 0000000000..05deb2017f --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/about/index.html @@ -0,0 +1,109 @@ +--- +title: About +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/About +--- +

이번 릴리즈의 새 기능

+

JavaScript 버전 1.5는 다음과 같은 개선과 새 기능을 제공합니다: +

런타임 오류
+런타임 오류가 예외로서 보고됩니다. +

숫자 표현 서식 개선
+숫자를 표현하는 서식이 Number.prototype.toExponential, Number.prototype.toFixed, Number.prototype.toPrecision 메소드를 포함함으로서 개선되었습니다. Number 개체 페이지를 보십시오. +

정규 표현식 개선
+정규표현식이 다음과 같이 개선되었습니다: +

+ +

조건부 함수 선언
+함수를 if 조건안에서 선언할 수 있습니다. 함수 정의 페이지를 참고하세요. +

함수 표현식
+함수를 표현식 안에서 선언할 수 있습니다. 함수 정의 페이지를 참고하세요. +

Multiple catch clauses
+Multiple catch clauses in a try...catch statement are supported. See The catch Block page. +

Getters와 Setters
+JavaScript writers can now add getters and setters to their objects. This feature is available only in the C implementation of JavaScript. See the Defining Getters and Setters page. +

상수
+읽기전용의 상수가 지원됩니다. This feature is available only in the C implementation of JavaScript. See the Constants page. +

+

미리 알고 있어야 할 것

+

이 안내서는 당신이 다음과 같은 배경지식을 지녔다고 가정합니다: +

+ +

C 혹은 Visual Basic에 대한 프로그래밍 경험이 있으면 좋지만, 필수사항은 아닙니다. +

+

JavaScript 버전

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
JavaScript 버전Navigator 버전
JavaScript 1.0Navigator 2.0
JavaScript 1.1Navigator 3.0
JavaScript 1.2Navigator 4.0-4.05
JavaScript 1.3Navigator 4.06-4.7x
JavaScript 1.4 
JavaScript 1.5Navigator 6.0
모질라 (오픈소스 브라우저)
+

표1: JavaScript와 Navigator 버전
+
+Each version of the Netscape Enterprise Server also supports a different version of JavaScript. To help you write scripts that are compatible with multiple versions of the Enterprise Server, this manual uses an abbreviation to indicate the server version in which each feature was implemented. +

+ + + + + + + + + + + + + +
AbbreviationEnterprise Server version
NES 2.0Netscape Enterprise Server 2.0
NES 3.0Netscape Enterprise Server 3.0
+

Table 2: Abbreviations of Netscape Enterprise Server versions +

+

JavaScript 정보를 찾을 수 있는 곳

+

The core JavaScript documentation includes the following books: +

+ +

If you are new to JavaScript, start with the Core JavaScript Guide. Once you have a firm grasp of the fundamentals, you can use the Core JavaScript Reference to get more details on individual objects and statements. +

+

문서 규약

+

JavaScript 응용프로그램은 많은 운영체제에서 실행됩니다. 이 책에 있는 정보는 모든 운영체제에 적용됩니다. 파일과 디렉토리 경로는 Windows 형식(디렉토리 이름을 구분하는데 역슬래시를 사용)으로 썼습니다. Unix에서는 역슬래시를 슬래시로 바꾸어 사용하면 됩니다. +

이 안내서에서 URL은 다음과 같은 형태로 씁니다. +

http://server.domain/path/file.html +

이 URL에서 "server"는 우리가 응용프로그램을 실행하는 서버 이름(research1이나 www 등)이고, "domain"은 인터넷 도메인 이름(netscape.com이나 uiuc.edu 등)입니다. "path"는 서버의 디렉토리 구조를 나타내고, "file.html"은 파일 이름입니다. 일반적으로 URL에서 이탤릭체로 쓴 부분은 알맞은 내용으로 바꿔써야 할 내용(placeholder)이고, 평범한 고정폭 글꼴은 그대로 쓰면 되는 내용입니다. Secure Socket Layer(SSL)을 사용하는 서버라면 http 대신 https를 쓰면 됩니다. +

이 안내서는 다음과 같은 관례를 따릅니다. +

+ +

{{ PreviousNext("Core_JavaScript_1.5_Guide", "Core_JavaScript_1.5_Guide:JavaScript_Overview") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/About", "fr": "fr/Guide_JavaScript_1.5/\u00c0_propos", "ja": "ja/Core_JavaScript_1.5_Guide/About", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/O" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/class-based_vs._prototype-based_languages/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/class-based_vs._prototype-based_languages/index.html new file mode 100644 index 0000000000..20601a0e81 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/class-based_vs._prototype-based_languages/index.html @@ -0,0 +1,26 @@ +--- +title: Class-Based vs. Prototype-Based Languages +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Class-Based_vs._Prototype-Based_Languages +--- +

클래스 기반언어와 프로토타입 기반언어

+

Java와 C++이라는 클래스 기반의 객체지향언어는 클래스와 인스턴스라는 2개의 다른 실체가 있다는 개념에 기초하고 있습니다.

+ +

JavaScript のようなプロトタイプベース言語はこの区別がありません。単にオブジェクトがあるだけです。プロトタイプベース言語には原型的なオブジェクトという概念があります。このオブジェクトは新しいオブジェクトの初期プロパティを取得する元になるテンプレートとして使用されます。どのオブジェクトもそれ独自のプロパティを指定できます。オブジェクト作成時にも実行時にも可能です。さらに、どのオブジェクトも別のオブジェクトに対するプロトタイプとして関連付けることができます。2 つ目のオブジェクトが 1 つ目のオブジェクトのプロトタイプを共有するということもできます。

+

クラスの定義

+

クラスベース言語ではクラス定義ごとにクラスを定義します。定義では特殊なメソッドを指定してそのクラスのインスタンスを作成することができます。そのようなメソッドはコンストラクタと呼びます。コンストラクタメソッドはインスタンスのプロパティに対する初期値を指定することができます。また、作成時に他の適当な処理を実行することもできます。new 演算子をコンストラクタメソッドと一緒に用いることでクラスのインスタンスを作成できます。

+

JavaScript は同様のモデルに従っていますが、コンストラクタと別になっているクラス定義がありません。その代わりに、プロパティと値からなる特定の初期的なセットを持つオブジェクトを作成するコンストラクタ関数を定義します。どの JavaScript 関数もコンストラクタとして使用できます。new 演算子をコンストラクタ関数とともに使用することで新しいオブジェクトを作成します。

+

サブクラスと継承

+

クラスベース言語ではクラス定義を通じてクラスの階層を作ります。クラス定義では新しいクラスがある既存のクラスのサブクラスになるように指定することができます。サブクラスはスーパークラスの全プロパティを継承します。さらに新しくプロパティを追加したり継承したものを変更することもできます。例えば、Employee クラスが name および dept プロパティのみを含んでおり、Manager は reports プロパティを追加する Employee のサブクラスであるとします。この場合、Manager クラスのインスタンスは name、dept、reports という 3 つのプロパティをすべて持つことになります。

+

JavaScript では、原型的なオブジェクトをどのコンストラクタ関数にも結びつけることができるようにして継承を実装しています。そのため、全く同じような Employee と Manager の例を作成することができますが、使用する用語が若干異なります。まず、Employee コンストラクタ関数を定義します。これは name および dept プロパティを指定します。次に Manager コンストラクタ関数を定義します。これは reports プロパティを指定します。最後に新しい Employee オブジェクトを Manager コンストラクタ関数に対するプロトタイプとして代入します。そして新しい Manager を作成すると、このオブジェクトは Employee オブジェクトから name および dept プロパティを継承します。

+

プロパティの追加と削除

+

クラスベース言語では一般的にクラスをコンパイル時に生成し、コンパイル時または実行時にクラスのインスタンスを作成します。クラス定義後にそのクラスのプロパティの数や型を変更することはできません。しかし、JavaScript ではどんなオブジェクトでも実行時にプロパティを追加したり削除したりすることができます。あるオブジェクトのセットでプロトタイプとして使用されているオブジェクトにプロパティを追加すると、そのプロトタイプの使用元であるオブジェクトにも新しいプロパティが追加されます。

+

違いの概要

+

次の表でこれらの違いをいくつか短くまとめてみます。この章の残りで、JavaScript のコンストラクタとプロトタイプを用いてオブジェクト階層を作成することについての詳細を説明していきます。また、この方法が Java ではどう変わるかという比較もします。

+ +
クラスベース (Java) プロトタイプベース (JavaScript)
クラスとインスタンスは異なる実体である。 すべてのオブジェクトはインスタンスである。
クラス定義を用いてクラスを定義する。また、コンストラクタメソッドを用いてクラスをインスタンス化する。 コンストラクタ関数を用いてオブジェクトのセットを定義し、作成する。
new 演算子を用いて単一のオブジェクトを作成する。 同じ。
既存のクラスのサブクラスを定義するクラス定義を用いてオブジェクト階層を構築する。 コンストラクタ関数に結びつけられたプロトタイプとしてオブジェクトを代入することでオブジェクト階層を構築する。
クラスチェーンに従ってプロパティを継承する。 プロトタイプチェーンに従ってプロパティを継承する。
クラス定義がクラスの全インスタンスの全プロパティを指定する。実行時に動的にプロパティを追加することはできない。 コンストラクタ関数またはプロトタイプがプロパティの初期セットを指定する。個々のオブジェクトやオブジェクトの全体のセットに動的にプロパティを追加したり、それらからプロパティを除去したりできる。
+
+

{{ PreviousNext("Core_JavaScript_1.5_Guide:Predefined_Core_Objects:String_Object", "Core_JavaScript_1.5_Guide:The_Employee_Example") }}

+
+

{{ languages( { "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/以類別為基礎的語言_vs._以原型為基礎的語言", "en": "en/Core_JavaScript_1.5_Guide/Class-Based_vs._Prototype-Based_Languages", "es": "es/Gu\u00eda_JavaScript_1.5/Lenguajes_basados_en_clases_frente_a_basados_en_prototipos", "fr": "fr/Guide_JavaScript_1.5/Langages_bas\u00e9s_sur_les_classes_et_langages_bas\u00e9s_sur_les_prototypes", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/J\u0119zyki_oparte_na_klasach_vs._oparte_na_prototypach", "zh-cn": "cn/Core_JavaScript_1.5_Guide/Class-Based_vs._Prototype-Based_Languages" } ) }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/constants/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/constants/index.html new file mode 100644 index 0000000000..48a697fdc2 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/constants/index.html @@ -0,0 +1,28 @@ +--- +title: Constants +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Constants +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +

상수

+

const 키워드를 이용하면 읽기 전용의 이름 있는 상수를 만들 수 있습니다. 상수 식별자(const identifier)는 변수의 식별자와 동일합니다. 문자나 밑줄로 시작해야 하고, 알파벳, 숫자, 밑줄 문자를 사용할 수 있습니다. +

+
const prefix = '212';
+
+

상수는 스크립트 실행 중에 값을 대입하거나 다시 선언하여 값을 바꿀 수 없습니다. +

전역 상수인 경우에도 항상 const 키워드를 붙여야 한다는 점만 제외하면, 상수의 범위 규칙은 변수의 경우와 동일합니다. const 키워드가 없으면 변수라고 판정됩니다. +

같은 범위에 있는 함수나 변수의 이름과 같은 이름으로 상수를 만들 수 없습니다. 예를 들어, +

+
//이 코드는 에러를 낼 것입니다
+function f() {};
+  const f = 5;
+
+//이 코드 또한 에러를 냅니다.
+function f() {
+  const g = 5;
+  var g;
+
+  //그 외 코드...
+
+}
+

{{ PreviousNext("Core_JavaScript_1.5_Guide:Variables", "Core_JavaScript_1.5_Guide:Literals") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Constants", "fr": "fr/Guide_JavaScript_1.5/Constantes", "ja": "ja/Core_JavaScript_1.5_Guide/Constants", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Sta\u0142e" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_a_regular_expression/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_a_regular_expression/index.html new file mode 100644 index 0000000000..d969b378f4 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_a_regular_expression/index.html @@ -0,0 +1,35 @@ +--- +title: Creating a Regular Expression +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_a_Regular_Expression +--- +

정규표현식 만들기

+

정규표현식은 다음의 두 가지 방법으로 만들 수 있습니다.

+ +
 re = /ab+c/; 
+
+
+
+
+ 정규표현식 상수값은 스크립트가 실행될 때 컴파일됩니다. 따라서 정규표현식의 값이 변하지 않을 경우, 이 방법을 사용하면 좀 더 나은 성능을 얻을 수 있습니다.
+
+
+
+ +
 re = new RegExp("ab+c"); 
+
+
+
+
+ 생성자를 이용하면 실행 시간에 정규표현식이 컴파일됩니다. 정규표현식 패턴이 바뀔 것을 알고 있거나, 또는 패턴을 사용자의 입력 등을 통해 외부에서 가져오려고 할 때 이 방법을 사용하십시오.
+
+
+
+
+

{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:Special_Operators", "Core_JavaScript_1.5_Guide:Writing_a_Regular_Expression_Pattern") }}

+
+

 

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_getters_and_setters/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_getters_and_setters/index.html new file mode 100644 index 0000000000..3238e19b0f --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_getters_and_setters/index.html @@ -0,0 +1,84 @@ +--- +title: Defining Getters and Setters +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Getters_and_Setters +--- +

getter/setter 정의하기

+ +

getter는 속성의 값을 얻어오는 메소드이고, setter는 속성의 값을 설정하는 메소드입니다. 우리는 언어에서 미리 정의한 핵심 개체들과 사용자 정의 개체에 getter/setter를 정의할 수 있습니다. getter와 setter를 정의할 때 쓰이는 문법은 개체 상수값 문법입니다.

+ +

다음의 JS 쉘 세션은 사용자가 정의한 개체 o에 대해서 getter와 setter가 어떻게 동작하는지 보여줍니다. JS 쉘은 JavaScript를 한 번에 실행(batch)하거나 대화식으로(interactively) 실행할 수 있게 해주는 응용프로그램입니다.

+ +

o 개체에는 이런 속성이 있습니다.

+ + + +
js> o = new Object;
+[object Object]
+js> o = {a:7, get b() {return this.a+1; }, set c(x) {this.a = x/2}};
+[object Object]
+js> o.a
+7
+js> o.b
+8
+js> o.c = 50
+js> o.a
+25
+js>
+
+ +

다음 JavaScript 쉘 세션은 이미 정의된 Date 모든 인스턴스에 year 속성을 추가하기 위해서 getter/setter가 어떻게 Date 프로토타입을 확장하는지 보여줍니다. 이 세션에서는 year 속성의 getter와 setter를 지원하기 위해서 Date에 있는 getFullYear 메소드와 setFullYear 메소드를 사용하고 있습니다.

+ +

이 문장들은 year 속성에 대한 getter와 setter를 정의합니다.

+ +
js> var d = Date.prototype;
+js> d.__defineGetter__("year", function() { return this.getFullYear(); });
+js> d.__defineSetter__("year", function(y) { this.setFullYear(y); });
+
+ +

이 문장들은 Date의 getter/setter를 사용합니다.

+ +
js> var now = new Date;
+js> print(now.year);
+2000
+js> now.year=2001;
+987617605170
+js> print(now);
+Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001
+
+ +
JavaScript 1.5를 개발하는 동안 이미 존재하는 개체에 getter/setter를 추가할 때 getter =, setter =이라는 식의 문법을 사용하던 때가 잠깐 있었습니다. 이 문법은 이제 사용하지 말아야 합니다. 현재의 JS 1.5 엔진에서는 경고를 발생시키고, 더 나중의 버전에서는 문법 에러를 발생시키게 될 것입니다.
+ +

 

+ +

요약

+ +

getter/setter를

+ + + +

개체 초기화 지정자를 이용할 때는 단순히 getter 메소드 앞에는 get을 써주고 setter 메소드 앞에는 set을 써주기만 하면됩니다. 물론 getter 메소드에는 매개변수가 없어야 하고 setter에는 정확히 하나만 있어야 합니다. 다음 예제에서와 같이 말입니다.

+ +
o = {
+  a:7,
+  get b() { return this.a+1; },
+  set c(x) { this.a = x/2; }
+};
+
+ +

개체가 생성된 이후에 어느 때라도 __defineGetter____defineSetter__라는 메소드를 이용하면 getter/setter를 정의할 수 있습니다. 두 메소드 모두 첫 번째 매개변수에 getter/setter 이름을 나타내는 문자열을 받습니다. 두 번째 매개변수는 getter/setter로서 호출될 함수를 받습니다. 예제를 보십시오.

+ +
o.__defineGetter__("b", function() { return this.a+1; });
+o.__defineSetter__("c", function(x) { this.a = x/2; });
+
+ +

두 가지 중에서 어떤 방식을 택할지는 프로그래밍 스타일이나 해야할 작업에 달려있습니다. 프로토타입을 정의하는데 이미 개체 초기화 지정자를 사용하고 있다면 거의 첫 번째 방식을 사용할 것입니다. 첫 번째가 좀 더 단순하고 자연스러운 방식입니다. 그러나 우리가 직접 프로토토입을 만들거나 개체를 생성할 수 없어서 나중에 getter/setter를 추가해야 하는 상황이라면 두 번째 방식을 사용할 수 밖에 없습니다. 두 번째 방식은 JavaScript의 동적인 특성을 잘 보여주는 방식입니다. 하지만 코드를 읽고 이해하기 어렵게 만들 수도 있습니다.

+ +

{{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Using_this_for_Object_References", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Deleting_Properties") }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_methods/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_methods/index.html new file mode 100644 index 0000000000..8e91a2007f --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_methods/index.html @@ -0,0 +1,43 @@ +--- +title: Defining Methods +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Methods +--- +

메소드 정의

+

+ + 메소드 + 는 개체와 연관되어 있는 함수입니다. 일반적인 함수를 정의하는 것과 같은 방법으로 메소드를 정의합니다. 그 후에, 존재하는 개체와 함수를 연관시키기 위해서 다음과 같은 문법을 사용합니다.

+
object.methodname = function_name
+
+

object는 존재하는 개체중에 하나이고, methodname은 지금 추가하려는 메소드 이름이며, function_name은 함수 이름입니다.

+

이제 우리는 개체의 메소드를 호출할 때 다음과 같이 할 수 있습니다.

+
object.methodname(params);
+
+

개체 생성자 함수에 메소드 정의를 포함시켜서 개체 타입에 대한 메소드를 정의할 수 있습니다. 예를 들어, 미리 정의된 car 개체의 속성을 출력해주는 함수를 정의할 수 있습니다.

+
function displayCar() {
+   var result = "A Beautiful " + this.year + " " + this.make
+      + " " + this.model;
+   pretty_print(result);
+}
+
+

pretty_print는 가로선과 문자열을 출력하는 함수입니다. 이 메소드가 포함된 개체를 참조하기 위해서 this를 사용하고 있다는 것을 주의해서 보십시오.

+

아래 문장을 개체 정의에 추가함으로써 이 함수를 car의 메소드로 만들 수 있습니다.

+
this.displayCar = displayCar;
+
+

그러므로 car 개체의 완벽한 정의는 아래와 같은 모습이 될 것입니다.

+
function car(make, model, year, owner) {
+   this.make = make;
+   this.model = model;
+   this.year = year;
+   this.owner = owner;
+   this.displayCar = displayCar;
+}
+
+

그러면 우리는 모든 car 개체에 대해서 이런 식으로 displayCar 메소드를 호출할 수 있게됩니다.

+
car1.displayCar()
+car2.displayCar()
+
+

이 코드는 다음 그림과 같은 내용을 만들어냅니다.

+

Image:obja.gif 그림 7.1: 메소드 출력 결과

+

{{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Properties_for_an_Object_Type", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Using_this_for_Object_References") }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_properties_for_an_object_type/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_properties_for_an_object_type/index.html new file mode 100644 index 0000000000..17c2aa7de8 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/defining_properties_for_an_object_type/index.html @@ -0,0 +1,11 @@ +--- +title: Defining Properties for an Object Type +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Properties_for_an_Object_Type +--- +

개체 형식에 속성 정의하기

+

prototype 속성을 이용하면 이미 정의해 놓은 개체 형식에 속성을 추가할 수 있습니다. 이 방법을 사용하면 개체의 인스턴스 하나에만 속성이 추가되는 것이 아니라 같은 타입의 모든 개체가 공유하는 속성을 정의합니다. 다음 코드는 car 형식의 모든 개체에 color 속성을 추가하고, car1 개체의 color 속성에 값을 할당하는 코드입니다.

+
Car.prototype.color=null;
+car1.color="black";
+
+

더 많은 정보를 얻으려면 기본 JavaScript 레퍼런스에 있는 Function 개체의 prototype 속성을 보십시오. {{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Indexing_Object_Properties", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Methods") }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/deleting_properties/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/deleting_properties/index.html new file mode 100644 index 0000000000..1b6f50cc11 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/deleting_properties/index.html @@ -0,0 +1,20 @@ +--- +title: Deleting Properties +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Deleting_Properties +--- +

속성 제거

+

delete 연산자를 사용하여 속성을 제거할 수 있습니다. 어떻게 속성을 제거하는지 코드를 보십시오.

+
//a와 b라는 속성을 가지는 새 개체를 만듭니다.
+myobj = new Object;
+myobj.a = 5;
+myobj.b = 12;
+
+//myobj가 속성 b만을 가지도록 속성 a를 지웁니다.
+delete myobj.a;
+
+

전역 변수를 선언할 때 var 키워드를 사용하지 않았다면 그 전역 변수를 제거하는데 delete 연산자를 사용할 수 있습니다.

+
g = 17;
+delete g;
+
+

더 많은 정보를 얻으려면 delete를 보십시오. {{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Getters_and_Setters", "Core_JavaScript_1.5_Guide:Predefined_Core_Objects") }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/index.html new file mode 100644 index 0000000000..8345ba1478 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/index.html @@ -0,0 +1,6 @@ +--- +title: Creating New Objects +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects +--- +{{wiki.localize('System.API.page-generated-for-subpage')}} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/indexing_object_properties/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/indexing_object_properties/index.html new file mode 100644 index 0000000000..84b9df2c2d --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/indexing_object_properties/index.html @@ -0,0 +1,9 @@ +--- +title: Indexing Object Properties +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Indexing_Object_Properties +--- +

개체 속성 접근하기

+

JavaScript 1.0에서는 개체의 속성을 참조할 때 개체 이름이나 순서 인덱스를 사용할 수 있습니다. 그러나 JavaScript 1.1과 그 이후 버전에서는 처음에 속성을 정의할 때 이름으로 정의했으면 항상 이름으로만 참조해야 하고, 인덱스로 정의했으면 인덱스로만 참조해야 합니다.

+

이런 제한은 앞 페이지 예제의 car 개체 형식처럼 생성자 함수로 개체와 개체 속성을 만들 때나 명시적으로 개별 속성을 만들 때(예를 들어 myCar.color = "red" 같은 식으로 속성을 추가할 때) 모두 적용됩니다. 그러므로 myCar{{ mediawiki.external(5) }} = "25 mpg"라고 인덱스를 이용해서 속성을 정의하면 그 이후로는 항상 myCar{{ mediawiki.external(5) }}로 참조할 수 있습니다.

+

이 규칙은 forms 배열 같이 HTML을 반영하여 생성된 개체에는 예외입니다. 이 배열에 있는 개체를 참조할 때는 순서(문서에 기록된 순서)를 나타내는 숫자나 이름(이름을 정의한 경우에만)을 이용하여 참조할 수 있습니다. 예를 들어, 문서에 있는 두 번째 <FORM> 태그가 "myForm"이라는 값을 가진 NAME 속성을 갖고 있다면 이 폼은 document.forms{{ mediawiki.external(1) }}, document.forms{{ mediawiki.external('\"myForm\"') }}, document.myForm으로 접근할 수 있습니다. {{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Using_a_Constructor_Function", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Properties_for_an_Object_Type") }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_a_constructor_function/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_a_constructor_function/index.html new file mode 100644 index 0000000000..552347b70e --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_a_constructor_function/index.html @@ -0,0 +1,58 @@ +--- +title: Using a Constructor Function +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_a_Constructor_Function +--- +

생성자 함수 사용하기

+

다른 방법으로, 다음 두 단계를 거쳐서 개체를 만들 수도 있습니다.

+
    +
  1. 생성자 함수를 작성함으로써 개체를 정의합니다.
  2. +
  3. new 키워드를 사용하여 개체의 인스턴스를 만듭니다.
  4. +
+

개체 형식을 정의하기 위해서, 개체의 이름, 속성, 메소드를 지정하는 함수를 만듭니다. 자동차를 나타내기 위한 개체를 만들고 싶다고 해봅시다. 그렇다면 이 형식이 car라고 불리길 원할 것이고, make, model, year라는 속성이 있기를 원할 것입니다. 원하는 것을 이루기 위해서 이런 함수를 작성합니다.

+
function car(make, model, year) {
+   this.make = make;
+   this.model = model;
+   this.year = year;
+}
+
+

함수의 인자로 전달받은 값을 개체의 속성에 할당하기 위해서 this를 사용했다는 것을 명심하십시오.

+

이제 우리는 mycar라는 개체를 이렇게 만들 수 있습니다.

+
mycar = new car("Eagle", "Talon TSi", 1993);
+
+

이 문장은 mycar를 만들고, 지정된 값을 mycar의 속성에 할당합니다. 그러면 mycar.make는 "Eagle"이라는 문자열 값을 가지고, mycar.year는 1993이라는 정수를 가질 것입니다.

+

우리는 new를 써서 car 개체를 몇 개라도 만들 수 있습니다.

+
kenscar = new car("Nissan", "300ZX", 1992);
+vpgscar = new car("Mazda", "Miata", 1990);
+
+

개체는 다른 개체를 속성으로 가질 수 있습니다. 예를 들어, person 개체를 다음과 같이 정의했다고 합시다.

+
function person(name, age, sex) {
+   this.name = name;
+   this.age = age;
+   this.sex = sex;
+}
+
+

그리고나서 person 개체의 인스턴스 두 개를 만듭니다.

+
rand = new person("Rand McKinnon", 33, "M");
+ken = new person("Ken Jones", 39, "M");
+
+

이제 우리는 car가 owner라는 속성으로 person 개체를 가지도록 car의 정의를 바꿀 수 있습니다.

+
function car(make, model, year, owner) {
+   this.make = make;
+   this.model = model;
+   this.year = year;
+   this.owner = owner;
+}
+
+

새 개체 인스턴스를 만들 때 이렇게 쓸 수 있습니다.

+
car1 = new car("Eagle", "Talon TSi", 1993, rand);
+car2 = new car("Nissan", "300ZX", 1992, ken);
+
+

위 문장에서 owner 인자로 문자열 상수값이나 정수값을 전달하는 대신 randken이라는 개체를 전달했다는 사실에 주의하십시오. 이제 car2의 소유자 이름을 알고 싶으면 이런식으로 접근할 수 있습니다.

+
car2.owner.name
+
+

정의된 개체에 아무때나 속성을 추가할 수 있다는 사실을 기억하십시오.

+
car1.color = "black"
+
+

이 문장은 car1에 color 속성을 추가하고 "black"이라는 값을 할당합니다. 그러나 이 문장이 다른 개체에 영향을 미치지는 않습니다. 같은 형식을 가지는 모든 개체에 새 속성을 추가하고 싶으면 car 개체 형식의 정의에 속성을 추가해야 합니다.

+

{{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Using_Object_Initializers", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Indexing_Object_Properties") }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_this_for_object_references/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_this_for_object_references/index.html new file mode 100644 index 0000000000..0ed663ae1f --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/creating_new_objects/using_this_for_object_references/index.html @@ -0,0 +1,25 @@ +--- +title: Using this for Object References +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_this_for_Object_References +--- +

this를 사용한 개체 참조

+

JavaScript에는 this라는 키워드가 있는데, 메소드 안에서 현재 개체를 참조하기 위해서 이 키워드를 사용할 수 있습니다. 예를 들어, 개체의 값 속성을 검증하는 validate라는 함수가 있다고 해봅시다.

+
function validate(obj, lowval, hival) {
+   if ((obj.value < lowval) || (obj.value > hival))
+      alert("Invalid Value!");
+}
+
+

그러면 폼의 각 요소의 onchange 이벤트 핸들러에서 validate를 호출할 때, 다음 예제와 같은 방법으로 this를 사용해서 폼 요소를 validate에 전달할 수 있습니다.

+
<input type="text" name="age" size="3"
+   onChange="validate(this, 18, 99)">
+
+

form 속성과 같이 사용하면, this는 현재 개체의 부모 폼을 참조할 수 있습니다. 다음 예제에서, myForm이라는 폼은 Text 개체와 버튼을 포함하고 있습니다. 사용자가 버튼을 클릭하면 Text 개체의 값을 폼 이름으로 바꿉니다. 버튼의 onclick 이벤트 핸들러에서 부모 폼인 myForm을 참조하기 위해서 this.form을 사용하고 있습니다.

+
<form name="myForm">
+<p><label>Form name:<input type="text" name="text1" value="Beluga"></label>
+<p><input name="button1" type="button" value="Show Form Name"
+      onclick="this.form.text1.value=this.form.name">
+</p>
+</form>
+
+

{{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Methods", "Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Getters_and_Setters") }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/expressions/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/expressions/index.html new file mode 100644 index 0000000000..d9f8bb0bf9 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/expressions/index.html @@ -0,0 +1,16 @@ +--- +title: Expressions +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Expressions +--- +

표현식

+

표현식은 상수(literals), 변수, 연산자 그리고 단일값을 반환하는 계산식(값은 숫자, 문자열, 논리값이 가능)이 알맞게 조합된 집합체다. +

개념적으로 보면 표현식에는 두가지 타입이 있다: 하나는 변수에 값을 할당하는 것이고 다른 하나는 단순히 값을 가지고 있는 것이다. 예를 들어, x = 7 이라는 표현식은 x 에 7이라는 값을 할당하는 표현식이다. 이 표현식은 스스로 7이라는 값을 부여한다. 이런 표현식들은 할당 연산자를 사용한다. 반면에, 3 + 4 라는 표현식은 단순히 7이라는 값을 계산할 뿐이다; 할당하지 않는다. 이런 표현식에서 사용되는 연산자는 그냥 단순히 연산자라고만 한다. +

JavaScript에는 다음과 같은 타입의 표현식이 있다: +

+ +

{{ PreviousNext("Core_JavaScript_1.5_Guide:Unicode", "Core_JavaScript_1.5_Guide:Operators") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Expressions", "fr": "fr/Guide_JavaScript_1.5/Expressions", "ja": "ja/Core_JavaScript_1.5_Guide/Expressions", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Wyra\u017cenia" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/javascript_overview/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/javascript_overview/index.html new file mode 100644 index 0000000000..310ab25c67 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/javascript_overview/index.html @@ -0,0 +1,44 @@ +--- +title: JavaScript Overview +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/JavaScript_Overview +--- +

JavaScript란 무엇인가?

+

JavaScript는 크로스 플랫폼, 객체 지향 스크립트 언어입니다. JavaScript는 작고, 가벼운 언어입니다; JavaScript는 단독으로 쓰이는 언어로는 유용하지 않지만, 웹 브라우져 같은 다른 제품이나 프로그램에 포함하기 쉽습니다. 호스트 환경에서 JavaScript는 그 환경의 다른 개체(object)들을 프로그램적으로 제어하기 위해서 그들과 연결될 수 있습니다.

+

기본 JavaScript(core JavaScript)는 Array, Date, Math등 기본이 되는 개체들(core set of objects)과 연산자, 제어 구조, 문장등 언어의 기본 요소들(core set of language elements)을 포함하고 있습니다. 기본 JavaScript는 다른 개체를 추가함으로써 다양한 목적을 위해 확장될 수 있습니다. 예를 들면 다음과 같은 것들입니다.

+ +

JavaScript의 LiveConnect 기능을 통해서, Java와 JavaScript 코드가 서로 통신할 수 있습니다. JavaScript에서 Java 개체를 초기화하여 개체의 공개 메소드와 필드에 접근할 수 있습니다. Java에서 JavaScript 개체, 속성(property), 메소드에 접근할 수 있습니다.

+

Netscape가 JavaScript를 개발했고 Netscape 브라우저에서 JavaScript가 가장 먼저 사용되었습니다.

+

JavaScript와 Java

+

JavaScript 와 Java 는 여러가지 면에서 비슷하지만 본질적으로 다릅니다. JavaScript는 Java 와 공통점이 있지만 Java 처럼 형(type)을 검사하지 않습니다. JavaScript는 Java 문법의 대부분과 제어흐름의 기본적인 개념들을 지원합니다.

+

Java의 클래스 선언으로 이루어지는 컴파일 타임 시스템에 대조적으로, JavaScript는 수, 불리언, 문자열 값을 나타내는 작은 규모의 자료형에 기반한 런타임 시스템을 지원합니다. JavaScript는 클래스 기반 개체 모델이 아닌 프로토타입 기반(prototype-based) 개체 모델을 갖고 있습니다. 프로토타입 기반 개체 모델은 동적인 상속을 제공합니다. 즉, 각각의 개체를 상속할 수 있는 것입니다. JavaScript는 또 특별히 선언시의 요구사항이 없는 함수도 지원합니다. 함수는 느슨하게 타입된 메소드로 실행됨으로써 개체의 속성이 될 수 있습니다.(Functions can be properties of objects, executing as loosely typed methods.)

+

Java에 비해 JavaScript는 형식이 자유로운 언어입니다. 모든 변수, 클래스, 메소드들을 꼭 선언 할 필요는 없습니다. 메소드가 public, private, protected 인지 고민해야할 필요가 없고, interface를 구현할 필요도 없습니다. 변수, 매개변수(parameter), 함수의 반환 형식도 명시적으로 지정할 필요가 없습니다.

+

Java는 클래스 기반 프로그래밍 언어로서, 빠른 실행과 형 안정성(type safety)을 위해 설계되었습니다. 형 안정성이란 예를 들면 Java에서 정수를 개체 참조로 변환할 수 없고, Java 바이트코드에 오류를 일으켜서 사적인(private) 메모리 공간에 접근할 수 없다는 말입니다. 자바의 클래스 기반 모델은 프로그램이 클래스와 클래스의 메소드로만 이루어진다는 의미입니다. Java의 클래스 상속과 엄격한 형 검사(strong typing)는 일반적으로 단단히 결합된 개체의 계층 구조를 필요로 합니다. 이런 요구사항이 JavaScript 프로그래밍에 비해 Java 프로그래밍을 더 복잡하게 만듭니다.

+

반면 JavaScript는 HyperTalk나 dBASE 같이 적은 줄수의 동적 타입 언어를 계승한 것입니다. 이런 스크립트 언어는 더 많은 사람들을 위한 프로그래밍 도구로서 제공되는데, 이 언어들이 문법이 쉽고, 내장되기에 쉬우며, 개체 생성에 요구 사항이 단순하기 때문입니다.

+ +
JavaScript Java
개체 지향. 개체의 형식 사이에 구분이 없음. 프로토타입 메커니즘을 통해 상속을 지원하고, 어떤 개체에든지 동적으로 속성과 메소드를 추가할 수 있습니다. 클래스 기반. 개체는 클래스 계층 구조를 관통하는 상속을 통해서 클래스와 인스턴스(instance)로 나뉩니다. 클래스와 인스턴스에는 동적으로 속성과 메소드를 추가할 수 없습니다.
변수의 자료형을 선언하지 않음(동적 형 검사) 변수의 자료형을 반드시 선언해야 함(정적 형 검사)
Cannot automatically write to hard disk. Cannot automatically write to hard disk.
+

표(Table) 1.1: JavaScript 와 Java 비교
+
+Java와 JavaScript 사이의 차이점에 대해서 더 알고 싶으시면 개체 모델의 상세 내용을 보시기 바랍니다.

JavaScript와 ECMAScript 명세

+

Netscape가 JavaScript를 개발했고, Netscape 브라우저에서 가장 처음으로 사용되었습니다. 그러나 Ecma International - 정보와 통신 시스템을 표준화하기 위한 유럽 기구(공식적으로 ECMA - the European Computer Manufacturers Association으로 알려짐) - 과 Netscape가 공동으로 작업하여 기본 JavaScript에 기반하여 표준화되고 국제적인 프로그래밍 언어를 만들어냈습니다. JavaScript의 표준화된 버전은 ECMAScript라고 부르고, 표준을 지원하는 응용프로그램에서는 모두 동일하게 동작합니다. 회사들은 그들의 JavaScript 구현을 개발하기 위해서 공개된 표준 언어를 사용할 수 있습니다. ECMAScript 표준은 ECMA-262 명세에 문서화되어 있습니다.

+

ECMA-262 표준은 ISO (International Organization for Standardization, 국제 표준화기구)의 승인을 받아 ISO-16262가 되었습니다. Mozilla 웹사이트에서 ECMA-262의 PDF 문서를 얻을 수 있습니다. the Ecma International 웹사이트 에서도 명세를 찾을 수 있습니다. ECMAScript 명세는 World Wide Web Consortium (W3C)에서 표준화 한 Document Object Model(DOM)에 대해서는 설명하지 않습니다. DOM은 HTML 문서 개체들이 스크립트에 노출되는 방식을 정의합니다.

+

JavaScript 버전과 ECMAScript 판본 사이의 관계

+

Netscape는 ECMA와 밀접하게 작업하여 ECMAScript Specification(ECMA-262)를 만들었습니다. JavaScript 버전과 ECMAScript 판본(edition)들 사이의 관계가 아래 표에 설명되어 있습니다.

+ +
JavaScript 버전 ECMAScript 판본과의 관계
JavaScript 1.1 ECMA-262, 1판은 JavaScript 1.1에 기초합니다.
JavaScript 1.2 JavaScript 1.2가 발표됐을 때 ECMA-262가 아직 완성되지 않았습니다. 다음과 같은 이유때문에 JavaScript 1.2는 ECMA-262 1판과 완벽하게 호환되지 않습니다.
  • Netscape는 JavaScript 1.2에 몇 가지 기능을 추가했으나, ECMA-262에서 고려하지 못했습니다.
  • ECMA-262는 두 가지 새 기능을 추가했습니다. 유니코드를 이용한 국제화, 모든 플랫폼에서의 동일한 동작. Date 개체 같은 JavaScript 1.2의 몇 가지 기능이 플랫폼에 의존적이었습니다.

JavaScript 1.3

JavaScript 1.3은 ECMA-262 1판과 완벽하게 호환됩니다.

JavaScript 1.3은 ==와 !=연산자를 제외하고는 JavaScript 1.2의 추가적인 기능을 그대로 유지하면서 JavaScript 1.2가 ECMA-262와 어긋나던 점들을 해결했습니다. ==, != 연산자는 ECMA-262에 맞추기 위해 수정되었습니다.

JavaScript 1.4

JavaScript 1.4는 ECMA-262 1판과 완벽하게 호환됩니다.

JavaScript 1.4가 발표되었을 때 ECMAScript 명세의 세 번째 버전이 아직 완성되지 않았습니다.

JavaScript 1.5 JavaScript 1.5는 ECMA-262 3판과 완벽하게 호환됩니다.
+

표 1.2: JavaScript 버전과 ECMAScript 판본
+
+참고: ECMA-262 2판은 1판에 편집상 사소한 변경과 버그 수정을 가한 판본입니다. 현재 ECMA의 TC39 워킹그룹에서 ECMAScript 4판을 작업하고 있습니다. 4판은 JavaScript 2.0과 대응될 것입니다.

+

JavaScript 기본 레퍼런스에서 ECMAScript 호환 기능을 보여줍니다.

+

JavaScript는 항상 ECMAScript Specification에 포함되지 않은 기능들을 포함할 것입니다. JavaScript는 추가적인 기능을 제공하지만 ECMAScript와 호환됩니다.

+

JavaScript 문서 vs ECMAScript 명세서

+

ECMAScript 명세는 ECMAScript를 구현하는데 필요한 요구사항을 모아놓은 것입니다. 이것은 우리가 JavaScript의 한 기능이 다른 ECMAScript 구현에서도 지원될 것인지 결정하는데 유용합니다. ECMAScript에서 지원하는 기능만을 사용하는 JavaScript 코드를 작성할 계획이라면 ECMAScript 명세를 살펴볼 필요가 있을 것입니다.

+

ECMAScript 문서는 스크립트 프로그래머를 돕기위해 작성된 것이 아닙니다. 스크립트 작성에 대한 정보를 얻으려면 JavaScript 문서를 보십시오.

+

JavaScript와 ECMAScript 용어

+

ECMAScript 명세는 JavaScript 프로그래머에게는 친숙하지 않은 용어와 문법을 사용하여 작성되었습니다. 비록 ECMAScript의 언어 설명이 다르긴 하지만 언어는 똑같습니다. JavaScript는 ECMAScript 명세에서 설명하는 모든 기능을 지원합니다.

+

JavaScript 문서는 JavaScript 프로그래머에게 적당한 언어의 측면을 설명합니다. 예를 들면 이렇습니다.

+ +

{{ PreviousNext("Core_JavaScript_1.5_Guide:About", "Core_JavaScript_1.5_Guide:Values") }}

+

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/JavaScript_Overview", "fr": "fr/Guide_JavaScript_1.5/Aper\u00e7u_de_JavaScript", "ja": "ja/Core_JavaScript_1.5_Guide/JavaScript_Overview", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Podgl\u0105d_JavaScriptu" } ) }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/literals/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/literals/index.html new file mode 100644 index 0000000000..dfaff2c586 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/literals/index.html @@ -0,0 +1,174 @@ +--- +title: Literals +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Literals +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +

상수값(Literal)

+

JavaScript에서 값을 표현하기 위해 상수값을 사용할 수 있습니다. 그것은 변수가 아니라 고정된 값으로서 "문자 그대로(literally)" 스크립트에 값을 제공하는 것입니다. 이 절에서 다음과 같은 상수값에 대해서 설명하겠습니다.

+ +

배열 상수값

+

배열 상수값은 대괄호([])안에 배열의 원소(element)를 0개 이상 나열한 것입니다. 배열 상수값으로 배열을 만드면 배열은 지정된 원소를 가지도록 초기화되고, 지정된 원소의 개수만큼의 길이를 갖게 됩니다.

+

다음 예제는 세 개의 원소를 가지고 길이가 3인 coffees 배열을 만드는 예제입니다.

+
coffees = ["French Roast", "Colombian", "Kona"]
+

참고 배열 상수값은 개체 초기화지정자(object initializer) 중의 하나입니다. 개체 초기화지정자 사용하기를 보십시오.

+

최상위 스크립트에서 상수값을 이용하여 배열을 만들면 JavaScript는 배열 상수값을 포함하는 표현식을 평가(evaluate)할 때마다 배열을 만듭니다. 또한, 함수 안에서 사용된 상수값은 함수가 호출될 때마다 생성됩니다.

+

배열 상수값은 Array 개체입니다. Array 개체에 대한 상세한 내용은 Array 개체를 보십시오.

+

배열 상수값의 추가적인 쉼표

+

배열 상수값에 모든 원소를 지정할 필요는 없습니다. 쉼표만 찍어 두면 값이 할당되지 않은 빈 공간을 가진 배열이 만들어집니다. 다음 예제는 fish 배열을 만듭니다.

+
fish = ["Lion", , "Angel"]
+

이 배열은 값을 가진 원소 두 개와 빈 원소 하나를 갖게됩니다. (fish{{ mediawiki.external(0) }}은 "Lion", fish{{ mediawiki.external(1) }}undefined, fish{{ mediawiki.external(2) }}는 "Angel"이라는 값을 가집니다.)

+

원소 목록 끝에 남겨둔 쉼표는 무시됩니다. 다음 예제에서 배열 길이는 3입니다. myList{{ mediawiki.external(3) }}은 만들어지지 않습니다. 그외에 목록에 있는 다른 쉼표들은 각각 새로운 원소를 나타냅니다.

+
myList = ['home', , 'school', ];
+

다음 예제에서 배열 길이는 4이고, myList{{ mediawiki.external(0) }}myList{{ mediawiki.external(2) }}는 비게 됩니다.

+
myList = [ , 'home', , 'school'];
+

다음 예제에서 배열 길이는 4이고 myList{{ mediawiki.external(1) }}myList{{ mediawiki.external(3) }}이 비게 됩니다. 오직 마지막 쉼표만 무시됩니다.

+
myList = ['home', , 'school', , ];
+

불리언 상수값

+

불리언 형은 두 가지 상수값을 가질 수 있는데, 그것은 truefalse입니다.

+

true, false라는 기본(primitive) 불리언 값과 true, false 값의 불리언 개체를 혼동하지 마십시오. 불리언 개체는 기본 불리언 데이터 형을 감싸는 역할을 할 뿐입니다. 더 많은 정보는 불리언 개체를 참조하십시오.

+

정수

+

10진수, 16진수, 8진수 정수를 쓸 수 있습니다. 10진수 정수 상수값은 0(영)으로 시작하지 않는 숫자의 나열입니다. 0(영)으로 시작하는 정수 상수값은 8진수입니다. 0x(또는 0X)로 시작하면 16진수입니다. 16진수는 0부터 9까지의 숫자와 a부터 f나 A부터 F까지의 문자를 포함할 수 있습니다. 8진수에는 0부터 7까지만 쓸 수 있습니다.

+

8진수 정수 상수값은 사용하지 말기를 추천하고 있으며, ECMA-262 표준 3판에서는 아예 제거되었습니다. 하위 호환성을 위해 JavaScript 1.5에서는 여전히 8진수 정수 상수값을 지원하고 있습니다.

+

몇 가지 정수 상수값을 예를 보여드리겠습니다.

+
0, 117, -345 (10진수)
+015, 0001, -077 (8진수)
+0x1123, 0x00111, -0xF1A7 (16진수 또는 "hex")
+
+

소수 상수값

+

소수 상수값은 이런 부분으로 이뤄집니다.

+ +

지수 부분은 "e"나 "E" 뒤에 숫자가 붙은 형태입니다. 숫자 앞에는 부호("+"나 "-")를 붙일 수도 있습니다. 소수 상수값은 적어도 하나의 숫자에 소수점 또는 지수 부분을 가져야 합니다.

+

소수 상수값의 몇 가지 예제를 보여드리겠습니다. 3.1415, -3.1E12, .1e12, 2E-12

+

개체 상수값

+

개체 상수값은 중괄호({}) 안에 특성(property) 이름과 그에 해당하는 값의 쌍을 나열한 것입니다. 문장(statement)의 시작 부분에 개체 상수값을 사용해서는 안됩니다. { 가 블럭의 시작을 나타내기 때문에, 에러가 나거나 의도하지 않은 동작을 보일 것입니다.

+

다음은 개체 상수값의 예입니다. car 개체의 첫 번째 원소는 myCar라는 특성을 정의하고 있습니다. 두 번째 원소는 getCar 특성을 정의하는데, (CarTypes("Honda"));라는 함수를 호출하고 있습니다. 세 번째 원소는 special 특성을 정의하는데에 Sales라는 변수를 사용합니다.

+
var Sales = "Toyota";
+
+function CarTypes(name) {
+   if(name == "Honda")
+      return name;
+   else
+      return "Sorry, we don't sell " + name + ".";
+}
+
+car = {myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales}
+
+document.write(car.myCar); // Saturn
+document.write(car.getCar); // Honda
+document.write(car.special); // Toyota
+

개체 특성 이름에 정수 상수값이나 문자열 상수값을 사용할 수 있고, 개체 안에 다른 개체를 포함시킬 수도 있습니다. 다음 예제를 보십시오.

+
car = {manyCars: {a: "Saab", b: "Jeep"}, 7: "Mazda"}
+
+document.write(car.manyCars.b); // Jeep
+document.write(car[7]); // Mazda
+
+

다음 사항을 참고하십시오.

+
foo = {a: "alpha", 2: "two"}
+document.write (foo.a)    // alpha
+document.write (foo[2])   // two
+//document.write (foo.2)  // Error: missing ) after argument list
+//document.write (foo[a]) // Error: a is not defined
+document.write (foo["a"]) // alpha
+document.write (foo["2"]) // two
+
+

문자열 상수값

+

문자열 상수값은 큰따옴표(")나 작은따옴표(')로 둘러싸인 0개 이상의 문자들 입니다. 문자열은 같은 종류의 따옴표로 묶어야 합니다. 즉, 작은따옴표 둘로 묶거나, 큰따옴표 둘로 묶어야 한다는 말입니다. 문자열 상수값의 예를 보여드리겠습니다.

+ +

우 리는 문자열 상수값에 String 개체의 모든 메소드를 호출할 수 있습니다. JavaScript는 자동으로 문자열 상수값을 임시 String 개체로 만들어서 메소드를 호출한 후, 임시 String 개체를 제거합니다. 문자열 상수값에 String.length 특성을 사용할 수도 있습니다. 이렇게 말입니다.

+ +

우리가 특별하게 String 개체를 필요로 하는 경우가 아니라면 문자열 상수값을 사용해야만 합니다. String 개체에 대한 자세한 내용은 String 개체를 보십시오.

+
문자열에서 특수문자 사용하기
+

다음 예제에서 볼 수 있듯이 일반적인 문자뿐만 아니라 특수문자도 문자열에 쓸 수 있습니다.

+
"one line \n another line"
+

JavaScript 문자열에 사용할 수 있는 특수문자를 표로 나타낸 것입니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
문자의미
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tTab
\vVertical tab
\'Apostrophe or single quote
\"Double quote
\\Backslash character (\).
\XXX세 자리 까지의 8진수 "XXX"로 지정하는 Latin-1 인코딩의 문자. 0부터 377 사이. 예를 들어, \251은 저작권 기호의 8진수 표현입니다.
\xXX두 자리 까지의 16진수 "XX"로 지정하는 Latin-1 인코딩의 문자. 00부터 FF 사이. 예를 들어, \xA9는 저작권 기호의 16진수 표현입니다.
\uXXXX네 자리의 16진수 "XXXX"로 지정하는 유니코드 문자. 예를 들어, \u00A9는 저작권 기호의 유니코드 표현입니다. 유니코드 이스케이프 시퀀스를 보십시오.
+

표 2.1: JavaScript 특수문자

+
문자 이스케이프
+

표 2.1에 없는 문자에 대해서는 역슬래시가 무시됩니다. 그러나 이러한 기능은 사용하지 않기를 권장하므로 사용을 피해야만 합니다.

+

역슬래시를 앞에 붙이면 문자열 안에 따옴표를 넣을 수 있습니다. 이것은 따옴표 "이스케이프(escaping)"라고 알려져 있습니다.

+
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."
+document.write(quote)
+
+

이 코드의 결과는 다음과 같습니다.

+
He read "The Cremation of Sam McGee" by R.W. Service.
+
+

문자열 안에 역슬래시 문자를 넣고 싶으면 역슬래시 문자를 이스케이프시켜야 합니다. 예를 들어, c:\temp 라는 경로를 문자열에 할당하고 싶으면 다음과 같이 하면 됩니다.

+
var home = "c:\\temp"
+
+

{{ PreviousNext("Core_JavaScript_1.5_Guide:Constants", "Core_JavaScript_1.5_Guide:Unicode") }}

+

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Literals", "fr": "fr/Guide_JavaScript_1.5/Constantes_litt\u00e9rales", "ja": "ja/Core_JavaScript_1.5_Guide/Literals", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Litera\u0142y" } ) }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/objects_and_properties/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/objects_and_properties/index.html new file mode 100644 index 0000000000..abe9ff83f4 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/objects_and_properties/index.html @@ -0,0 +1,39 @@ +--- +title: Objects and Properties +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Objects_and_Properties +--- +

객체와 속성

+

자바스크립트 객체는 객체를 구성하는 속성을 가지고 있습니다. 속성에는 간단한 방법으로 접근할 수 있습니다.: +

+
객체이름.속성이름
+
+

객체 이름과 속성 이름 두 가지 모두에 대해 알기쉬운 예가 있습니다. 속성은 값을 지정하여 정의합니다. 예를 들어 myCar라는 객체가 있다면(객체가 이미 존재한다고 가정합니다.), make, model, year라는 속성에 다음과 같이 값을 지정할 수 있습니다. +

+
myCar.make = "Ford";
+myCar.model = "Mustang";
+myCar.year = 1969;
+
+

배열은 한 가지 변수 이름으로 결합되어 있는 연속된 값의 집합입니다. 자바스크립트에서 속성과 배열은 밀접한 관련이 있습니다; 말하자면 그 두 가지는 같은 데이터 구조에 다른 인터페이스라는 뜻입니다. 예를 들면 myCar 객체에 다음과 같이 접근할 수도 있습니다: +

+
myCar["make"] = "Ford";
+myCar["model"] = "Mustang";
+myCar["year"] = 1967;
+
+

이러한 배열의 종류는 연관 배열이라고 부릅니다. 왜냐하면 각각의 인덱스 요소가 문자열 값과 연관되어 있기 때문입니다. 이러한 방식에 대한 설명은 다음의 함수에 객체와 객체의 이름을 입력했을 때 객체의 속성을 표시해주는 다음과 같은 함수에서 알아볼 수 있습니다: +

+
function show_props(obj, obj_name) {
+   var result = "";
+   for (var i in obj)
+      result += obj_name + "." + i + " = " + obj[i] + "\n";
+   return result;
+}
+
+

결과적으로 call show_props(myCar, "myCar")라는 함수 호출은 다음과 같은 값을 반환합니다: +

+
myCar.make = Ford
+myCar.model = Mustang
+myCar.year = 1967
+
+

{{ PreviousNext("Core_JavaScript_1.5_Guide:Predefined_Functions:escape_and_unescape_Functions", "Core_JavaScript_1.5_Guide:Creating_New_Objects") }} +

{{ languages( { "fr": "fr/Guide_JavaScript_1.5/Objets_et_propri\u00e9t\u00e9s", "ja": "ja/Core_JavaScript_1.5_Guide/Objects_and_Properties", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Obiekty_i_w\u0142a\u015bciwo\u015bci" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/arithmetic_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/arithmetic_operators/index.html new file mode 100644 index 0000000000..ce55c0e3f2 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/arithmetic_operators/index.html @@ -0,0 +1,44 @@ +--- +title: Arithmetic Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/Arithmetic_Operators +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +

산술 연산자

+

산술 연산자는 수(상수값이든지 변수든지)를 받아서 하나의 수를 반환합니다. 표준 산술 연산자는 더하기(+), 빼기(-), 곱하기(*), 나누기(/)입니다. 이 연산자들은 대부분의 다른 프로그래밍 언어에서 처럼 동작합니다. 예외적으로 / 연산자는 JavaScript에서 소수를 반환합니다. C나 Java 같은 다른 언어에서는 / 연산자가 소수 부분은 잘라버립니다. 예를 들면 이렇습니다. +

+
1/2 //returns 0.5 in JavaScript
+1/2 //returns 0 in Java
+
+

JavaScript는 다음 표에 나오는 산술 연산자를 제공합니다. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
연산자설명예제
%
(나머지)
2항(binary) 연산자. 두 피연산자의 나눗셈에서 나온 나머지를 반환합니다.12 % 5 returns 2.
++
(증가)
단항(unary) 연산자. 피연산자에 1을 더함. 전위 연산자(++x)를 사용하면 피연산자에 1을 더한 후 그 값을 반환합니다. 후위 연산자(x++)를 사용하면 피연산자에 1을 더하기 전에 피연산자의 값을 반환합니다.x가 3일 때, ++xx를 4로 만들고 4를 반환합니다. 반면 x++x를 4로 만들고 3을 반환합니다.
--
(감소)
단항 연산자. 피연산자에서 1을 뺌. 반환값은 증가 연산자와 동일한 방식으로 결정됩니다.x가 3일 때, --xx를 2로 만들고 2를 반환합니다. 반면 x--x를 2로 만들고 3을 반환합니다.
-
(단항 부정)
단항 연산자. 피연산자의 부호를 바꾼 값을 반환합니다.x가 3이면 -x는 -3을 반환합니다.
+

표 3.4: 산술 연산자 +

{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:Comparison_Operators", "Core_JavaScript_1.5_Guide:Operators:Bitwise_Operators") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators/Arithmetic_Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs/Op\u00e9rateurs_arithm\u00e9tiques", "ja": "ja/Core_JavaScript_1.5_Guide/Operators/Arithmetic_Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory/Operatory_arytmetyczne" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/assignment_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/assignment_operators/index.html new file mode 100644 index 0000000000..dbc284f12f --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/assignment_operators/index.html @@ -0,0 +1,62 @@ +--- +title: Assignment Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/Assignment_Operators +--- +

할당 연산자

+

할당 연산자는 왼쪽 피연산자에 오른쪽 피연산자의 값을 할당합니다. 가장 기본적인 할당 연산자에는 등호(=)가 있는데, 왼쪽 피연산자의 값을 오른쪽 연산자에 할당합니다. 즉, x = y 라고 하면 y의 값이 x에 할당되는 것입니다.

+

다른 할당 연산자는 다음 표에서 보듯이 표준연산을 약식으로 쓰는 것입니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
약식 연산자의미
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
x <<= yx = x << y
x >>= yx = x >> y
x >>>= yx = x >>> y
x &= yx = x & y
x ^= yx = x ^ y
x |= yx = x | y
+

표: 할당 연산자

+

{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators", "Core_JavaScript_1.5_Guide:Operators:Comparison_Operators") }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/bitwise_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/bitwise_operators/index.html new file mode 100644 index 0000000000..860e6787e9 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/bitwise_operators/index.html @@ -0,0 +1,101 @@ +--- +title: Bitwise Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/Bitwise_Operators +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +


+

+

비트 연산자

+

비트 연산자는 피연산자를 10진수나 16진수, 8진수로 다루지 않고 32개의 비트 집합으로 다룹니다. 예를 들어, 10진수 9는 2진수로 1001입니다. 비트 연산자는 2진수 표현으로 연산을 하지만 반환값은 JavaScript 표준 수 값으로 반환합니다. +

JavaScript의 비트 연산자를 다음 표에 요약했습니다. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
연산자사용법설명
비트 ANDa & b두 피연산자의 대응되는 비트가 모두 1이면 1을 반환.
비트 ORa | b두 피연산자의 대응되는 비트에서 둘 중 하나가 1이거나 모두 1인 경우 1을 반환.
비트 XORa ^ b두 피연산자의 대응되는 비트에서 둘 중 하나가 1이고, 둘 다 1이 아닐 경우 1을 반환.
비트 NOT~ a피연산자의 비트를 뒤집음.
왼쪽으로 이동a << ba의 2진수 표현을 b 비트만큼 왼쪽으로 이동함. 오른쪽은 0으로 채움.
부호 비트로 채우는 오른쪽 이동a >> ba의 2진수 표현을 b 비트만큼 오른쪽으로 이동함. 오른쪽 남는 비트는 버림.
0으로 채우는 오른쪽 이동a >>> ba의 2진수 표현을 b 비트만큼 오른쪽으로 이동함. 오른쪽 남는 비트는 버리고, 왼쪽은 0으로 채움.
+

표 3.5: 비트 연산자 +

+

비트 논리 연산자

+

개념적으로 비트 논리 연산자는 다음과 같이 동작합니다. +

+ +

예를 들어, 9를 2진수로 쓰면 1001이고 15를 2진수로 표현하면 1111입니다. 두 값에 비트 연산을 적용하면 결과는 다음과 같습니다. +

+ +

비트 이동 연산자

+

비트 이동 연산자는 피연산자 두 개를 받습니다. 첫 번째는 이동하려는 수이고, 두 번째는 첫 번째 피연산자를 몇 비트나 이동시킬지 나타내는 비트 수입니다. 이동 방향은 사용된 연산자에 따라 다릅니다. +

이동 연산자는 피연산자를 32비트 정수로 변환하여 연산하고, 왼쪽 연산자와 같은 자료형으로 반환합니다. +

이동 연산자는 다음 표에 있습니다. +

+ + + + + + + + + + + + + + + + + + + + +
연산자설명예제
<<
+(왼쪽 이동)
이 연산자는 첫 번째 피연산자의 비트를 지정된 수만큼 왼쪽으로 옮깁니다. 왼쪽으로 넘친 비트는 버립니다. 오른쪽 빈 자리는 0으로 채웁니다. 9<<2는 36을 반환합니다. 1001을 왼쪽으로 2비트 이동하면 100100이 되고 이것은 36이기 때문입니다.
>>
+(부호 비트로 채우는 오른쪽 이동)
이 연산자는 첫 번째 피연산자의 비트를 지정된 수 만큼 오른쪽으로 옮깁니다. 오른쪽으로 넘친 비트는 버립니다. 왼쪽 빈 자리는 원래 가장 왼쪽에 있던 비트 값으로 채웁니다.9>>2는 2를 반환합니다. 1001을 2비트 오른쪽으로 이동하면 10이 되는데 이것은 2이기 때문입니다. 비슷하게 -9>>2는 -3을 반환하는데, 부호가 유지되기 때문입니다.
>>>
+(0으로 채우는 오른쪽 이동)
이 연산자는 첫 번째 피연산자의 비트를 지정된 수 만큼 오른쪽으로 옮깁니다. 오른쪽으로 넘친 비트는 버립니다. 왼쪽 빈 자리는 0으로 채웁니다.19>>>2는 4를 반환합니다. 10011을 2비트 오른쪽으로 이동하면 100이 되기 때문입니다. 음수가 아닌 수에 대해서는 0을 채우는 오른쪽 이동이나 부호 비트로 채우는 오른쪽 이동이 똑같은 결과를 반환합니다.
+

표 3.6: 비트 이동 연산자 +

{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:Arithmetic_Operators", "Core_JavaScript_1.5_Guide:Operators:Logical_Operators") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators/Bitwise_Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs/Op\u00e9rateurs_bit-\u00e0-bit", "ja": "ja/Core_JavaScript_1.5_Guide/Operators/Bitwise_Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory/Operatory_bitowe" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/index.html new file mode 100644 index 0000000000..53b8e67492 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/index.html @@ -0,0 +1,108 @@ +--- +title: Operators +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators +--- +

연산자

+

JavaScript에는 다음과 같은 연산자 타입이 있습니다. 이 섹션은 연산자에 대해 기술하고 연산자 우선순위에 대한 정보를 제공합니다. +

+ +

JavaScript는 이항연산자와 단항연산자를 모두 사용할 수 있습니다. 이항연산자는 두개의 피연산자(operand)를 가지며, 하나의 피연산자는 연산자 앞에 나머지 하나는 뒤에 위치합니다: +

+
operand1 operator operand2
+
+

예를 들자면, 3+4 혹은 x*y와 같은 것입니다. +

단항연산자는 연산자 앞 혹은 뒤쪽에 하나의 피연산자만 있으면 됩니다: +

+
operator operand
+
+

혹은 +

+
operand operator
+
+

예를 들자면, x++ 혹은 ++x와 같은 것입니다. +

덧붙여, JavaScript는 한개의 삼항연산자, 조건 연산자를 가지고 있습니다. 삼항 연산자는 세개의 피연산자가 필요합니다. +

+

연산자 우선순위

+

관련된 논의에 따라서, 아래의 표는 우선순위 순으로 내림차순 정렬되었습니다. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
연산자 타입사용하는 연산자
멤버 .  []
호출 / 인스턴스 생성 ()  new
부정/증감 !  ~  -  +  ++  --  typeof  void  delete
곱하기/나누기 *  /  %
더하기/빼기 +  -
비트 이동 <<  >>  >>>
관계 <  <=  >  >=  in  instanceof
같음 ==  !=  ===  !==
비트연산-and &
비트연산-xor ^
비트연산-or |
논리연산-and &&
논리연산-or ||
조건 ?:
할당 =  +=  -=  *=  /=  %=  <<=  >>=  >>>=  &=  ^=  |=
컴마,
+

표: 연산자 우선순위 +

이 표의 보다 자세한 버전은 레퍼런스 섹션에 있는 각 연산자별 상세한 추가 설명 링크를 참고하세요. +

{{ PreviousNext("Core_JavaScript_1.5_Guide:Expressions", "Core_JavaScript_1.5_Guide:Operators:Assignment_Operators") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs", "ja": "ja/Core_JavaScript_1.5_Guide/Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/logical_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/logical_operators/index.html new file mode 100644 index 0000000000..6b30493f83 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/logical_operators/index.html @@ -0,0 +1,68 @@ +--- +title: Logical Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/Logical_Operators +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +

논리 연산자

+

논리 연산자는 주로 불리언(논리적) 값과 함께 사용됩니다. 그때 논리 연산자는 불리언 값을 반환합니다. 그러나 &&와 || 연산자는 실제로는 피연산자 중에 하나의 값을 반환하기 때문에, 이 연산자가 불리언 값이 아닌 값과 함께 사용되면 불리언 값이 아닌 값을 반환할 것입니다. 다음 표에 논리 연산자에 대해서 설명했습니다. +

+ + + + + + + + + + + + + + + + + + + + + +
연산자사용법설명
&&expr1 && expr2(논리적 AND) expr1이 false로 변환될 수 있으면 expr1을 반환하고, 그렇지 않으면 expr2를 반환합니다. 그러므로 불리언 값과 같이 사용하면 피연산자 둘 모두가 true일 때 &&는 true를 반환하고 그렇지 않을 때는 false를 반환합니다.
||expr1 || expr2(논리적 OR) expr1이 true로 변환될 수 있으면 expr1을 반환하고 그렇지 않으면 expr2를 반환합니다. 그러므로 불리언 값과 같이 사용하면 ||는 피연산자 중에서 하나만 true이면 true를 반환합니다. 둘 다 false이면 false를 반환합니다.
!!expr(논리적 NOT) 피연산자가 true로 변환될 수 있으면 false를 반환합니다. 그렇지 않으면 true를 반환합니다.
+

표 3.7: 논리 연산자 +

false로 변환될 수 있는 표현식은 null, 0, 빈 문자열(""), undefined로 평가될 수 있는 표현식들입니다. +

다음 코드는 && 연산자를 사용하는 예를 보여줍니다. +

+
a1=true && true       // t && t returns true
+a2=true && false      // t && f returns false
+a3=false && true      // f && t returns false
+a4=false && (3 == 4)  // f && f returns false
+a5="Cat" && "Dog"     // t && t returns Dog
+a6=false && "Cat"     // f && t returns false
+a7="Cat" && false     // t && f returns false
+
+

다음 코드는 || 연산자를 사용하는 예를 보여줍니다. +

+
o1=true || true       // t || t returns true
+o2=false || true      // f || t returns true
+o3=true || false      // t || f returns true
+o4=false || (3 == 4)  // f || f returns false
+o5="Cat" || "Dog"     // t || t returns Cat
+o6=false || "Cat"     // f || t returns Cat
+o7="Cat" || false     // t || f returns Cat
+
+

다음 코드는 ! 연산자를 사용하는 예를 보여줍니다. +

+
n1=!true              // !t returns false
+n2=!false             // !f returns true
+n3=!"Cat"             // !t returns false
+
+

단축 평가

+

논리 표현식이 왼쪽부터 오른쪽으로 평가되기 때문에 다음 규칙을 이용해서 "단축(short-circuit)" 평가를 할 수 있습니다. +

+ +

이 규칙을 따라 평가를 수행한다고 해서 피연산자를 모두 평가할 때와 결과가 달라지지 않습니다. 아무 표현식 부분은 평가되지 않기 때문에 아무런 부수 효과(side effect)도 일어나지 않는다는 것에 주의하십시오. +

{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:Bitwise_Operators", "Core_JavaScript_1.5_Guide:Operators:String_Operators") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators/Logical_Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs/Op\u00e9rateurs_logiques", "ja": "ja/Core_JavaScript_1.5_Guide/Operators/Logical_Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory/Operatory_logiczne" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/special_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/special_operators/index.html new file mode 100644 index 0000000000..aa66b296fc --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/special_operators/index.html @@ -0,0 +1,228 @@ +--- +title: Special Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/Special_Operators +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +

특수 연산자

+

JavaScript 다음과 같은 특별한 연산자를 제공합니다. +

+ +

조건 연산자

+

조건 연산자는 JavaScript에서 유일하게 세 개의 피연산자를 사용하는 연산자입니다. 연산자는 조건에 따라 둘 중에 하나의 값을 가질 수 있습니다. 문법은 이렇습니다. +

+
condition ? val1 : val2
+
+

condition이 true이면 연산자는 val1의 값을 갖습니다. 그렇지 않으면 val2의 값을 갖습니다. 다른 표준 연산자를 사용할 수 있는 곳이면 어디든지 조건 연산자를 사용할 수 있습니다. +

+
status = (age >= 18) ? "adult" : "minor"
+
+

이 문장은 age가 18이거나 더 큰 경우에 status 변수에 "adult"라는 값을 할당합니다. 그렇지 않으면 "minor"라는 값을 할당합니다. +

+

쉼표 연산자

+

쉼표 연산자(,)는 단순히 피연산자 둘을 모두 평가하고 두 번째 피연산자의 값을 반환하는 연산자입니다. 이 연산자는 주로 for 반복문에서 변수 여러 개가 매번 업데이트 되게 하는데 쓰입니다. +

예를 들어 a가 각각 10줄의 원소를 가지는 2차원 배열일 때, 다음 코드에서는 변수 두 개를 한 번에 바꾸기 위해서 쉼표 연산자를 사용하고 있습니다. 이 코드는 배열의 대각선 원소를 출력합니다. +

+
for (var i=0, j=9; i <= 9; i++, j--)
+   document.writeln("a["+i+"]["+j+"]= " + a[i][j])
+
+

delete

+

delete는 개체(object), 개체의 속성(property), 배열의 특정 인덱스에 있는 원소(element)를 지우는 연산자입니다. 문법은 이렇습니다. +

+
delete objectName
+delete objectName.property
+delete objectName[index]
+delete property // with 문장 안에서만 유효합니다
+
+

objectName은 개체 이름이고, property는 개체에 존재하는 속성이고, index는 배열의 원소 위치를 나타내는 정수입니다. +

네 번째 형식은 개체의 속성을 지우는 코드인데, with 문장 안에서만 사용할 수 있습니다. +

암시적으로 선언된 변수를 지울 때는 delete 연산자를 사용할 수 있지만 var 문장을 이용해서 선언된 변수는 지울 수 없습니다. +

delete 연산자 실행이 성공하면, 속성이나 원소가 undefined로 설정됩니다. delete 연산자는 실행이 가능하면 true를 반환하고, 불가능하면 false를 반환합니다. +

+
x=42
+var y= 43
+myobj=new Number()
+myobj.h=4      // h라는 속성을 만듭니다
+delete x       // returns true (암시적으로 선언된 변수는 지울 수 있습니다)
+delete y       // returns false (var로 선언한 변수는 지울 수 없습니다)
+delete Math.PI // returns false (미리 정의된 속성은 지울 수 없습니다)
+delete myobj.h // returns true (사용자 정의 속성은 지울 수 있습니다)
+delete myobj   // returns true (암시적으로 선언되었으므로 지울 수 있습니다)
+
+

배열의 원소를 지우기
+배열의 원소를 지울 때, 배열의 길이에는 변화가 없습니다. 예를 들어, a{{ mediawiki.external(3) }}, a{{ mediawiki.external(4) }}를 지우더라도 a{{ mediawiki.external(4) }}와 a{{ mediawiki.external(3) }}은 여전히 정의되지 않습니다. +

delete 연산자가 배열 원소를 제거할 때 원소는 더이상 배열에 존재하지 않습니다. 아래 예제에서 trees{{ mediawiki.external(3) }}은 delete로 제거되었습니다. +

+
trees=new Array("redwood","bay","cedar","oak","maple")
+delete trees[3]
+if (3 in trees) {
+   // 이 블록은 실행되지 않습니다.
+}
+
+

배열 원소가 존재하긴 하지만 정의되지 않은 값을 가지도록 하고 싶다면 delete 연산자 대신 undefined 키워드를 사용하십시오. 다음 예제에서 trees{{ mediawiki.external(3) }}undefined 값을 할당했지만 배열 요소는 여전히 존재합니다. +

+
trees=new Array("redwood","bay","cedar","oak","maple")
+trees[3]=undefined
+if (3 in trees) {
+   // 이 블록은 실행됩니다.
+}
+
+

in

+

in 연산자는 지정된 속성이 지정된 개체에 있으면 true를 반환합니다. 문법은 이렇습니다. +

+
propNameOrNumber in objectName
+
+

propNameOrNumber은 속성 이름을 나타내는 문자열이나 배열 인덱스를 나타내는 수이고, objectName은 개체 이름입니다. +

다음 예제는 in 연산자의 몇 가지 사용법을 보여줍니다. +

+
// 배열
+trees=new Array("redwood","bay","cedar","oak","maple")
+0 in trees        // returns true
+3 in trees        // returns true
+6 in trees        // returns false
+"bay" in trees    // returns false (원하는 인덱스를 지정해야 하는데,
+                  // 그 인덱스에 있는 값을 지정하면 안됩니다.)
+"length" in trees // returns true (length는 배열의 속성입니다.)
+
+// 미리 정의된 개체
+"PI" in Math          // returns true
+myString=new String("coral")
+"length" in myString  // returns true
+
+// 사용자 개체
+mycar = {make:"Honda",model:"Accord",year:1998}
+"make" in mycar  // returns true
+"model" in mycar // returns true
+
+

instanceof

+

instanceof는 지정된 개체가 지정된 개체 형식이면 true를 반환합니다. 문법은 이렇습니다. +

+
objectName instanceof objectType
+
+

objectNameobjectType과 비교할 개체의 이름이고, objectType은 개체 형식으로 DateArray 같은 것입니다. +

실행중에 개체의 형식을 알고 싶으면 instanceof를 사용하면 됩니다. 예를 들어 예외를 처리할 때, 발생한 예외의 형식에 따라 서로 다른 예외 처리 코드를 실행할 수 있습니다. +

다음 코드에서 theDayDate 개체인지 결정하기 위해서 instanceof를 사용합니다. theDayDate 개체이기 때문에 if문 안에 있는 문장이 실행됩니다. +

+
theDay=new Date(1995, 12, 17)
+if (theDay instanceof Date) {
+   // 실행할 문장
+}
+
+

new

+

사용자 정의 개체 형식이나 Array, Boolean, Date, Function, Image, Number, Object, Option, RegExp, String 같이 미리 정의된 개체 형식의 인스턴스를 만들 때 new 연산자를 사용합니다. 서버에서는 DbPool, Lock, File, SendMail 등을 만들 때 사용할 수 있습니다. new는 다음과 같이 사용합니다. +

+
objectName = new objectType ( param1 [,param2] ...[,paramN] )
+
+

개체 초기화 지정자 사용하기에 설명한 것처럼 개체 초기화 지정자를 이용해서 개체를 만들 수도 있습니다. +

더 많은 정보를 얻으려면 JavaScript 레퍼런스의 new 연산자 페이지를 보시기 바랍니다. +

+

this

+

현재 개체를 참조할 때 this 키워드를 사용합니다. 일반적으로 this는 메소드를 호출하는 개체를 참조합니다. 다음과 같이 사용하면 됩니다. +

+
this[.propertyName]
+
+

예제 1.
+개체의 value 속성이 높거나 낮은 값을 가지는지 검증하는 validate라는 함수가 있다고 가정합시다. +

+
function validate(obj, lowval, hival) {
+   if ((obj.value < lowval) || (obj.value > hival))
+      alert("Invalid Value!")
+}
+
+

이제 우리는 폼의 각 요소의 onChange 이벤트 핸들러에서 validate 함수를 호출하면서, this를 이용하여 스스로를 함수에 전달할 수 있습니다. +

+
<B>Enter a number between 18 and 99:</B>
+<INPUT TYPE = "text" NAME = "age" SIZE = 3
+   onChange="validate(this, 18, 99)">
+
+

예제 2.
+form 속성과 결합되면, this는 현재 개체가 포함된 폼을 참조할 수 있습니다. 다음 예제에서 myForm 폼은 Text 개체와 버튼을 포함하고 있습니다. 사용자가 버튼을 클릭하면 Text 개체의 값이 폼 이름으로 설정됩니다. 버튼의 onClick 이벤트 핸들러는 부모 폼인 myForm을 참조하기 위해서 this.form을 사용하고 있습니다. +

+
<FORM NAME="myForm">
+Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
+<P>
+<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
+   onClick="this.form.text1.value=this.form.name">
+</FORM>
+
+

typeof

+

typeof 연산자는 둘 중 한 가지 방법으로 사용할 수 있습니다. +

+
1. typeof operand
+2. typeof (operand)
+
+

typeof 연산자는 피연산자의 평가되지 않은 형식을 나타내는 문자열을 반환합니다. 피연산자는 string, variable, keyword, object 등의 타입을 반환하게 됩니다. 괄호는 선택적입니다. +

우리가 이런 변수를 정의했다고 해봅시다. +

+
var myFun = new Function("5+2")
+var shape="round"
+var size=1
+var today=new Date()
+
+

typeof는 이 변수들에 대해서 다음과 같은 결과를 반환할 것입니다. +

+
typeof myFun is function
+typeof shape is string
+typeof size is number
+typeof today is object
+typeof dontExist is undefined
+
+

truenull 키워드에 대해서 typeof 연산자는 다음과 같은 결과를 반환합니다. +

+
typeof true is boolean
+typeof null is object
+
+

수와 문자열에 대해서 typeof 연산자는 다음과 같은 결과를 반환합니다. +

+
typeof 62 is number
+typeof 'Hello world' is string
+
+

속성 값에 대해서 typeof 연산자는 속성이 포함하고 있는 값의 형식을 반환합니다. +

+
typeof document.lastModified is string
+typeof window.length is number
+typeof Math.LN2 is number
+
+

메소드와 함수에 사용하면 typeof 연산자는 다음과 같은 결과를 반환합니다. +

+
typeof blur is function
+typeof eval is function
+typeof parseInt is function
+typeof shape.split is function
+
+

미리 정의된 개체들에 대해서 typeof 연산자는 다음과 같은 결과를 반환합니다. +

+
typeof Date is function
+typeof Function is function
+typeof Math is function
+typeof Option is function
+typeof String is function
+
+

void

+

void 연산자는 다음과 같이 사용할 수 있습니다. +

+
1. void (expression)
+2. void expression
+
+

void 연산자는 표현식이 값을 반환하지 않으면서 평가되어야 한다고 지정하는데 사용됩니다. expression은 평가하려는 JavaScript 표현식입니다. 표현식을 감싸는 괄호는 선택적이지만 사용하는 쪽이 더 좋은 스타일입니다. +

표현식을 하이퍼텍스트 링크로 지정하기 위해서 void 연산자를 사용할 수 있습니다. 표현식이 평가되기는 하지만 현재 문서 대신 로드되지는 않습니다. +

아래 코드는 사용자가 클릭할 때 아무 동작도 하지 않는 하이퍼텍스트 링크를 만듭니다. 사용자가 링크를 클릭하면 void(0)는 정의되지 않은 것(undefined)으로 평가되고 JavaScript에서 아무런 효과가 없습니다. +

+
<A HREF="javascript:void(0)">Click here to do nothing</A>
+
+

다음 코드는 클릭하면 폼을 제출하는 하이퍼텍스트 링크를 만듭니다. +

+
<A HREF="javascript:void(document.form.submit())">
+Click here to submit</A>
+
+

{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:String_Operators", "Core_JavaScript_1.5_Guide:Creating_a_Regular_Expression") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators/Special_Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs/Op\u00e9rateurs_sp\u00e9ciaux", "ja": "ja/Core_JavaScript_1.5_Guide/Operators/Special_Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory/Operatory_specjalne" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/string_operators/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/string_operators/index.html new file mode 100644 index 0000000000..41c6c07286 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/operators/string_operators/index.html @@ -0,0 +1,11 @@ +--- +title: String Operators +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Operators/String_Operators +translation_of: Web/JavaScript/Guide/Expressions_and_Operators +--- +

문자열 연산자

+

문자열 값에 사용할 수 있는 비교 연산자 외에도 연결 연산자(+)가 있는데, 이 연산자는 두 문자열 값을 연결한 새로운 문자열 값을 반환합니다. 예를 들어, "my " + "string""my string"라는 문자열을 반환합니다. +

축약된 할당 연산자인 += 또한 문자열 연결에 사용할 수 있습니다. 예를 들어 mystring 변수가 "alpha"라는 값을 가지고 있을 때, mystring += "bet"은 "alphabet"으로 평가되고, 그 값이 mystring에 할당됩니다. +

{{ PreviousNext("Core_JavaScript_1.5_Guide:Operators:Logical_Operators", "Core_JavaScript_1.5_Guide:Operators:Special_Operators") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Operators/String_Operators", "fr": "fr/Guide_JavaScript_1.5/Op\u00e9rateurs/Op\u00e9rateurs_li\u00e9s_aux_cha\u00eenes", "ja": "ja/Core_JavaScript_1.5_Guide/Operators/String_Operators", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Operatory/Operacje_na_\u0142a\u0144cuchach" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/array_object/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/array_object/index.html new file mode 100644 index 0000000000..1f6ef48f3a --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/array_object/index.html @@ -0,0 +1,133 @@ +--- +title: Array Object +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Array_Object +--- +

Array 개체

+

JavaScript에는 명시적인 배열 자료형이 없습니다. 하지만 배열을 다루기 위해서 Array 개체와 그 개체의 메소드를 이용할 수 있습니다. Array 개체에는 다양한 방법으로 배열을 다루기 위한 메소드들이 있는데, 배열을 합치거나, 순서를 뒤집거나, 정렬하는 등의 작업을 할 수 있습니다. 배열 길이를 알 수 있는 속성과 정규 표현식에 사용할 수 있는 속성들이 있습니다. + + 배열 + 은 이름이나 색인으로 참조할 수 있는 값들을 모아놓은, 값의 순서가 유지되는 집합입니다. 예를 들어, 우리는 고용 번호로 색인된 고용인의 이름을 담고 있는 emp라는 배열을 만들 수 있습니다. 이 때 emp{{ mediawiki.external(1) }}는 1번 고용인, emp{{ mediawiki.external(2) }} 2번 고용인이 되는 것입니다.

+

 

+

배열 만들기

+

Array 개체는 이렇게 만들 수 있습니다.

+
1. arrayObjectName = new Array(element0, element1, ..., elementN)
+2. arrayObjectName = new Array(arrayLength)
+
+

arrayObjectName은 새 개체의 이름이거나 존재하는 다른 개체의 속성 이름입니다. Array 개체의 속성이나 메소드를 이용할 때는 arrayObjectName은 존재하는 Array 개체 이름이거나 존재하는 다른 개체의 속성입니다.

+

element0, element1, ..., elementN는 배열의 원소(element)가 될 값들입니다. 이런 식으로 지정하면, 나열한 값들을 원소로 가지고, 길이는 값의 개수인 배열이 만들어집니다.

+

arrayLength는 배열의 초기 길이입니다. 다음 코드는 원소 다섯 개를 가지는 배열을 만듭니다.

+
billingMethod = new Array(5)
+
+

배열 상수값 또한 Array 개체입니다. 예를 들어, 다음과 같은 상수값은 Array 개체입니다. 배열 상수값에 대한 자세한 내용은 배열 상수값을 보시기 바랍니다.

+
coffees = ["French Roast", "Columbian", "Kona"]
+
+

배열에 원소 넣기

+

원소에 값을 할당함으로써 배열에 값을 넣을 수 있습니다.

+
emp[1] = "Casey Jones"
+emp[2] = "Phil Lesh"
+emp[3] = "August West"
+
+

배열을 만들 때 값을 넣을 수도 있습니다.

+
myArray = new Array("Hello", myVar, 3.14159)
+
+

배열 원소 참조하기

+

배열 원소의 순서를 나타내는 숫자로 원소를 참조할 수 있습니다. 예를 들어 다음과 같은 배열을 만들었다고 해봅시다.

+
myArray = new Array("Wind","Rain","Fire")
+
+

그러면 첫 번째 원소는 myArray{{ mediawiki.external(0) }}으로 참조할 수 있고, 두 번째 원소는 myArray{{ mediawiki.external(1) }}로 참조할 수 있습니다.

+

원소의 색인은 영(0)부터 시작하지만 배열 길이(예를 들면 myArray.length)는 배열의 원소 개수를 나타냅니다.

+

 

+

Array 개체의 메소드

+

Array 개체는 다음과 같은 메소드들을 가지고 있습니다.

+ +
myArray = new Array("1","2","3")
+myArray = myArray.concat("a", "b", "c"); // myArray는 ["1", "2", "3", "a", "b", "c"]이 되었습니다.
+
+ +
myArray = new Array("Wind","Rain","Fire")
+list = myArray.join(" - "); // list는 "Wind - Rain - Fire"입니다.
+
+ +
myArray = new Array("1", "2", "3");
+last=myArray.pop(); // MyArray는 ["1", "2"], last = "3"이 되었습니다.
+
+ +
myArray = new Array("1", "2");
+myArray.push("3"); // MyArray는 ["1", "2", "3"]이 되었습니다.
+
+ +
myArray = new Array ("1", "2", "3");
+myArray.reverse(); // myArray = [ "3", "2", "1" ]이 되었습니다.
+
+ +
myArray = new Array ("1", "2", "3");
+first=myArray.shift(); // MyArray는 ["2", "3"], first는 "1"이 되었습니다.
+
+ +
myArray = new Array ("a", "b", "c", "d", "e");
+myArray = myArray.slice(1,4); //색인 1부터 색인 4 바로 앞까지의 원소를 추출해서 [ "b", "c", "d" ]를 반환합니다.
+
+ +
myArray = new Array ("1", "2", "3", "4", "5");
+myArray.splice(1,3,"a","b","c", "d"); // MyArray는 ["1", "a", "b", "c", "d", "5"]가 되었습니다.
+// 이 코드는 색인 1(즉 "2")부터 원소 세 개를 제거하고, 그 자리에 원소를 추가합니다.
+
+ +
myArray = new Array("Wind","Rain","Fire")
+myArray.sort(); // 배열을 정렬했으므로 myArrray = [ "Fire", "Rain", "Wind" ]가 되었습니다.
+
+

sort 메소드에 배열을 어떻게 정렬할지 결정하는 콜백 함수를 전해줄 수 있습니다. 그 함수는 두 값을 비교해서 다음 셋 중 하나를 반환해야 합니다.

+ +

예를 들어 다음 코드는 원소의 마지막 글자를 기준으로 배열을 정렬합니다.

+
var sortFn = function(a,b){
+    if (a[a.length - 1] < b[b.length - 1]) return -1;
+    if (a[a.length - 1] > b[b.length - 1]) return 1;
+    if (a[a.length - 1] == b[b.length - 1]) return 0;
+    }
+myArray.sort(sortFn); // 배열을 정렬했으므로 myArray = ["Wind","Fire","Rain"]가 되었습니다.
+
+ +

2차원 배열

+

다음 코드는 2차원 배열을 만듭니다.

+
a = new Array(4)
+for (i=0; i < 4; i++) {
+   a[i] = new Array(4)
+   for (j=0; j < 4; j++) {
+      a[i][j] = "["+i+","+j+"]"
+   }
+}
+
+

바로 위 코드는 이런 배열을 만들어냅니다.

+
Row 0:[0,0][0,1][0,2][0,3]
+Row 1:[1,0][1,1][1,2][1,3]
+Row 2:[2,0][2,1][2,2][2,3]
+Row 3:[3,0][3,1][3,2][3,3]
+
+

배열과 정규 표현식

+

배열이 정규 표현식과 문자열을 매치한 결과로 생성되었을 때, 그 배열은 매치에 대한 정보를 제공하는 속성과 원소를 포함하고 있습니다. RegExp.exec, String.match, String.split의 반환 값은 배열입니다. 정규 표현식과 관련된 배열 사용에 대한 정보를 얻으려면 4장 정규 표현식을 보십시오.

+

{{ PreviousNext("Core_JavaScript_1.5_Guide:Predefined_Core_Objects", "Core_JavaScript_1.5_Guide:Predefined_Core_Objects:Boolean_Object") }}

diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/index.html new file mode 100644 index 0000000000..9306e0ea94 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/predefined_core_objects/index.html @@ -0,0 +1,20 @@ +--- +title: Predefined Core Objects +slug: >- + Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Predefined_Core_Objects +translation_of: Web/JavaScript/Guide +--- +

미리 정의된 기본 개체

+

이 절에서는 기본 JavaScrip에 미리 정의된 개체에 대해서 설명하겠습니다. +

+ +

{{ PreviousNext("Core_JavaScript_1.5_Guide:Creating_New_Objects:Deleting_Properties", "Core_JavaScript_1.5_Guide:Predefined_Core_Objects:Array_Object") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Predefined_Core_Objects", "fr": "fr/Guide_JavaScript_1.5/Objets_pr\u00e9d\u00e9finis", "ja": "ja/Core_JavaScript_1.5_Guide/Predefined_Core_Objects", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Obiekty_predefiniowane" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/unicode/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/unicode/index.html new file mode 100644 index 0000000000..562b7a53a0 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/unicode/index.html @@ -0,0 +1,109 @@ +--- +title: Unicode +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Unicode +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +

유니코드

+

유니코드는 세계의 주요한 문자 언어를 교환하고 표현하기 위한 문자-코딩 표준입니다. 유니코드는 아메리카, 유럽, 중동, 아프리카, 인도, 아시아, 태평양 지역(Pacifica)의 언어를 포함하며 고문자와 기술 분야 기호들도 포함합니다. 유니코드는 공통적인 기술 분야, 수학 분야 기호 뿐만 아니라 여러 언어를 포함한 텍스트의 교환, 처리, 표현을 지원합니다. 유니코드는 나라마다 서로 다른 문자 표준으로 인해서 여러 언어를 포함했을 때 발생하는 국제화 문제를 해결할 수 있기를 희망합니다. 하지만 아직은 모든 현대 문자, 고대 문자를 지원하지는 못합니다. +

유니코드 문자 집합은 알려진 모든 인코딩을 위해 사용될 수 있습니다. 유니코드는 ASCII (American Standard Code for Information Interchange, 정보 교환을 위한 미국 표준 코드) 문자 집합을 본떠 만들어졌습니다. 각각의 문자에 숫자와 이름을 부여한 것입니다. 문자 인코딩은 문자의 정체성(identity)과 숫자 값(코드 위치)와 함께 숫자 값의 비트 표현을 명시합니다. 16비트 숫자 값(코드 값)은 U+0041처럼 접두어 U뒤에 16진수를 붙여서 표시합니다. 이 값의 유일한 이름은 LATIN CAPITAL LETTER A입니다. +

JavaScript 1.3 이전 버전은 유니코드를 지원하지 않습니다. +

+

유니코드와 ASCII 및 ISO 사이의 호환성

+

유니코드는 ISO 10646의 부분집합인 국제 표준 ISO/IEC 10646-1; 1993과 완벽하게 호환됩니다. +

몇몇 인코딩 표준(UTF-8, UTF-16, ISO UCS-2를 포함하는)들이 실제 비트 값으로 유니코드를 표현하기 위해 사용됩니다. +

UTF-8 인코딩은 ASCII 문자와 호환되며 많은 프로그램이 UTF-8을 지원합니다. 앞쪽 128개의 유니코드 문자는 ASCII 문자에 대응되며 같은 바이트 값을 가지고 있습니다. U+0020부터 U+007E 까지의 유니코드 문자는 ASCII 문자 0x20 부터 0x7E 까지와 동일합니다. 라틴 알파벳을 지원하고 7비트 문자 집합을 사용하는 ASCII와는 달리, UTF-8은 한 문자를 위해서 한 개부터 네 개 사이의 8진수(octet)를 사용합니다. ("8진수"는 바이트 또는 8비트를 의미합니다.) 이 방법으로 수백만개의 문자를 표현할 수 있습니다. 다른 인코딩 표준인 UTF-16은 유니코드 문자를 표현하기 위해 2바이트를 사용합니다. 이스케이프 시퀀스를 이용하여 UTF-16은 4바이트를 써서 모든 유니코드 범위를 표현합니다. ISO UCS-2 (Universal Character Set, 세계 문자 집합)은 2바이트를 사용합니다. +

JavaScript와 Navigator가 UTF-8/유니코드를 지원한다는 것은 우리가 비 라틴 문자와 국제화되고 지역화된 문자에다 특수한 기술 분야 기호까지 JavaScript 프로그램에 쓸 수 있다는 것을 의미합니다. 유니코드는 여러 언어를 포함한 텍스트를 인코딩할 수 있는 표준적인 방법을 제공합니다. UTF-8 인코딩이 ASCII와 호환되기 때문에, ASCII 문자를 프로그램에 사용할 수 있습니다. 우리는 JavaScript의 주석, 문자열 리터럴, 식별자(identifier), 정규 표현식에 비 ASCII 유니코드 문자를 쓸 수 있습니다. +

+

유니코드 이스케이프 시퀀스

+

우리는 문자열 리터럴, 정규 표현식, 식별자에 유니코드 이스케이프 시퀀스를 사용할 수 있습니다. 이스케이프 시퀀스는 ASCII 문자 여섯 개로 이루어지는데, \u 뒤에 16진수를 표현하는 숫자 네 개가 붙은 모양입니다. 예를 들어 \u00A9는 저작권 기호를 나타냅니다. JavaScript에서 모든 유니코드 이스케이프 시퀀스는 문자 한 개로 인식됩니다. +

다음의 코드는 저작권 문자와 "Netscape Communications"라는 문자열을 반환합니다. +

+
x="\u00A9 Netscape Communications"
+

다음의 표는 자주 사용되는 특수 문자의 유니코드 값을 모은 것입니다. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
분류유니코드 값이름형식화된 이름(Format name)
공백 문자\u0009Tab<TAB>
 \u000BVertical Tab<VT>
 \u000CForm Feed<FF>
 \u0020Space<SP>
줄 끝 문자\u000ALine Feed<LF>
 \u000DCarriage Return<CR>
그 외 유니코드 이스케이프 시퀀스\u0008Backspace<BS>
 \u0009Horizontal Tab<HT>
 \u0022Double Quote"
 \u0027Single Quote'
 \u005C Backslash\
+

표 2.2: 특수 문자의 유니코드 값 +

JavaScript에서 유니코드 이스케이프 시퀀스는 Java와 다릅니다. JavaScript에서, 이스케이프 시퀀스가 특수 문자로 먼저 해석되지 않습니다. 예를 들어, 줄 끝 이스케이프 시퀀스가 문자열에 포함되어 있어도 함수에 의해 해석되기 전까지는 문자열을 자르지 않습니다. 주석에 포함된 이스케이프 시퀀스는 모두 무시됩니다. Java에서는 한 줄 주석에 이스케이프 시퀀스가 있으면 유니코드 문자로 해석됩니다. 문자열 리터럴에서 Java 컴파일러는 이스케이프 시퀀스를 먼저 해석합니다. 예를 들어 줄 끝 이스케이프 문자(즉 \u000A)가 Java에서 사용되면 문자열 리터럴을 끝나게 합니다. Java에서는 줄 끝 문자가 문자열 리터럴에 포함될 수 없으므로, 에러가 발생합니다. 문자열 리터럴에 개행 문자를 넣으려면 반드시 \n을 사용해야 합니다. JavaScript에서 이스케이프 시퀀스는 \n과 같은 방식으로 동작합니다. +

+
참고: 긴 문자열을 변환하는 웹 프로그램 Hot-Tips' Unicode Converter, by Bob Foley.
+

JavaScript 파일에서 유니코드 문자

+

초기 버전의 Gecko는 XUL에서 로드되는 JavaScript 파일의 인코딩이 Latin-1일 것이라고 가정했습니다. Gecko 1.8부터는 XUL 파일의 인코딩으로 부터 JavaScript 파일의 인코딩을 유추하도록 변경되었습니다. 더 많은 정보는 International characters in XUL JavaScript 페이지를 참고하시기 바랍니다. +

+

유니코드로 문자 표시하기

+

우리는 다른 언어나 기술 분야 기호를 표시하기 위해서 유니코드를 사용할 수 있습니다. 문자를 제대로 표시하기 위해서는 Mozilla Firefox나 Netscape 같은 클라이언트가 유니코드를 지원해야 합니다. 게다가 클라이언트에서 사용할 수 있는 적절한 유니코드 글꼴이 필요하고, 클라이언트 플랫폼이 유니코드를 지원해야 합니다. 종종 유니코드 글꼴이 모든 유니코드 문자를 표시하지 못하는 경우가 있습니다. Windows 95 같은 몇몇 플랫폼은 유니코드를 부분적으로만 지원합니다. +

비 ASCII 문자 입력을 받기 위해서는 클라이언트가 유니코드로 입력을 보내야 합니다. 표준 확장 키보드(standard enhanced keyborad)를 사용하면 클라이언트에서 유니코드가 지원하는 추가적인 문자를 쉽게 입력할 수 없습니다. 때때로 유니코드 문자를 입력하려면 유니코드 이스케이프를 사용하는 방법 밖에 없을 때도 있습니다. +

유니코드에 대한 더 많은 정보를 얻으려면 유니코드 홈페이지나 The Unicode Standard, Version 2.0, published by Addison-Wesley, 1996 를 보시기 바랍니다. +

{{ PreviousNext("Core_JavaScript_1.5_Guide:Literals", "Core_JavaScript_1.5_Guide:Expressions") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Unicode", "fr": "fr/Guide_JavaScript_1.5/Unicode", "ja": "ja/Core_JavaScript_1.5_Guide/Unicode", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Unicode" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/values/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/values/index.html new file mode 100644 index 0000000000..8fcd0070e9 --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/values/index.html @@ -0,0 +1,39 @@ +--- +title: Values +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Values +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +

+

JavaScript는 다음과 같은 값 형식을 인식합니다. +

+ +

이렇게 조금 적어보이는 값 형식 또는 "자료형"이지만 훌륭한 기능을 작성할 수 있습니다. 정수와 실수 사이에 엄격한 구분은 없습니다. JavaScript에는 명시적인 날짜 자료형은 없습니다. 하지만 Date 개체를 이용하면 됩니다. +Object함수는 언어의 또다른 기초 요소입니다. 개체는 값을 포함할 수 있는 이름 붙은 어떤 것이라고 생각하면 되고, 함수는 프로그램이 수행할 수 있는 실행 절차라고 생각하면 됩니다. +

+

자료형 변환

+

JavaScript는 동적 타입 언어입니다. 이 말은 변수를 선언할 때 타입을 지정하지 않아도 되고, 스크립트 실행중에 필요에 따라 자동으로 자료형이 바뀐다는 말입니다. 예를 들어 다음과 같이 변수를 선언할 수 있습니다. +

+
var answer = 42
+
+

그 후에 이 변수에 문자열 값을 할당할 수 있습니다. +

+
answer = "Thanks for all the fish..."
+
+

JavaScript는 동적 타입 언어이기 때문에, 이렇게 대입하더라도 에러를 내지 않습니다. +

숫자와 문자열 값을 + 연산자로 계산하는 표현식에서, JavaScript는 숫자를 문자열로 변환합니다. 예를 들어 다음과 같은 문장을 생각해봅시다. +

+
x = "The answer is " + 42 // returns "The answer is 42"
+y = 42 + " is the answer" // returns "42 is the answer"
+
+

다른 연산자를 사용하는 문장에서는 숫자를 문자열로 변환하지 않습니다. +

+
"37" - 7 // returns 30
+"37" + 7 // returns "377"
+
+

{{ PreviousNext("Core_JavaScript_1.5_Guide:JavaScript_Overview", "Core_JavaScript_1.5_Guide:Variables") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Values", "fr": "fr/Guide_JavaScript_1.5/Valeurs", "ja": "ja/Core_JavaScript_1.5_Guide/Values", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Warto\u015bci" } ) }} diff --git a/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/variables/index.html b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/variables/index.html new file mode 100644 index 0000000000..f31c37bc9c --- /dev/null +++ b/files/ko/web/javascript/guide/obsolete_pages/core_javascript_1.5_guide/variables/index.html @@ -0,0 +1,64 @@ +--- +title: Variables +slug: Web/JavaScript/Guide/Obsolete_Pages/Core_JavaScript_1.5_Guide/Variables +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +

변수

+

우리는 프로그램 내에서 값에 이름을 부여하기 위해서 변수를 사용할 수 있습니다. 변수의 이름은 "식별자(identifier)"라고 불리며, 몇 가지 규칙을 따라야 합니다. +

JavaScript 의 식별자는 문자(letter)나 밑줄(_)이나 달러 기호($)로 시작해야 합니다. 그 뒤에는 숫자(0-9)도 올 수 있습니다. JavaScript는 대소문자를 구별하기 때문에, 문자는 대문자 "A"부터 "Z"까지와 소문자 "a"부터 "z"까지를 사용할 수 있습니다. +

JavaScript 1.5부터, 식별자에 å나 ü같은 ISO 8859-1이나 유니코드 문자를 사용할 수 있습니다. 또한 유니코드 이스케이프 시퀀스 페이지에 나열된 \uXXXX 형식 유니코드 이스케이프 시퀀스를 식별자에 쓸 수도 있습니다. +

규칙에 맞는 이름 몇 가지는 이런 것입니다. Number_hits, temp99, _name. +

+

변수 선언

+

변수를 선언하는 방법에는 두 가지가 있습니다. +

+ +

변수를 평가하기(Evaluating)

+

초기값을 지정하지 않고 var 문장을 이용해서 선언한 변수는 undefined라는 값을 갖습니다. +

선언하지 않은 변수에 접근하려고 하면 ReferenceError 예외가 발생합니다. +

+
var a;
+print("The value of a is " + a); // prints "The value of a is undefined"
+print("The value of b is " + b); // throws ReferenceError exception
+
+

변수가 값을 갖고 있는지 결정하기 위해서 undefined를 사용할 수 있습니다. 다음 코드에서 input에는 값을 할당하지 않아서 if문은 true로 평가됩니다. +

+
var input;
+if(input === undefined){
+   doThis();
+} else {
+   doThat();
+}
+

Not sure how the following is related to "Variables" section +undefined값을 참/거짓을 판별하는 구문에 쓰면 false로 평가됩니다. 예를 들어 다음 코드에서는 myArray의 원소가 정의되지 않았기 때문에 myFunction 함수가 실행됩니다. +

+
myArray=new Array()
+if (!myArray[0])
+   myFunction();
+

숫자가 필요한 문맥에서 null 변수를 평가하면 null 값은 0으로 평가되고, 참/거짓이 필요한 문맥에서는 false로 평가됩니다. +When you evaluate a null variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example: +

+
var n = null;
+n * 32; //0을 반환합니다
+

변수 범위

+

함 수 외부에서 선언한 변수는 "전역(global)" 변수라고 부릅니다. 그 변수는 현재 문서의 모든 코드에서 접근할 수 있기 때문입니다. 함수 안에서 선언한 변수는 "지역(local)" 변수라고 부릅니다. 그 변수는 함수 안에서만 접근할 수 있기 때문입니다. +

JavaScript에는 블록 문장 범위가 없습니다. 대신 그 블록이 포함된 코드의 지역 범위에 포함됩니다. 예를 들어 다음 코드에서는 conditionfalse이면 예외를 발생시키는 대신 0을 출력합니다. +

+
if (condition) {
+  var x = 5;
+}
+print(x ? x : 0);
+
+

JavaScript의 변수와 관련해서 또다른 색다른 점은 나중에 선언될 변수에 예외 발생없이 접근할 수 있다는 것입니다. +

+
print(x === undefined); // prints "true"
+var x = 3;
+
+

전역 변수

+

need links to pages discussing scope chains and the global object +전역 변수는, 실제로는 "전역 개체(global object)"의 속성(property)입니다. 웹 페이지에서 전역 개체는 window이므로, window.variable 문장을 이용해서 전역 변수에 접근할 수 있습니다. +

그러므로, window나 frame 이름을 이용하면 다른 window나 frame에 정의된 전역 변수에 접근할 수 있습니다. 예를 들어 phoneNumber라는 변수를 FRAMESET 문서에 정의했다면, 자식 frame에서 parent.phoneNumber로 그 변수에 접근할 수 있습니다. +

{{ PreviousNext("Core_JavaScript_1.5_Guide:Values", "Core_JavaScript_1.5_Guide:Constants") }} +

{{ languages( { "en": "en/Core_JavaScript_1.5_Guide/Variables", "fr": "fr/Guide_JavaScript_1.5/Variables", "ja": "ja/Core_JavaScript_1.5_Guide/Variables", "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Zmienne" } ) }} diff --git a/files/ko/web/javascript/guide/text_formatting/index.html b/files/ko/web/javascript/guide/text_formatting/index.html new file mode 100644 index 0000000000..027e92c262 --- /dev/null +++ b/files/ko/web/javascript/guide/text_formatting/index.html @@ -0,0 +1,275 @@ +--- +title: 텍스트 서식 +slug: Web/JavaScript/Guide/Text_formatting +translation_of: Web/JavaScript/Guide/Text_formatting +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}
+ +

이 장에서는 JavaScript에서 문자열과 텍스트로 작업하는 방법을 소개합니다.

+ +

문자열

+ +

 JavaScript의 {{Glossary("문자열")}} 유형은 원문의 데이터를 나타내는데 사용됩니다. 이는 16비트 부호 없는 정수 값(UTF-16 code units)의 "요소" 집합입니다. String의 각 요소(문자)는 String에서 하나의 위치를 차지합니다. 첫 번째 요소는 인덱스 0 다음은 인덱스 1 등등... 문자열의 길이는 요소의 수와 같습니다. 문자열 리터럴 또는 문자열 객체를 사용하여 문자열을 만들 수 있습니다.

+ +

 

+ +

주의 : 이페이지를 수정한다면 MDN bug 857438이 해결될 때 까지 U+FFFF이상의 문자를 포함하지 마세요. ( https://bugzilla.mozilla.org/show_bug.cgi?id=857438 ).

+ +

문자열 리터럴

+ +

작은따옴표나 큰따옴표를 사용하여 간단한 문자열을 만들 수 있습니다:

+ +
'foo'
+"bar"
+ +

보다 많은 문자열을 이스케이프 시퀀스를 사용하여 만들 수 있습니다

+ +

16진수 이스케이프 시퀀스

+ +

\x 뒤에 수는 16진수로 해석(interpreted)됩니다.

+ +
'\xA9' // "©"
+
+ +

유니코드 이스케이프 시퀀스

+ +

유니코드 이스케이프 시퀀스는 \u 다음에 적어도 네 개의 16진수 숫자(digit)를 필요로 합니다.

+ +
'\u00A9' // "©"
+ +

유니코드 코드 포인트 이스케이프

+ +

ECMAScript 6의 새로운 기능. 유니 코드 포인트 이스케이프를 사용하면 16 진수를 사용하여 모든 문자를 이스케이프 처리 할 수 ​​있으므로 최대 0x10FFFF의 유니 코드 코드 포인트를 사용할 수 있습니다. 간단한 유니 코드 이스케이프를 사용하면 동일한 결과를 얻기 위해서 서로 게이트를 별도로 작성해야하는 경우가 있습니다.

+ +

{{jsxref("String.fromCodePoint()")}} 나 {{jsxref("String.prototype.codePointAt()")}}를 참고하세요.

+ +
'\u{2F804}'
+
+// the same with simple Unicode escapes
+'\uD87E\uDC04'
+ +

문자열 개체

+ +

{{jsxref("문자열")}} 개체는 문자열 기본 데이터 형식의 래퍼입니다.

+ +
var s = new String("foo"); // Creates a String object
+console.log(s); // Displays: { '0': 'f', '1': 'o', '2': 'o'}
+typeof s; // Returns 'object'
+
+ +

여러분은 문자열 리터럴 값에 문자열 개체의 방법 중 하나를 호출 할 수 있습니다.—JavaScript가 자동으로 문자열 리터럴을 임시 문자열 개체로 변환하고, 메서드를 호출하고, 그리고나서 임시 문자열 개체를 삭제합니다. 또한, String.length 속성을 문자열 리터럴과 함께 사용할 수 있습니다.

+ +

특별히 String 개체를 사용할 필요가 없지 않는 한, String 개체는 직관에 반하는 행동을 할 수 있기 때문에 여러분은 string 리터럴을 사용해야합니다. 예를들어:

+ +
var s1 = "2 + 2"; // Creates a string literal value
+var s2 = new String("2 + 2"); // Creates a String object
+eval(s1); // Returns the number 4
+eval(s2); // Returns the string "2 + 2"
+ +

문자열 개체 문자열의 문자 수를 나타내는 하나의 속성, 길이를 갖습니다. 예를 들어, "Hello, World!"가 13자 이므로 다음 코드는 x를 값 13으로 할당합니다. String 객체는 문자열에있는 UTF-16 코드 단위의 수를 나타내는 길이가 하나의 속성을 가집니다. 예를 들어, 다음 코드에서는 "Hello, World!"가 UTF-16 코드 단위로 표현되는 13개의 문자를 가지고 있기 때문에 x 값이 13이 됩니다. 배열 브래킷 스타일을 사용하여 각 코드 단위에 액세스 할 수 있습니다. 문자열은 변경 불가능한 배열과 같은 객체이기 때문에 개별 문자를 변경할 수 없습니다.

+ +
var mystring = 'Hello, World!';
+var x = mystring.length;
+mystring[0] = 'L'; // This has no effect, because strings are immutable
+mystring[0]; // This returns "H"
+ +

유니 코드 스칼라 값이 U + FFFF (희귀 한 중국어 / 일본어 / 한국어 / 베트남어 문자 및 일부 이모티콘)보다 큰 문자는 각각 서로 다른 두 개의 코드 단위로 UTF-16에 저장됩니다. 예를 들어, 단일 문자 U + 1F600 "Emoji grinning face"를 포함하는 문자열은 길이가 2입니다. 대괄호를 사용하여 이러한 문자열의 개별 코드 단위에 액세스하면 일치하지 않는 대리 코드 단위가있는 문자열이 만들어지는 등의 바람직하지 않은 결과가 발생할 수 있습니다. 유니 코드 표준 위반 MDN 버그 857438이 수정 된 후에 예제가 이 페이지에 추가되어야합니다. {{jsxref ( "String.fromCodePoint ()")}} 또는 {{jsxref ( "String.prototype.codePointAt ()")}}도 참조하십시오.

+ +

String 객체는 다양한 메서드가 있습니다: 문자열 자체의 변경된 결과를 반환하는 substringtoUpperCase가 그것!

+ +

다음 표는 {{jsxref("문자열")}} 개체의 메서드를 요약한 것입니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

문자열 메서드

+
MethodDescription
{{jsxref("String.charAt", "charAt")}}, {{jsxref("String.charCodeAt", "charCodeAt")}}, {{jsxref("String.codePointAt", "codePointAt")}} +

문자열에서 지정된 위치에 있는 문자나 문자 코드를 반환합니다.

+
{{jsxref("String.indexOf", "indexOf")}}, {{jsxref("String.lastIndexOf", "lastIndexOf")}} +

문자열에서 지정된 부분 문자열의 위치나 지정된 부분 문자열의 마지막 위치를 각각 반환합니다.

+
{{jsxref("String.startsWith", "startsWith")}}, {{jsxref("String.endsWith", "endsWith")}}, {{jsxref("String.includes", "includes")}} +

문자열 시작하고, 끝나고, 지정된 문자열을 포함하는지의 여부를 반환합니다.

+
{{jsxref("String.concat", "concat")}} +

두 문자열의 텍스트를 결합하고 새로운 문자열을 반환합니다.

+
{{jsxref("String.fromCharCode", "fromCharCode")}}, {{jsxref("String.fromCodePoint", "fromCodePoint")}} +

유니코드 값의 지정된 시퀀스로부터 문자열을 구축합니다. 문자열 인스턴스가 아닌 문자열 클래스의 메서드입니다.

+
{{jsxref("String.split", "split")}} +

부분 문자열로 문자열을 분리하여 문자열 배열로 문자열 개체를 분할합니다.

+
{{jsxref("String.slice", "slice")}} +

문자열의 한 부분을 추출하고 새 문자열을 반환합니다.

+
{{jsxref("String.substring", "substring")}}, {{jsxref("String.substr", "substr")}} +

어느 시작 및 종료 인덱스 또는 시작 인덱스 길이를 지정하여, 문자열의 지정된 일부를 반환합니다.

+
{{jsxref("String.match", "match")}}, {{jsxref("String.replace", "replace")}}, {{jsxref("String.search", "search")}} +

정규 표현식으로 작업합니다.

+
{{jsxref("String.toLowerCase", "toLowerCase")}},
+ {{jsxref("String.toUpperCase", "toUpperCase")}}
+

.모든 소문자 또는 대문자에서 각각 문자열을 반환합니다.

+
{{jsxref("String.normalize", "normalize")}}호출 문자열 값 유니 코드 표준화 양식을 반환합니다.
{{jsxref("String.repeat", "repeat")}} +

주어진 회를 반복하는 개체 요소로 이루어진 문자열을 반환합니다.

+
{{jsxref("String.trim", "trim")}}문자열의 시작과 끝에서 공백을 자릅니다.
+ +

다중 선 템플릿 문자열

+ +

템플릿 문자열은 포함 식을 용납하는 문자열 리터럴입니다. 여러분은 그것들과 함께 다중 선 문자열 및 문자열 보간 기능을 사용할 수 있습니다.

+ +

템플릿 문자열은 작은따옴표나 큰따옴표 대신에 back-tick (` `) (grave accent)문자로 묶습니다. 템플릿 문자열은 자리 표시자를 포함 할 수 있습니다. 이들은 달러 기호 중괄호로 표시됩니다.  (${expression})

+ +

다중 선

+ +

소스에 삽입하는 새로운 선 문자는 템플릿 문자열의 일부입니다. 정상적인 문자열을 사용하면, 여러분은 다중 선 문자열을 얻기 위해 다음과 같은 구문을 사용해야합니다:

+ +
console.log("string text line 1\n\
+string text line 2");
+// "string text line 1
+// string text line 2"
+ +

다중 선 문자열과 같은 효과를 얻기 위해, 여러분은 이제 쓸 수 있습니다:

+ +
console.log(`string text line 1
+string text line 2`);
+// "string text line 1
+// string text line 2"
+ +

포함식

+ +

일반 문자열 내에서 표현식을 포함하기 위해, 다음과 같은 구문을 사용합니다:

+ +
var a = 5;
+var b = 10;
+console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
+// "Fifteen is 15 and
+// not 20."
+ +

이제, 템플릿 문자열을 가지고, 여러분은 읽기와 같이 대체를 만드는 syntactic sugar의 사용을 할 수 있습니다:

+ +
var a = 5;
+var b = 10;
+console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
+// "Fifteen is 15 and
+// not 20."
+ +

자세한 내용은 JavaScript 참조에서 템플릿 문자열에 대해 읽어보세요.

+ +

국제화

+ +

{{jsxref("Intl")}} 개체는  ECMA스크립트 국제 API에 언어와 문자열과 숫자서식과 날짜와 시간서식을 제공하는 명칭공간입니다.  {{jsxref("Collator")}}, {{jsxref("NumberFormat")}}, 와 {{jsxref("DateTimeFormat")}} 개체들을 위한 생성자들은  Intl 개체의 특성들입니다.

+ +

날짜와 시간서식

+ +

{{jsxref("DateTimeFormat")}} 개체는 날짜와 시간을 서식하기에 유용합니다. 다음 코드는 미국에서 쓰이는 영어로 날짜를 서식합니다. (결과는 다른 시간대와 다릅니다)

+ +
var msPerDay = 24 * 60 * 60 * 1000;
+
+// July 17, 2014 00:00:00 UTC.
+var july172014 = new Date(msPerDay * (44 * 365 + 11 + 197));
+
+var options = { year: "2-digit", month: "2-digit", day: "2-digit",
+                hour: "2-digit", minute: "2-digit", timeZoneName: "short" };
+var americanDateTime = new Intl.DateTimeFormat("en-US", options).format;
+
+console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT
+
+ +

숫자 서식

+ +

{{jsxref("NumberFormat")}}개체는 통화를 위해 숫자를 서식하는것에 대해 유용하다.

+ +
var gasPrice = new Intl.NumberFormat("en-US",
+                        { style: "currency", currency: "USD",
+                          minimumFractionDigits: 3 });
+
+console.log(gasPrice.format(5.259)); // $5.259
+
+var hanDecimalRMBInChina = new Intl.NumberFormat("zh-CN-u-nu-hanidec",
+                        { style: "currency", currency: "CNY" });
+
+console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五
+
+ +

조합

+ +

{{jsxref("Collator")}}개체는 문자열을 비교하고 구분하는 것에 대해 유용합니다.

+ +

예를 들어, 실제로 독일에선 phonebook과 dictionary라는 2개의 다른 종류의 명령어들이 있습니다. 전화기록부류는 소리를 강조합니다. 그리고 구분에 앞서 다른것들은 “ä”, “ö”인것처럼 "ae", "oe"로 확장됐습니다. 

+ +
var names = ["Hochberg", "Hönigswald", "Holzman"];
+
+var germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk");
+
+// as if sorting ["Hochberg", "Hoenigswald", "Holzman"]:
+console.log(names.sort(germanPhonebook.compare).join(", "));
+// logs "Hochberg, Hönigswald, Holzman"
+
+ +

어떤 독일말들은 여분의 변모음과 함께 활용한다. 그래서 사전안에서 이것은 변모음을 무시하라고 명령하기에 실용적이다.

+ +
var germanDictionary = new Intl.Collator("de-DE-u-co-dict");
+
+// as if sorting ["Hochberg", "Honigswald", "Holzman"]:
+console.log(names.sort(germanDictionary.compare).join(", "));
+// logs "Hochberg, Holzman, Hönigswald"
+
+ +

{{jsxref("Intl")}}API에 대한 자세한 내용은 Introducing the JavaScript Internationalization API를 참조하세요.

+ +

{{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}

diff --git a/files/ko/web/javascript/guide/using_promises/index.html b/files/ko/web/javascript/guide/using_promises/index.html new file mode 100644 index 0000000000..bc847e561a --- /dev/null +++ b/files/ko/web/javascript/guide/using_promises/index.html @@ -0,0 +1,361 @@ +--- +title: Using promises +slug: Web/JavaScript/Guide/Using_promises +tags: + - Promise + - Promises +translation_of: Web/JavaScript/Guide/Using_promises +--- +
{{jsSidebar("JavaScript Guide")}}{{PreviousNext("Web/JavaScript/Guide/Details_of_the_Object_Model", "Web/JavaScript/Guide/Iterators_and_Generators")}}
+ +

{{jsxref("Promise")}}는 비동기 작업의 최종 완료 또는 실패를 나타내는 객체입니다. 대부분 여러분은 이미 만들어진 promise를 사용했었기 때문에 이 가이드에서는 어떻게 promise를 만드는지 설명하기에 앞서 promise의 사용법에 대해 설명합니다.

+ +

기본적으로 promise는 함수에 콜백을 전달하는 대신에, 콜백을 첨부하는 방식의 객체입니다.
+  

+ +

비동기로 음성 파일을 생성해주는  createAudioFileAsync()라는 함수가 있었다고 생각해보세요. 해당 함수는 음성 설정에 대한 정보를 받고, 두 가지 콜백 함수를 받습니다. 하나는 음성 파일이 성공적으로 생성되었을때 실행되는 콜백, 그리고 다른 하나는 에러가 발생했을때 실행되는 콜백입니다.

+ +

createAudioFileAsync()는 함수는 아래와 같이 사용됩니다.  

+ +
function successCallback(result) {
+  console.log("Audio file ready at URL: " + result);
+}
+
+function failureCallback(error) {
+  console.log("Error generating audio file: " + error);
+}
+
+createAudioFileAsync(audioSettings, successCallback, failureCallback);
+ +

…모던한 함수들은 위와 같이 콜백들을 전달지 않고 콜백을 붙여 사용할 수 있게 Promise를 반환해줍니다.

+ +

만약 createAudioFileAsync() 함수가 Promise를 반환해주도록 수정해본다면, 다음과 같이 간단하게 사용되어질 수 있습니다.

+ +
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);
+ +

…조금 더 간단하게 써보자면:

+ +
const promise = createAudioFileAsync(audioSettings);
+promise.then(successCallback, failureCallback);
+ +

우리는 이와 같은 것을 비동기 함수 호출이라고 부릅니다. 이런 관례는 몇 가지 장점을 갖고 있습니다. 각각에 대해 한번 살펴보도록 합시다.

+ +

Guarantees

+ +

콜백 함수를 전달해주는 고전적인 방식과는 달리, Promise는 아래와 같은 특징을 보장합니다.

+ + + +

Promise의 가장 뛰어난 장점 중의 하나는 chaining입니다.

+ +

Chaining

+ +

보통 하나나 두 개 이상의 비동기 작업을 순차적으로 실행해야 하는 상황을 흔히 보게 됩니다. 순차적으로 각각의 작업이 이전 단계 비동기 작업이 성공하고 나서 그 결과값을 이용하여 다음 비동기 작업을 실행해야 하는 경우를 의미합니다. 우리는 이런 상황에서 promise chain을 이용하여 해결하기도 합니다.

+ +

then() 함수는 새로운 promise를 반환합니다. 처음에 만들었던 promise와는 다른 새로운 promise입니다.

+ +
const promise = doSomething();
+const promise2 = promise.then(successCallback, failureCallback);
+
+ +

또는

+ +
const promise2 = doSomething().then(successCallback, failureCallback);
+
+ +

두 번째 promise는 doSomething() 뿐만 아니라 successCallback or failureCallback 의 완료를 의미합니다. successCallback or failureCallback 또한 promise를 반환하는 비동기 함수일 수도 있습니다. 이 경우 promise2에 추가 된 콜백은 successCallback또는 failureCallback에 의해 반환된 promise 뒤에 대기합니다.

+ +

기본적으로, 각각의 promise는 체인 안에서 서로 다른 비동기 단계의 완료를 나타냅니다.

+ +

예전에는 여러 비동기 작업을 연속적으로 수행하면 고전적인 '지옥의 콜백 피라미드'가 만들어 졌었습니다.

+ +
doSomething(function(result) {
+  doSomethingElse(result, function(newResult) {
+    doThirdThing(newResult, function(finalResult) {
+      console.log('Got the final result: ' + finalResult);
+    }, failureCallback);
+  }, failureCallback);
+}, failureCallback);
+
+ +

모던한 방식으로 접근한다면, 우리는 콜백 함수들을 반환된 promise에 promise chain을 형성하도록 추가할 수 있습니다:

+ +
doSomething().then(function(result) {
+  return doSomethingElse(result);
+})
+.then(function(newResult) {
+  return doThirdThing(newResult);
+})
+.then(function(finalResult) {
+  console.log('Got the final result: ' + finalResult);
+})
+.catch(failureCallback);
+
+ +

then 에 넘겨지는 인자는 선택적(optional)입니다. 그리고 catch(failureCallback) 는 then(null, failureCallback) 의 축약입니다. 이 표현식을 화살표 함수로 나타내면 다음과 같습니다.

+ +
doSomething()
+.then(result => doSomethingElse(result))
+.then(newResult => doThirdThing(newResult))
+.then(finalResult => {
+  console.log(`Got the final result: ${finalResult}`);
+})
+.catch(failureCallback);
+
+ +

중요: 반환값이 반드시 있어야 합니다, 만약 없다면 콜백 함수가 이전의 promise의 결과를 받지 못합니다.
+ (화살표 함수 () => x는 () => {return x;}와 같습니다).

+ +

Chaining after a catch

+ +

chain에서 작업이 실패한 후에도 새로운 작업을 수행하는 것이 가능하며 매우 유용합니다. (예 : catch) 다음 예를 읽으십시오:

+ +
new Promise((resolve, reject) => {
+    console.log('Initial');
+
+    resolve();
+})
+.then(() => {
+    throw new Error('Something failed');
+
+    console.log('Do this');
+})
+.catch(() => {
+    console.log('Do that');
+})
+.then(() => {
+    console.log('Do this, whatever happened before');
+});
+
+ +

그러면 다음 텍스트가 출력됩니다.

+ +
Initial
+Do that
+Do this, whatever happened before
+
+ +

참고: "Do this" 텍스트가 출력되지 않은 것을 주의깊게 보십시오. "Something failed" 에러가 rejection을 발생시켰기 때문입니다.

+ +

Error propagation

+ +

'콜백 지옥'에서 failureCallback이 3번 발생한 것을 기억 할 것입니다. promise chain에서는 단 한 번만 발생하는것과 비교되죠.

+ +
doSomething()
+.then(result => doSomethingElse(result))
+.then(newResult => doThirdThing(newResult))
+.then(finalResult => console.log(`Got the final result: ${finalResult}`))
+.catch(failureCallback);
+ +

기본적으로 promise chain은 예외가 발생하면 멈추고 chain의 아래에서 catch를 찾습니다. 이것은 동기 코드가 어떻게 동작 하는지 모델링 한 것입니다.

+ +
try {
+  const result = syncDoSomething();
+  const newResult = syncDoSomethingElse(result);
+  const finalResult = syncDoThirdThing(newResult);
+  console.log(`Got the final result: ${finalResult}`);
+} catch(error) {
+  failureCallback(error);
+}
+ +

비동기 코드를 사용한 이러한 대칭성은 ECMAScript 2017에서 async/await 구문(Syntactic sugar) 에서 최고로 느낄 수 있습니다.

+ +
async function foo() {
+  try {
+    const result = await doSomething();
+    const newResult = await doSomethingElse(result);
+    const finalResult = await doThirdThing(newResult);
+    console.log(`Got the final result: ${finalResult}`);
+  } catch(error) {
+    failureCallback(error);
+  }
+}
+ +

이것은 promise를 기반으로 합니다. doSomething()은 이전 함수와 같습니다. 문법은 이곳에서 확인 할 수 있습니다.

+ +

Promise는 모든 오류를 잡아내어, 예외 및 프로그래밍 오류가 발생해도 콜백 지옥의 근본적인 결함을 해결합니다. 이는 비동기 작업의 기능 구성에 필수적입니다.

+ +

Promise rejection events

+ +

Promise가 reject될 때마다 두 가지 이벤트 중 하나가 전역 범위에 발생합니다.(일반적으로, 전역 범위는 {{domxref("window")}}거나, 웹 워커에서 사용되는 경우, {{domxref("Worker")}}, 혹은 워커 기반 인터페이스입니다.) 두 가지 이벤트는 다음과 같습니다.

+ +
+
{{domxref("Window.rejectionhandled_event", "rejectionhandled")}}
+
executor의 reject함수에 의해 reject가 처리 된 후 promise가 reject 될 때 발생합니다.
+
{{domxref("Window.unhandledrejection_event", "unhandledrejection")}}
+
promise가 reject되었지만 사용할 수 있는 reject 핸들러가 없을 때 발생합니다.
+
+ +

({{domxref("PromiseRejectionEvent")}} 유형인) 두 이벤트에는 멤버 변수인 promise와 reason 속성이 있습니다. {{domxref ( "PromiseRejectionEvent.promise", "promise")}}는 reject된 promise를 가리키는 속성이고, {{domxref ( "PromiseRejectionEvent.reason", "reason")}}은 promise가 reject된 이유를 알려 주는 속성입니다.

+ +

이들을 이용해 프로미스에 대한 에러 처리를 대체(fallback)하는 것이 가능해지며, 또한 프로미스 관리시 발생하는 이슈들을 디버깅하는 데 도움을 얻을 수 있습니다. 이 핸들러들은 모든 맥락에서 전역적(global)이기 때문에, 모든 에러는 발생한 지점(source)에 상관없이 동일한 핸들러로 전달됩니다.

+ +

특히 유용한 사례 : {{Glossary("Node.js")}}로 코드를 작성할 때, 흔히 프로젝트에서 사용하는 모듈이 reject된 프로미스를 처리하지 않을 수 있습니다. 이런 경우 노드 실행시 콘솔에 로그가 남습니다. 이를 수집에서 분석하고 직접 처리할 수도 있습니다. 아니면 그냥 콘솔 출력을 어지럽히는 것을 막기 위해 그럴 수도 있죠. 이런 식으로 {{domxref("Window.unhandledrejection_event", "unhandledrejection")}}(영어) 이벤트를 처리하는 핸들러를 추가하면 됩니다.

+ +
window.addEventListener("unhandledrejection", event => {
+  /* You might start here by adding code to examine the
+     promise specified by event.promise and the reason in
+     event.reason */
+
+  event.preventDefault();
+}, false);
+ +

이벤트의 {{domxref("Event.preventDefault", "preventDefault()")}} 메서드를 호출하면 reject 된 프로미스가 처리되지 않았을 때 JavaScript 런타임이 기본 동작을 수행하지 않습니다. 이 기본 동작은 대개 콘솔에 오류를 기록하는 것이기 때문에, 이것은 확실히 NodeJS를 위한 것이죠.

+ +

제대로 하려면, 당연한 말이지만, 이 이벤트를 그냥 무시해버리기 전에 reject된 프로미스 코드에 실제로 버그가 없는지 확실히 검사해야 합니다.

+ +

오래된 콜백 API를 사용하여 Promise만들기

+ +

{{jsxref ( "Promise")}}는 생성자를 사용하여 처음부터 생성 될 수 있습니다. 이것은 오래된 API를 감쌀 때만 필요합니다.

+ +

이상적인 프로그래밍 세계에서는 모든 비동기 함수는 promise을 반환해야 하지만. 불행히도 일부 API는 여전히 success 및 / 또는 failure 콜백을 전달하는 방식일거라 생각합니다.. 예를 들면 {{domxref ( "WindowTimers.setTimeout", "setTimeout ()")}} 함수가 있습니다.

+ +
setTimeout(() => saySomething("10 seconds passed"), 10000);
+
+ +

예전 스타일의 콜백과 Promise를 합치는것 문제가 있습니다. 함수 saySomething()이 실패하거나 프로그래밍 오류가 있으면 아무 것도 잡아 내지 않습니다. setTimeout의 문제점 입니다.

+ +

다행히도 우리는 setTimeout을 Promise로 감쌀 수 있습니다. 가장 좋은 방법은 가능한 가장 낮은 수준에서 문제가되는 함수를 래핑 한 다음 다시는 직접 호출하지 않는 것입니다.

+ +
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
+
+wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback);
+
+ +

기본적으로 promise constructor는 promise를 직접 해결하거나 reject 할 수 있는 실행자 함수를 사용합니다. setTimeout()은 함수에서 fail이 일어나거나 error가 발생하지 않기 때문에 이 경우 reject를 사용하지 않습니다.

+ +

Composition

+ +

{{jsxref ( "Promise.resolve ()")}}와 {{jsxref ( "Promise.reject ()")}}는 각각 이미 resolve되거나 reject 된 promise를 여러분이 직접 생성하기위한 바로 가기입니다. 가끔 유용하게 사용됩니다.

+ +

{{jsxref("Promise.all()")}}와 {{jsxref("Promise.race()")}}는 비동기 작업을 병렬로 실행하기위한 두 가지 구성 도구입니다.

+ +

우리는 병렬로 작업을 시작하고 모든 작업이 다음과 같이 끝날 때까지 기다릴 수 있습니다.

+ +
Promise.all([func1(), func2(), func3()])
+.then(([result1, result2, result3]) => { /* use result1, result2 and result3 */ });
+ +

Sequential composition is possible using some clever JavaScript:

+ +

고급진 JavaScript를 사용하여 순차적 구성이 가능합니다.

+ +
[func1, func2, func3].reduce((p, f) => p.then(f), Promise.resolve())
+.then(result3 => { /* use result3 */ });
+
+ +

기본적으로 Promise.resolve().then(func1).then(func2).then(func3);과 같은 약속 체인으로 비동기 함수 배열을 축소합니다.

+ +

이것은 재사용 가능한 작성 기능으로 만들 수 있는데, 이는 함수형 프로그래밍에서 일반적인 방식입니다.

+ +
const applyAsync = (acc,val) => acc.then(val);
+const composeAsync = (...funcs) => x => funcs.reduce(applyAsync, Promise.resolve(x));
+
+ +

composeAsync() 함수는 여러 함수를 인수로 받아들이고 composition 파이프 라인을 통해 전달되는 초기 값을 허용하는 새 함수를 반환합니다.

+ +
const transformData = composeAsync(func1, func2, func3);
+const result3 = transformData(data);
+
+ +

ECMAScript 2017에서는 async / await를 사용하여 순차적 구성을보다 간단하게 수행 할 수 있습니다.

+ +
let result;
+for (const f of [func1, func2, func3]) {
+  result = await f(result);
+}
+/* use last result (i.e. result3) */
+ +

Timing

+ +

To avoid surprises, functions passed to then() will never be called synchronously, even with an already-resolved promise:

+ +

놀라움(역자 주. 에러가 난다거나, 코드가 문제가 생긴다거나..했을때의 그 놀라움..)을 피하기 위해 then()에 전달 된 함수는 already-resolved promise에 있는 경우에도 동기적으로 호출되지 않습니다.

+ +
Promise.resolve().then(() => console.log(2));
+console.log(1); // 1, 2
+
+ +

즉시 실행되는 대신 전달 된 함수는 마이크로 태스크 대기열에 저장됩니다. 즉, 자바 스크립트 이벤트 루프의 현재 실행이 끝날 때 대기열이 비면 나중에 실행됩니다.

+ +
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
+
+wait().then(() => console.log(4));
+Promise.resolve().then(() => console.log(2)).then(() => console.log(3));
+console.log(1); // 1, 2, 3, 4
+ +

Nesting

+ +
+

역자 주. 아래부분에 대한 번역이 미흡합니다. 원문을 참고해 주세요

+
+ +

간단한 promise 체인은 중첩이 부주의 한 구성의 결과 일 수 있으므로 중첩하지 않고 평평하게 유지하는 것이 가장 좋습니다. common mistakes를 참조하십시오.

+ +

(Simple promise chains are best kept flat without nesting, as nesting can be a result of careless composition. See common mistakes.)

+ +

중첩은 catch 문 범위를 제한하는 제어 구조입니다. 특히, 중첩 된 catch는 중첩 된 범위 외부의 체인에있는 오류가 아닌 범위 및 그 이하의 오류 만 잡습니다. 올바르게 사용하면 오류 복구에서보다 정확한 결과를 얻을 수 있습니다.

+ +
doSomethingCritical()
+.then(result => doSomethingOptional(result)
+  .then(optionalResult => doSomethingExtraNice(optionalResult))
+  .catch(e => {})) // Ignore if optional stuff fails; proceed.
+.then(() => moreCriticalStuff())
+.catch(e => console.log("Critical failure: " + e.message));
+
+ +

여기에 있는 선택적 단계는 들여 쓰기가 아닌 중첩되어 있지만 주위의 바깥 쪽 ( 및 ) 의 규칙적이지 않은 배치를 하지않도록 조심하세요.

+ +

inner neutralizing catch 문은 doSomethingOptional()doSomethingExtraNice()에서 발생한 오류를 catch 한 후에 코드가 moreCriticalStuff()로 다시 시작됩니다. 중요하게도 doSomethingCritical()이 실패하면 해당 오류는 최종 (외부) catch에 의해서만 포착됩니다.

+ +

Common mistakes

+ +

promise chains을 작성할 때 주의해야 할 몇 가지 일반적인 실수는 다음과 같습니다. 이러한 실수 중 몇 가지는 다음 예제에서 나타납니다.

+ +
// Bad example! Spot 3 mistakes!
+
+doSomething().then(function(result) {
+  doSomethingElse(result) // Forgot to return promise from inner chain + unnecessary nesting
+  .then(newResult => doThirdThing(newResult));
+}).then(() => doFourthThing());
+// Forgot to terminate chain with a catch!
+
+ +

첫 번째 실수는 제대로 체인을 연결하지 않는 것입니다. 이것은 우리가 새로운 promise를 만들었지 만 그것을 반환하는 것을 잊었을때 일어납니다. 결과적으로 체인이 끊어 지거나 오히려 두 개의 독립적 인 체인이 경쟁하게됩니다. 즉, doFourthThing()doSomethingElse() 또는 doThirdThing()이 완료 될 때까지 기다리지 않고 의도하지 않은 것처럼 병렬로 실행됩니다. 별도의 체인은 별도의 오류 처리 기능을 가지고있어서 잡기 어려운 오류가 발생합니다.

+ +

두 번째 실수는 불필요하게 중첩되어 첫 번째 실수를 가능하게 만드는 것입니다. 중첩은 내부 오류 처리기의 범위를 제한합니다. 의도하지 않은 경우 에러가 캐치되지 않는 오류가 발생할 수 있습니다. 이 변형은 promise constructor anti-pattern입니다.이 패턴은 이미 약속을 사용하는 코드를 감싸기 위해 promise 생성자의 중복 사용과 중첩을 결합합니다.

+ +

세 번째 실수는 catch로 체인을 종료하는 것을 잊는 것입니다. 약속되지 않은 약속 체인은 대부분의 브라우저에서 예상하지 못한 약속 거부를 초래합니다.

+ +

좋은 경험 법칙은 항상 약속의 사슬을 반환하거나 종결하는 것이며, 새로운 약속을 얻 자마자 즉각적으로 돌려서 물건을 평평하게하는 것입니다.

+ +
doSomething()
+.then(function(result) {
+  return doSomethingElse(result);
+})
+.then(newResult => doThirdThing(newResult))
+.then(() => doFourthThing())
+.catch(error => console.log(error));
+ +

() => x 은  () => { return x; }.의 축약형임을 참고하세요

+ +

이제는 적절한 오류 처리 기능을 갖춘 결정성있는 단일 체인이 있습니다.

+ +

async/await를 사용하면 대부분의 문제를 해결할 수 있습니다. 이러한 문법의 가장 흔한 실수는 await키워드를 빼먹는 것입니다.

+ +

See also

+ + + +

{{PreviousNext("Web/JavaScript/Guide/Details_of_the_Object_Model", "Web/JavaScript/Guide/Iterators_and_Generators")}}

diff --git a/files/ko/web/javascript/guide/values,_variables,_and_literals/index.html b/files/ko/web/javascript/guide/values,_variables,_and_literals/index.html new file mode 100644 index 0000000000..629cbd069a --- /dev/null +++ b/files/ko/web/javascript/guide/values,_variables,_and_literals/index.html @@ -0,0 +1,708 @@ +--- +title: 문법과 자료형 +slug: 'Web/JavaScript/Guide/Values,_variables,_and_literals' +tags: + - Guide + - JavaScript + - 'l10n:priority' +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/소개", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
+ +

이 장은 JavaScript의 기본 문법과 변수 선언, 자료형 및 리터럴을 다룹니다.

+ +

기본

+ +

JavaScript는 문법의 대부분을 Java와 C, C++로부터 차용하고 있으며, Awk, Perl, Python의 영향도 받았습니다.

+ +

JavaScript는 대소문자를 구별하며 유니코드 문자셋을 이용합니다. 따라서 다음과 같은 코드도 유효합니다.

+ +
var 갑을 = "병정";
+var Früh = "foobar"; // Früh: 독일어로 "이른"
+
+ +

하지만 Frühfrüh와 다릅니다. 대소문자를 구분하기 때문입니다.

+ +

JavaScript에서는 명령을 {{Glossary("Statement", "명령문(statement)")}}이라고 부르며, 세미콜론(;)으로 구분합니다.

+ +

명령문이 한 줄을 다 차지할 경우에는 세미콜론이 필요하지 않습니다. 그러나 한 줄에 두 개 이상의 명령문이 필요하다면 세미콜론으로 구분해야 합니다. ECMAScript는 세미콜론을 자동으로 삽입해 명령문을 끝내는 규칙(ASI)도 가지고 있습니다. (더 많은 정보는 JavaScript의 어휘 문법 에 대한 자세한 참고서를 참고하세요) 하지만, 세미콜론이 필요하지 않은 경우라도 항상 세미콜론으로 끝마치는 편이 버그 예방 차원에서 더 좋은 습관이라고 여겨집니다.

+ +

JavaScript의 스크립트 소스는 왼쪽에서 오른쪽으로 탐색하면서 토큰, 제어 문자, 줄바꿈 문자, 주석이나 공백으로 이루어진 입력 element의 시퀀스로 변환됩니다. 스페이스, 탭, 줄바꿈 문자는 공백으로 간주됩니다.

+ +

주석

+ +

주석의 구문은 C++ 및 다른 많은 언어와 똑같습니다.

+ +
// 한 줄 주석
+
+/* 이건 더 긴,
+ * 여러 줄 주석입니다.
+ */
+
+/* 그러나, /* 중첩된 주석은 쓸 수 없습니다 */ SyntaxError */
+ +

주석은 공백처럼 행동하며 스크립트 실행 시 버려집니다.

+ +
+

참고: 몇몇 자바스크립트 파일의 시작부에 #!/usr/bin/env node와 같은 형태의 주석 문법이 쓰이는 것을 볼 수 있습니다. 이것은 해시백 주석 문법이라고 하는데, 이 특별한 주석은 스크립트를 실행할 때 쓸 특별한 자바스크립트 인터프리터의 경로를 설정할 때 쓰입니다.  해시백 주석을 참고하여 자세한 내용을 확인할 수 있습니다.

+
+ +

선언

+ +

JavaScript의 선언에는 3가지 방법이 있습니다.

+ +
+
{{jsxref("Statements/var", "var")}}
+
변수를 선언. 추가로 동시에 값을 초기화.
+
{{jsxref("Statements/let", "let")}}
+
블록 범위(scope) 지역 변수를 선언. 추가로 동시에 값을 초기화.
+
{{jsxref("Statements/const", "const")}}
+
블록 범위 읽기 전용 상수를 선언.
+
+ +

변수

+ +

어플리케이션에서 값에 상징적인 이름으로 변수를 사용합니다. 변수명은 {{Glossary("식별자(identifier)")}}라고 불리며 특정 규칙을 따릅니다.

+ +

JavaScript 식별자는 문자, 밑줄(_) 혹은 달러 기호($)로 시작해야 하는 반면 이후는 숫자(0-9)일 수도 있습니다. JavaScript가 대소문자를 구분하기에, 문자는 "A"부터 "Z"(대문자)와 "a"부터 "z"(소문자)까지 모두 포함합니다.

+ +

ISO 8859-1 혹은 Unicode 문자(가령 å 나 ü)도 식별자에 사용할 수 있습니다(좀 더 상세한 내용은 이 블로그 글을 참고). 또한 Unicode escape sequences도 식별자에 문자로 사용할 수 있습니다.

+ +

적절한 이름으로는 Number_hits, temp99, $credit_name등입니다.

+ +

변수 선언

+ +

변수 선언은 아래 3가지 방법으로 가능합니다.

+ + + +

간단히 변수에 값을 할당 할 수도 있습니다. 예를 들어, x = 42 와 같은 구문은 선언되지 않는 전역변수 를 만듭니다. 뿐만 아니라, 자바스크립트의 엄격한 경고를 만들어냅니다. 선언되지 않은 전역변수는 의도되지 않은 동작을 만들어내고는 합니다. 따라서 선언되지 않는 전역변수를 사용하면 안됩니다.

+ +

변수 할당

+ +

지정된 초기값 없이 var 혹은 let 문을 사용해서 선언된 변수는 {{jsxref("undefined")}} 값을 갖습니다.

+ +

선언되지 않은 변수에 접근을 시도하는 경우 {{jsxref("ReferenceError")}} 예외가 발생합니다.

+ +
var a;
+console.log("a 값은 " + a); // "a 값은 undefined"로 로그가 남음.
+
+console.log('b 값은 ' + b); // b 값은 undefined
+var b;
+
+console.log("c 값은 " + c); // ReferenceError 예외 던짐
+
+let x;
+console.log('x 값은 ' + x); // x 값은 undefined
+
+console.oog('y 값은 ' + y); // ReferenceError 예외 던짐
+let y;
+
+ +

undefined를 사용하여 변수값이 있는지 확인할 수 있습니다. 아래 코드에서, input 변수는 값이 할당되지 않았고 if문은 true로 평가합니다.

+ +
var input;
+if(input === undefined) {
+  doThis();
+} else {
+  doThat();
+}
+
+ +

undefined 값은 boolean 문맥(context)에서 사용될 때 false로 동작합니다. 예를 들어, 아래 코드는 myArray 요소가 undefined이므로 myFunction 함수를 실행합니다.

+ +
var myArray = [];
+if (!myArray[0]) myFunction();
+
+ +

undefined 값은 수치 문맥에서 사용될 때 NaN으로 변환됩니다.

+ +
var a;
+a + 2; // NaN으로 평가
+ +

{{jsxref("null")}} 값을 평가할 때, 수치 문맥에서는 0으로, boolean 문맥에서는 false로 동작합니다. 예를 들면,

+ +
var n = null;
+console.log(n * 32); // 콘솔에 0 으로 로그가 남음.
+
+ +

변수 범위

+ +

어떤 함수의 바깥에 변수를 선언하면, 현재 문서의 다른 코드에 해당 변수를 사용할 수 있기에 전역 변수라고 합니다. 만약 함수 내부에 변수를 선언하면, 오직 그 함수 내에서만 사용할 수 있기에 지역 변수라고 부릅니다.

+ +

ECMAScript 6 이전의 JavaScript는 block 문 범위가 없습니다. 그래서 오히려, 블록 내에 선언된 변수는 그 블록 내에 존재하는 함수(혹은 전역 범위)에 지역적입니다. 예를 들어서 아래의 코드는 5라는 로그를 남깁니다. x의 범위가 이 경우 if문 블록이 아니라 x가 선언된 함수(나 전역 문맥)이기 때문입니다.

+ +
if (true) {
+  var x = 5;
+}
+console.log(x); // 5
+
+ +

ECMAScript 6에 도입된 let 선언을 사용했을 때, 이 동작은 바뀌었습니다.

+ +
if (true) {
+  let y = 5;
+}
+console.log(y); // ReferenceError: y is not defined
+ +

변수 호이스팅

+ +

또 다른 JavaScript 변수의 특이한 점은 예외를 받지 않고도, 나중에 선언된 변수를 참조할 수 있다는 것입니다. 이 개념은 호이스팅(hoisting)으로 알려져 있습니다. 즉 JavaScript 변수가 어떤 의미에서 "끌어올려지거"나 함수나 문의 최상단으로 올려지는 것을 말합니다. 하지만, 끌어올려진 변수는 undefined 값을 반환합니다. 그래서 심지어 이 변수를 사용 혹은 참조한 후에 선언 및 초기화하더라도, 여전히 undefined를 반환합니다.

+ +
/**
+ * Example 1
+ */
+console.log(x === undefined); // logs "true"
+var x = 3;
+
+
+/**
+ * Example 2
+ */
+// undefined 값을 반환함.
+var myvar = "my value";
+
+(function() {
+  console.log(myvar); // undefined
+  var myvar = "local value";
+})();
+
+ +

위 예제는 아래 예제와 동일하게 볼 수 있습니다.

+ +
/**
+ * Example 1
+ */
+var x;
+console.log(x === undefined); // logs "true"
+x = 3;
+
+/**
+ * Example 2
+ */
+var myvar = "my value";
+
+(function() {
+  var myvar;
+  console.log(myvar); // undefined
+  myvar = "local value";
+})();
+ +

호이스팅 때문에, 함수 내의 모든 var 문은 가능한 함수 상단 근처에 두는 것이 좋습니다. 이 방법은 코드를 더욱 명확하게 만들어줍니다.

+ +

ECMAScript 2015의 let (const)는 변수를 블록의 상단으로 올리지 않습니다.
+ 변수가 선언되기 전에 블록 안에서 변수를 참조하게 되면 {{jsxref("ReferenceError")}}를 발생시키게 됩니다.
+ 변수는 블록 시작부터 선언이 처리될 때까지 'temporal dead zone'에 위치하게 됩니다.

+ +
console.log(x); // ReferenceError
+let x = 3;
+
+ +

함수 호이스팅

+ +

함수에서는 단지 함수 선언만 상단으로 끌어올려집니다. 함수 표현식은 그렇지 않습니다.

+ +
/* 함수 선언 */
+
+foo(); // "bar"
+
+function foo() {
+  console.log('bar');
+}
+
+
+/* 함수 표현식 */
+
+baz(); // TypeError: baz is not a function
+
+var baz = function() {
+  console.log('bar2');
+};
+ +

전역 변수

+ +

전역 변수는 사실 global 객체의 속성(property)입니다. 웹 페이지에서 global 객체는 {{domxref("window")}} 이므로, windows.variable 구문을 통해 전역 변수를 설정하고 접근할 수 있습니다.

+ +

그 결과, window 혹은 frame의 이름을 지정하여 한 window 혹은 frame에서 다른 window 혹은 frame에 선언된 전역 변수에 접근할 수 있습니다. 예를 들어, phoneNumber 라는 변수가 문서에 선언된 경우, iframe에서 parent.phoneNumber로 이 변수를 참조할 수 있습니다.

+ +

상수

+ +

{{jsxref("Statements/const", "const")}} 키워드로 읽기 전용 상수를 만들 수 있습니다. 상수 식별자의 구문은 변수 식별자와 같습니다. 문자, 밑줄이나 달러 기호로 시작해야 하고 문자, 숫자나 밑줄을 포함할 수 있습니다.

+ +
const PI = 3.14;
+
+ +

상수는 스크립트가 실행 중인 동안 대입을 통해 값을 바꾸거나 재선언될 수 없습니다. 값으로 초기화해야 합니다.

+ +

상수에 대한 범위 규칙은 let 블록 범위 변수와 동일합니다. 만약 const 키워드가 생략된 경우에는, 식별자는 변수를 나타내는 것으로 간주됩니다.

+ +

상수는 같은 범위에 있는 함수나 변수와 동일한 이름으로 선언할 수 없습니다. 예를 들어,

+ +
// 오류가 발생합니다
+function f() {};
+const f = 5;
+
+// 역시 오류가 발생합니다
+function f() {
+  const g = 5;
+  var g;
+
+  //statements
+}
+
+ +

그러나, 상수에 할당된 객체의 속성은 보호되지 않아서 다음의 문은 문제없이 실행됩니다.

+ +
const MY_OBJECT = {'key': 'value'};
+MY_OBJECT.key = 'otherValue';
+
+ +

또한, 배열의 내용도 보호되지 않아서 다음의 문도 문제없이 실행됩니다.

+ +
const MY_ARRAY = ['HTML','CSS'];
+MY_ARRAY.push('JAVASCRIPT');
+console.log(MY_ARRAY); //logs ['HTML','CSS','JAVASCRIPT'];
+
+ +

데이터 구조 및 형

+ +

데이터 형

+ +

최신 ECMAScript 표준은 7가지 데이터 형을 정의합니다.

+ + + +

이 데이터 형이 비교적 많지 않지만, 어플리케이션에 유용한 기능을 수행할 수 있습니다. {{jsxref("Object", "객체")}}와 {{jsxref("Function", "함수")}}는 언어의 다른 기본 요소입니다. 객체는 값을 위한 컨테이너, 함수는 어플리케이션이 수행할 수 있는 절차(procedure)로 생각할 수 있습니다.

+ +

자료형 변환

+ +

JavaScript는 동적 형지정(정형) 언어입니다. 이는 변수를 선언할 때 데이터 형을 지정할 필요가 없음을 의미합니다. 또한 데이터 형이 스크립트 실행 도중 필요에 의해 자동으로 변환됨을 뜻합니다. 그래서, 예를 들어, 다음과 같이 변수를 정의할 수 있습니다.

+ +
var answer = 42;
+ +

그리고 나중에, 동일한 변수에 문자열 값을 할당할 수도 있습니다. 아래와 같이,

+ +
answer = "Thanks for all the fish...";
+
+ +

JavaScript는 동적 형지정 언어이므로, 이 할당은 오류 메시지가 발생하지 않습니다.

+ +

숫자와 문자열 값 사이에 + 연산자를 포함한 식에서, JavaScript는 숫자 값을 문자열로 변환합니다. 예를 들어, 아래와 같은 문이 있습니다.

+ +
x = "The answer is " + 42 // "The answer is 42"
+y = 42 + " is the answer" // "42 is the answer"
+ +

다른 연산자를 포함한 식의 경우, JavaScript는 숫자 값을 문자열로 변환하지 않습니다. 예를 들면,

+ +
"37" - 7 // 30
+"37" + 7 // 377
+
+ +

문자열을 숫자로 변환하기

+ +

숫자를 나타내는 값이 문자열로 메모리에 있는 경우, 변환을 위한 메서드가 있습니다.

+ + + +

parseInt는 오직 정수만 반환하므로, 소수에서는 사용성이 떨어집니다. 게다가 parseInt를 잘 사용하기 위해서는 항상 진법(Radix) 매개변수를 포함해야 합니다. 진법 매개변수는 변환에 사용될 진법을 지정하는데 사용됩니다.

+ +

문자열을 숫자로 변환하는 대안은 +(단항 더하기) 연산자입니다.

+ +
"1.1" + "1.1" = "1.11.1"
+(+"1.1") + (+"1.1") = 2.2
+// 참고: 괄호는 명확성을 위해 추가, 필요한 것은 아닙니다.
+
+ +

리터럴

+ +

JavaScript에서 값을 나타내기 위해 리터럴을 사용합니다. 이는 말 그대로 스크립트에 부여한 고정값으로, 변수가 아닙니다. 이 절에서는 다음과 같은 형태의 리터럴을 설명합니다.

+ + + +

배열 리터럴

+ +

배열 리터럴은 0개 이상의 식(expression) 목록입니다. 각 식은 배열 요소를 나타내고 대괄호([])로 묶입니다. 배열 리터럴을 사용하여 배열을 만들 때, 그 요소로 지정된 값으로 초기화되고, 그 길이는 지정된 인수의 갯수로 설정됩니다.

+ +

아래 예제는 요소가 3개로 길이가 3인 coffees 배열을 만듭니다.

+ +
var coffees = ["French Roast", "Colombian", "Kona"];
+
+ +
+

참고: 배열 리터럴은 일종의 객체 이니셜라이저(initialiizer)입니다. Using Object Initializers 참고.

+
+ +

배열이 최상단 스크립트에서 리터럴을 사용하여 만들어진 경우, JavaScript는 배열 리터럴을 포함한 식을 평가할 때마다 배열로 해석합니다. 게다가, 함수에서 사용되는 리터럴은 함수가 호출될 때마다 생성됩니다.

+ +

배열 리터럴은 배열 객체입니다. 배열 객체에 대한 자세한 내용은 {{jsxref("Array")}}와 Indexed collections 참고.

+ +

배열 리터럴의 추가 쉼표

+ +

배열 리터럴에서 모든 요소를 지정할 필요는 없습니다. 만약 잇달아 두 개의 쉼표를 두면, 배열은 지정되지 않은 요소를 undefined로 만듭니다. 다음 예제는 fish 배열을 만듭니다.

+ +
var fish = ["Lion", , "Angel"];
+
+ +

이 배열은 값이 있는 두 요소와 빈 요소 하나를 가집니다(fish[0]은 "Lion", fish[1]undefined, fish[2]는 "Angel").

+ +

만약 요소 목록을 후행(trailing) 쉼표로 끝낸다면, 그 쉼표는 무시됩니다. 다음 예제에서, 배열의 길이는 3입니다. myList[3]은 없습니다. 목록의 다른 모든 쉼표는 새로운 요소를 나타냅니다.

+ +
+

참고: 후행 쉼표는 구버전 브라우저에서 오류를 유발할 수 있으므로 제거하는게 최선입니다.

+
+ +
var myList = ['home', , 'school', ];
+
+ +

아래 예제에서, 배열의 길이는 4이며, myList[0]myList[2]는 값이 빠졌습니다.

+ +
var myList = [ , 'home', , 'school'];
+
+ +

아래 예제에서, 배열의 길이는 4이며, myList[1]myList[3]은 값이 빠졌습니다. 마지막 쉼표는 무시됩니다.

+ +
var myList = ['home', , 'school', , ];
+
+ +

추가 쉼표의 동작을 이해하는 것은 JavaScript를 언어로서 이해하는데 중요하지만, 코드를 작성할 때는 빠진 요소의 값을 명시적으로 undefined로 선언하는 것이 코드의 명확성과 유지보수성을 높입니다.

+ +

불리언 리터럴

+ +

불리언 형은 truefalse의 리터럴 값을 가집니다.

+ +

원시 불린 값 truefalse와 Boolean 객체의 true 및 false 값을 혼동하지 마세요. Boolean 객체는 원시 불린 데이터 형을 감싸는 래퍼(wrapper)입니다. 더 많은 정보는 {{jsxref("Boolean")}}을 참고하세요.

+ +

정수 리터럴

+ +

정수는 10진, 16진, 8진 및 2진수로 표현될 수 있습니다.

+ + + +

다음은 정수 리터럴 예제입니다.

+ +
0, 117 및 -345 (10진수)
+015, 0001 및 -0o77 (8진수)
+0x1123, 0x00111 및 -0xF1A7 (16진수)
+0b11, 0b0011 및 -0b11 (2진수)
+
+ +

더 많은 정보는 Lexical grammar reference의 Numeric literals를 참고하세요.

+ +

부동 소수점 리터럴

+ +

부동 소수점 리터럴은 아래와 같은 부분으로 이루어집니다.

+ + + +

지수부는 "e"나 "E" 다음에 오며 부호("+"나 "-")가 달릴 수 있는 정수입니다. 부동 소수점 리터럴은 적어도 숫자 하나와 소수점 혹은 "e"(나 "E")가 있어야 합니다.

+ +

더 간결하게 설명하면, 구문은 다음과 같습니다.

+ +
[(+|-)][digits][.digits][(E|e)[(+|-)]digits]
+
+ +

예를 들면,

+ +
3.1415926
+-.123456789
+-3.1E+12
+.1e-23
+
+ +

객체 리터럴

+ +

객체 리터럴은 중괄호({})로 묶인 0개 이상인 객체의 속성명과 관련 값 쌍 목록입니다. 문의 시작에 객체 리터럴을 사용해서는 안됩니다. 이는 {가 블록의 시작으로 해석되기 때문에 오류를 이끌거나 의도한 대로 동작하지 않습니다.

+ +

아래는 객체 리터럴의 예제입니다. car 객체의 첫째 요소는 myCar 속성을 정의하고 문자열 "Saturn"을 할당합니다. 반면 둘째 요소인 getCar 속성은 function (carTypes("Honda"))을 호출한 결과가 즉시 할당됩니다. 셋째 요소 special 속성은 기존 변수 sales를 사용합니다.

+ +
var sales = "Toyota";
+
+function carTypes(name) {
+  if (name === "Honda") {
+    return name;
+  } else {
+
+  }
+    return "Sorry, we don't sell " + name + ".";
+}
+
+var car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales };
+
+console.log(car.myCar);   // Saturn
+console.log(car.getCar);  // Honda
+console.log(car.special); // Toyota
+
+ +

게다가, 속성명으로 숫자나 문자열 리터럴을 사용하거나 또다른 객체 리터럴 내부에 객체를 중첩할 수도 있습니다. 아래 예제는 이 옵션을 사용합니다.

+ +
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
+
+console.log(car.manyCars.b); // Jeep
+console.log(car[7]); // Mazda
+
+ +

객체 속성명은 빈 문자열 포함 어떤 문자열도 될 수 있습니다. 속성명이 유효한 JavaScript {{Glossary("식별자")}}나 숫자가 아닌 경우, 따옴표로 묶여야 합니다. 또한 유효한 식별자가 아닌 속성명은 점(.) 속성으로 접근할 수 없습니다. 대신 배열 같은 표기법("[]")으로 접근하고 값을 설정할 수 있습니다.

+ +
var unusualPropertyNames = {
+  "": "An empty string",
+  "!": "Bang!"
+}
+console.log(unusualPropertyNames."");   // SyntaxError: Unexpected string
+console.log(unusualPropertyNames[""]);  // An empty string
+console.log(unusualPropertyNames.!);    // SyntaxError: Unexpected token !
+console.log(unusualPropertyNames["!"]); // Bang!
+
+ +

향상된 객체 리터럴

+ +

ES2015에서, 객체 리터럴은 구성에서 프로토타입 설정, foo: foo 할당을 위한 단축 표기, 메서드 정의, super 클래스 호출 및 식으로 동적인 속성명 계산을 지원하기 위해 확장됐습니다. 그에 따라 객체 리터럴 및 클래스 선언이 함께 더 가까워지고, 객체 기반 설계는 같은 일부 편의기능으로 득을 볼 수 있습니다.

+ +
var obj = {
+    // __proto__
+    __proto__: theProtoObj,
+    // ‘handler: handler’의 단축 표기
+    handler,
+    // Methods
+    toString() {
+     // Super calls
+     return "d " + super.toString();
+    },
+    // Computed (dynamic) property names
+    [ 'prop_' + (() => 42)() ]: 42
+};
+ +

아래를 참고하세요.

+ +
var foo = {a: "alpha", 2: "two"};
+console.log(foo.a);    // alpha
+console.log(foo[2]);   // two
+//console.log(foo.2);  // Error: missing ) after argument list
+//console.log(foo[a]); // Error: a is not defined
+console.log(foo["a"]); // alpha
+console.log(foo["2"]); // two
+
+ +

정규식 리터럴

+ +

정규식 리터럴은 (정규식 상세) 슬래시 사이에 감싸인 패턴입니다. 다음은 정규식 리터럴 예제입니다.

+ +
var re = /ab+c/;
+ +

문자열 리터럴

+ +

문자열 리터럴은 큰 따옴표(") 혹은 작은 따옴표(')로 묶인 0개 이상의 문자입니다. 문자열은 같은 형 따옴표, 즉 큰 따옴표 쌍이나 작은 따옴표 쌍으로 구분되어야 합니다. 아래는 문자열 리터럴의 예제입니다.

+ +
"foo"
+'bar'
+"1234"
+"one line \n another line"
+"John's cat"
+
+ +

문자열 리터럴 값은 문자열 객체의 모든 메서드를 호출할 수 있습니다. JavaScript는 자동으로 문자열 리터럴을 임시 문자열 객체로 변환, 메서드를 호출하고 나서 임시 문자열 객체를 폐기합니다. 또한 문자열 리터럴에서도 String.length 속성을 사용할 수 있습니다.

+ +
console.log("John's cat".length)
+// 공백을 포함한 문자열 내 심볼 갯수가 출력됩니다.
+// 여기서는, 10.
+
+ +

ES2015에서는, 템플릿 리터럴도 사용할 수 있습니다. 템플릿 문자열은 문자열 구성을 위한 달콤한 구문을 제공합니다. 이는 Perl, Python 등에 있는 문자열 삽입(interpolation) 기능과 비슷합니다. 마음대로, 문자열 구성을 사용자 정의하고 인젝션 공격을 피하거나 문자열 콘텐츠로 더 고레벨 데이터 구조를 구성하기 위한 태그가 추가될 수 있습니다.

+ +
// 기본적인 문자열 리터럴 생성
+`In JavaScript '\n' is a line-feed.`
+
+// 여러 줄 문자열
+`In JavaScript this is
+ not legal.`
+
+// 문자열 삽입
+var name = "Bob", time = "today";
+`Hello ${name}, how are you ${time}?`
+
+// Construct an HTTP request prefix is used to interpret the replacements and construction
+POST`http://foo.org/bar?a=${a}&b=${b}
+     Content-Type: application/json
+     X-Credentials: ${credentials}
+     { "foo": ${foo},
+       "bar": ${bar}}`(myOnReadyStateChangeHandler);
+ +

꼭 문자열 객체를 사용할 필요가 없는 경우 문자열 리터럴을 사용해야 합니다. 문자열 객체에 대해 자세한 사항은 {{jsxref("String")}}을 참고하세요.

+ +

문자열에서 특수 문자 사용

+ +

보통 문자에 더해서, 문자열에 아래 예제와 같이 특수 문자도 포함할 수 있습니다.

+ +
"one line \n another line"
+
+ +

다음 표는 JavaScript 문자열에 사용할 수 있는 특수 문자 목록입니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
표: JavaScript 특수 문자
문자
\0Null Byte
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tTab
\vVertical tab
\'Apostrophe 혹은 작은 따옴표
\"큰 따옴표
\\백슬래시
\XXXLatin-1 인코딩 문자는 0 - 377 사이 8진수 3자리까지 지정될 수 있습니다. 예를 들어, \251은 copyright 심볼을 표현하는 8진수 시퀀스입니다.
\xXXLatin-1 인코딩 문자는 00 - FF 사이의 16진수 2자리로 지정될 수 있습니다. 예를 들어, \xA9는 copyright 심볼을 표현하는 16진수 시퀀스입니다.
\uXXXX유니코드 문자는 16진수 4자리로 지정될 수 있습니다. 예를 들어, \u00A9는 copyright 심볼을 표현하는 유니코드 열입니다. Unicode escape sequences를 참고하세요.
\u{XXXXX}유니코드 코드 포인트 이스케이프. 예를 들어, \u{2F804}는 간단한 유니코드 이스케이프 \uD87E\uDC04와 같습니다.
+ +

문자 이스케이프

+ +

표에 없는 문자의 경우 전행 백슬래시는 무시되지만, 이 용법은 더 이상 사용되지 않으며, 사용을 피해야 합니다.

+ +

전행 백슬래시와 함께 문자열 안에 따옴표를 사용할 수 있습니다. 이것을 따옴표 이스케이프라고 합니다. 예를 들어,

+ +
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
+console.log(quote);
+
+ +

이 코드의 결과는,

+ +
He read "The Cremation of Sam McGee" by R.W. Service.
+
+ +

백슬래시를 문자열 내에 포함시키기 위해서는, 백슬래시 문자를 이스케이프 해야 합니다. 예를 들어, 파일 경로 c:\temp를 문자열에 할당하기 위해서는 아래와 같이 사용합니다.

+ +
var home = "c:\\temp";
+
+ +

또한 줄바꿈 역시 전행 백슬래시로 이스케이프할 수 있습니다. 백슬래시와 줄바꿈 모두 문자열 값에서는 사라집니다.

+ +
var str = "this string \
+is broken \
+across multiple\
+lines."
+console.log(str);   // this string is broken across multiplelines.
+
+ +

JavaScript에는 "heredoc" 구문은 없지만, 줄바꿈 이스케이프와 각 줄 끝 이스케이프된 줄바꿈을 추가하여 흉내낼 수 있습니다.

+ +
var poem =
+"Roses are red,\n\
+Violets are blue.\n\
+I'm schizophrenic,\n\
+And so am I."
+
+ +

ECMAScript 2015에서는 템플릿 리터럴(template literals)이라는 새로운 리터럴이 소개되었습니다. 이 것은 다중 문자열을 포함한 많은 새로운 기능을 가지고 있습니다!

+ +
var poem =
+`Roses are red,
+Violets are blue.
+Sugar is sweet,
+and so is foo.`
+
+ +

추가 정보

+ +

이 장은 선언과 형에 대한 기본 구문에 초점을 맞춥니다. JavaScript 언어 구조에 대해 더 많이 배우려면, 다음 장을 참고하세요.

+ + + +

다음 장에서는, 흐름 제어 구조와 오류 처리를 살핍니다.

+ +

{{PreviousNext("Web/JavaScript/Guide/소개", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}

diff --git a/files/ko/web/javascript/guide/working_with_objects/index.html b/files/ko/web/javascript/guide/working_with_objects/index.html new file mode 100644 index 0000000000..192e22604c --- /dev/null +++ b/files/ko/web/javascript/guide/working_with_objects/index.html @@ -0,0 +1,500 @@ +--- +title: Working with objects +slug: Web/JavaScript/Guide/Working_with_Objects +translation_of: Web/JavaScript/Guide/Working_with_Objects +--- +

자바스크립트는 간단한 객체기반 패러다임 상에서 만들어졌다. 객체는 프로퍼티의 모음이며, 프로퍼티는 "이름"(name 또는 key)과 "값"(value)의 연결로 이루어진다 . 프로퍼티의 값으로 함수가 될 수 있는데, 이런 프로퍼티는 메소드라고 불린다. 브라우저 안에 미리 정의 된 객체뿐 아니라 사용자들이 직접 자신만의 객체를 정의할 수도 있다.

+ +

이 절에서는 객체, 프로퍼티, 함수, 메소드가 어떻게 사용되는지, 그리고 사용자를 위한 새로운 객체를 생성하는 방법을 설명한다

+ +

개요

+ +

자바스크립트에서의 객체는 다른 프로그래밍 언어에서와 비슷하게 현실 세계에서의 사물(objects)과 비교해 볼 수 있다. 자바스크립트에서의 객체의 개념은 실세계상에서의 인식 가능한 사물로 이해할 수 있다.

+ +

객체는 단독으로 존재 가능한 개체(entity)이며, 프로퍼티(property)과 타입(type)을 가진다. 예를 들어 컵과 비교를 해 본다면 컵은 사물 객체인데 색깔, 모양, 무게, 재료 등의 속성(프로퍼티)을 가지고 있다. 비슷하게 자바스크립트의 객체는 그 특징을 결정짓는 여러 프로퍼티를 가진다.

+ +

객체와 프로퍼티

+ +

자바스크립트의 객체에는 그와 연관된 프로퍼티가 있다. 프로퍼티는 객체에 붙은 변수(variable)라고 설명할 수 있겠다. 객체의 프로퍼티는 일반 자바스크립의 변수와 기본적으로 똑같은데, 다만 객체에 속해있다는 차이만 있을 뿐이다. 객체의 프로퍼티들이 객체의 특징을 규정한다. 프로퍼티에 접근할 때는 도트(점) 표기법을 사용한다.

+ +
objectName.propertyName
+
+ +

자바스크립트의 모든 변수가 그렇듯이, 객체의 이름과 프로퍼티 이름은 모두 대소문자를 구별한다. 프로퍼티를 새로 정의하려면 그냥 이름과 값을 추가하면 된다. 예를 들어 myCar 라는 이름의 객체를 생성하고, 거기에 make, model, and year 라는 프로퍼티들을 추가해보자:

+ +
var myCar = new Object();
+myCar.make = "Ford";
+myCar.model = "Mustang";
+myCar.year = 1969;
+
+ +

대괄호 표기법을 사용하여 객체의 프로퍼티에 접근할 수 있다. 객체는 연관배열(associative arrays)이라고도 불리는데, 각 프로퍼티는 하나의 문자열 이름과 연관되어(associated) 이것을 통해 접근할 수 있기 때문이다. 예를 들면 myCar 객체의 프로퍼티에 다음과 같이 접근할 수 있다.

+ +
myCar["make"] = "Ford";
+myCar["model"] = "Mustang";
+myCar["year"] = 1969;
+
+ +

객체의 프로퍼티 이름은 유효한 자바스크립트 문자열이거나 문자열로 변환이 가능한 것이면 어떤 것이든 가능하며, 심지어 빈 문자열도 된다. 하지만 자바스크립트 식별자(identifier)로 적합하지 않으면 (예 : 하이픈, 빈칸을 포함하거나 숫자로 시작하는 이름), 대괄호를 이용한 표기법으로만 접근이 가능하다. 이 표기법은 프로퍼티 이름이 사전에 미리 결정되지 않고 런타임 시점에 결정되는 경우에 특히 유용하다. 아래의 예를 보자.

+ +
var myObj = new Object(),
+    str = "myString",
+    rand = Math.random(),
+    obj = new Object(); // 변수 4개를 콤마를 사용하여 한번에 생성하고 할당.
+
+myObj.type              = "Dot syntax";
+myObj["date created"]   = "String with space";
+myObj[str]              = "String value";
+myObj[rand]             = "Random Number";
+myObj[obj]              = "Object";
+myObj[""]               = "Even an empty string";
+
+console.log(myObj);
+
+ +

변수에 저장된 문자열을 이용해서도 프로퍼티에 접근할 수 있다.

+ +
+
var propertyName = "make";
+myCar[propertyName] = "Ford";
+
+propertyName = "model";
+myCar[propertyName] = "Mustang";
+
+
+ +

대괄호 표기법을 for...in 과 함께 사용하면 객체의 열거가능한 프로퍼티를 나열할 수 있다. 이것이 어떻게 작동하는지 알기 위해 아래의 함수를 보자. 이 함수는 객체와 객체 이름을 함수의 인자로 전달받아서 객체의 프로퍼티들을 출력해 준다.

+ +
function showProps(obj, objName) {
+  var result = "";
+  for (var i in obj) {
+    if (obj.hasOwnProperty(i)) {
+        result += objName + "." + i + " = " + obj[i] + "\n";
+    }
+  }
+  return result;
+}
+
+ +

showProps(myCar, "myCar") 함수를 호출하면 다음과 같은 문자열을 반환한다.

+ +
myCar.make = Ford
+myCar.model = Mustang
+myCar.year = 1969
+ +

모든 것이 객체

+ +

자바스크립트 세상에서는 거의 모든 것들이 객체이다. null 과 undefined 를 제외한 모든 원시 타입도 객체로 취급된다. 이러한 원시 타입들에도 프로퍼티가 추가될 수 있고 (설명 필요: assigned properties of some types are not persistent), 모두 객체로서의 특징을 갖는다.

+ +

객체의 프로퍼티 나열하기

+ +

ECMAScript 5 를 기준으로 객체의 프로퍼티를 나열/순회하는 방법이 세 가지 있다.

+ + + +

ECMAScript 5 이전 버전에서는 객체의 모든 프로퍼티를 나열하는 자체적인 방법이 제공되지 않았다. 하지만 아래 함수를 이용하면 가능하다.

+ +
function listAllProperties(o){
+	var objectToInspect;
+	var result = [];
+
+	for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)){
+		result = result.concat(Object.getOwnPropertyNames(objectToInspect));
+	}
+
+	return result;
+}
+
+ +

이 트릭은 객체의 "숨겨진" 프로퍼티를 알아내는 데 유용하다. (숨겨진 프로퍼티란 프로토타입 체인 상의 프로퍼티 중 객체를 통해 접근이 불가능한 것들을 말하는데 동일 이름의 다른 프로퍼티가 프로퍼티 체인 상에서 먼저 존재하는 경우에 발생한다).  만약 접근 가능한 프로퍼티만 나열하고 싶다면 배열에서 중복되는 프로퍼티들을 제거하면 된다.

+ +

객체 생성하기

+ +

자바스크립트에는 미리 정의된 객체가 몇 개 존재한다. 사용자는 여기에 추가적으로 자신의 객체를 생성할 수 있다. 자바스크립트 1.2 부터는 객체 이니셜라이저(initializer) 를 이용하여 객체를 생성할 수 있다. 또 다른 방법으로는 먼저 생성자 함수를 정의한 후 이 함수와 new 연산자를 이용하여 인스턴스를 만들수 있다.

+ +

객체 이니셜라이저

+ +

생성자 함수를 사용하는 방법 대신, 객체 이니셜라이저를 사용하여 객체를 생성할 수 있다. 이 방식은 때때로 "리터럴 표기에 의한 객체 생성"(creating objects with literal notation) 이라고도 불린다. 객체 이니셜라이저라는 단어는 C++ 에서도 비슷한 의미로 사용된다.

+ +

객체 이니셜라이저를 이용한 객체 생성의 문법은 다음과 같다.

+ +
var obj = { property_1:   value_1,   // property_# may be an identifier...
+            2:            value_2,   // or a number...
+            // ...,
+            "property n": value_n }; // or a string 
+ +

obj는 새로 만들어질 객체 이름이고, property_i는 식별자 (이름, 숫자, 또는 스트링 리터럴), value_i 는 수식인데 이 값이 property_i 에 할당 된다. obj 변수에 할당 (assignment =) 하는 것은 선택 사항이다; 이 생성된 객체를 다른 곳에서 참조할 필요가 없다면 변수에 할당하지 않아도 된다. (만약 이 생성된 객체를 변수를 사용하지 않고 구문 안에서 바로 사용하려면 블럭 구문과 혼돈되지 않도록 리터널을 괄호로 감싸줄 필요가 있다.)

+ +

객체 이니셜라이저는 수식이고, 각각의 이니셜라이저가 포함된 구문이 실행될 때 마다 이니셜라이저 수식에 의해 새로운 객체가 하나씩 생성이 된다. 똑같은 이니셜라이저에 의해 생성된 객체라도 서로 별개이며 비교 결과는 동일하지 않음 (not equal) 이 된다. 객체는 마치 new Object() 호출이 실행된 것 처럼 생성이 된다; 즉, 객체 이니셜라이저 수식에 의해 만들어진 객체들은 Object의 인스턴스들이 된다.

+ +

다음 문장은 수식cond가 참일 경우 객체를 만들어서 변수 x 에 할당한다:

+ +
if (cond) var x = {hi: "there"};
+
+ +

다음 예제는 myHonda을 생성하고 세개의 속성을 추가한다. engine 속성 역시 자신의 속성들을 가지고 있는 객체이다.

+ +
var myHonda = {color: "red", wheels: 4, engine: {cylinders: 4, size: 2.2}};
+
+ +

객체 이니셜라이저를 이용하여 배열을 만들 수 있다. array literals 를 참조하기 바란다.

+ +

JavaScript 1.1 과 그 이전 버전에서는, 객체 이니셜라이저를 사용할 수 없었다. 항상 생성자 함수를 쓰거나 생성 목적으로 제공되는 별도 함수를 사용했어야 했다. Using a constructor function 참고.

+ +

생성자 함수 사용하기

+ +

다른 방법으로는 다음 두 단계에 따라 객체를 생성할 수 있다:

+ +
    +
  1. 생성자 함수를 작성하여 객체 타입을 정의한다. 객체 타입 이름의 첫 글자는 반드시 대문자를 사용하는 좋은 관례가 있으므로 따르기를 권장한다.
  2. +
  3. new를 이용하여 객체의 인스턴스를 생성한다.
  4. +
+ +

객체의 타입을 정의하려면 타입의 이름, 속성(프로퍼티), 메소드 등을 기술하는 함수를 하나 만들어야 한다. 예를 들면, 여러분이 자동차를 위한 객체 타입을 만들기 원한다면, 이 객체의 타입의 이름은 car이고, 이 타입은 제조사, 모델, 생산연도를 위한 속성을 포함하길 원할 것이다. 아마도 다음과 같은 함수를 작성하게 될 것이다:

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+
+ +

함수 인자로 전달 받은 값을 객체의 속성에 할당하기 위해서 this를 사용 한 것에 주목하기 바란다.

+ +

이제 다음과 같이 하여 mycar라는 이름의 객체를 생성할 수 있다:

+ +
var mycar = new Car("Eagle", "Talon TSi", 1993);
+
+ +

이 문장은 mycar를 만들고 특정 값들을 속성으로 할당하고 있다. 이렇게 하면 mycar.make의 값은 문자열 "Eagle" 이 되고, mycar.year는 정수 1993 이 된다.

+ +

new를 이용하면 어떤 갯수의 car 객체도 만들 수 있다. 예를 들면 다음과 같다.

+ +
var kenscar = new Car("Nissan", "300ZX", 1992);
+var vpgscar = new Car("Mazda", "Miata", 1990);
+
+ +

객체는 또 다른 객체를 속성으로 가질 수 있다. 예를 들어 여러분이 person 이라는 객체를 다음과 같이 정의를 했고:

+ +
function Person(name, age, sex) {
+  this.name = name;
+  this.age = age;
+  this.sex = sex;
+}
+
+ +

그리고 두 개의 새 person 객체의 인스턴스를 만들었다고 하면:

+ +
var rand = new Person("Rand McKinnon", 33, "M");
+var ken = new Person("Ken Jones", 39, "M");
+
+ +

car의 정의에 person 객체의 값을 갖는 owner 속성을 추가하도록 수정할 수 있다:

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+}
+
+ +

수정된 새 객체의 인스턴스를 만들려면 다음과 같이 하면 된다:

+ +
var car1 = new Car("Eagle", "Talon TSi", 1993, rand);
+var car2 = new Car("Nissan", "300ZX", 1992, ken);
+
+ +

위 문장은 문자열 리터럴이나 정수를 넘기는 대신 객체 randken을 owners를 위한 인자로 전달하고 있다. car2의 소유자 이름을 찾고 싶다면 다음과 같은 속성을 사용할 수 있다.:

+ +
car2.owner.name
+
+ +

이미 정의 된 객체에도 새로운 속성을 추가할 수 있다.

+ +
car1.color = "black";
+
+ +

위 문장은 속성 color를 car1 에 추가하고, 그 값으로는 "black"을 지정하고 있다. 그러나 이것은 다른 객체들에는 영향을 주지 않는다. 새 속성을 해당 타입의 모든 객체들에 다 추가하고 싶다면, 이 속성을 car 객체 타입의 정의에 추가해야 한다.

+ +

Object.create 메서드 사용하기

+ +

객체는 Object.create 메서드를 이용해서 생성될 수 있다. 이 메서드는 사용할 프로토타입 객체를 사용자가 직접 선택할 수 있기 때문에 상당히 유용하다. (객체 생성시 생성자 함수가 없어도 가능하다). 이 메서드에 대한 더 자세한 정보는 {{jsxref("Object.create()")}} 를 참고하도록 하자.

+ +
// Animal properties and method encapsulation
+var Animal = {
+  type: "Invertebrates", // Default value of properties
+  displayType : function(){  // Method which will display type of Animal
+    console.log(this.type);
+  }
+}
+
+// Create new animal type called animal1
+var animal1 = Object.create(Animal);
+animal1.displayType(); // Output:Invertebrates
+
+// Create new animal type called Fishes
+var fish = Object.create(Animal);
+fish.type = "Fishes";
+fish.displayType(); // Output:Fishes
+ +

상속

+ +

JavaScript 에서의 모든 객체들은 최소한 하나의 다른 객체로부터 상속을 받는다. 상속을 제공하는 객체를 프로토타입이라고 부르며, 상속되는 속성들은 prototype 이라는 생성자 객체에서 찾을 수 있다.

+ +

객체 프로퍼티의 인덱싱

+ +

JavaScript 1.0에서는 객체의 속성을 참조할 때 속성 이름을 이용하거나 또는 숫자 인덱스를 이용할 수 있었다. 하지만 JavaScript 1.1과 그 이후 부터는 처음에 프로퍼티를 이름으로 정의하면 항상 이름으로만 참조를 할 수 있고, 처음에 인덱스를 이용하여 정의하면 인덱스를 이용해서만 참조할 수 있다.

+ +

이 제약 사항은 생성자 함수를 이용하여 객체와 프로퍼티를 생성할 때 (앞에서 Car 객체 타입의 예)에도 동일하게 적용되고, 개개의 속성을 명시적으로 지정할 때 (예: myCar.color = "red")에도 마찬가지이다. 만약 처음에 객체 속성을 정의할 때 myCar[5] = "25 mpg" 처럼 인덱스 방식을 사용하면, 그 이후에도 계속 myCar[5] 방식으로만 참조할 수 있다.

+ +

forms 배열과 같이 HTML 로부터 얻어지는 객체들에는 이 규칙이 적용되지 않는다. 숫자를 이용하거나 (이 객체가 문서 상에 존재하는 순서에 따라) 또는 태그의 attribute 이름으로 참조가 가능하다. 예를 들면 HTML 문서에서 두 번째 <FORM> 태그가 "myForm" 이라는 값의 NAME attribute 를 가지고 있다면, 이 form을 document.forms[1] 또는 document.forms["myForm"] 또는 document.myForm 와 같이 접근할 수 있다.

+ +

객체의 프로퍼티 정의

+ +

prototype 프로퍼티를 사용하여 미리 정의된 객체 타입에 속성을 추가할 수 있다. 이렇게 정의된 속성은 해당 객체 타입의 한 인스턴스에만 적용되는 것이 아니라 해당 객체 타입의 모든 인스턴스가 갖게 된다. 다음 코드에서는 car 타입의 객체 전체에 color 프로퍼티를 추가한 후, car1 인스턴스의 color 프로퍼티에 값을 할당하는 것을 보여준다.

+ +
Car.prototype.color = null;
+car1.color = "black";
+
+ +

더 많은 정보는 JavaScript Reference에서 Function 객체의 prototype 속성을 참조

+ +

메소드 정의

+ +

메소드는 한 객체와 연관된(associated) 함수이며, 간단하게 말해 객체의 프로퍼티 중에서 함수인 것을 메소드라고 한다. 메소드를 정의하는 방식은 일반 함수를 정의하는 것과 동일하고, 다만 어떤 객체의 프로퍼티로 할당되어야 한다는 점이 차이가 난다. 자세한 것은 method definitions를 참조하자. 다음은 메소드 정의의 한 예이다.

+ +
objectName.methodname = function_name;
+
+var myObj = {
+  myMethod: function(params) {
+    // ...do something
+  }
+};
+
+ +

첫번째 줄은 이미 존재하는 objectName이라는 객체에 methodname이라는 이름의 메소드를 추가하는 것이다. function_name 은 메소드로 사용될 함수의 이름이다. 두번째 줄부터는 객체를 정의할 때 메소드를 같이 정의하는 예이다.

+ +

그러고 나면 다음과 같이 해당 객체의 문맥(context)에서 메소드를 호출할 수 있다.

+ +
object.methodname(params);
+
+ +

객체 생성자 함수에 메소드 정의를 포함시킴으로써 해당 객체 타입의 메소드를 정의할 수 있다. 한 예로 이전에 정의한 car 객체의 프로퍼티를 형식에 맞춰 출력하는 함수를 정의할 수 있는데, 다음과 같다.

+ +
function displayCar() {
+  var result = "A Beautiful " + this.year + " " + this.make
+    + " " + this.model;
+  pretty_print(result);
+}
+
+ +

위에서 pretty_print는 수평 규칙과 문자열을 나타내 주는 함수이다. 여기서 사용한 this는 해당 메소드가 속한 객체를 가리킨다는 점을 기억하자.

+ +

아래와 같은 코드를 car객체의 정의에 추가함으로써 해당 함수를 car객체의 메소드로 만들 수 있다.

+ +
this.displayCar = displayCar;
+
+ +

따라서 car객체의 전체 정의는 아래와 같이 됩니다.

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+  this.displayCar = displayCar;
+}
+
+ +

그리고 각각의 객체(인스턴스)를 가지고 displayCar메서드를 아래와 같이 호출 할 수 있습니다:

+ +
car1.displayCar();
+car2.displayCar();
+
+ +

객체 참조를 위해 this 를 사용하기

+ +

자바스크립트는 특별한 키워드를 가지고 잇습니다. 바로 this라는 키워드이다. 메서드 내부에서 this 키워드를 사용하게 되면 해당 메서드를 포함한 객체를 가리키게 된다. 예를 들어 특정 객체의 속성값의 상한과 하한 값의 범위에 있는지를 확인하는 validate라는 함수를 아래와 같이 작성한다고 했을 때, 

+ +
function validate(obj, lowval, hival) {
+  if ((obj.value < lowval) || (obj.value > hival))
+    alert("Invalid Value!");
+}
+
+ +

validate메서드를 각각의 form 요소들의 onchange 이벤트 핸들러에서 호출할 수 있다. 그 때, 다음 예제처럼 this 키워드를 사용해서 해당 form요소를 인자로 넘길 수 있다. 

+ +
<input type="text" name="age" size="3"
+  onChange="validate(this, 18, 99)">
+
+ +

일반적으로 this는 메서드를 호출하는 객체를 지칭합니다. 

+ +

 myFormform속성과 함께 사용할때, this키워드는 현재 객체의 부모 form을 지칭한다. 다음의 예제에서, myForm form은 텍스트 객체와 버튼 객체를 가지고 있다. 사용자가 해당 버튼을 클릭했을때, myForm form안에 있는 텍스트 객체의 값을 myForm form의 이름으로 설정한다. 해당 버튼의 onclick 이벤트 처리자는 부모 form인 myForm을 지칭하기 위해 this.form를 사용한다. 

+ +
<form name="myForm">
+<p><label>Form name:<input type="text" name="text1" value="Beluga"></label>
+<p><input name="button1" type="button" value="Show Form Name"
+     onclick="this.form.text1.value = this.form.name">
+</p>
+</form>
+ +

getters 와 setters 정의

+ +

getter 메서드는 특정 속성의 값을 받아 오기 위한 메서드 입니다. setter메서드는 특정 속성의 값을 설정하기 위한 메서드 입니다. 새로운 속성을 추가 하기 위해 getter와 setter 메서드들을 미리 정의된 객체 혹은 사용자 정의 객체에 정의 하 수 있습니다.  getter와 setter메서드들을 정의 하기 위한 문법은 객체 구문 문법을 사용합니다.

+ +

자바스크립트 1.8.1버전부터, 객체와 배열 초기화에서 속성들을 설정하고자 할 경우 setter메서드들은 더이상 사용이 불가합니다.

+ +

다음의 JS 쉘은 getter와 setter메서드들이 사용자 정의객체인 o에서 어떻게 작동하는지를 보여 줍니다. JS쉘은 개발자가 배치 모드 혹은 대화형 모드에서 자바스크립트 코드를 테스트하기위한 하나의 어플리케이션입니다. 

+ +
js> var o = {a: 7, get b() {return this.a + 1;}, set c(x) {this.a = x / 2}};
+[object Object]
+js> o.a;
+7
+js> o.b;
+8
+js> o.c = 50;
+js> o.a;
+25
+
+ +

o 객체의 속성이 다음과 같을 때,

+ + + +

[gs]et 속성명()  문법이 실제 사용되는 메서드명이라고 생각이 될지라도, "[gs]et 속성명()" 문법(__define[GS]etter__와는 반대로)을 사용한 객체 구문 문법으로 정의된 getter와 setter메서드들의 이름들은 실제 getter 메서드들의 이름이 아니라는 점에 유의 하세요.  "[gs]et 속성명()" 문법을 사용하여 getter, setter메서드내의 함수명을 작성하기 위해서는, Object.defineProperty (혹은 Object.prototype.__defineGetter__ 레거시 콜백)을 사용하여 프로그램적으로 분명한 이름의 함수명을 사용하세요. 

+ +

아래의 자바스크립트 쉡은 이미 정의된 Date 클래스의 모든 인스턴스들에 년도 속성을 추가 하기 위해 getter와 setter 메서드들이 Date 프로토타입을 확장하는 방법을 보여 줍니다. 

+ +

아래의 구문들은 년도 속성 추가를 위한 getter와 setter메서드를 정의합니다:

+ +
js> var d = Date.prototype;
+js> Object.defineProperty(d, "year", {
+    get: function() {return this.getFullYear() },
+    set: function(y) { this.setFullYear(y) }
+});
+
+ +

아래의 구문들은 Date객체에서 getter와 setter메서드를 사용하는 법을 보여 줍니다:

+ +
js> var now = new Date;
+js> print(now.year);
+2000
+js> now.year = 2001;
+987617605170
+js> print(now);
+Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001
+
+
+ +

원칙적으로, getter와 setter는 둘 중 하나가 될 수 있다.

+ + + +

object initializers를 사용해서 getter와 setter메서드들을 정의할 경우, getter메서드는 get, setter메서드는 set이라는 접두사만 추가하면 됩니다. 물론 getter메서드는 인자를 받지 않는 반면, setter 메서드는 정확히 하나의 인자(설정할 새로운 값)만을 받습니다. 

+ +
var o = {
+  a: 7,
+  get b() { return this.a + 1; },
+  set c(x) { this.a = x / 2; }
+};
+
+ +

Object.defineProperties 메서드를 사용하면 객체 생성이후라도 언제든지 getter and setter메서드들을 객체에 추가할 수 있습니다. Object.defineProperties 메서드의 첫번째 인자는 getter and setter메서드들을 추가할 객체이고, 두번째 인자는 getter and setter메서드들의 이름과 getter and setter메서드들의 정의를 가지고 있는 객체가 되어야 합니다. 이전 예제와 동일하게 사용된 getter and setter메서드들을 정의하고 있는 예제는 아래와 같습니다:

+ +
var o = { a:0 }
+
+Object.defineProperties(o, {
+    "b": { get: function () { return this.a + 1; } },
+    "c": { set: function (x) { this.a = x / 2; } }
+});
+
+o.c = 10 // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
+console.log(o.b) // Runs the getter, which yields a + 1 or 6
+
+ +

당신의 프로그래밍 스타일과 현재 진행 중인 작업에 따라 getter and setter메서드들을 정의할 수 있는 두가지 양식 중 하나를 선택하여 사용할 수 있습니다. prototype을 정의 할때 object initializer를 사용했다면 앞으로도 대부분 첫번째 양식을 선택 하여 작성을 할 것입니다. 이 양식이 보다 간결하고 자연스럽기 때문입니다. 하지만 prototype 혹은 특정 객체를 작성하지 않고서 나중에 getter and setter 메서드를 추가하고자 한다면 두번째 양식만이 가능한 선택입니다.  두번째 양식은 아마도 자바스크립트의 동적 속성을 가장 잘 나타내고 있습니다. 하지만 코드 작성과 읽고 이해하는 부분에 어려움이 있습니다. 

+ +
+

Firefox 3.0 이전 버전의 경우, getter and setter 메서드들은 DOM 요소들에는 지원되지 않습니다. 이전 버전의 Firefox에서는 아무런 에러 없이 작동하지 않을 것입니다. 이것에 대한 예외가 필요하다면, HTMLElement의 prototype(HTMLElement.prototype.__define[SG]etter__)을 변경하고 예외를 던지는 것이 하나의 방법입니다.

+ +

Firefox 3.0 버전에서는 이미 정의된 속서에 대해 getter or setter를 정의 할 경우 예외가 발생됩니다. 이전 버전의 Firefox에서는 아니지만 해당 속성을 반드시 사전에 제거해야만 합니다. 

+
+ +

추가로 볼 것들 

+ + + +

프로퍼티의 삭제

+ +

상속 받지 않은 속성은 delete 연산자를 이용하여 제거 할 수 있다. 다음 코드는 어떻게 속성을 제거하는지 보여준다.

+ +
// 새 객체 myobj를 두 개의 속성 a, b 와 함께 생성
+var myobj = new Object;
+myobj.a = 5;
+myobj.b = 12;
+
+// 속성을 삭제. myobj 에는 속성 b 만 남게 됨.
+delete myobj.a;
+console.log ("a" in myobj) // "false"를 출력
+
+ +

var 키워드로 선언하지 않은 전역 변수도 delete를 이용하여 삭제를 할 수 있다:

+ +
g = 17;
+delete g;
+
+ +

더 자세한 정보는 delete를 보면 된다.

+ +

객체 간의 비교

+ +

JavaScript 에서는 객체들은 레퍼런스 타입이다. 두 개의 별개 객체들은, 설령 그 속성 값들이 모두 다 동일하다고 하더라도, 절대로 동일하다고 비교(equal)될 수 없다. In JavaScript objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

+ +
// 속성은 같지만 서로 별개인 두 변수와 두 객체
+var fruit = {name: "apple"};
+var fruitbear = {name: "apple"};
+
+fruit == fruitbear // false 리턴
+fruit === fruitbear // false 리턴
+ +
// 두 개의 변수이지만 하나의 객체
+var fruit = {name: "apple"};
+var fruitbear = fruit;  // fruit 객체 레퍼런스를 fruitbear 에 할당
+
+// here fruit and fruitbear are pointing to same object
+fruit == fruitbear // true 리턴
+fruit === fruitbear // true 리턴
+
+ +

비교 연산자에 대한 상세한 정보는 Comparison operators를 참고하기 바란다.

+ +

추가 검토

+ + + +
{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}
diff --git "a/files/ko/web/javascript/guide/\352\260\235\354\262\264_\353\252\250\353\215\270\354\235\230_\354\204\270\353\266\200\354\202\254\355\225\255/index.html" "b/files/ko/web/javascript/guide/\352\260\235\354\262\264_\353\252\250\353\215\270\354\235\230_\354\204\270\353\266\200\354\202\254\355\225\255/index.html" new file mode 100644 index 0000000000..230d5cb9e1 --- /dev/null +++ "b/files/ko/web/javascript/guide/\352\260\235\354\262\264_\353\252\250\353\215\270\354\235\230_\354\204\270\353\266\200\354\202\254\355\225\255/index.html" @@ -0,0 +1,714 @@ +--- +title: 객체 모델의 세부 사항 +slug: Web/JavaScript/Guide/객체_모델의_세부사항 +translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}
+ +

자바스크립트는 클래스 기반이 아닌 prototype에 기초한 객체 기반 언어 입니다. 이런 차이점으로 인해, 객체들의 계층 구조의 생성과 속성 및 속성 값의 상속을 어떻게 구현해야 하는지에 대한 부분이 덜 분명할 수 있습니다. 이번 장에서는 이런 상황을 명확하게 하고자 합니다. 

+ +

이번 장에선 이미 자바스크립트를 어느 정도 알고 있고, 간단한 객체를 생성하는 함수들을 사용해보았다는 가정하에 진행합니다.

+ +

클래스 기반 언어 대 프로토타입 기반 언어

+ +

Java와 C++같은 클래스 기반의 언어들은 두개의 구별되는 개념에 기반을 두고 있습니다: 그건 바로 클래스와 인스턴스입니다.

+ + + +

자바스크립트같은 프로토타입기반의 언어들은 위와 같은 클래스와 인스턴스의 차이를 두지 않습니다. 간단하게 객체들을 가질 뿐입니다. prototype기반의 언어는 원형(프로토타입)의 객체 개념을 가지고 있습니다. 하나의 객체는 새로운 객체를 생성했을 때 초기 속성을 가질 수 있도록 하는 형판(template)으로 사용됩니다. 객체는 생성될 때 혹은 실행 시에 자기 자신의 속성을 명시할 수 있습니다. 추가적으로, 객체들은 또 다른 객체를 생성하기 위한 프로토타입으로 연관지어 질 수 있으며 프로토타입으로부터 생성된 두번째 객체가 프로토타입인 첫번째 객체의 속성을 공유(혹은 접근)하는 것을 허용합니다. 

+ +

클래스 정의

+ +

클래스 기반의 언어들에서, 별도의 클래스를 생성하고 그 안에서 해당 클래스를 정의 할 수 있습니다. 해당 정의에서 클래스의 인스턴스를 생성할 수 있는 생성자라고하는 특별한 메서드를 명시할 수 있습니다. 생성자는 해당 인스턴스의 초기 속성 값을 지정할 수 있고, 생성 시점에, 다른 적절한 처리를 수행 할 수 있습니다. 클래스의 인스턴스를 생성하기 위해서 new 연산자와 함께 생성자를 호출해야 합니다. 

+ +

자바스크립트는 위와 비슷한 방법을 취합니다. 하지만 생성자이외에 따로 클래스 정의를 가지고 있지는 않습니다. 대신, 특정 속성및 속성값들을 가지고 객체를 생성하는 생성자 함수를 정의할 수 있습니다. 특정 자바스크립트 함수는 생성자로 사용 될 수 있습니다. 새로운 객체를 생성할려면 new연산자와 함께 생성자 함수를 사용해야 합니다.

+ +
+

ECMAScript 2015에 클래스 선언이 새롭게 소개되었습니다.

+ +
+

ECMAScript 2015에서 소개된 자바스크립트 클래스는 주로 문법적 설탕으로 기존 자바스크립트 프로토타입 기반 상속에  읽기 좋은 형식으로 바뀌었습니다. 이 클래스 문법이 자바스크립트에 새로운 객체 중심 상속 모델을 소개한 것은 아닙니다.

+
+
+ +

하위 클래스와 상속

+ +

클래스 기반 언어에서는 클래스 정의를 통해 클래스 계층구조를 생성합니다. 클래스를 정의할 때 이미 존재하는 클래스의 하위 클래스를 새로운 클래스로 지정할 수 있습니다. 이 하위 클래스는 부모 클래스의 모든 속성을 상속받으며 추가로 새로운 속성을 추가하거나 상속받은 속성을 수정할 수 있습니다. 예를 들어  이름(name)과 부서(dept)을 가진 직원(Employee) 클래스와 그 하위 클래스에 보고(reports) 속성을 추가한 관리자(Manager) 클래스가 있다고 해봅시다. 이 경우 관리자(Manager)의 인스턴스는 다음과 같이 세가지 속성을 모두 가질 수 있습니다 - 이름(name),  부서(dept),  보고(reports).

+ +

자바스크립트는 생성자 함수와 프로토타입 객체를 연결해 상속을 구현합니다. 이런 식으로 직원(Employee) — 관리자(Manager) 예제를 똑같이 구현할 수 있지만 조금 다른 * 사용합니다. 먼저, 이름(name),  부서(dept) 속성을 명시하여 직원(Employee) 생성자 함수를 정의합니다. 그런 다음, 직원(Employee)의 생성자를 호출한 후 보고(reports) 속성을 명시해 관리자(Manager) 생성자 함수를 정의합니다. 마지막으로 Employee.prototype 에서 파생된 새로운 객체를  관리자(Manager) 생성자 함수의 프로토타입으로 지정합니다. 그런 다음 새로운 관리자(Manager)를 만들면 관리자(Manager) 객체를 직원(Employee) 객체로부터 이름(name),  부서(dept) 속성을 상속받습니다. 

+ +

속성의 추가 삭제

+ +

클래스 기반의 언어들에서는, 일반적으로 컴파일 시점에 클래스를 생성한 후에 컴파일 시점 혹은 실행 시에 해당 클래스의 인스턴스를 생성합니다. 클래스가 한번 정의된 후에 클래스를 다시 컴파일 하지 않는다면, 속성의 갯수나 형식을 변경할 수 없습니다. 하지만 자바스크립트에서느 실행 시에 객체의 속성을 추가 혹은 삭제 할 수 있습니다.  만약 객체군의 프로토타입으로 사용되는 객체에 속성을 추가하면, 프로토타입이 되는 객체들에도 새로운 속성이 추가가 됩니다.

+ +

차이점들에 대한 정리

+ +

다음 표는 이런 차이점들에 대한 간략한 요약을 포함하고 있습니다. 이번 장의 다음 내용들은 객체의 계층 구조를 생성하기 위한 자바스크립트 생성자와 프로토타입들의 사용에 대한 세부 사항에 대해 기술합니다. 그리고 동일한 작업을 자바에서 어떻게 처리해야 하는지도 비교해서 살펴보겠습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
클래스 기반(자바)과 프로토타입(prototype)기반(자바스크립트) 객체 시스템의 비교
클래스 기반(자바)원형 기반(자바스크립트)
클래스와 인스턴스는 별개입니다.모든 객체는 다른 객체로부터 상속을 받습니다.
클래스 정의를 가지고 클래스를 생성하고 생성자 메서드로 인스턴스를 생성합니다.생성자 함수를 가지고 객체군을 정의 및 생성합니다.
new 연산자로 하나의 객체(인스턴스)를 생성합니다.동일합니다.
이미 존재하는 클래스에 대한 하위 클래스를 정의함으로써 객체의 계층구조를 생성합니다.하나의 객체를 생성자 함수와 결합된 프로토타입에 할당함으로써 객체의 계층구조를 생성 합니다.
클래스의 상속 구조에 따라 속성을 상속 받습니다.프로토타입 체인에 따라  속성을 상속 받습니다.
클래스 정의는 모든 인스턴스의 모든 속성을 명시합니다. 실행시에 동적으로 속성을 추가할 수 없습니다.생성자 함수 혹은 프로토타입은 초기 속성들을 명시합니다. 개별 객체 혹은 전체 객체군에 동적으로 속성을 추가 삭제할 수 있습니다.
+ +

직원 예제

+ +

이장의 나머지 부분에서는 다음과 같은 직원 객체의 계층구조를 사용합니다. 

+ +
+

직원 객체의 계층 구조.

+ +

+ + +
+ +

계층 구조 생성

+ +

직원 계층 구조를 구현하기 위한 적절한 생성자 함수를 정의하는 방법에는 여러가지가 있습니다. 개발하려고 하는 어플리케이션에 따라 생성자 함수를 정의 하는 방법은 달라질 수 있습니다. 

+ +

이번 절에서는 상속을 구현하기 위한 간단한 (비교적 유연하지는 않은) 정의 방법을 보여 줄 것입니다. 이런 정의 방법을 사용하게되면, 객체를 생성할 때 어떤 속성 값도 지정을 할 수 없습니다. 새로이 생성된 객체들은 기본값들을 가지고 있으며, 나중에 해당 속성 값들을 변경할 수 있습니다.

+ +

실제 어플리케이션에서는, 객체를 생성할때, 해당 객체가 가져야할 속성을 인자로 받는 생성자를 정의 할수 있습니다.(보다 자세한 사항은 다음을 참조하세요. More flexible constructors). 지금 당장은, 상속이 어떻게 작동하는지를 보여주기 위한 간단한 예제를 사용합니다. 

+ +

다음의 자바와 자바스크립트로 작성된 직원 정의는 비슷합니다. 차이점은 자바언어에서는 개별 속성에 대한 타입(type)을 일일이 지정을 해야 하지만  자바스크립트에서는 일일이 개별 속성에 대한 타입(type)을 지정할 필요가 없다는 것입니다.(이런 이유로 자바스크립트가 약하게 형식화된 언어로 불리는 반면 자바는 강력하게 형식화된 언어로 불립니다.)

+ + + + + + + + +
+

자바스크립트

+ +
+function Employee() {
+  this.name = "";
+  this.dept = "general";
+}
+
+

자바

+ +
+public class Employee {
+   public String name = "";
+   public String dept = "general";
+}
+
+
+ +

관리자와 근로자 정의는 계층 구조상에서 상위에 위치하는 객체를 어떻게 표시하는지에 대한 차이점을 보여 줍니다. 자바스크립트에서는 생성자 함수 정의 이후에 언제든 생성자 함수의 프로토타입(prototype) 속성의 값으로 프로토타입 인스턴스를 추가할 수 있습니다.  자바에서는 클래스 정의에 상위 클래스를 명시해야 합니다. 클래스 정의 이후에는 상위 클래스를 변경할 수 없습니다.

+ +
+

자바스크립트

+ +
function Manager() {
+  Employee.call(this);
+  this.reports = [];
+}
+Manager.prototype = Object.create(Employee.prototype);
+
+function WorkerBee() {
+  Employee.call(this);
+  this.projects = [];
+}
+WorkerBee.prototype = Object.create(Employee.prototype);
+
+ +

자바

+ +
public class Manager extends Employee {
+   public Employee[] reports = new Employee[0];
+}
+
+
+
+public class WorkerBee extends Employee {
+   public String[] projects = new String[0];
+}
+
+
+
+
+ +

엔지니어와 영업사원 정의들은 객체들을 생성합니다. 생성된 객체는 근로자 객체의 하위 객체이고 따라서 직원 객체의 하위 객체가 됩니다. 상속 관계에 따라 엔지니어와 영업사원 객체들은 근로자와 직원객체의 속성을 가지게 됩니다. 게다가, 상속받은 부서 속성은 엔지니어와 영업사원에서 재정되어 새로운 값을 가지게 됩니다. 

+ +
+

자바스크립트

+ +
function SalesPerson() {
+   WorkerBee.call(this);
+   this.dept = "sales";
+   this.quota = 100;
+}
+SalesPerson.prototype = Object.create(WorkerBee.prototype);
+
+function Engineer() {
+   WorkerBee.call(this);
+   this.dept = "engineering";
+   this.machine = "";
+}
+Engineer.prototype = Object.create(WorkerBee.prototype);
+
+ +

Java

+ +
public class SalesPerson extends WorkerBee {
+   public double quota;
+   public dept = "sales";
+   public quota = 100.0;
+}
+
+
+public class Engineer extends WorkerBee {
+   public String machine;
+   public dept = "engineering";
+   public machine = "";
+}
+
+
+ +

이런 정의 방법을 통해, 기본값을 가지는 각각의 속성을 포함하는 객체의 인스턴스를 생성할 수 있습니다. 다음 그림은 새로운 객체를 생성하고 새로운 객체에 대한 속성값들을 보여 표시하기 위한 자바스크립트의 정의들을 보여 줍니다.

+ +
+

유의사항: 클래스 기반 언어들에서 인스턴스라는 용어는 특정한 기술적 의미를 가지고 있습니다. 이러한 언어들에서,  하나의 인스턴스란 하나의 클래스의 개별적인  실체이며 클래스와는 근본적으로 다릅니다. 자바스크립트에서는 클래스와 인스턴스 간의 차이가 없기 때문에, "인스턴스"가 이런 기술적 의미를 갖지 않습니다. 하지만, 자바스크립트에 대해서 얘기하자면, 비공식적으로 "인스턴스"는 특정한 생성자 함수를 이용하여 생성된 오브젝트를  의미합니다. 그래서 이번 예제에서는 jane Engineer 의 인스턴스라고 할 수 있습니다. 이와 유사하게, 부모, 자식, 상위, 하위의 용어들은 자바스크립트에서 공식적인 의미를 갖지 않습니다; 다만 프로토타입 체인 상의 상위 또는 하위 객체를 지칭하기 위해서 비공식적으로 사용할 수 있습니다.

+
+ +

간단한 정의로 객체 생성

+ +
+

객체의 계층구조

+ +

오른쪽에 보이는 코드로 생성된 객체의 계층 구조는 아래와 같습니다.

+ +

+ +

개별 객체들

+ +
var jim = new Employee;
+// jim.name is ''
+// jim.dept is 'general'
+
+var sally = new Manager;
+// sally.name is ''
+// sally.dept is 'general'
+// sally.reports is []
+
+var mark = new WorkerBee;
+// mark.name is ''
+// mark.dept is 'general'
+// mark.projects is []
+
+var fred = new SalesPerson;
+// fred.name is ''
+// fred.dept is 'sales'
+// fred.projects is []
+// fred.quota is 100
+
+var jane = new Engineer;
+// jane.name is ''
+// jane.dept is 'engineering'
+// jane.projects is []
+// jane.machine is ''
+
+
+ +

객체 속성들

+ +

이번 장에서는 객체가 프로토타입체인 상의 다른 객체로부터 특성을 상속받는 방법과 런타임 상에서 프로퍼티를 추가하면 무슨 일이 일어나는 지 살펴봅니다.

+ +

속성 상속

+ +

아래 구문처럼 WorkerBee 생성자로 mark 객체를 생성했다고 가정합니다.

+ +
var mark = new WorkerBee;
+
+ +

new 연산자를 만나면, 자바스크립트는 새로운 일반 객체를 생성하고 암묵적으로 내부의 [[Prototype]](__proto__) 속성의 값을 WorkerBee.prototype 의 값으로 할당하며, 해당 객체를 this 키워드의 값으로써 생성자 함수 WorkerBee에 전달합니다. 내부의 [[Prototype]] 속성은 속성값을 반환하기 위해 사용할 프로토타입 체인을 결정합니다. 이런 속성들이 할당되면, 자바스크립트는 새 객체를 반환하고, 할당 구문에 의해 변수 mark를 객체에 할당합니다.

+ +

이러한 절차는 mark가 프로토타입 체인으로부터 상속받는  속성의 값을 mark 객체 내부에(local values) 명시적으로 부여하진 않습니다. 당신이 속성의 값을 요청하면, 자바스크립트는 먼저 해당 객체에 값이 존재하는지 확인합니다. 존재한다면, 해당 값이 반환됩니다. 만약 해당 객체에 값이 없다면, 프로토타입 체인을 (내장 [[Prototype]] 속성;__proto__을 이용하여)확인합니다. 체인 상의 어떤 객체가 해당 속성의 값을 가지고 있다면 그 값이 반환됩니다. 그런 속성이 발견되지 않는다면, 자바스크립트는 객체가 속성을 가지고있지 않다고 할 것입니다. 이런 식으로, mark 객체는 다음의 속성과 값을 가집니다.

+ +
mark.name = "";
+mark.dept = "general";
+mark.projects = [];
+ +

mark 객체는 mark.__proto__로 연결되어 있는 원형의 객체로부터 이름(name)과 부서(dept)에 대한 값을 상속 받습니다. 근로자(WorkerBee) 생성자로부터 projects속성에 대한 값을 할당을 받습니다.이것들이 자바스크립트내에서 속성과 속성 값의 상속입니다. 이런 과정의 몇몇 세부 사항들은 Property inheritance revisited에서 다룹니다. 

+ +

이런 생성자들은 당신이 직접 인스턴스에만 해당 하는 값을 설정하도록 하지 않기때문에, 객체에 대한 이런 정보들은 일반적으로 적용됩니다. 근로자(WorkerBee)로부터 생성된 모든 새로운 객체들은 기본값이 적용된 속성 값들을 가지게 됩니다. 물론, 속성 값들을 변경할 수 있습니다. 아래처럼 특정 인스턴스에만 해당하는 값을 설정할 수 있습니다. 

+ +
mark.name = "Doe, Mark";
+mark.dept = "admin";
+mark.projects = ["navigator"];
+ +

속성 추가

+ +

자바스크립트에선, 실행 시점에 특정 객체에 속성들을 추가 할 수 있습니다.생성자 함수가 제공하는 속성외에 다른 속성을 추가할 수 있습니다. 특정 단일 객체에 속성을 추가하기 위해선, 다음과 같이 해당 객체에 값을 할당 하면 됩니다:

+ +
mark.bonus = 3000;
+
+ +

이렇게 하면 mark객체는 보너스(bonus)속성을 가지게 됩니다. 하지만 mark객체를 제외한 나머지 근로자(WorkerBee)객체들은 보너스 속성을 가지지 않습니다. 

+ +

만약 생성자 함수의 원형으로 사용되는 객체에 새로운 속성을 추가한다면,  해당 프로토타입 객체(prototype)의 속성을 상속받는 모든 객체에 해당 속성이 추가됩니다. 예를 들면, 전문분야(specialty)속성을 모든 직원 객체에 다음과 같은 구문으로 추가할 수 있습니다:

+ +
Employee.prototype.specialty = "none";
+
+ +

위의 구문을 실행한 직후, mark객체는 "none"이라는 값을 가지는 전문분야(specialty)속성을 가지게 됩니다.아래의 그림들은 해당 속성을 추가한 후 엔지니어(Engineer) 프로토타입에 대해 해당 속성을 재정의 했을 경우 각 객체에 미치는 영향을 보여줍니다.

+ +


+ 속성의 추가

+ +

좀 더 유연한 생성자들

+ +

지금까지 살펴 본 생성자 함수들은 인스턴스를 생성하면서 동시에 속성값을 지정할 수 없었습니다. 자바의 경우, 인스턴스를 생성 시 생성자에 인자들을 넘겨주어 인스턴스의 속성들을 초기화 할 수 있습니다. 다음의 예제 그림들은 자바처럼 인스턴스 생성 시 속성값을 설정하는 방법을 보여줍니다.

+ +


+ Specifying properties in a constructor, take 1

+ +

다음의 표는 자바와 자바스크립트 각각의 생성자와 객체에 대한 정의를 보여 줍니다. 

+ +
+

자바스크립트

+ +

자바

+
+ +
+
function Employee (name, dept) {
+  this.name = name || "";
+  this.dept = dept || "general";
+}
+
+ +
public class Employee {
+   public String name;
+   public String dept;
+   public Employee () {
+      this("", "general");
+   }
+   public Employee (String name) {
+      this(name, "general");
+   }
+   public Employee (String name, String dept) {
+      this.name = name;
+      this.dept = dept;
+   }
+}
+
+
+ +
+
function WorkerBee (projs) {
+
+ this.projects = projs || [];
+}
+WorkerBee.prototype = new Employee;
+
+ +
public class WorkerBee extends Employee {
+   public String[] projects;
+   public WorkerBee () {
+      this(new String[0]);
+   }
+   public WorkerBee (String[] projs) {
+      projects = projs;
+   }
+}
+
+
+ +
+
+function Engineer (mach) {
+   this.dept = "engineering";
+   this.machine = mach || "";
+}
+Engineer.prototype = new WorkerBee;
+
+ +
public class Engineer extends WorkerBee {
+   public String machine;
+   public Engineer () {
+      dept = "engineering";
+      machine = "";
+   }
+   public Engineer (String mach) {
+      dept = "engineering";
+      machine = mach;
+   }
+}
+
+
+ +

자바스크립트의 속성값을 설정하는 방법은 기본값을 설정하기 위한 관용구를 사용합니다.

+ +
this.name = name || "";
+
+ +

자바스크립트의 OR 논리 연산자(||) 첫번째 인자를 평가합니다. 첫번째 인자가 참이면 첫번째 인자를 반환하고 그렇지 않은 경우는 두번째 인자를 반환합니다. 그러므로, 위의 코드는 name인자가 name 속성에 사용 가능한 값을 가지고 있는지 확인합니다. 확인 결과 name속성에 사용가능한 값을 가지고 있을 경우, 해당 값을 this.name에 설정하게 됩니다. 반대로 그렇지 않은 경우는 빈 문자열을 this.name에 설정합니다.얼핏 보면 헛갈리지만 보다 짧은 관용구를 사용하였습니다.

+ +
+

주의: 만약 인자로 false와 빈 문자열 값을 줄 경우 해당 구문은 예상한 대로 작동하지 않을 수 있습니다.

+
+ +

이런 정의들을 가지고, 객체의 인스턴스를 생성할때, 객체 자신만의 속성에 대한 값을 지정할 수 있습니다. 새로운 Engineer를 생성하기 위해서 다음과 같은 구문을 사용할 수 있습니다:

+ +
var jane = new Engineer("belau");
+
+ +

Jane의 속성들은 다음과 같습니다:

+ +
jane.name == "";
+jane.dept == "engineering";
+jane.projects == [];
+jane.machine == "belau"
+
+ +

위와 같은 코드 구문으로는 name과 같이 상속받은 속성에 대한 초기값을 지정할 수 없습니다.만약 상속 받은 속성의 초기값을 설정하고자 한다면, 생성자 함수의 코드를 변경해야 합니다.

+ +

지금까지, 원형 객체를 생성한 후, 그 새로운 객체 자신의 속성과 속성 값을 지정하는 것을 살펴 보았습니다. 프로토타입 체인상에서 해당 생성자가 상위 객체에 대한 생성자를 직접 호출 함으로써 더 많은 속성을 추가하도록 할 수 있습니다. 다음의 그림은 새로운 정의 방법을 보여 줍니다.

+ +


+ 생성자내에서 속성들 정의, 그림 2

+ +

그럼 좀 더 상세하게 생성자 내에서 속성들을 정의하는 것을 살펴 보겠습니다. 다음은 엔지니어(Engineer) 생성자의 새로운 정의입니다:

+ +
function Engineer (name, projs, mach) {
+  this.base = WorkerBee;
+  this.base(name, "engineering", projs);
+  this.machine = mach || "";
+}
+
+ +

다음과 같이 새로운 엔지니어(Engineer)객체를 생성할 수 있습니다:

+ +
var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
+
+ +

다음과 같은 순서에 따라 객체를 생성하고 속성을 정의하게 됩니다:

+ +
    +
  1. new 연산자는 프로토타입 객체를 생성하고 생성된 객체의 __proto__속성을 Engineer.prototype으로 설정합니다.
  2. +
  3. new 연산자는 새로이 생성된 객체를 엔지니어(Engineer)생성자에 this 키워드의 값으로 전달합니다.
  4. +
  5. 생성자는 생성한 객체에 대한 base라는 새로운 속성을 생성하고 근로자(WorkerBee) 생성자의 값을 base 속성에 할당합니다. 이런 과정은 근로자(WorkerBee) 생성자를 엔지니어(Engineer)객체의 메서드로 만듭니다. base 속성의 이름은 그리 특별하지 않습니다. 다른 어떤 속성명을 사용해도 무방합니다. base 속성명은 단지 해당 속성의 목적을 환기시키기 위한 것입니다.
  6. +
  7. +

    생성자는 base 메서드에 필요한 인자들 ("Doe, Jane" and ["navigator", "javascript"])을 주어 호출합니다.명시적으로 생성자에서 사용한 "engineering"은 모든 엔지니어(Engineer)객체들이 상속받은 부서 속성에 대한 동일한 값을 가지며, 직원(Employee)으로부터 상속받은 값을 재정의 하는 것을 나타냅니다.

    +
  8. +
  9. base가 엔지니어(Engineer)의 메서드이기때문에 base메서드 내에서 this키워드를 스텝1에서 생성한 객체를 지칭하도록 해줍니다. 따라서, 근로자(WorkerBee) 함수는 차례대로 "Doe, Jane""engineering" 인자를 직원(Employee)생성자에 전달합니다. 직원(Employee)생성자로부터 반환 시, 근로자(WorkerBee)함수는 남은 인자들을 프로젝트(projects)속성을 설정하기 위해 사용합니다. 
  10. +
  11. base메서드로부터 반환 시, 엔지니어(Engineer) 생성자는 해당 객체의 장비(machine)속성을 "belau"로 초기화 합니다.
  12. +
  13. 생성자로부터 반환 시, 새롭게 생성된 객체를 jane변수에 할당 합니다.
  14. +
+ +

엔지니어(Engineer) 생성자내에서 근로자(WorkerBee)생성자를 호출하면, 엔지니어(Engineer)에 대한 상송을 적절하게 설정할 수 도 있을 것이라고 생각할 수 있을 것입니다.하지만 그렇지 않습니다. 근로자(WorkerBee)생성자를 호출하는 것은 엔지니어(Engineer)객체로 하여금 호출되는 모든 생성자 함수내에서 열거된 속성들을 가지고도록 보장합니다.그러나, 나중에 직원(Employee)혹은 근로자(WorkerBee) 원형에 속성을 추가한다면, 엔지니어(Engineer)객체에 의해 추가된 속성들은 상속이 되지 않습니다. 예를 들어, 아래와 같은 구문을 작성하였다고 가정합니다:

+ +
function Engineer (name, projs, mach) {
+  this.base = WorkerBee;
+  this.base(name, "engineering", projs);
+  this.machine = mach || "";
+}
+var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
+Employee.prototype.specialty = "none";
+
+ +

jane객체는 전문분야(specialty)속성을 상속받지 않습니다.

+ +
function Engineer (name, projs, mach) {
+  this.base = WorkerBee;
+  this.base(name, "engineering", projs);
+  this.machine = mach || "";
+}
+Engineer.prototype = new WorkerBee;
+var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
+Employee.prototype.specialty = "none";
+
+ +

이제 jane객체의 전문분야(specialty)속성은 "none"이 되었습니다.

+ +

call() 혹은 apply() 메서드를 사용는 것은 상속을 구현하는 또 다른 방법입니다. 다음의 두 예제는 동일한 결과를 보여줍니다. 

+ +
+
function Engineer (name, projs, mach) {
+  this.base = WorkerBee;
+  this.base(name, "engineering", projs);
+  this.machine = mach || "";
+}
+
+ +
function Engineer (name, projs, mach) {
+  WorkerBee.call(this, name, "engineering", projs);
+  this.machine = mach || "";
+}
+
+
+ +

base를 사용하지 않고 구현을 하기 때문에, call() 메서드를 사용하여 상속을 구현하는 것이 보다 깔끔합니다.

+ +

속성 상속의 재고

+ +

이전 절에서 자바스크립트의 생성자와 원형(prototype)이 어떤 방식으로 상속과 객체의 계층 구조를 제공하는지를 살펴 보았습니다. 이번장에서는 이전 절에서 반드시 명백하게 짚고 넘어가지 않은 일부 미묘한 점들에 대해 살펴보겠습니다.

+ +

객체 자신의 값과 상속받은 값

+ +

이번 장에서 이미 설명된 것 처럼, 객체의 속성에 접근할 때, 자바스크립트는 아래와 같은 절차를 따릅니다.

+ +
    +
  1. 해당 속성에 대한 객체 자신의 값이 있는지 확인하고 있으면 그 값을 반환한다.
  2. +
  3. 객체 자신의 값이 없으면 __proto__ 속성을 사용하여 프로토타입 체인을 확인한다.
  4. +
  5. 프로토타입 체인상의 특정 객체가 해당 속성에 대한 값을 가지고 있다면 해당 객체의 값을 반환한다.
  6. +
  7. 해당 속성을 가진 어떤 객체도 발견하지 못하면 해당 객체는 그 속성을 가지고 있지 않은 것으로 판단한다.
  8. +
+ +

이런 단계들의 결과는 생성자 및 프로토타입 체인등의 것들을 어떻게 정의 하느냐에 따라 달라집니다. 아래와 같은 원래의 예제는 이런 정의들을 가지고 있습니다:

+ +
function Employee () {
+  this.name = "";
+  this.dept = "general";
+}
+
+function WorkerBee () {
+  this.projects = [];
+}
+WorkerBee.prototype = new Employee;
+
+ +

이런 정의들을 가지고, amy라는 근로자(WorkerBee)인스턴스를 아래와 같이 생성하였다고 가정합니다.

+ +
var amy = new WorkerBee;
+
+ +

amy객체는 프로젝트라는 자신만의 속성을 가집니다.이름과 부서 속성들은 amy 자신의 속성이 아닌 amy객체의 __proto__속성을 통해 가지고 온 속성들입니다. 따라서 amy는 이런 속성들의 값을 가지게 됩니다.

+ +
amy.name == "";
+amy.dept == "general";
+amy.projects == [];
+
+ +

직원(Employee)과 연관되어 있는 프로토타입내의 이름 속성의 값을 아래와 같이 변경하였다고 가정합니다.

+ +
Employee.prototype.name = "Unknown"
+
+ +

얼핏보기에, 새로운 값이 모든 직원 인스턴스에 적용이 될것으로 예상하겠지만 그렇지 않습니다. 

+ +

직원 객체의 인스턴스를 생성할때, 해당 인스턴스는 이름 속성에 대해 자신이 가지고 있는 값(빈 문자열)을 취하게 됩니다.이것이 의미하는 것은 새로운 직원 객체를 생성하여 근로자(WorkerBee)의 프로토타입에 설정을 할때, WorkerBee.prototype이 이름 속성에 대한 자신만의 값을 가지고 있다는 것입니다.그러므로, amy객체(근로자 인스턴스)의 이름 속성에 대해 검색할때, WorkerBee.prototype내에서 이름 속성에 대한 amy 객체 자신의 값을 찾게됩니다. 그렇기때문에 Employee.prototype까지의 프로토타입 체인을 검색하지 않게 됩니다.

+ +

실행시에 객체의 속성 값을 변경하고 새로운 값이 모든 하위 객체들에게도 적용되도록 할려면, 객체의 생성자함수에서는 속성을 정의할 수 없습니다. 대신에, 생성자와 연결된 프로토타입에 추가할 수 있습니다. 예를 들어, 이전의 코드를 아래와 같이 변경하였다고 가정합니다:

+ +
function Employee () {
+  this.dept = "general";
+}
+Employee.prototype.name = "";
+
+function WorkerBee () {
+  this.projects = [];
+}
+WorkerBee.prototype = new Employee;
+
+var amy = new WorkerBee;
+
+Employee.prototype.name = "Unknown";
+
+ +

이 경우 amy 객체의 이름 속성의 값은 "Unknown"이 됩니다.

+ +

위의 예제에서처럼, 객체 생성 시에 객체의 속성에 대한 기본 값을 설정하고 실행 시에 해당 속성의 값을 변경하기를 원한다면, 해당 속성들을 생성자 함수 자체안에가 아닌 생성자의 프로토타입에 설정 하여야 합니다.

+ +

인스턴스 관계 결정

+ +

자바스크립트에서의 속성 검색은 객체 자신의 속성들을 먼저 살펴보고 해당 속성명을 찾지 못할 경우, 객체의 특별한 속성인 __proto__내에서 찾게 됩니다. 이런 검색은 재귀적으로 진행되며, 이런 과정을 "프로토타입 체인에서의 검색"이라고 합니다.

+ +

특별한 속성인 __proto__객체가 생성이 될때 설정이 됩니다. __proto__속성은 생성자의 프로토타입 속성의 값으로 설정이 됩니다. 따라서 new Foo() 표현식은 __proto__ == Foo.prototype인 객체를 생성합니다. 결과적으로 Foo.prototype의 속성들에 대한 변경은 new Foo() 표현식으로 생성한 모든 객체에 대한 속성 검색을 변경하게 됩니다.

+ +

모든 객체는 __proto__라는 객체 속성을 가집니다.(예외: Object). 모든 함수들은 prototype이라는 객체 속성을 가집니다. 따라서 객체들은 '프로토타입 상속'에 의해 다른 객체들과의 관계를 가지게 됩니다.객체의 __proto__속성과 함수의 prototype 객체를 비교하여 상속을 테스트 해볼 수 있습니다. 자바스크립트는 특정 객체가 함수 prototype으로부터 상속 받는 객체일 경우 참(true)를 반환하는  instanceof라는 연산자를 제공합니다. 예를 들면,

+ +
var f = new Foo();
+var isTrue = (f instanceof Foo);
+ +

Inheriting properties에 나오는 예제와 동일한 정의들을 작성해 놓았을 경우, 보다 상세한 예제는 아래와 같습니다.엔지니어(Engineer)객체를 아래와 같이 생성합니다:

+ +
var chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");
+
+ +

생성된 객체를 가지고 아래와 같은 구문을 실행할 경우 각 구문에 대한 결과는 모두 참(true)입니다.

+ +
chris.__proto__ == Engineer.prototype;
+chris.__proto__.__proto__ == WorkerBee.prototype;
+chris.__proto__.__proto__.__proto__ == Employee.prototype;
+chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;
+chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;
+
+ +

주어진 이런 상황에서, instanceOf를 다음과 같이 직접 작성할 수 있을 것입니다:

+ +
function instanceOf(object, constructor) {
+   object = object.__proto__;
+   while (object != null) {
+      if (object == constructor.prototype)
+         return true;
+      if (typeof object == 'xml') {
+        return constructor.prototype == XML.prototype;
+      }
+      object = object.__proto__;
+   }
+   return false;
+}
+
+ +
+

주의: 위의 구현내용은 최신 버전의 자바스크립트에서 XML객체들이 표현되는 방법의 특질을 해결하기 위해 해당 객체의 타입이 "xml"인지 확인합니다. 핵심적인 세부 사항을 확인하려면 {{ bug(634150) }}를 참조하세요.

+
+ +

위의 instanceOf함수를 사용하면 아래의 표현들은 모두 참(true)입니다:

+ +
instanceOf (chris, Engineer)
+instanceOf (chris, WorkerBee)
+instanceOf (chris, Employee)
+instanceOf (chris, Object)
+
+ +

하지만 아래의 표현식은 거짓(false)가 됩니다:

+ +
instanceOf (chris, SalesPerson)
+
+ +

생성자내에서의 전역 정보

+ +

생성자를 생성할때, 생성자내에서 전역 정보를 설정할 경우, 주의를 해야 합니다. 예를 들어, 각각의 새로운 직원에게 자동으로 고유한 ID값을 할당하기를 원한다고 했을 때, 다음과 같은 직원(Employee) 정의를 사용할 수 있을 것입니다:

+ +
var idCounter = 1;
+
+function Employee (name, dept) {
+   this.name = name || "";
+   this.dept = dept || "general";
+   this.id = idCounter++;
+}
+
+ +

이런 정의 내용을 가지고, 새로운 직원을 생성했을 때, 생성자는 다음의 고유한 ID값을 새로운 직원객체에 할당하고 전역 ID 카운터를 증가 시킵니다. 따라서 다음과 같은 구문으로 각각의 객체를 생성한다면, 결과는 victoria.id는 1 그리고 harry.id는 2가 됩니다:

+ +
var victoria = new Employee("Pigbert, Victoria", "pubs")
+var harry = new Employee("Tschopik, Harry", "sales")
+
+ +

얼핏보면 괜찮아 보입니다. 하지만 이유를 불문하고 직원 객체가 생성될때마다 idCounter는 증가분을 가지게 됩니다.이번장에서 나온 예제에서처럼 전체 직원(Employee) 객체의 계층 구조를 생성하였다면, 프로토타입을 설정할때마다 직원 생성자는 매번 호출 됩니다.다음과 같은 코드를 작성하였다고 가정합니다:

+ +
var idCounter = 1;
+
+function Employee (name, dept) {
+   this.name = name || "";
+   this.dept = dept || "general";
+   this.id = idCounter++;
+}
+
+function Manager (name, dept, reports) {...}
+Manager.prototype = new Employee;
+
+function WorkerBee (name, dept, projs) {...}
+WorkerBee.prototype = new Employee;
+
+function Engineer (name, projs, mach) {...}
+Engineer.prototype = new WorkerBee;
+
+function SalesPerson (name, projs, quota) {...}
+SalesPerson.prototype = new WorkerBee;
+
+var mac = new Engineer("Wood, Mac");
+
+ +

여기서 생략된 정의가 base속성을 가지고 해당 생성자를 프로토타입 체인내의 상위 생성자들을 호출한닥고 좀 더 가정하면, 이런 경우, 생성된 mac객체의 id값은 5가 됩니다.

+ +

어플리케이셔네 따라, 카운터가 이렇게 추가적으로 증가된 것은 문제가 될 수도 그렇지 않을 수 도 있습니다. 카운터에 정확한 값이 설정되기를 원한다면, 사용가능한 해결적은 아래와 같은 생성자를 대신 사용하는 것입니다:

+ +
function Employee (name, dept) {
+   this.name = name || "";
+   this.dept = dept || "general";
+   if (name)
+      this.id = idCounter++;
+}
+
+ +

prototype으로 사용할 직원 인스턴스를 생성할 때, 생성자에 인자들을 주어선 안됩니다. 이 생성자 정의를 사용하여, 인자들을 주지 않을 경우, 생성자는 id에 값을 할당하지 않으며 카운터를 갱신하지 않습니다. 따라서, id값을 가지는 직원 객체에 대해, 반드시 해당 직원의 이름을 명시해야 합니다. 이 예제의 경우 mac인스턴스의 id값은 1이 됩니다.

+ +

다중상속 금지

+ +

몇몇 객체 지향언어들은 다중 상속을 허용합니다. 그것은, 관련이 없는 부모 객체들로 부터 속성들과 값들을 상속 받을 수 있는 것을 말합니다. 자바스크립트는 다중 상속을 지원하지 않습니다.

+ +

속성 값의 상속은 속성에 대한 값을 찾기 위한 프로토타입 체인을 검색에 의해 실행 시점에 이루어 집니다. 하나의 객체는 오로지 하나의 결합된 prototype만을 가지기 때문에, 자바스크립트는 동적으로 하나 이상의 프로토타입 체인으로 부터 상속을 할 수 없습니다. 

+ +

자바스크립트에서, 하나 이상의 다른 생성자 함수를 호출하는 생성자를 사용할 수 있습니다. 이것은 다중 상속처럼 보여질 수 있습니다. 예를 들어, 다음과 같은 구문들을 살펴보세요:

+ +
function Hobbyist (hobby) {
+   this.hobby = hobby || "scuba";
+}
+
+function Engineer (name, projs, mach, hobby) {
+   this.base1 = WorkerBee;
+   this.base1(name, "engineering", projs);
+   this.base2 = Hobbyist;
+   this.base2(hobby);
+   this.machine = mach || "";
+}
+Engineer.prototype = new WorkerBee;
+
+var dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo")
+
+ +

WorkerBee의 정의는 이번 장의 이전에 사용된 것과 동일하다고 가정합니다.이런 경우, dennis객체는 다음과 같은 속성들을 가지게 됩니다:

+ +
dennis.name == "Doe, Dennis"
+dennis.dept == "engineering"
+dennis.projects == ["collabra"]
+dennis.machine == "hugo"
+dennis.hobby == "scuba"
+
+ +

 따라서 dennis객체는 Hobbyist 생성자로부터 취미(hobby)속성을 받아 오지 않습니다. 그런데 Hobbyist생성자의 프로토타입에 속성을 추가 했다고 가정하면 

+ +
Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]
+
+ +

dennis객체는 새로이 추가된 속성을 상속받지 않습니다.

+ +
{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}
diff --git "a/files/ko/web/javascript/guide/\353\251\224\355\203\200_\355\224\204\353\241\234\352\267\270\353\236\230\353\260\215/index.html" "b/files/ko/web/javascript/guide/\353\251\224\355\203\200_\355\224\204\353\241\234\352\267\270\353\236\230\353\260\215/index.html" new file mode 100644 index 0000000000..fe4fa13f83 --- /dev/null +++ "b/files/ko/web/javascript/guide/\353\251\224\355\203\200_\355\224\204\353\241\234\352\267\270\353\236\230\353\260\215/index.html" @@ -0,0 +1,258 @@ +--- +title: 메타 프로그래밍 +slug: Web/JavaScript/Guide/메타_프로그래밍 +translation_of: Web/JavaScript/Guide/Meta_programming +--- +
{{jsSidebar("JavaScript Guide")}} {{Previous("Web/JavaScript/Guide/Iterators_and_Generators")}}
+ +

Starting with ECMAScript 2015, JavaScript gains support for the {{jsxref("Proxy")}} and {{jsxref("Reflect")}} objects allowing you to intercept and define custom behavior for fundamental language operations (e.g. property lookup, assignment, enumeration, function invocation, etc). With the help of these two objects you are able to program at the meta level of JavaScript.

+ +

Proxies

+ +

 ECMAScript 6에서 소개되었습니다, {{jsxref("Proxy")}} 객체는  특정 작업을 가로막는것과  사용자 정의 행위를 시행하는것을 허용합니다.예를 들면 객체가 속성을 가지는 것입니다:

+ +
var handler = {
+  get: function(target, name){
+    return name in target ? target[name] : 42;
+  }
+};
+var p = new Proxy({}, handler);
+p.a = 1;
+console.log(p.a, p.b); // 1, 42
+
+ +

The Proxy object defines a target (an empty object here) and a handler object in which a get trap is implemented. Here, an object that is proxied will not return undefined when getting undefined properties, but will instead return the number 42.

+ +

Additional examples are available on the {{jsxref("Proxy")}} reference page.

+ +

Terminology

+ +

The following terms are used when talking about the functionality of proxies.

+ +
+
{{jsxref("Global_Objects/Proxy/handler","handler","","true")}}
+
Placeholder object which contains traps.
+
traps
+
The methods that provide property access. This is analogous to the concept of traps in operating systems.
+
target
+
Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.
+
invariants
+
Semantics that remain unchanged when implementing custom operations are called invariants. If you violate the invariants of a handler, a {{jsxref("TypeError")}} will be thrown.
+
+ +

Handlers and traps

+ +

The following table summarizes the available traps available to Proxy objects. See the reference pages for detailed explanations and examples.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Handler / trapInterceptionsInvariants
{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}}{{jsxref("Object.getPrototypeOf()")}}
+ {{jsxref("Reflect.getPrototypeOf()")}}
+ {{jsxref("Object/proto", "__proto__")}}
+ {{jsxref("Object.prototype.isPrototypeOf()")}}
+ {{jsxref("Operators/instanceof", "instanceof")}}
+
    +
  • getPrototypeOf method must return an object or null.
  • +
  • If target is not extensible, Object.getPrototypeOf(proxy) method must return the same value as Object.getPrototypeOf(target).
  • +
+
{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}}{{jsxref("Object.setPrototypeOf()")}}
+ {{jsxref("Reflect.setPrototypeOf()")}}
If target is not extensible, the prototype parameter must be the same value as Object.getPrototypeOf(target).
{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}{{jsxref("Object.isExtensible()")}}
+ {{jsxref("Reflect.isExtensible()")}}
Object.isExtensible(proxy) must return the same value as Object.isExtensible(target).
{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}{{jsxref("Object.preventExtensions()")}}
+ {{jsxref("Reflect.preventExtensions()")}}
Object.preventExtensions(proxy) only returns true if Object.isExtensible(proxy) is false.
{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}{{jsxref("Object.getOwnPropertyDescriptor()")}}
+ {{jsxref("Reflect.getOwnPropertyDescriptor()")}}
+
    +
  • getOwnPropertyDescriptor must return an object or undefined.
  • +
  • A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
  • +
  • A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.
  • +
  • A property cannot be reported as existent, if it does not exists as an own property of the target object and the target object is not extensible.
  • +
  • A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object.
  • +
  • The result of Object.getOwnPropertyDescriptor(target)can be applied to the target object using Object.defineProperty and will not throw an exception.
  • +
+
{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}{{jsxref("Object.defineProperty()")}}
+ {{jsxref("Reflect.defineProperty()")}}
+
    +
  • A property cannot be added, if the target object is not extensible.
  • +
  • A property cannot be added as or modified to be non-configurable, if it does not exists as a non-configurable own property of the target object.
  • +
  • A property may not be non-configurable, if a corresponding configurable property of the target object exists.
  • +
  • If a property has a corresponding target object property then Object.defineProperty(target, prop, descriptor) will not throw an exception.
  • +
  • In strict mode, a false return value from the defineProperty handler will throw a {{jsxref("TypeError")}} exception.
  • +
+
{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}Property query: foo in proxy
+ Inherited property query: foo in Object.create(proxy)
+ {{jsxref("Reflect.has()")}}
+
    +
  • A property cannot be reported as non-existent, if it exists as a non-configurable own property of the target object.
  • +
  • A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible.
  • +
+
{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}Property access: proxy[foo]and proxy.bar
+ Inherited property access: Object.create(proxy)[foo]
+ {{jsxref("Reflect.get()")}}
+
    +
  • The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable data property.
  • +
  • The value reported for a property must be undefined if the corresponding target object property is non-configurable accessor property that has undefined as its [[Get]] attribute.
  • +
+
{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}Property assignment: proxy[foo] = barand proxy.foo = bar
+ Inherited property assignment: Object.create(proxy)[foo] = bar
+ {{jsxref("Reflect.set()")}}
+
    +
  • Cannot change the value of a property to be different from the value of the corresponding target object property if the corresponding target object property is a non-writable, non-configurable data property.
  • +
  • Cannot set the value of a property if the corresponding target object property is a non-configurable accessor property that has undefined as its [[Set]] attribute.
  • +
  • In strict mode, a false return value from the sethandler will throw a {{jsxref("TypeError")}} exception.
  • +
+
{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}Property deletion: delete proxy[foo] and delete proxy.foo
+ {{jsxref("Reflect.deleteProperty()")}}
A property cannot be deleted, if it exists as a non-configurable own property of the target object.
{{jsxref("Global_Objects/Proxy/handler/enumerate", "handler.enumerate()")}}Property enumeration / for...in: for (var name in proxy) {...}
+ {{jsxref("Reflect.enumerate()")}}
The enumerate method must return an object.
{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}{{jsxref("Object.getOwnPropertyNames()")}}
+ {{jsxref("Object.getOwnPropertySymbols()")}}
+ {{jsxref("Object.keys()")}}
+ {{jsxref("Reflect.ownKeys()")}}
+
    +
  • The result of ownKeys is a List.
  • +
  • The Type of each result List element is either {{jsxref("String")}} or {{jsxref("Symbol")}}.
  • +
  • The result List must contain the keys of all non-configurable own properties of the target object.
  • +
  • If the target object is not extensible, then the result List must contain all the keys of the own properties of the target object and no other values.
  • +
+
{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}proxy(..args)
+ {{jsxref("Function.prototype.apply()")}} and {{jsxref("Function.prototype.call()")}}
+ {{jsxref("Reflect.apply()")}}
There are no invariants for the handler.applymethod.
{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}new proxy(...args)
+ {{jsxref("Reflect.construct()")}}
The result must be an Object.
+ +

Revocable Proxy

+ +

The {{jsxref("Proxy.revocable()")}} method is used to create a revocable Proxy object. This means that the proxy can be revoked via the function revoke and switches the proxy off. Afterwards, any operation on the proxy leads to a {{jsxref("TypeError")}}

+ +
var revocable = Proxy.revocable({}, {
+  get: function(target, name) {
+    return '[[' + name + ']]';
+  }
+});
+var proxy = revocable.proxy;
+console.log(proxy.foo); // "[[foo]]"
+
+revocable.revoke();
+
+console.log(proxy.foo);  // TypeError is thrown
+proxy.foo = 1;           // TypeError again
+delete proxy.foo;        // still TypeError
+typeof proxy;            // "object", typeof doesn't trigger any trap
+ +

Reflection

+ +

{{jsxref("Reflect")}} is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of the {{jsxref("Global_Objects/Proxy/handler","proxy handlers","","true")}}. Reflect is not a function object.

+ +

Reflect helps with forwarding default operations from the handler to the target.

+ +

With {{jsxref("Reflect.has()")}} for example, you get the in operator as a function:

+ +
Reflect.has(Object, 'assign'); // true
+ +

A better apply function

+ +

In ES5, you typically use the {{jsxref("Function.prototype.apply()")}} method to call a function with a given this value and arguments provided as an array (or an array-like object).

+ +
Function.prototype.apply.call(Math.floor, undefined, [1.75]);
+ +

With {{jsxref("Reflect.apply")}} this becomes less verbose and easier to understand:

+ +
Reflect.apply(Math.floor, undefined, [1.75]);
+// 1;
+
+Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]);
+// "hello"
+
+Reflect.apply(RegExp.prototype.exec, /ab/, ['confabulation']).index;
+// 4
+
+Reflect.apply(''.charAt, 'ponies', [3]);
+// "i"
+ +

Checking if property definition has been successful

+ +

With {{jsxref("Object.defineProperty")}}, which returns an object if successful, or throws a {{jsxref("TypeError")}} otherwise, you would use a {{jsxref("Statements/try...catch","try...catch")}} block to catch any error that occurred while defining a property. Because {{jsxref("Reflect.defineProperty")}} returns a Boolean success status, you can just use an {{jsxref("Statements/if...else","if...else")}} block here:

+ +
if (Reflect.defineProperty(target, property, attributes)) {
+  // success
+} else {
+  // failure
+}
+ +

{{Previous("Web/JavaScript/Guide/Iterators_and_Generators")}}

+ +

 

diff --git "a/files/ko/web/javascript/guide/\354\206\214\352\260\234/index.html" "b/files/ko/web/javascript/guide/\354\206\214\352\260\234/index.html" new file mode 100644 index 0000000000..cac0779ee0 --- /dev/null +++ "b/files/ko/web/javascript/guide/\354\206\214\352\260\234/index.html" @@ -0,0 +1,153 @@ +--- +title: Introduction +slug: Web/JavaScript/Guide/소개 +tags: + - JavaScript + - 가이드 + - 안내서 + - 자바스크립트 +translation_of: Web/JavaScript/Guide/Introduction +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
+ +

이 장은 JavaScript를 소개하고 그 일부 기초 개념을 다룹니다.

+ +

무엇을 미리 알고 있어야 하나요?

+ +

이 안내서는 당신이 다음의 기본적인 배경지식이 있다고 가정합니다.

+ + + +

어디서 JavaScript 정보를 찾을 수 있을까

+ +

MDN에 있는 JavaScript 문서는 다음 세가지 파트로 되어있습니다.

+ + + +

JavaScript가 처음이라면, learning areaJavaScript Guide에 있는 문서를 먼저 보세요. 일단 기초를 확실히 파악한 후에는, 각 객체와 문(statement)에 대한 더 자세한 정보를 JavaScript Reference에서 확인할 수 있습니다.

+ +

JavaScript는 무엇인가?

+ +

JavaScript는 크로스-플랫폼, 객체지향 스크립트 언어입니다. 작고 가벼운 언어입니다. 호스트 환경(가령, 웹 브라우저) 내에서, JavaScript는 프로그램 제어를 제공하기 위해 그 환경의 객체에 연결될 수 있습니다. Node.Js와 같은 자바 스크립트의 고급 서버언어로 사용 할 수도 있습니다.이것을 사용하면 단순히 파일을 다운로드하는 것 (예 : 여러 컴퓨터 간의 실시간 공동 작업)보다 웹 사이트에 더 많은 기능을 추가 할 수 있습니다. 호스트 환경 (예 : 웹 브라우저) 내에서 JavaScript는 해당 환경의 객체에 연결되어 프로그래밍 방식으로 제어 할 수 있습니다.

+ +

JavaScript는 Array, Date, Math와 같은 객체에 대한 표준 라이브러리와 연산자(operator), 제어 구조, 문과 같은 언어 요소의 코어 집합을 포함합니다. 코어 JavaScript는 거기에 추가 객체를 보충하여 다양한 목적으로 확장될 수 있습니다. 예를 들면:

+ + + +

이것은 브라우저에서 JavaScript가 웹 페이지 (DOM)의 모양을 바꿀 수 있음을 의미합니다. 또한 서버의 Node.js JavaScript는 브라우저에 작성된 코드의 사용자 정의 요청에 응답 할 수 있습니다.

+ +

JavaScript 와 Java

+ +

JavaScript 와 Java는 여러 면에서 비슷하지만 어떤 면에서는 근본적으로 다릅니다. JavaScript 언어는 Java를 닮았지만 Java의 정적 형지정(static typing)과 강한 형 검사(strong type checking)가 없습니다. JavaScript는 대부분의 Java 식 구문, 명명 규칙 및 기본적인 흐름 제어 구조를 따릅니다. 그것이 LiveScript에서 JavaScript로 이름이 바뀐 이유였습니다.

+ +

Java의 선언에 의해 생성되는 클래스의 컴파일-타임 시스템과는 달리, JavaScript는 숫자, 불리언, 그리고 문자열 값을 표현하는 적은 수의 자료 형을 기반으로 한 런타임 시스템을 지원합니다. JavaScript 는 더 일반적인 클래스 기반 객체 모델 대신에 프로토타입 기반 객체 모델을 갖습니다. 프로토타입 기반 모델은 동적 상속을 제공합니다. 즉, 상속된 대상은 각각의 객체에 따라 다양할 수 있습니다. JavaScript는 또한 어떤 특정한 선언을 요구하지 않는 함수도 지원합니다. 함수는 객체의 속성이나, 타입이 느슨하게 형지정된 채 실행되는 메소드가 될 수 있습니다.

+ +

JavaScript는 Java에 비해 매우 자유로운 형태의 언어입니다. 여러분은 모든 변수, 클래스, 및 메소드를 선언하지 않아도 됩니다. 여러분은 메소드가 public, private, 또는 protected 인지 염려할 필요가 없고 인터페이스를 구현하지 않아도 됩니다. 변수, 매개변수(parameter), 및 함수의 반환 형은 명시적으로 지정되지 않습니다.

+ +

Java는 빠른 실행과 형 안전성(type safety)을 위해 설계된 클래스 기반 프로그래밍 언어입니다. 형 안전성은, 예를 들어, 여러분이 Java 정수를 객체의 레퍼런스로 형변환(cast)하거나 Java 바이트코드를 변경하여 private 메모리에 접근할 수 없음을 의미합니다. Java의 클래스 기반 모델은 프로그램이 오로지 클래스와 그 메소드로만 구성된다는 것을 뜻합니다. Java의 클래스 상속과 강한 형지정은 보통 단단하게 결합된 객체 계층구조를 요구합니다. 이러한 요구는 Java 프로그래밍을 JavaScript 프로그래밍보다 더 복잡하게 만듭니다.

+ +

반면에, JavaScript는 HyperTalk 과 dBASE 같은 더 작고 동적 형지정이 가능한 언어들의 정신을 계승했습니다. 이러한 스크립팅 언어는 더 쉬운 구문과 특별한 내장(built-in) 기능 및 객체 생성을 위한 최소 요구사항으로 인해 훨씬 더 많은 사람들에게 프로그래밍 도구를 제공합니다.

+ + + + + + + + + + + + + + + + + + + + + + + +
Java와 비교한 JavaScript
JavaScriptJava
객체 지향. 객체의 형 간에 차이 없음. 프로토타입 메커니즘을 통한 상속, 그리고 속성과 메서드는 어떤 객체든 동적으로 추가될 수 있음.클래스 기반. 객체는 클래스 계층구조를 통한 모든 상속과 함께 클래스와 인스턴스로 나뉨. 클래스와 인스턴스는 동적으로 추가된 속성이나 메소드를 가질 수 없음.
변수 자료형이 선언되지 않음(dynamic typing, loosely typed).변수 자료형은 반드시 선언되어야 함(정적 형지정, static typing).
하드 디스크에 자동으로 작성 불가.하드 디스크에 자동으로 작성 가능.
+ +

JavaScript와 Java의 차이에 대한 더 많은 정보는, 객체 모델의 세부사항 장을 보세요.

+ +

JavaScript 와 ECMAScript 명세

+ +

JavaScript는 JavaScript에 기반한 표준화된 국제 프로그래밍 언어를 제공하기 위해Ecma International 에서 표준화 됩니다 — European association for standardizing information and communication systems (ECMA는 이전에 European Computer Manufacturers Association의 두문자어였습니다). ECMAScript라 불리는 이 JavaScript의 표준화 버전은 표준을 지원하는 모든 어플리케이션에서 같은 방식으로 동작합니다. 회사들은 그들의 JavaScript 구현을 개발하기 위해 공개 표준 언어를 사용할 수 있습니다. ECMAScript 표준은 ECMA-262 명세(specification)에서 문서화되었습니다. JavaScript와 ECMAScript 명세 판의 여러 버전에 대한 더 많은 것을 배우려면 New in JavaScript 을 보세요.

+ +

ECMA-262 표준은 또한 IOS-16262로서 ISO (국제 표준화 기구) 에 의해 승인되었습니다. Ecma International website 에서 그 명세를 찾을 수 있습니다. ECMAScript 명세는 World Wide Web Consortium (W3C) 나  WHATWG (Web Hypertext Application Technology Working Group)에 의해 표준화된 Document Object Model (DOM)을 설명하지 않습니다. DOM은 여러분의 스크립트에 HTML 문서 객체를 드러내는 방법을 정의합니다. JavaScript로 프로그래밍을 할 때 사용되는 여러 기술들에 대한 정보를 얻으 시려면, JavaScript technologies overview 를 참고하세요.

+ +

JavaScript 문서 vs ECMAScript 명세

+ +

ECMAScript 명세는 ECMAScript 구현을 위한 요구사항의 집합입니다; 여러분이 여러분의 ECMAScript 구현이나 엔진(가령 Firefox의 SpiderMonkey, 또는 Chrome의 v8)에서 표준을 따르는 언어의 기능을 구현하길 원할 때 유용합니다.

+ +

ECMAScript 문서는 스크립트 프로그래머를 돕기 위함이 아닙니다; 스크립트 작성을 위한 정보는 JavaScript 문서를 사용하세요.

+ +

ECMAScript 명세는 JavaScript 프로그래머에게 익숙하지 않을 수 있는 용어와 문법을 사용합니다. 언어의 기술이 ECMAScript 에서 다를 수 있지만, 언어 그 자체는 같습니다. JavaScript는 ECMAScript 명세에 서술된 모든 기능을 지원합니다.

+ +

JavaScript 문서는 JavaScript 프로그래머에게 적합한 언어의 측면을 설명합니다.

+ +

JavaScript 시작하기

+ +

JavaScript 시작은 쉽습니다: 최신 웹 브라우저만 있으면 됩니다. 이 안내서는 현재 Firefox의 최신 버전에서만 사용 가능한 약간의 JavaScript 기능을 포함하므로, 가장 최신 버전의 Firefox를 사용하기를 권합니다.

+ +

JavaScript를 실험하기 유용한 두 도구가 Firefox에 내장되어 있습니다: Web Console과 Scratchpad.

+ +

웹 콘솔

+ +

웹 콘솔은 현재 로드된 페이지에 대한 정보를 보이고, 또한 여러분이 현재 페이지에서 JavaScript 식을 실행해볼 수 있는 명령어 입력줄(command line)을 제공합니다.

+ +

웹 콘솔을 열기 위해서는, Firefox의 "도구" 메뉴 하위에 있는 "개발자" 메뉴의 "웹 콘솔"을 선택(윈도우와 리눅스에서는 Ctrl+Shift+I, 맥에서는  Cmd-Option-K)합니다. 브라우저 창의 아래에 웹 콘솔이 나타납니다. 콘솔의 바닥을 따라 나온 것이 여러분이 JavaScript를 입력할 수 있는 명령어 입력줄이고, 실행 결과는 바로 위 공간에 표시됩니다:

+ +

+ +

이 콘솔은 eval과 완전히 동일하게 동작합니다:마지막 입력된 표현식이 반환되죠. 간단하게 생각해서, 콘솔에 뭔가 입력할 때마다 eval로 감싼 console.log로 둘러싸인 형태라고 보시면 됩니다.

+ +
function greetMe(yourName) { alert('Hello ' + yourName); } console.log(eval('3 + 5'));
+ +

Scratchpad

+ +

Web Console은 한 줄 JavaScript를 실행하기에 훌륭합니다. 하지만 비록 여러 줄을 실행할 수 있지만, 아주 불편하고 Web Console을 사용해 여러분의 샘플 코드를 저장할 수도 없습니다. 그러므로 좀 더 복잡한 예제를 위해서는 Scratchpad가 더 나은 도구입니다.

+ +

Scratchpad를 열기 위해, Firefox의 메뉴 "Tools" 의 하위에 있는 "Web Developer" 메뉴의 "Scratchpad" 를 선택합니다(단축키: Shift+F4). 이것은 분리된 창에서 열리고 브라우저에서 JavaScript를 작성하고 실행하기 위해 사용할 수 있는 에디터입니다. 여러분은 또한 디스크로부터 스크립트를 부르거나 저장할 수도 있습니다.

+ +

+ +

Hello world

+ +

JavaScript 작성을 시작하기 위해서, Scratchpad를 열고 첫 JavaScript 코드 "Hello World" 를 작성하세요.

+ +
(function(){
+  "use strict";
+  /* Start of your code */
+  function greetMe(yourName) {
+    alert('Hello ' + yourName);
+  }
+
+  greetMe('World');
+  /* End of your code */
+})();
+ +

패드에서 코드를 선택하고 Ctrl + R 키를 눌러 브라우저에서 펼쳐지는 것을 지켜보십시오! 다음 페이지에서 이 가이드는 JavaScript 구문 및 언어 기능을 소개하므로보다 복잡한 응용 프로그램을 작성할 수 있습니다. 그러나 당분간은 (function () { "use strict"를 코드 앞에 추가하고}}) ();를 코드마지막에 추가하세요. 아직은 이코드가 뭔지 잘 모르겠지만 나중에 이 코드가 의미하는 것을 배울 것입니다, 지금은 간단히 다음과 같다고 생각하세요.

+ +
    +
  1. 성능을 크게 개선합니다.
  2. +
  3. 초보자가 실수하게 만드는 Javascript의 일부 시맨틱을 막습니다.
  4. +
  5. 콘솔에서 실행되는 코드 스니펫이 서로 상호 작용하지 못하도록합니다 (예 : 한 콘솔 실행에서 생성 된 내용을 다른 콘솔 실행에 사용하는 경우).
  6. +
+ +

{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}

diff --git "a/files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/assertions/index.html" "b/files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/assertions/index.html" new file mode 100644 index 0000000000..350c50f8f9 --- /dev/null +++ "b/files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/assertions/index.html" @@ -0,0 +1,244 @@ +--- +title: Assertions +slug: Web/JavaScript/Guide/정규식/Assertions +translation_of: Web/JavaScript/Guide/Regular_Expressions/Assertions +--- +

{{jsSidebar("JavaScript Guide")}}

+ +

Assertions에는 행이나 단어의 시작 · 끝을 나타내는 경계와 (앞, 뒤 읽고 조건식을 포함한) 어떤 식 으로든 매치가 가능한 것을 나타내는 다른 패턴이 포함됩니다.

+ +
{{EmbedInteractiveExample("pages/js/regexp-assertions.html", "taller")}}
+ +

Types

+ +

Boundary-type assertions

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
CharactersMeaning
^ +

Matches the beginning of input. If the multiline flag is set to true, also matches immediately after a line break character. For example, /^A/ does not match the "A" in "an A", but does match the first "A" in "An A".

+ +
+

This character has a different meaning when it appears at the start of a group.

+
+
$ +

Matches the end of input. If the multiline flag is set to true, also matches immediately before a line break character. For example, /t$/ does not match the "t" in "eater", but does match it in "eat".

+
\b +

Matches a word boundary. This is the position where a word character is not followed or preceded by another word-character, such as between a letter and a space. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero.

+ +

Examples:

+ +
    +
  • /\bm/ matches the "m" in "moon".
  • +
  • /oo\b/ does not match the "oo" in "moon", because "oo" is followed by "n" which is a word character.
  • +
  • /oon\b/ matches the "oon" in "moon", because "oon" is the end of the string, thus not followed by a word character.
  • +
  • /\w\b\w/ will never match anything, because a word character can never be followed by both a non-word and a word character.
  • +
+ +

To match a backspace character ([\b]), see Character Classes.

+
\B +

Matches a non-word boundary. This is a position where the previous and next character are of the same type: Either both must be words, or both must be non-words, for example between two letters or between two spaces. The beginning and end of a string are considered non-words. Same as the matched word boundary, the matched non-word boundary is also not included in the match. For example, /\Bon/ matches "on" in "at noon", and /ye\B/ matches "ye" in "possibly yesterday".

+
+ +

Other assertions

+ +
+

Note: The ? character may also be used as a quantifier.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
CharactersMeaning
x(?=y) +

Lookahead assertion: Matches "x" only if "x" is followed by "y". For example, /Jack(?=Sprat)/ matches "Jack" only if it is followed by "Sprat".
+ /Jack(?=Sprat|Frost)/ matches "Jack" only if it is followed by "Sprat" or "Frost". However, neither "Sprat" nor "Frost" is part of the match results.

+
x(?!y) +

Negative lookahead assertion: Matches "x" only if "x" is not followed by "y". For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal point. /\d+(?!\.)/.exec('3.141') matches "141" but not "3.

+
(?<=y)x +

Lookbehind assertion: Matches "x" only if "x" is preceded by "y". For example, /(?<=Jack)Sprat/ matches "Sprat" only if it is preceded by "Jack". /(?<=Jack|Tom)Sprat/ matches "Sprat" only if it is preceded by "Jack" or "Tom". However, neither "Jack" nor "Tom" is part of the match results.

+
(?<!y)x +

Negative lookbehind assertion: Matches "x" only if "x" is not preceded by "y". For example, /(?<!-)\d+/ matches a number only if it is not preceded by a minus sign. /(?<!-)\d+/.exec('3') matches "3". /(?<!-)\d+/.exec('-3')  match is not found because the number is preceded by the minus sign.

+
+ +

Examples

+ +

General boundary-type overview example

+ +
// Using Regex boundaries to fix buggy string.
+buggyMultiline = `tey, ihe light-greon apple
+tangs on ihe greon traa`;
+
+// 1) Use ^ to fix the matching at the begining of the string, and right after newline.
+buggyMultiline = buggyMultiline.replace(/^t/gim,'h');
+console.log(1, buggyMultiline); // fix 'tey', 'tangs' => 'hey', 'hangs'. Avoid 'traa'.
+
+// 2) Use $ to fix matching at the end of the text.
+buggyMultiline = buggyMultiline.replace(/aa$/gim,'ee.');
+console.log(2, buggyMultiline); // fix  'traa' => 'tree'.
+
+// 3) Use \b to match characters right on border between a word and a space.
+buggyMultiline = buggyMultiline.replace(/\bi/gim,'t');
+console.log(3, buggyMultiline); // fix  'ihe' but does not touch 'light'.
+
+// 4) Use \B to match characters inside borders of an entity.
+fixedMultiline = buggyMultiline.replace(/\Bo/gim,'e');
+console.log(4, fixedMultiline); // fix  'greon' but does not touch 'on'.
+
+ +

Matching the beginning of an input using a ^ control character

+ +

입력 시작시 일치를 위해 ^를 사용하십시오. 이 예에서는 /^A/ regex로 'A'로 시작하는 결과를 얻습니다. 여기서 ^는 한 가지 역할 만합니다. 적절한 결과를 보기위해 화살표 함수가있는 필터 메소드를 사용합니다.

+ +
let fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"];
+
+// Select fruits started with 'A' by /^A/ Regex.
+// Here '^' control symbol used only in one role: Matching begining of an input.
+
+let fruitsStartsWithA = fruits.filter(fruit => /^A/.test(fruit));
+console.log(fruitsStartsWithA); // [ 'Apple', 'Avocado' ]
+
+ +

두 번째 예제에서 ^는 두 가지 모두에 사용됩니다 : 입력의 일치 시작점, 그룹에서 사용될 때 부정 또는 보완 문자 세트.

+ +
let fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"];
+
+// Selecting fruits that dose not start by 'A' by a /^[^A]/ regex.
+// In this example, two meanings of '^' control symbol are represented:
+// 1) Matching begining of the input
+// 2) A negated or complemented character set: [^A]
+// That is, it matches anything that is not enclosed in the brackets.
+
+let fruitsStartsWithNotA = fruits.filter(fruit => /^[^A]/.test(fruit));
+
+console.log(fruitsStartsWithNotA); // [ 'Watermelon', 'Orange', 'Strawberry' ]
+ +

Matching a word boundary

+ +
let fruitsWithDescription = ["Red apple", "Orange orange", "Green Avocado"];
+
+// Select descriptions that contains 'en' or 'ed' words endings:
+let enEdSelection = fruitsWithDescription.filter(descr => /(en|ed)\b/.test(descr));
+
+console.log(enEdSelection); // [ 'Red apple', 'Green Avocado' ]
+ +

Lookahead assertion

+ +
// JS Lookahead assertion x(?=y)
+
+let regex = /First(?= test)/g;
+
+console.log('First test'.match(regex)); // [ 'First' ]
+console.log('First peach'.match(regex)); // null
+console.log('This is a First test in a year.'.match(regex)); // [ 'First' ]
+console.log('This is a First peach in a month.'.match(regex)); // null
+
+ +

Basic negative lookahead assertion

+ +

For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal point. /\d+(?!\.)/.exec('3.141') matches "141" but not "3.

+ +
console.log(/\d+(?!\.)/g.exec('3.141')); // [ '141', index: 2, input: '3.141' ]
+
+ +

Different meaning of '?!' combination usage in Assertions and  Ranges 

+ +

Different meaning of ?! combination usage in Assertions /x(?!y)/ and Ranges [^?!].

+ +
let orangeNotLemon = "Do you want to have an orange? Yes, I do not want to have a lemon!";
+
+// Different meaning of '?!' combination usage in Assertions /x(?!y)/ and  Ranges /[^?!]/
+let selectNotLemonRegex = /[^?!]+have(?! a lemon)[^?!]+[?!]/gi
+console.log(orangeNotLemon.match(selectNotLemonRegex)); // [ 'Do you want to have an orange?' ]
+
+let selectNotOrangeRegex = /[^?!]+have(?! an orange)[^?!]+[?!]/gi
+console.log(orangeNotLemon.match(selectNotOrangeRegex)); // [ ' Yes, I do not want to have a lemon!' ]
+
+ +

Lookbehind assertion

+ +
let oranges = ['ripe orange A ', 'green orange B', 'ripe orange C',];
+
+let ripe_oranges = oranges.filter( fruit => fruit.match(/(?<=ripe )orange/));
+console.log(ripe_oranges); // [ 'ripe orange A ', 'ripe orange C' ]
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-assertion', 'RegExp: Assertions')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +

For browser compatibility information, check out the main Regular Expressions compatibility table.

+ +

See also

+ + diff --git "a/files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/groups_and_ranges/index.html" "b/files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/groups_and_ranges/index.html" new file mode 100644 index 0000000000..2e2109b4ed --- /dev/null +++ "b/files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/groups_and_ranges/index.html" @@ -0,0 +1,91 @@ +--- +title: Groups and Ranges +slug: Web/JavaScript/Guide/정규식/Groups_and_Ranges +translation_of: Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges +--- +

{{jsSidebar("JavaScript Guide")}}{{draft}}

+ +

그룹(Groups)과 범위(ranges)는 표현 문자의 그룹과 범위를 나타냅니다.

+ +

Types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CharactersMeaning
x|y +

x또는 y와 매칭되는 경우. 예를들면 /green|red/ 은 "green apple"의 "green"과 매치되고 "red apple"의 "red"와 매치됩니다.

+
[xyz]
+ [a-c]
+

A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character. It is also possible to include a character class in a character set.

+ +

For example, [abcd] is the same as [a-d]. They match the "b" in "brisket" and the "c" in "chop".

+ +

For example, [abcd-] and [-abcd] match the "b" in "brisket", the "c" in "chop" and the "-" (hyphen) in "non-profit".

+ +

For example, [\w-] is the same as [A-Za-z0-9_-]. They match the "b" in "brisket", the "c" in "chop" and the "n" in "non-profit".

+
+

[^xyz]
+ [^a-c]

+
+

A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character. For example, [^abc] is the same as [^a-c]. They initially match "o" in "bacon" and "h" in "chop".

+ +
+

The ^ character may also indicate the beginning of input.

+
+
(x) +

Capturing group: Matches x and remembers the match. For example, /(foo)/ matches and remembers "foo" in "foo bar". 

+ +

A regular expression may have multiple capturing groups. In results, matches to capturing groups typically in an array whose members are in the same order as the left parentheses in the capturing group. This is usually just the order of the capturing groups themselves. This becomes important when capturing groups are nested. Matches are accessed using the index of the the result's elements ([1], ..., [n]) or from the predefined RegExp object's properties ($1, ..., $9).

+ +

Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).

+ +

String.match() won't return groups if the /.../g flag is set. However, you can still use String.matchAll() to get all matches.

+
\n +

Where n is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses). For example, /apple(,)\sorange\1/ matches "apple, orange," in "apple, orange, cherry, peach". A complete example follows this table.

+
(?<Name>x) +

Named capturing group: Matches x and stores it on the groups property of the returned matches under the name specified by <Name>. The angle brackets ('<' and '>') are required for group name.

+ +

For example, to extract the United States area code from a phone number, I could use /\((?<area>\d\d\d)\)/. The resulting number would appear under matches.groups.area.

+
(?:x)Non-capturing group: Matches x but does not remember the match. The matched substring cannot be recalled from the resulting array's elements ([1], ..., [n]) or from the predefined RegExp object's properties ($1, ..., $9).
+ +

Examples

+ +

Browser support

+ +

Firefox currently doesn't support named groups. See corresponding issue.

+ +

See also

diff --git "a/files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/index.html" "b/files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/index.html" new file mode 100644 index 0000000000..5fbbcef0a0 --- /dev/null +++ "b/files/ko/web/javascript/guide/\354\240\225\352\267\234\354\213\235/index.html" @@ -0,0 +1,666 @@ +--- +title: 정규 표현식 +slug: Web/JavaScript/Guide/정규식 +tags: + - 자바스크립트 + - 정규식 +translation_of: Web/JavaScript/Guide/Regular_Expressions +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}}
+ +

정규 표현식은 문자열에 나타는 특정 문자 조합과 대응시키기 위해 사용되는 패턴입니다. 자바스크립트에서, 정규 표현식 또한 객체입니다.  이 패턴들은 {{jsxref("RegExp")}}의 {{jsxref("RegExp.exec", "exec")}} 메소드와 {{jsxref("RegExp.test", "test")}} 메소드  ,그리고 {{jsxref("String")}}의  {{jsxref("String.match", "match")}}메소드 , {{jsxref("String.replace", "replace")}}메소드 , {{jsxref("String.search", "search")}}메소드 ,  {{jsxref("String.split", "split")}} 메소드와 함께 쓰입니다 . 이 장에서는 자바스크립트의 정규식에 대하여 설명합니다.

+ +

정규 표현식 만들기

+ +

(역주: 정규 표현식을 줄여서 '정규식'이라고 하기도 합니다. 아래 부분부터 '정규식'이라는 용어를 사용하겠습니다.)

+ +

정규식을 만드는 방법에는 두 가지가 있습니다.

+ +

정규식 리터럴(슬래쉬"/"로 감싸는 패턴)을 사용하는 방법은 다음과 같습니다.

+ +
var re = /ab+c/;
+
+ +

정규식 리터럴은 스크립트가 불러와질 때 컴파일됩니다. 만약 정규식이 상수라면, 이렇게 사용하는 것이 성능을 향상시킬 수 있습니다.

+ +

다른 방법으로는,  {{jsxref("RegExp")}} 객체의 생성자 함수를 호출하는 방법도 있습니다:

+ +
var re = new RegExp("ab+c");
+
+ +

생성자 함수를 사용하면 정규식이 실행 시점에 컴파일됩니다. 정규식의 패턴이 변경될 수 있는 경우, 혹은 사용자 입력과 같이 다른 출처로부터 패턴을 가져와야 하는 경우에는 생성자 함수를 사용하세요.

+ +

정규식 패턴 작성하기

+ +

정규식 패턴은 /abc/ 같이 단순 문자로 구성될 수도 있고, /ab*c/ 또는 /Chapter (\d+)\.\d*/와 같이 단순 문자와 특수 문자의 조합으로 구성될 수도 있습니다. 마지막 예제는 기억장치처럼 쓰이는 괄호를 포함하고 있습니다. {{web.link("#.ED.8C.A8.ED.84.B4.ED.99.94.EB.90.9C_.EB.B6.80.EB.B6.84_.EB.AC.B8.EC.9E.90.EC.97.B4_.EC.9D.BC.EC.B9.98_.EC.82.AC.EC.9A.A9.ED.95.98.EA.B8.B0", "패턴화된 부분 문자열 일치 사용하기") }}에서 설명하는것 처럼 패턴에서 괄호를 포함한 부분은 나중에 사용하기 위하여 저장됩니다.

+ +

단순 패턴 사용하기

+ +

단순 패턴은 문자열을 있는 그대로 대응시키고자 할 때 사용됩니다. 예를 들어, /abc/라는 패턴은 문자열에서 정확히 'abc' 라는 문자들이 모두 함께 순서대로 나타나야 대응됩니다. 위의 패턴은 "Hi, do you know your abc's?" 와 "The latest airplane designs evolved from slabcraft." 두가지 예에서 부분 문자열 'abc'에 대응될 것입니다.  'Grab crab' 이라는 문자열에서 'ab c' 라는 부분 문자열을 포함하고 있지만, 'abc'를 정확하게 포함하고 있지 않기 때문에 대응되지 않습니다.

+ +

특수 문자 사용하기

+ +

검색에서 하나 이상의 b들을 찾거나, 혹은 공백을 찾는 것과 같이 '있는 그대로의 대응' 이상의 대응을 필요로 할 경우, 패턴에 특수한 문자를 포함시킵니다. 예를 들어, /ab*c/ 패턴은  'a' 문자 뒤에 0개 이상의 'b' 문자(* 문자는 바로 앞의 문자가 0개 이상이라는 것을 의미합니다)가 나타나고 바로 뒤에 'c' 문자가 나타나는 문자 조합에 대응됩니다. 문자열 "cbbabbbbcdebc," 에서 위의 패턴은 부분 문자열 'abbbbc' 와 대응됩니다.

+ +

아래 표는 정규식에서 사용되는 모든 특수문자 목록 및 그에 대한 설명입니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
정규식에서의 특수문자
CharacterMeaning
\ +

다음의 규칙에 따라 일치합니다:
+
+ 특수 문자가 아닌 문자(non-special character) 앞에서 사용된 백슬래시는 '해당 문자는 특별하고, 문자 그대로 해석되면 안된다'는 사실을 가리킵니다. 예를 들어, 앞에 \가 없는 'b'는 보통 소문자 b가 나오는 패턴과 대응됩니다. 그러나 '\b' 자체는 어떤 문자와도 대응되지 않습니다; 이 문자는 특별한 단어 경계 문자를 형성합니다.
+
+ 특수 문자 앞에 위치한 백슬래시는 '다음에 나오는 문자는 특별하지않고, 문자 그대로 해석되어야 한다'는 사실을 가리킵니다. 예를 들어, 패턴 /a*/ 에서의 특수문자 '*'는 0개 이상의 'a' 문자가 등장함을 나타냅니다. 이와는 다르게, 패턴 /a\*/ 는 '*'이 특별하지 않다는 것을 나타내며, 'a*'와 같은 문자열과 대응될 수 있습니다.
+
+ RegExp("pattern") 표기를 쓰면서 \ 자체를 이스케이프 하는 것을 잊지 마세요. 왜냐하면 \ 는 문자열에서도 이스케이프 문자이기 때문입니다. (역주: /a\*/ 와 같은 패턴을 생성자로 만들려면 new RegExp('a\\*')와 같이 백슬래시 자체를 이스케이프 시켜주어야 합니다.)

+
^입력의 시작 부분에 대응됩니다. 만약 다중행 플래그가 참으로 설정되어 있다면, 줄 바꿈 문자 바로 다음 부분과도 대응됩니다.
+
+ 예를 들어, /^A/ 는 "an A" 의 'A'와는 대응되지 않습니다, 그러나 "An E" 의 'A'와는 대응됩니다.
+
+ '^' 가 문자셋([abc]) 패턴의 첫 글자로 쓰인다면, 그 때는 전혀 다른 의미를 가집니다. 자세한 내용은 역 문자셋을 참고하세요.
$ +

입력의 끝 부분과 대응됩니다. 만약 다중행 플래그가 참으로 설정되어 있다면, 줄 바꿈 문자의 바로 앞 부분과도 대응됩니다.

+ +

예를 들어, /t$/ 는 "eater" 의 't'에는 대응되지 않습니다, 그러나 "eat" 과는 대응됩니다.

+
* +

앞의 표현식이 0회 이상 연속으로 반복되는 부분과 대응됩니다. {0,} 와 같은 의미입니다.

+ +

예를 들어, /bo*/ 는 "A ghost booooed" 의 'boooo' 와 대응되고, "A bird warbled" 의 'b'에 대응되지만 "A goat grunted" 내의 어느 부분과도 대응되지 않습니다.

+
+ +

앞의 표현식이 1회 이상 연속으로 반복되는 부분과 대응됩니다. {1,} 와 같은 의미입니다.

+ +

예를 들어, /a+/ 는 "candy"의 'a'에 대응되고 "caaaaaaandy" 의 모든 'a'들에 대응되지만, "cndy" 내의 어느 부분과도 대응되지 않습니다.

+
?앞의 표현식이 0 또는 1회 등장하는 부분과 대응됩니다. {0,1} 와 같은 의미입니다.
+
+ 예를 들어, /e?le?/ 는 "angel"의 'el' 에 대응되고, "angle"의 'le' 에 대응되고 또한 "oslo" 의 'l'에도 대응됩니다.
+
+ 만약 수량자 *, +, ?, {} 바로 뒤에 사용하면, 기본적으로 탐욕스럽던(가능한 한 많이 대응시킴) 수량자를 탐욕스럽지 않게(가능한 가장 적은 문자들에 대응시킴) 만듭니다. 예를 들어, /\d+/를 "123abc"에 적용시키면 "123"과 대응됩니다. 그러나 /\d+?/를 같은 문자열에 적용시키면 오직 "1"과만 대응됩니다.
+
+ 또한 이 문자는 x(?=y)x(?!y) 항목에서 설명하는 바와 같이 사전 검증(lookahead assertion)을 위해서도 쓰입니다.
+  
. +

개행 문자를 제외한 모든 단일 문자와 대응됩니다.

+ +

예를 들어, /.n/는 "nay, an apple is on the tree"에서 'an'과 'on'에 대응되지만, 'nay' 에는 대응되지 않습니다.

+
(x) +

다음의 예제가 보여주는것 처럼 'x'에 대응되고, 그것을 기억합니다. 괄호는 포획 괄호(capturing parentheses)라 불립니다.
+
+ 패턴 /(foo) (bar) \1 \2/ 안의 '(foo)' 와 '(bar)'는 문자열"foo bar foo bar"에서 처음의 두 단어에 대응되고 이를 기억합니다. 패턴 내부의 \1\2는 문자열의 마지막 두 단어에 대응됩니다. (역주: \n 패턴은 앞의 n번째 포획괄호에 대응된 문자열과 똑같은 문자열에 대응됩니다.) \1, \2, \n과 같은 문법은 정규식의 패턴 부분에서 사용됩니다. 정규식의 치환 부분에서는 $1, $2, $n과 같은 문법이 사용되어야 합니다. 예를 들어, 'bar foo'.replace( /(...) (...)/, '$2 $1')와 같이 사용되어야 합니다. $& 패턴은 앞에서 대응된 전체 문자열을 가리킵니다.

+
(?:x)'x'에 대응되지만 대응된 것을 기억하지 않습니다. 괄호는 비포획 괄호(non-capturing parentheses)라고 불리우고, 정규식 연산자가 같이 동작할 수 있게 하위 표현을 정의할 수 있습니다. 정규식 예제 /(?:foo){1,2}/을 생각해보세요. 만약 정규식이 /foo{1,2}/라면, {1,2}는 'foo'의 마지막 'o' 에만 적용됩니다. 비포획 괄호과 같이 쓰인다면, {1,2}는 단어 'foo' 전체에 적용됩니다.
x(?=y) +

오직 'y'가 뒤따라오는 'x'에만 대응됩니다. 이것은 lookahead 라고 불립니다.

+ +

예를 들어, /Jack(?=Sprat)/ 는 'Sprat'가 뒤따라오는 'Jack' 에만 대응됩니다. /Jack(?=Sprat|Frost)/는 'Sprat' 또는 'Frost'가 뒤따라오는 'Jack'에만 대응됩니다. 그러나, 'Sprat' 및 'Frost' 는 대응 결과의 일부가 아닙니다.

+
x(?!y) +

'x'뒤에  'y'가 없는경우에만 'x'에 일치합니다. 이것은 negated lookahead 라고 불립니다.

+ +

예를 들어, /\d+(?!\.)/는 소숫점이 뒤따라오지 않는 숫자에 일치합니다. 정규식 /\d+(?!\.)/.exec("3.141")는 '3.141' 이 아닌 '141'에 일치합니다.

+
x|y +

'x' 또는 'y'에 대응됩니다.

+ +

예를 들어, /green|red/는 "green apple"의 'green'에 대응되고, "red apple."의 'red'에 대응됩니다.

+
{n}앞 표현식이 n번 나타나는 부분에 대응됩니다. n은 반드시 양의 정수여야 합니다.
+
+ 예를 들어, /a{2}/는 "candy,"의 'a'에는 대응되지 않지만, "caandy,"의 모든 a 와, "caaandy."의 첫 두 a 에는 대응됩니다.
{n,m} +

nm은 양의 정수이고, n <= m를 만족해야 합니다. 앞 문자가 최소 n개, 최대 m개가 나타나는 부분에 대응됩니다. m이 생략된다면, m은 ∞로 취급됩니다.

+ +

예를 들어, /a{1,3}/는 "cndy"에서 아무것에도 대응되지 않지만, "caandy,"의 첫 두 a 와 "caaaaaaandy"의 첫 세 a 에 대응됩니다. "caaaaaaandy"에서 더 많은 a 들이 있지만, "aaa"에만 대응된다는 점에 주목하세요.

+
[xyz]문자셋(Character set) 입니다. 이 패턴 타입은 괄호 안의 어떤 문자(이스케이프 시퀀스까지 포함)와도 대응됩니다. 점(.) 이나 별표 (*) 같은 특수 문자는 문자셋 내부에서는 특수 문자가 아닙니다. 따라서 이스케이프시킬 필요가 없습니다. 하이픈을 이용하여 문자의 범위를 지정해줄 수 있습니다.
+
+ 예를 들어, 패턴 [a-d] 는 패턴 [abcd] 와 똑같이 동작하며, "brisket"의 'b' 에 일치하고, "city"의 'c' 에 일치합니다. 패턴 /[a-z.]+/ /[\w.]+/ 는 "test.i.ng" 전체 문자열이 일치합니다.
[^xyz] +

부정 문자셋(negated character set) 또는 보충 문자셋(complemented character set)입니다. 괄호 내부에 등장하지 않는 어떤 문자와도 대응됩니다. 하이픈을 이용하여 문자의 범위를 지정할 수 있습니다. 일반적인 문자셋에서 작동하는 모든 것은 여기에서도 작동합니다.

+ +

예를 들어, 패턴[^abc]는 패턴[^a-c]와 동일합니다. 두 패턴은 "brisket"의 'r', "chop."의 'h' 에 대응됩니다.

+
[\b]백스페이스(U+0008)에 대응됩니다. 이와 같이, 백스페이스 문자 리터럴에 대응시키려면, 대괄호("[]")를 이용해야만 합니다. (\b와 혼동하지 마세요.)
\b +

단어 경계에 대응됩니다. 단어 경계는 다른 '단어 문자'가 앞이나 뒤에 등장하지 않는 위치에 대응됩니다. 단어의 경계는 대응 결과에 포함되지 않는다는 사실에 주의하세요. 다른 말로는, 단어의 경계에 대응되는 문자열의 길이는 항상 0입니다. (패턴 [\b]와 혼동하지 마세요.)

+ +

예제:
+ /\bm/는 "moon"의 'm'에 대응됩니다;
+ /oo\b/ 는 "moon"의 'oo' 부분에 대응되지 않는데, 왜냐하면 'oo'를 뒤따라오는 'n'이 단어 문자이기 때문입니다;
+ /oon\b/는 "moon"의 'oon'에 대응됩니다. 왜냐하면, 'oon'은 문자열의 끝이라서, 뒤따라오는 단어 문자가 없기 때문입니다 ;
+ /\w\b\w/는 어떤 것에도 일치하지 않습니다. 왜냐하면, 단어 문자는 절대로 비 단어 문자와 단어 문자 두개가 뒤따라올수 없기 때문입니다.

+ +
+

숙지하세요: 자바스크립트의 정규식 엔진은 특정 문자 집합을 '단어 문자'로 정의합니다. 이 집단에 속하지 않는 모든 문자는 단어 분리(word break) 로 여겨집니다. 단어 문자로 간주되는 문자들은 얼마 없습니다: 오로지 로마자 소문자와 대문자, 10진수 숫자, 밑줄 문자로 구성되어 있습니다. "é" 또는 "ü" 같이, 강세 표시 문자들은 안타깝게도 단어 분리(word breaks) 로 취급됩니다.

+
+
\B +

단어 경계가 아닌 부분에 대응됩니다. 아래와 같은 경우들이 있습니다:

+ +
    +
  • 문자열의 첫 번째 문자가 단어 문자가 아닌 경우, 해당 문자의 앞 부분에 대응됩니다.
  • +
  • 문자열의 마지막 문자가 단어 문자가 아닌 경우, 해당 문자의 뒷 부분에 대응됩니다.
  • +
  • 두 단어 문자의 사이에 대응됩니다.
  • +
  • 단어 문자가 아닌 두 문자 사이에 대응됩니다.
  • +
  • 빈 문자열에 대응됩니다.
  • +
+ +

문자열의 시작 부분과 끝 부분은 단어가 아닌 것으로 간주됩니다.

+ +

예를 들어, /\B../ 는 "noonday"의 'oo'와 대응되며, /y\B./ 는 "possibly yesterday."의 'ye'와 대응됩니다.

+
\cX +

문자열 내부의 제어 문자에 대응됩니다. 여기서 X는 A에서 Z까지의 문자 중 하나입니다.

+ +

예를 들어, /\cM/는 문자열에서 control-M (U+000D)에 대응됩니다.

+
\d +

숫자 문자에 대응됩니다. [0-9]와 동일합니다.

+ +

예를 들어, /\d/ 또는 /[0-9]/는 "B2 is the suite number."에서 '2'에 대응됩니다.

+
\D +

숫자 문자가 아닌 문자에 대응됩니다. [^0-9]와 동일합니다.

+ +

예를 들어, /\D/ 또는 /[^0-9]/는 "B2 is the suite number."의 'B'에 대응됩니다.

+
\f폼피드 (U+000C) 문자에 대응됩니다.
\n줄 바꿈 (U+000A) 문자에 대응됩니다.
\r캐리지 리턴(U+000D) 문자에 대응됩니다.
\s +

스페이스, 탭, 폼피드, 줄 바꿈 문자등을 포함한 하나의 공백 문자에 대응됩니다. [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].와 동일합니다.

+ +

예를 들어, /\s\w*/는 "foo bar."의 ' bar'에 대응됩니다.

+
\S +

공백 문자가 아닌 하나의 문자에 대응됩니다. [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. 와 동일합니다.

+ +

예를 들어, /\S\w*/는 "foo bar."의 'foo' 에 대응됩니다.

+
\t탭 (U+0009) 문자에 대응됩니다.
\v수직 탭(U+000B) 문자에 대응됩니다.
\w +

밑줄 문자를 포함한 영숫자 문자에 대응됩니다. [A-Za-z0-9_] 와 동일합니다. (역주: 여기에 대응되는 문자를 단어 문자라고 합니다.)

+ +

예를 들어, /\w/는 "apple,"의 'a' 에 대응되고, "$5.28,"의 '5'에 대응되고,"3D."의 '3'에 대응됩니다.

+
\W +

단어 문자가 아닌 문자에 대응됩니다. [^A-Za-z0-9_] 와 동일합니다.

+ +

예를 들어, /\W/ 또는 /[^A-Za-z0-9_]/는 "50%."의 '%' 에 대응됩니다.

+
\n +

정규식 내부의 n번째 괄호에서 대응된 부분에 대한 역참조 입니다. 여기서, n은 양의 정수입니다.

+ +

예를 들어, /apple(,)\sorange\1/는 "apple, orange, cherry, peach."의 'apple, orange,' 에 일치합니다.

+
\0널 (U+0000)문자에 대응합니다. 이 때 다른 숫자를 뒤에 쓰지 마세요. 왜냐하면 \0<digits>는 8진 이스케이프 시퀀스이기 때문입니다.
\xhh코드가 hh(두 16진 숫자)인 문자에 일치합니다.
\uhhhh코드가 hhhh(네개의 16진 숫자)인 문자에 일치합니다.
+ +

사용자 입력을 이스케이프해서 정규식 내부에서 문자 그대로 취급해야 하는 경우, 간단히 치환을 하면 됩니다:

+ +
function escapeRegExp(string){
+  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $&는 일치한 전체 문자열을 의미합니다.
+}
+ +

괄호를 사용하기

+ +

정규식 내부의 일부를 둘러싼 괄호는, 해당 부분에서 대응된 문자열을 기억하는 효과를 갖습니다. 기억된 문자열은 이후 {{ web.link("#.ED.8C.A8.ED.84.B4.ED.99.94.EB.90.9C_.EB.B6.80.EB.B6.84_.EB.AC.B8.EC.9E.90.EC.97.B4_.EC.9D.BC.EC.B9.98_.EC.82.AC.EC.9A.A9.ED.95.98.EA.B8.B0", "패턴화된 부분 문자열 일치 사용하기") }}에서 설명한 것처럼 다른 곳에서 사용하기 위하여 불러와질 수 있습니다.

+ +

예를 들면, 패턴 /Chapter (\d+)\.\d*/는 패턴의 일부분이 기억될 거라는 사실을 나타냅니다. 이 패턴은 하나 이상의 숫자(\d는 숫자를 의미하고 +는 1개 이상을 의미합니다.) 이후에 하나의 소숫점(\가 앞에 붙은 소숫점은 문자 그대로의 문자 '.' 에 대응됨을 나타냅니다), 그뒤 0개 이상의 숫자(\d 는 숫자, * 는 0개 이상을 의미합니다.)가 뒤따라오는 'Chapter ' 문자열에 대응됩니다. 더해서, 괄호는 처음으로 일치하는 숫자 문자들을 기억하기 위하여 사용되었습니다.

+ +

이 패턴은 "Open Chapter 4.3, paragraph 6"에 나타나며, '4'가 기억됩니다. 이 패턴은 "Chapter 3 and 4"에는 나타나지 않습니다. 왜냐하면 문자열이 '3'이후에 마침표를 가지고 있지 않기 때문입니다.

+ +

부분 문자열을 대응시키면서도 해당 부분을 기억하지 않으려면, 괄호의 첫머리에 ?:패턴을 사용하세요. 예를 들어, (?:\d+)는 1개 이상의 숫자에 대응되지만 해당 문자들을 기억하지 않습니다.

+ +

정규식 사용하기

+ +

정규식은 RegExp, test, exec, String, match, replace, search, split 메소드와 함께 쓰입니다. 이 메소드는 JavaScript reference에서 잘 설명되어 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
정규식에서 쓰이는 메소드
MethodDescription
{{jsxref("RegExp.exec", "exec")}}대응되는 문자열을 찾는 RegExp 메소드입니다. 정보를 가지고 있는 배열을 반환합니다. 대응되는 문자열을 찾지 못했다면 null을 반환합니다.
{{jsxref("RegExp.test", "test")}}대응되는 문자열이 있는지 검사하는 RegExp 메소드 입니다. true 나 false를 반환합니다.
{{jsxref("String.match", "match")}}대응되는 문자열을 찾는 RegExp 메소드입니다. 정보를 가지고 있는 배열을 반환합니다. 대응되는 문자열을 찾지 못했다면 null을 반환합니다.
{{jsxref("String.search", "search")}} +

대응되는 문자열이 있는지 검사하는 String 메소드 입니다. 대응된 부분의 인덱스를 반환합니다. 대응되는 문자열을 찾지 못했다면 -1을 반환합니다.

+
{{jsxref("String.replace", "replace")}}대응되는 문자열을 찾아 다른 문자열로 치환하는 String 메소드입니다.
{{jsxref("String.split", "split")}}정규식 혹은 문자열로 대상 문자열을 나누어 배열로 반환하는 String 메소드입니다.
+ +

문자열 내부에 패턴과 대응되는 부분이 있는지 알고 싶다면, test 나 search 메소드를 사용하세요; 좀 더 많은 정보를 원하면 (대신 실행이 느림)  exec 나 match 메소드를 사용하세요. 만약 exec 나 match 메소드를 사용했는데 대응되는 부분이 있다면, 이 메소드는 배열을 반환하고 정규식 객체의 속성을 업데이트 합니다. 만약 대응되는 부분이 없다면, exec 메소드는 null 을 반환합니다. (즉, false와 같은 의미로 사용될 수 있습니다.).

+ +

아래의 예에서는, 문자열 내부에서 대응되는 부분을 찾기 위해 exec 메소드를 사용했습니다.

+ +
var myRe = /d(b+)d/g;
+var myArray = myRe.exec("cdbbdbsbz");
+
+ +

만약 정규식 속성에 접근할 필요가 없다면, 아래와 같이 myArray를 만드는 다른 방법도 있습니다:

+ +
var myArray = /d(b+)d/g.exec("cdbbdbsbz");
+
+ +

문자열로부터 정규식을 만들고 싶다면, 이런 방법도 있습니다:

+ +
var myRe = new RegExp("d(b+)d", "g");
+var myArray = myRe.exec("cdbbdbsbz");
+
+ +

위의 스크립트에서는, 대응되는 부분이 발견되었고 아래의 표에서 설명하는 대로 배열을 반환하며 속성을 갱신합니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
정규식 실행결과
ObjectProperty or indexDescriptionIn this example
myArray대응된 문자열 및 기억한 모든 부분 문자열['dbbd', 'bb', index: 1, input: 'cdbbdbsbz']
index입력된 문자열에서 대응된 부분에 해당하는 인덱스 (0부터 시작)1
input입력된 원본 문자열"cdbbdbsbz"
[0]마지막으로 대응된 문자열"dbbd"
myRelastIndex다음 검색 시 검색을 시작할 인덱스 (이 속성은 g 옵션을 설정한 정규식에 대해서만 설정됩니다. 자세한 사항은 {{ web.link("#Advanced_searching_with_flags", "Advanced Searching With Flags") }} 부분을 참고하세요.)5
source패턴 문자열. 정규식이 생성될 때 갱신됩니다. 실행 시점에는 갱신되지 않습니다."d(b+)d"
+ +

위 예제에서의 두 번째 형태처럼, 정규식 객체를 변수에 대입하지 않고도 사용할 수 있습니다. 하지만, 이렇게 하면 정규식 객체가 매번 새로 생성됩니다. 이러한 이유로, 만약 변수에 대입하지 않는 형태를 사용하는 경우 나중에 그 정규식의 속성에 접근할 수 없게 됩니다. 예를 들어, 이러한 스크립트가 있을 수 있습니다:

+ +
var myRe = /d(b+)d/g;
+var myArray = myRe.exec("cdbbdbsbz");
+console.log("The value of lastIndex is " + myRe.lastIndex);
+
+// "The value of lastIndex is 5"
+
+ +

그러나, 만약 이러한 스크립트가 있으면:

+ +
var myArray = /d(b+)d/g.exec("cdbbdbsbz");
+console.log("The value of lastIndex is " + /d(b+)d/g.lastIndex);
+
+// "The value of lastIndex is 0"
+
+ +

두 구문에서의 /d(b+)d/g 는 서로 다른  정규식 객체이고, 따라서 별개의 lastIndex 속성을 갖게 됩니다. 정규식 객체의 속성을 사용해야 하는 경우라면, 먼저 변수에 대입하세요.

+ +

괄호로 둘러싼 패턴 사용하기

+ +

정규식 패턴에 괄호를 사용하면, 그 부분을 별도로 대응시키면서 대응된 부분을 기억합니다. 예를 들면, /a(b)c/ 는 'abc' 와 대응되면서 'b'를 기억합니다. 괄호로 감싸진 문자열을 불러오려면, 배열 요소 [1], ..., [n] 를 사용하세요.

+ +

괄호로 감쌀 수 있는 문자의 개수에는 제한이 없습니다. 반환된 배열은 찾아낸 모든 것들을 갖고 있습니다. 다음의 예는 괄호로 둘러싸진 부분이 어떻게 대응되는지 보여줍니다.

+ +

다음의 예는 문자열 내부의 단어를 바꾸기 위해 {{jsxref("String.replace", "replace()")}} 메소드를 이용하고 있습니다. 치환 문자열로는 $1$2 를 사용하고 있는데, 이는 각각 첫 번째와 두 번째 괄호가 쳐진 부분에 대응된 문자열을 가리킵니다.

+ +
var re = /(\w+)\s(\w+)/;
+var str = "John Smith";
+var newstr = str.replace(re, "$2, $1");
+console.log(newstr);
+
+// "Smith, John"
+
+ +

플래그를 사용한 고급검색

+ +

정규식은 여섯 개의 플래그를 설정해줄 수 있으며, 이를 통해 전역 검색 또는 대소문자 구분 없는 검색을 수행할 수 있습니다. 이 플래그들은 각기 사용될 수도 있고 함께 사용될 수도 있고 순서에 구분이 없습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Regular expression flags
FlagDescription
g전역 검색
i대소문자 구분 없는 검색
m다중행(multi-line) 검색
s.에 개행 문자도 매칭(ES2018)
u유니코드; 패턴을 유니코드 코드 포인트의 나열로 취급합니다.
y"sticky" 검색을 수행. 문자열의 현재 위치부터 검색을 수행합니다. {{jsxref("RegExp.sticky", "sticky")}} 문서를 확인하세요.
+ +

정규식에 플래그를 포함시키려면, 아래 문법을 사용하세요:

+ +
var re = /pattern/flags;
+
+ +

혹은 아래와 같이 할 수도 있습니다:

+ +
var re = new RegExp("pattern", "flags");
+
+ +

이 플래그는 정규식에 합쳐지는 정보임을 기억하는게 좋습니다. 이것들은 나중에 추가되거나 제거될 수 없습니다.

+ +

예를 들어, re = /\w+\s/g 는 한 개 이상의 문자열 뒤에 공백이 하나 있는 패턴을 찾는 정규식을 생성합니다. 그리고 문자열 전체에 걸쳐 이 조합을 검색합니다.

+ +
var re = /\w+\s/g;
+var str = "fee fi fo fum";
+var myArray = str.match(re);
+console.log(myArray);
+
+// ["fee ", "fi ", "fo "]
+
+ +

아래 코드는:

+ +
var re = /\w+\s/g;
+
+ +

이렇게 바꿔쓸 수 있습니다:

+ +
var re = new RegExp("\\w+\\s", "g");
+
+ +

그리고 똑같은 결과를 얻습니다.

+ +

 .exec() 메소드를 사용할 때에는 'g' 플래그에 대한 동작이 다릅니다.  ("클래스"와 "인수"의 역할이 뒤바뀝니다:  .match()를 사용할 때는, string 클래스가 메소드를 갖고 정규식은 인수였던 것에 반해, .exec()를 사용할 때는 정규식이 메소드를 갖고 문자열이 인수가 됩니다. str.match(re) 과 re.exec(str)를 비교해보세요.)  'g' 플래그와  .exec() 메소드가 함께 사용되면 진행상황에 대한 정보가 반환됩니다.

+ +
var xArray; while(xArray = re.exec(str)) console.log(xArray);
+// 다음과 같이 출력됩니다:
+// ["fee ", index: 0, input: "fee fi fo fum"]
+// ["fi ", index: 4, input: "fee fi fo fum"]
+// ["fo ", index: 7, input: "fee fi fo fum"]
+ +

m 플래그는 여러 줄의 입력 문자열이 실제로 여러 줄로서 다뤄져야 하는 경우에 쓰입니다. 만약 m 플래그가 사용되면, ^$ 문자는 전체 문자열의 시작과 끝에 대응되는 것이 아니라 각 라인의 시작과 끝에 대응됩니다.

+ +

예시

+ +

다음의 예는 정규 표현식의 몇 가지 사용법을 보여줍니다.

+ +

입력 문자열에서 순서를 변경하기

+ +

다음 예는 정규식의 , string.split()과 string.replace()의 사용을 설명합니다. 그것은 공백, 탭과 정확히 하나의 세미콜론의 구분으로 이름(이름을 먼저)이 포함된 대략 형식의 입력 문자열을 정리합니다. 마지막으로, 순서(성을 먼저)를 뒤바꾸고 목록을 정렬합니다.

+ +
// The name string contains multiple spaces and tabs,
+// and may have multiple spaces between first and last names.
+var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ; Chris Hand ";
+
+var output = ["---------- Original String\n", names + "\n"];
+
+// Prepare two regular expression patterns and array storage.
+// Split the string into array elements.
+
+// pattern: possible white space then semicolon then possible white space
+var pattern = /\s*;\s*/;
+
+// Break the string into pieces separated by the pattern above and
+// store the pieces in an array called nameList
+var nameList = names.split(pattern);
+
+// new pattern: one or more characters then spaces then characters.
+// Use parentheses to "memorize" portions of the pattern.
+// The memorized portions are referred to later.
+pattern = /(\w+)\s+(\w+)/;
+
+// New array for holding names being processed.
+var bySurnameList = [];
+
+// Display the name array and populate the new array
+// with comma-separated names, last first.
+//
+// The replace method removes anything matching the pattern
+// and replaces it with the memorized string—second memorized portion
+// followed by comma space followed by first memorized portion.
+//
+// The variables $1 and $2 refer to the portions
+// memorized while matching the pattern.
+
+output.push("---------- After Split by Regular Expression");
+
+var i, len;
+for (i = 0, len = nameList.length; i < len; i++){
+  output.push(nameList[i]);
+  bySurnameList[i] = nameList[i].replace(pattern, "$2, $1");
+}
+
+// Display the new array.
+output.push("---------- Names Reversed");
+for (i = 0, len = bySurnameList.length; i < len; i++){
+  output.push(bySurnameList[i]);
+}
+
+// Sort by last name, then display the sorted array.
+bySurnameList.sort();
+output.push("---------- Sorted");
+for (i = 0, len = bySurnameList.length; i < len; i++){
+  output.push(bySurnameList[i]);
+}
+
+output.push("---------- End");
+
+console.log(output.join("\n"));
+
+ +

입력을 확인하기 위해 특수 문자를 사용하기

+ +

다음 예에서, 사용자는 전화번호를 입력 할 것으로 예상됩니다. 사용자가 "Check" 버튼을 누를 때, 스크립트는 번호의 유효성을 검사합니다. 번호가 유효한 경우(정규식에 의해 지정된 문자 시퀀스와 일치합니다), 스크립트는 사용자에게 감사하는 메시지와 번호를 확인하는 메시지를 나타냅니다. 번호가 유효하지 않은 경우, 스크립트는 전화번호가 유효하지 않다는 것을 사용자에게 알립니다.

+ +

비 캡처링 괄호 (?: , 정규식은 세 자리 숫자를 찾습니다 \d{3} OR | 왼쪽 괄호\( 세 자리 숫자 다음에 \d{3}, 닫는 괄호 다음에 \), (비 캡처링 괄호를 종료)) 안에, 하나의 대시, 슬래시, 또는 소수점을 다음과 같이 발견했을 때,  세 자리 숫자 다음에 d{3}, 대시의 기억 매치, 슬래시, 또는 소수점 다음에 \1, 네 자리 숫자 다음에 \d{4} 문자를 기억합니다([-\/\.]).

+ +

사용자가 <Enter> 키를 누를 때 활성화 변경 이벤트는 RegExp.input의 값을 설정합니다.

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+    <meta http-equiv="Content-Script-Type" content="text/javascript">
+    <script type="text/javascript">
+      var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;
+      function testInfo(phoneInput){
+        var OK = re.exec(phoneInput.value);
+        if (!OK)
+          window.alert(OK.input + " isn't a phone number with area code!");
+        else
+          window.alert("Thanks, your phone number is " + OK[0]);
+      }
+    </script>
+  </head>
+  <body>
+    <p>Enter your phone number (with area code) and then click "Check".
+        <br>The expected format is like ###-###-####.</p>
+    <form action="#">
+      <input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button>
+    </form>
+  </body>
+</html>
+
+ +

{{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}}

diff --git "a/files/ko/web/javascript/guide/\355\225\250\354\210\230/index.html" "b/files/ko/web/javascript/guide/\355\225\250\354\210\230/index.html" new file mode 100644 index 0000000000..cf9d928eb3 --- /dev/null +++ "b/files/ko/web/javascript/guide/\355\225\250\354\210\230/index.html" @@ -0,0 +1,658 @@ +--- +title: 함수 +slug: Web/JavaScript/Guide/함수 +translation_of: Web/JavaScript/Guide/Functions +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}
+ +

함수는 JavaScript에서 기본적인 구성 블록 중의 하나입니다. 함수는 작업을 수행하거나 값을 계산하는 문장 집합 같은 자바스크립트 절차입니다. 함수를 사용하려면 함수를 호출하고자 하는 범위 내에서 함수를 정의해야만 합니다.

+ +

세부 사항에 대해서는 exhaustive reference chapter about JavaScript functions를 참조하세요.

+ +

함수 정의

+ +

함수 선언

+ +

함수 정의(또는 함수 선언)는 다음과 같은 함수 키워드로 구성되어 있습니다:

+ + + +

예를 들어, 다음의 코드는 square라는 간단한 함수를 정의하였습니다:

+ +
function square(number) {
+  return number * number;
+}
+ +

함수 squarenumber라는 하나의 매개변수를 가집니다. 이 함수는 인수 (즉, number) 자체를 곱하여 반환하는 하나의 문장으로 구성되어 있습니다. return 문은 함수에 의해 반환된 값을 지정합니다.

+ +
return number * number;
+ +

기본 자료형인 매개변수(number와 같은)는 값으로 함수에 전달됩니다; 즉, 값이 함수로 전달됩니다. 그러나 함수가 매개변수의 값을 바꾸더라도 이는 전역적으로 또는 함수를 호출하는 곳에는 반영되지 않습니다.

+ +

만약 여러분이 매개변수로 (예: {{jsxref("Array")}}이나 사용자가 정의한 객체와 같이 기본 자료형이 아닌 경우)를 전달하거나 함수가 객체의 속성을 변하게 하는 경우, 다음의 예처럼 그 변화는 함수 외부에서 볼 수 있습니다:

+ +
function myFunc(theObject) {
+  theObject.make = "Toyota";
+}
+
+var mycar = {make: "Honda", model: "Accord", year: 1998};
+var x, y;
+
+x = mycar.make; // x 의 값은 "Honda" 입니다.
+
+myFunc(mycar);
+y = mycar.make; // y 의 값은 "Toyota" 입니다.
+                // (make 속성은 myFunc에서 변경되었습니다.)
+
+ +

함수 표현식

+ +

위에서 함수 선언은 구문적인 문(statement)이지만, 함수 표현식( function expression)에 의해서 함수가 만들어 질 수도 있습니다. 이 같은 함수를 익명이라고 합니다. 이 말은 모든 함수가 이름을 가질 필요는 없다는 것을 뜻합니다. 예를 들어, 함수 square은 다음과 같이 정의 될 수도 있습니다:

+ +
var square = function(number) { return number * number };
+var x = square(4) // x 의 값은 16 입니다.
+ +

하지만, 함수 표현식에서 함수의 이름을 지정 할 수 있으며, 함수내에서 자신을 참조하는데 사용되거나, 디버거 내 스택 추적에서 함수를 식별하는 데 사용될 수 있습니다.

+ +
var factorial = function fac(n) { return n<2 ? 1 : n*fac(n-1) };
+
+console.log(factorial(3));
+
+ +

함수 표현식은 함수를 다른 함수의 매개변수로 전달할 때 편리합니다. 다음 예는 첫 번째 인자로로 함수를, 두 번째 인자로 배열을 받는 map 함수를 보여줍니다.

+ +
function map(f,a) {
+  var result = [], // Create a new Array
+      i;
+  for (i = 0; i != a.length; i++)
+    result[i] = f(a[i]);
+  return result;
+}
+
+ +

다음 코드에서, 함수 표현식으로 정의된 함수를 인자로 받아, 2번 째 인자인 배열의 모든 요소에 대해 그 함수를 실행합니다.

+ +
function map(f, a) {
+  var result = []; // Create a new Array
+  var i; // Declare variable
+  for (i = 0; i != a.length; i++)
+    result[i] = f(a[i]);
+      return result;
+}
+var f = function(x) {
+   return x * x * x;
+}
+var numbers = [0, 1, 2, 5, 10];
+var cube = map(f,numbers);
+console.log(cube);
+ +

함수는 [0, 1, 8, 125, 1000] 을 반환합니다.

+ +

JavaScript에서 함수는 조건에 의해 정의될 수 있습니다. 예를 들어, 다음 함수 정의는 오직 num이 0일 때 경우에 만 myFunc을 정의합니다.

+ +
var myFunc;
+if (num == 0){
+  myFunc = function(theObject) {
+    theObject.make = "Toyota"
+  }
+}
+ +

여기에 기술된 바와 같이 함수를 정의하는것에 더하여 {{jsxref("eval", "eval()")}} 과 같이 런타임에 문자열에서 함수들을 만들기위해 {{jsxref("Function")}} 생성자를 사용할 수 있습니다.

+ +

객체내의 한 속성이 함수인 경우 메서드라고 합니다. Working with objects에서 객체와 방법에 대해 자세히 알아보세요.

+ +

함수 호출

+ +

함수를 정의하는 것은 함수를 실행하는 것이 아닙니다. 함수를 정의하는 것은 간단히 함수의 이름을 지어주고, 함수가 호출될 때 무엇을 할지 지정 해주는 것입니다. 사실 함수를 호출하는 것은 나타나있는 매개변수를 가지고 지정된 행위를 수행하는 것입니다. 예를 들어, 만약 여러분이 함수 square를 정의한다면, 함수를 다음과 같이 호출할 수 있습니다.

+ +
square(5);
+
+ +

위의 문장은 5라는 인수를 가지고 함수를 호출합니다. 함수는 이 함수의 실행문을 실행하고 값 25를 반환합니다.

+ +

함수는 호출될 때 범위 내에 있어야 합니다. 그러나 함수의 선언은 이 예에서와 같이, 호이스팅 될 수 있습니다. (코드에서 호출 아래에 선언문이 있습니다.):

+ +
console.log(square(5));
+/* ... */
+function square(n) { return n*n }
+
+ +

함수의 범위는 함수가 선언된 곳이거나, 전체 프로그램 에서의 최상위 레벨(전역)에 선언된 곳입니다.

+ +
+

비고: 위에 구문을 사용하여 함수를 정의하는 경우에만 작동합니다 (즉, function funcName(){} ). 아래와 같은 코드는 작동되지 않습니다. 이것이 의미하는 바는, 함수 호이스팅은 오직 함수 선언과 함께 작동하고, 함수 표현식에서는 동작하지 않습니다.

+
+ +
console.log(square);   // square는 초기값으로 undefined를 가지고 호이스트된다.
+console.log(square(5));  // TypeError: square는 함수가 아니다.
+square = function (n) {
+  return n * n;
+}
+
+ +

함수의 인수는 문자열과 숫자에 제한되지 않습니다. 여러분은 함수에 전체 객체를 전달할 수 있습니다. show_props() 함수(Working with objects에서 정의된)는 인수로 객체를 취하는 함수의 예입니다.

+ +

함수는 자신을 호출할 수 있습니다. 예를 들어, 팩토리얼을 재귀적으로 계산하는 함수가 있습니다:

+ +
function factorial(n){
+  if ((n == 0) || (n == 1))
+    return 1;
+  else
+    return (n * factorial(n - 1));
+}
+
+ +

여러분은 다음과 같이 1부터 5까지의 팩토리얼을 계산할 수 있습니다.

+ +
var a, b, c, d, e;
+a = factorial(1); // a gets the value 1
+b = factorial(2); // b gets the value 2
+c = factorial(3); // c gets the value 6
+d = factorial(4); // d gets the value 24
+e = factorial(5); // e gets the value 120
+
+ +

함수를 호출하는 다른 방법들이 있습니다. 함수를 동적 호출해야 하거나, 함수의 인수의 수가 달라져야 하거나, 함수 호출의 맥락이 런타임에서 결정된 특정한 객체로 설정될 필요가 있는 경우가 자주 있습니다. 함수가 그 자체로 객체이고 이들 객체는 차례로 메서드를({{jsxref("Function")}} 객체를 참조) 가지고 있습니다. 이들 중 하나인 {{jsxref("Function.apply", "apply()")}} 메서드는 이러한 목표를 달성하기 위해 사용될 수 있습니다.

+ +

함수의 범위

+ +

함수 내에서 정의된 변수는 변수가 함수의 범위에서만 정의되어 있기 때문에, 함수 외부의 어느 곳에서든 액세스할 수 없습니다. 그러나, 함수가 정의된 범위 내에서 정의된 모든 변수나 함수는 액세스할 수 있습니다. 즉, 전역함수는 모든 전역 변수를 액세스할 수 있습니다. 다른 함수 내에서 정의 된 함수는 부모 함수와 부모 함수가 액세스 할 수 있는 다른 변수에 정의된 모든 변수를 액세스할 수 있습니다.

+ +
// The following variables are defined in the global scope
+var num1 = 20,
+    num2 = 3,
+    name = "Chamahk";
+
+// This function is defined in the global scope
+function multiply() {
+  return num1 * num2;
+}
+
+multiply(); // Returns 60
+
+// A nested function example
+function getScore () {
+  var num1 = 2,
+      num2 = 3;
+
+  function add() {
+    return name + " scored " + (num1 + num2);
+  }
+
+  return add();
+}
+
+getScore(); // Returns "Chamahk scored 5"
+
+ +

범위와 함수 스택

+ +

재귀

+ +

함수는 자신을 참조하고 호출할 수 있습니다. 함수가 자신을 참조하는 방법은 세 가지가 있습니다.

+ +
    +
  1. 함수의 이름
  2. +
  3. arguments.callee
  4. +
  5. 함수를 참조하는 범위 내 변수
  6. +
+ +

예를 들어, 다음 함수의 정의를 고려해보세요.

+ +
var foo = function bar() {
+   // statements go here
+};
+
+ +

함수 본문 내에서 다음은 모두 동일합니다.

+ +
    +
  1. bar()
  2. +
  3. arguments.callee()
  4. +
  5. foo()
  6. +
+ +

자신을 호출하는 함수를 재귀 함수라고 합니다. 어떤 면에서, 재귀는 루프와 유사합니다. 둘 다 동일한 코드를 여러 번 실행하고, 조건(무한 루프를 방지하거나, 이 경우에는 오히려 무한 재귀하는)을 요구합니다. 예를 들어, 다음 루프는:

+ +
var x = 0;
+while (x < 10) { // "x < 10" is the loop condition
+   // do stuff
+   x++;
+}
+
+ +

아래와 같이 재귀 함수와 그 함수에 대한 호출로 변환될 수 있습니다.

+ +
function loop(x) {
+  if (x >= 10) // "x >= 10" 는 탈출 조건 ("!(x < 10)"와 동등)
+    return;
+  // do stuff
+  loop(x + 1); // the recursive call
+}
+loop(0);
+
+ +

그러나 일부 알고리즘은 단순 재귀 루프로 변환할 수 없습니다. 예를 들어, 트리 구조(가령, DOM)의 모든 노드를 얻는 것은 재귀를 사용하여 보다 쉽게 할 수 있습니다:

+ +
function walkTree(node) {
+  if (node == null) //
+    return;
+  // do something with node
+  for (var i = 0; i < node.childNodes.length; i++) {
+    walkTree(node.childNodes[i]);
+  }
+}
+
+ +

함수  loop 와 비교하여, 각 재귀 호출 자체는 여기에 많은 재귀 호출을 만듭니다.

+ +

재귀적 알고리즘은 비 재귀적인 알고리즘으로 변환 할 수 있습니다. 그러나 변환된 알고리즘이 훨씬 더 복잡하며 그렇게 함으로써 스택의 사용을 요구합니다. 사실, 재귀 자체가 함수 스택을 사용 합니다.

+ +

스택형 동작은 다음의 예에서 볼 수 있습니다:

+ +
function foo(i) {
+  if (i < 0)
+    return;
+  console.log('begin:' + i);
+  foo(i - 1);
+  console.log('end:' + i);
+}
+foo(3);
+
+// Output:
+
+// begin:3
+// begin:2
+// begin:1
+// begin:0
+// end:0
+// end:1
+// end:2
+// end:3
+ +

중첩된 함수와 클로저

+ +

여러분은 함수 내에 함수를 끼워 넣을 수 있습니다. 중첩 된 (내부) 함수는 그것을 포함하는 (외부) 함수와 별개입니다. 그것은 또한 클로저를 형성합니다. 클로저는 그 변수(“폐쇄”라는 표현)를 결합하는 환경을 자유롭게 변수와 함께 가질 수 있는 표현(전형적인 함수)입니다.

+ +

중첩 함수는 클로저이므로, 중첩된 함수는 그것을 포함하는 함수의 인수와 변수를 “상속”할 수 있는 것을 의미합니다. 즉, 내부 함수는 외부 함수의 범위를 포함합니다.

+ +

요약하면:

+ + + + + +

다음 예는 중첩된 함수를 보여줍니다:

+ +
function addSquares(a,b) {
+  function square(x) {
+    return x * x;
+  }
+  return square(a) + square(b);
+}
+a = addSquares(2,3); // returns 13
+b = addSquares(3,4); // returns 25
+c = addSquares(4,5); // returns 41
+
+ +

내부 함수는 클로저를 형성하기 때문에, 여러분은 외부 함수를 호출하고, 외부 및 내부 함수 모두에 인수를 지정할 수 있습니다.

+ +
function outside(x) {
+  function inside(y) {
+    return x + y;
+  }
+  return inside;
+}
+fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it
+result = fn_inside(5); // returns 8
+
+result1 = outside(3)(5); // returns 8
+
+ +

변수의 보존

+ +

중첩된 내부 함수가 반환될 때 외부 함수의 인수 x가 보존된다는 점을 알 수 있습니다. 클로저는 그것을 참조하는 모든 범위에서 인수와 변수를 보존해두어야 합니다. 매번 호출될 때마다 잠재적으로 다른 인수를 제공할 수 있기 때문에, 클로저는 외부 함수에 대하여 매번 새로 생성됩니다. 메모리는 그 무엇도 내부 함수에 접근하지 않을 때만 해제됩니다.

+ +

변수의 보존은 일반 객체에서 참조를 저장해두는 것과 다르지 않지만, 사용자가 직접 참조를 설정하는 것이 아니고 자세히 들여다볼 수 없어서 종종 명확하지 않습니다.

+ +

다중 중첩 함수

+ +

함수는 다중 중첩될 수 있습니다. 즉, 함수 (C)를 포함하는 함수 (B)를 포함하는 함수 (A). 여기에서 두 함수 B와 C는 모두 클로저를 형성합니다. 그래서 B는 A를 엑세스할 수 있고, C는 B를 액세스 할 수 있습니다. 이와 같이, 클로저는 다중 범위를 포함 할 수 있습니다; 그들은 재귀적으로 그것을 포함하는 함수의 범위를 포함합니다. 이것을 범위 체이닝이라 합니다.(그것을 “체이닝”이라 하는 이유는 추후에 설명할 것입니다.)

+ +

다음 예를 살펴 보겠습니다:

+ +
function A(x) {
+  function B(y) {
+    function C(z) {
+      console.log(x + y + z);
+    }
+    C(3);
+  }
+  B(2);
+}
+A(1); // logs 6 (1 + 2 + 3)
+
+ +

이 예에서, C는 B의 y와 A의 x를 엑세스 합니다. 이 때문에 수행할 수 있습니다:

+ +
    +
  1. B는 A를 포함하는 클로저를 형성합니다. 즉, B는 A의 인수와 변수를 엑세스할 수 있습니다.
  2. +
  3. C는 B를 포함하는 클로저를 형성합니다.
  4. +
  5. B의 클로저는 A를 포함하고, C의 클로저는 A를 포함하기 때문에, C는 B와 A의 인수와 변수를 엑세스할 수 있습니다. 즉, 순서대로 C는 A와 B의 범위를 체이닝합니다.
  6. +
+ +

그러나 역은 사실이 아닙니다. A는 C에 접근 할 수 없습니다. 왜냐하면 A는 B의 인수와 변수(C는 B변수)에 접근할수 없기 때문입니다. 그래서 C는 B에게만 사적으로 남게됩니다.

+ +

이름 충돌

+ +

클로저의 범위에서 두 개의 인수 또는 변수의 이름이 같은 경우, 이름 충돌이 있습니다. 더 안쪽 범위가 우선순위를 갖습니다. 그래서 가장 바깥 범위는 우선순위가 가장 낮은 반면에, 가장 안쪽 범위는 가장 높은 우선순위를 갖습니다. 이것이 범위 체인(scope chaini)입니다. 체인에서 첫번째는 가장 안쪽 범위이고, 마지막 가장 바깥 쪽의 범위입니다. 다음 사항을 고려하세요:

+ +
function outside() {
+  var x = 10;
+  function inside(x) {
+    return x;
+  }
+  return inside;
+}
+result = outside()(20); // returns 20 instead of 10
+
+ +

이름 충돌이 x를 반환하는 문과 내부의 매개 변수 x와 외부 변수 x 사이에서 발생합니다. 여기에서 범위 체이닝은 {내부, 외부, 전역 객체}입니다. 따라서 내부의 x는 외부의 x보다 높은 우선순위를 갖게 되고, 20(내부의 x)이 10(외부의 x) 대신에 반환됩니다.

+ +

클로저

+ +

클로저는 자바스크립트의 강력한 기능 중 하나입니다. 자바스크립트는 함수의 중첩(함수 안에 함수를 정의하는것)을 허용하고, 내부함수가 외부 함수 안에서 정의된 모든 변수와 함수들을 완전하게 접근 할 수 있도록 승인해줍니다.(그리고 외부함수가 접근할수 있는 모든 다른 변수와 함수들까지) 그러나 외부 함수는 내부 함수 안에서 정의된 변수와 함수들에 접근 할 수 없습니다. 이는 내부 함수의 변수에 대한 일종의 캡슐화를 제공합니다. 또한, 내부함수는 외부함수의 범위에 접근할 수 있기 때문에, 내부 함수가 외부 함수의 수명을 초과하여 생존하는 경우, 외부함수에서 선언된 변수나 함수는 외부함수의 실행 기간보다 오래갑니다. 클로저는 내부 함수가 어떻게든 외부 함수 범위 밖의 모든 범위에서 사용 가능해지면 생성됩니다.

+ +
var pet = function(name) {   // 외부 함수는 'name'이라 불리는 변수를 정의합니다.
+  var getName = function() {
+    return name;             // 내부 함수는 외부 함수의 'name' 변수에 접근합니다.
+  }
+  return getName;            // 내부 함수를 리턴함으로써, 외부 범위에 노출됩니다.
+},
+myPet = pet("Vivie");
+
+myPet();                     // "Vivie"로 리턴합니다.
+
+ +

클로저는 위 코드보다 더 복잡해 질 수도 있습니다. 외부 함수의 내부 변수를 다루는 메서드를 포함한 객체도 반환될 수도 있습니다.

+ +
var createPet = function(name) {
+  var sex;
+
+  return {
+    setName: function(newName) {
+      name = newName;
+    },
+
+    getName: function() {
+      return name;
+    },
+
+    getSex: function() {
+      return sex;
+    },
+
+    setSex: function(newSex) {
+      if(typeof newSex == "string" && (newSex.toLowerCase() == "male" || newSex.toLowerCase() == "female")) {
+        sex = newSex;
+      }
+    }
+  }
+}
+
+var pet = createPet("Vivie");
+pet.getName();                  // Vivie
+
+pet.setName("Oliver");
+pet.setSex("male");
+pet.getSex();                   // male
+pet.getName();                  // Oliver
+
+ +

위 코드에서, 외부 함수의 'name' 이란 변수는 내부 함수에서 접근이 가능합니다. 그리고 그 내장 함수를 통하는 방법 말고는 내부 변수로 접근할 수 없습니다. 내부 함수의 내부 변수는 외부 인수와 변수를 안전하게 저장합니다. 내부 변수는 내부 함수가 작동하기 위해 '지속적'이고 '갭슐화된' 데이터를 보유합니다. 함수는 변수로 할당되거나, 이름을 가질 필요가 없습니다.

+ +
var getCode = (function(){
+  var secureCode = "0]Eal(eh&2";    // A code we do not want outsiders to be able to modify...
+
+  return function () {
+    return secureCode;
+  };
+})();
+
+getCode();    // Returns the secureCode
+
+ +

그러나 클로저를 쓰면서 조심해야 할 위험이 많이 있습니다. 만약 내부 함수가 외부 함수의 범위에 있는 이름과 같은 변수를 정의하였을 경우, 다시는 외부 함수 범위의 변수를 참조(접근)할 방법이 없습니다.

+ +
var createPet = function(name) {  // 외부 함수가 "name" 이라는 변수를 정의하였다
+  return {
+    setName: function(name) {    // 내부 함수 또한 "name" 이라는 변수를 정의하였다
+      name = name;               // ??? 어떻게 우리는 외부 함수에 정의된 "name"에 접근할까???
+    }
+  }
+}
+
+ +

인수(arguments) 객체 사용하기

+ +

함수의 인수는 배열과 비슷한 객체로 처리가 됩니다. 함수 내에서는, 전달 된 인수를 다음과 같이 다룰 수 있습니다. :

+ +
arguments[i]
+
+ +

i 는 0 으로 시작하는 순서 번호입니다. 따라서 함수에 전달된 첫 번째 인수는 arguments[0] 입니다. 총 인수의 개수는 arguments.length 에서 얻을 수 있습니다.

+ +

인수(arguments) 객체를 이용하면, 보통 함수에 정의된 개수보다 많은 인수를 넘겨주면서 함수를 호출할 수 있습니다. 이것은 얼마나 많은 인수가 함수로 넘겨질지 모르는 상황에서 유용합니다. arguments.length를 함수에 실제로 넘겨받은 인수의 수를 알아낼 때 사용할 수 있고 , 각각의 인수에 인수(arguments) 객체를  이용하여 접근 할 수 있습니다.

+ +

예를 들어, 몇 개의 문자열을 연결하는 함수를 생각해 봅시다. 이 함수의 유일한 형식 인수는 각 문자열을 구분해주는 문자를 나타내는 문자열입니다 . 이 함수는 다음과 같이 정의됩니다:

+ +
function myConcat(separator) {
+   var result = ""; // 리스트를 초기화한다
+   var i;
+   // arguments를 이용하여 반복한다
+   for (i = 1; i < arguments.length; i++) {
+      result += arguments[i] + separator;
+   }
+   return result;
+}
+
+ +

어떤 개수의 인수도 이 함수로 넘겨줄 수 있고, 이 함수는 각각의 인수를 하나의 문자열 "리스트" 로 연결합니다. :

+ +
// returns "red, orange, blue, "
+myConcat(", ", "red", "orange", "blue");
+
+// returns "elephant; giraffe; lion; cheetah; "
+myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
+
+// returns "sage. basil. oregano. pepper. parsley. "
+myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
+
+ +
+

Note: 인수(arguments) 객체는 배열과 닮은 것이지 배열이 아닙니다. 인수(arguments) 객체는 번호 붙여진 인덱스와 길이 속성을 가지고 있다는 점에서 배열과 닮은 것입니다. 인수(arguments) 객체는 배열을 다루는 모든 메서드를 가지고 있지 않습니다.

+
+ +

더 자세한 정보를 얻고 싶으면 자바스크립트 참조문의 {{jsxref("Function")}}객체에 대하여 보세요.

+ +

함수의 매개변수

+ +

 ECMAScript 2015와 함께 시작된,두 종류의 매개변수가 있습니다 : 디폴트 매개변수 , 나머지 매개변수.

+ +

디폴트 매개변수

+ +

자바스크립트에서, 함수의 매개변수는 undefined 가 기본으로 설정됩니다. 그러나, 어떤 상황에서는 다른 값을 기본값으로 가진 것이 유용할 때가 있습니다. 이때가 디폴트 매개변수가 도움을 줄 수 있는 상황입니다.

+ +

옛날엔, 기본값을 설정하는 보편적인 전략은 함수의 본문에서 매개변수 값을 테스트하여 그 값이 undefined 인 경우에 값을 할당하는 것이었습니다. 다음과 같은 예제에서, 함수호출 시 b 매개변수에 아무 값을 주지 않으면, a*b 계산 시 b 매개변수의 값은 undefined 일 것이므로 multiply 함수 호출은 NaN을 리턴할 것입니다. 그러나 이런 것은 이 예제의 2번째 줄에서 걸립니다:

+ +
function multiply(a, b) {
+  b = typeof b !== 'undefined' ?  b : 1;
+
+  return a*b;
+}
+
+multiply(5); // 5
+
+ +

디폴트 매개변수와 함께라면, 함수 본문에서 검사하는 부분은 필요가 없습니다. 이제 , 함수 머리에서 b 의 기본값에 간단히 1을 넣어주면 됩니다:

+ +
function multiply(a, b = 1) {
+  return a*b;
+}
+
+multiply(5); // 5
+ +

더 자세한 내용을 보고 싶으시면,  default parameters 문서를 참조하세요.

+ +

나머지 매개변수

+ +

 나머지 매개변수 구문을 사용하면 배열로 불확실한 개수의 인수를 나타낼 수 있습니다. 이 예제에서, 우리는 나머지 매개변수를 2번째 인수부터 마지막 인수까지 얻기 위하여 사용하였습니다. 그리고 우리는 첫번째 값으로 나머지 매개변수에 곱하였습니다. 이 예제는 다음 섹션에서 소개할  화살표(arrow) 함수 입니다.

+ +
function multiply(multiplier, ...theArgs) {
+  return theArgs.map(x => multiplier * x);
+}
+
+var arr = multiply(2, 1, 2, 3);
+console.log(arr); // [2, 4, 6]
+ +

화살표 함수

+ +

 화살표 함수 표현 (뚱뚱한 화살표(fat arrow) 함수라고 알려진)은 함수 표현과 비교하였을때 짧은 문법을 가지고 있고 사전적으로 this 값을 묶습니다. 화살표 함수는 언제나 익명입니다. hacks.mozilla.org 블로그 포스트 "ES6 In Depth: Arrow functions" 를 참조하세요.

+ +

화살표  함수 소개에 영향을 주는 두 요소: 더 짧은 함수와 바인딩 되지않은 this.

+ +

더 짧은 함수

+ +

어떤 함수적 패턴에서는, 더 짧은 함수가 환영받습니다. 다음을 비교해 보세요:

+ +
var a = [
+  "Hydrogen",
+  "Helium",
+  "Lithium",
+  "Beryl­lium"
+];
+
+var a2 = a.map(function(s){ return s.length });
+
+console.log(a2); // logs [8, 6, 7, 9]
+
+var a3 = a.map( s => s.length );
+
+console.log(a3); // logs [8, 6, 7, 9]
+ +

사전적 this

+ +

화살표 함수에서, 모든 new함수들은  그들의  this 값을 정의합니다 (생성자로서의 새로운 객체, 정의되지 않은 strict mode의 함수 호출,   함수가 "object method"로 호출했을때의 context object ,등등.). 이런 것은 객체지향 프로그래밍 스타일에서 짜증을 불러 일으킵니다.

+ +
function Person() {
+  // The Person() constructor defines `this` as itself.
+  this.age = 0;
+
+  setInterval(function growUp() {
+    // In nonstrict mode, the growUp() function defines `this`
+    // as the global object, which is different from the `this`
+    // defined by the Person() constructor.
+    this.age++;
+  }, 1000);
+}
+
+var p = new Person();
+ +

IECMAScript 3/5 에서는, 이 문제는 this 안의 값을 뒤덮을 수 있는변수에 할당하면서 고쳐졌습니다.

+ +
function Person() {
+  var self = this; // Some choose `that` instead of `self`.
+                   // Choose one and be consistent.
+  self.age = 0;
+
+  setInterval(function growUp() {
+    // The callback refers to the `self` variable of which
+    // the value is the expected object.
+    self.age++;
+  }, 1000);
+}
+ +

또는, 적절한 this 값이 growUp() 함수에 전달되도록, 바인딩된 함수가 생성될 수 있습니다.

+ + + +

화살표 함수에는 this;가 없습니다. 화살표 함수를 포함하는 객체 값이 사용됩니다. 따라서 다음 코드에서 setInterval에 전달 된 함수 내의 this 값은 화살표 함수를 둘러싼 함수의 this와 같은 값을 갖습니다.

+ +
function Person() {
+  this.age = 0;
+
+  setInterval(() => {
+    this.age++; // |this| properly refers to the person object
+  }, 1000);
+}
+
+var p = new Person();
+ +

미리 정의된 함수들

+ +

자바스크립트에는 최고 등급의 몇가지 내장함수가 있습니다:

+ +
+
{{jsxref("Global_Objects/eval", "eval()")}}
+
+

eval() 메소드는 문자열로 표현된 자바스크립트 코드를 수행합니다.

+
+
{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}
+
+

uneval() 메소드는  {{jsxref("Object")}}의 소스코드를 표현하는 문자열을 만듭니다.

+
+
{{jsxref("Global_Objects/isFinite", "isFinite()")}}
+
+

전역 isFinite() 함수는 전달받은 값이 유한한지 결정합니다. 만약 필요하다면, 매개변수는 첫번째로 숫자로 변환됩니다.

+
+
{{jsxref("Global_Objects/isNaN", "isNaN()")}}
+
+

isNaN() 함수는 {{jsxref("Global_Objects/NaN", "NaN")}}인지 아닌지 결정합니다. Note:  isNaN 함수 안의 강제 변환은  흥미로운 규칙을 가지고 있습니다;  {{jsxref("Number.isNaN()")}}을 대신 사용하고 싶을것입니다, ECMAScript 6 에서 정의된,또는 값이 숫자값이 아닐때,  typeof 를 사용할 수도 있습니다 .

+
+
{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}
+
+

parseFloat() 함수는  문자열 인수 값을 해석하여 부동소숫점 수를 반환합니다.

+
+
{{jsxref("Global_Objects/parseInt", "parseInt()")}}
+
+

parseInt() 함수는 문자열 인수 값을 해석하여 특정한 진법의 정수를 반환합니다  (수학적 수 체계를 기반으로 해서).

+
+
{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}
+
+

decodeURI() 함수는  사전에 {{jsxref("Global_Objects/encodeURI", "encodeURI")}}을 통해 만들어지거나 비슷한 과정을 통해 만들어진 URI(Uniform Resource Identifier)  를 해독합니다.

+
+
{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}
+
+

decodeURIComponent() 메소드는 사전에{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}}를 통하여 만들어 지거나 또는 비슷한 과정을 통해 만들어진 URI (Uniform Resource Identifier) 컴포넌트를 해독합니다.

+
+
{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}
+
+

encodeURI() 메소드는  URI(Uniform Resource Identifier)를  각 인스턴스의 특정한 문자를 한개, 두개,세개, 또는 네개의 UTF-8인코딩으로 나타내어지는 연속된 확장문자들과 바꾸는 방법으로 부호화 합니다 .(두"surrogate"문자로 구성된 문자들은 오직 네개의 연속된 확장문자 입니다. ).

+
+
{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}
+
+

encodeURIComponent() 메소드는  URI(Uniform Resource Identifier) 컴포넌트를  각 인스턴스의 특정한 문자를 한개, 두개,세개, 또는 네개의 UTF-8인코딩으로 나타내어지는 연속된 확장문자들과 바꾸는 방법으로 부호화 합니다 .(두"surrogate"문자로 구성된 문자들은 오직 네개의 연속된 확장문자 입니다. ).).

+
+
{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}
+
+

곧 사라질 escape() 메소드는 한 문자열에서 특정 문자들이 16진 확장 비트열로 바뀌어진 문자열로 계산합니다.  {{jsxref("Global_Objects/encodeURI", "encodeURI")}} 또는 {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} 를 사용하세요.

+
+
{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}
+
+

곧 사라질 unescape() 메소드는 문자열에서 확장 비트열이 확장 비트열이 나타내는 문자로 바뀌어진 문자열로 계산합니다.  {{jsxref("Global_Objects/escape", "escape")}}에서 확장 비트열이 소개될 것입니다.  unescape() 메소드가 곧 사라지기 때문에,  {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} 를 대신 사용하세요.

+
+
+ +

{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}

+ + + + diff --git a/files/ko/web/javascript/index.html b/files/ko/web/javascript/index.html new file mode 100644 index 0000000000..923d422500 --- /dev/null +++ b/files/ko/web/javascript/index.html @@ -0,0 +1,118 @@ +--- +title: JavaScript +slug: Web/JavaScript +tags: + - JavaScript + - Landing + - Learn + - 'l10n:priority' + - 자바스크립트 +translation_of: Web/JavaScript +--- +
{{JsSidebar}}
+ +

JavaScript(JS)는 가벼운 인터프리터 또는 JIT 컴파일 프로그래밍 언어로, {{Glossary("First-class Function", "일급 함수")}}를 지원합니다. 웹 페이지의 스크립트 언어로서 제일 유명하지만 {{Glossary("Node.js")}}, Apache CouchDB, Adobe Acrobat처럼 많은 비 브라우저 환경에서도 사용하고 있습니다. JavaScript는 {{Glossary("Prototype-based programming", "프로토타입 기반")}}의 동적 다중 패러다임 스크립트 언어로, 객체지향형, 명령형, 선언형(함수형 프로그래밍 등) 스타일을 지원합니다. 자세한 내용은 JavaScript에 대하여를 참고하세요.

+ +

이 문서는 JavaScript 언어 자체만 다루며 웹 페이지를 비롯한 다른 사용 환경에 대해서는 다루지 않습니다. 웹 페이지의 특정 {{Glossary("API")}}에 대하여 알고 싶다면 웹 APIDOM을 참고하시기 바랍니다.

+ +

JavaScript의 표준은 ECMAScript입니다. 2012년 기준 최신 브라우저는 모두 ECMAScript 5.1을 온전히 지원합니다. 이전 브라우저의 경우는 최소한 ECMAScript 3까지는 지원합니다. 2015년 6월 17일 ECMA International에서는 공식명 ECMAScript 2015 로 불리는 ECMAScript의 6번째 주 버전을 발표했습니다(보통 ECMAScript 6 혹은 ES6으로 불립니다). 그 이후 ECMAScript 표준의 출시 주기는 1년입니다. 이 문서는 최신 초안(현재 ECMAScript 2020)에 기반을 둡니다.

+ +

JavaScript를 Java 프로그래밍 언어와 혼동해서는 안 됩니다. "Java"와 "JavaScript" 두 가지 모두 Oracle이 미국 및 기타 국가에 등록한 상표입니다. 하지만, 두 언어는 문법 체계와 사용 방법이 전혀 다릅니다.

+ +
+
+

자습서

+ +

안내서 및 자습서와 함께 JavaScript 프로그램을 짜는 법을 알아보세요.

+ +

입문

+ +

JavaScript를 배우고 싶지만 JavaScript 또는 프로그래밍에 대한 이전 경험이 없는 경우 Web 개발 학습하기의 JavaScript 주제를 방문하세요. 사용할 수 있는 전체 모듈은 다음과 같습니다.

+ +
+
JavaScript 첫 걸음
+
"JavaScript는 무엇인가요?", "어떤 모습인가요?", "뭘 할 수 있나요?"와 같은 기본적인 질문에 대답하면서 변수, 문자열, 숫자, 배열과 같은 JavaScript의 주요 기능에 대해서도 알아봅니다.
+
JavaScript 구성 요소
+
JavaScript의 핵심 기본 기능에 대한 이해를 넓히기 위해 조건문, 반복문, 함수, 이벤트와 같이 흔히 찾을 수 코드 블록의 형태에 대해서 알아봅니다.
+
JavaScript 객체 소개
+
JavaScript에 대한 지식을 쌓고, 보다 효율적인 코드를 작성하기 위해서는 JavaScript의 객체지향적인 모습을 이해해야 합니다.
+
비동기 JavaScript
+
비동기 JavaScript가 중요한 이유와, 비동기적 코드를 사용해 서버에서 리소스 가져오기 등 블록킹 연산을 효율적으로 처리하는 방법을 알아봅니다.
+
클라이언트측 웹 API
+
API란 무엇인지 탐색해보고, 제일 흔히 사용해서 개발 중 자주 마주치게 될 일부 API의 사용법을 배웁니다.
+
+

JavaScript 안내서

+
+
JavaScript 안내서
+
+

JavaScript 또는 다른 언어의 경험을 가진 독자를 대상으로 한 JavaScript 상세 안내서입니다.

+
+
+ +

중급

+ +
+
JavaScript 재입문
+
JavaScript에 대해 안다고 생각하는 이들을 위한 개요.
+
JavaScript 데이터 구조
+
JavaScript에서 이용 가능한 데이터 구조 개요.
+
같음 비교 및 동일성
+
JavaScript는 세 가지 다른 값 비교 연산을 제공합니다: ===를 사용한 엄격한(strict) 같음, ==를 사용한 느슨한(loose) 같음 및 {{jsxref("Global_Objects/Object/is", "Object.is()")}} 메서드.
+
클로저
+
클로저는 함수와 그 함수가 선언 된 어휘 환경의 조합입니다.
+
+ +

고급

+ +
+
상속 및 프로토타입 체인
+
널리 오해 받고 과소 평가된 프로토타입(원형) 기반 상속의 설명.
+
엄격 모드
+
엄격 모드는 초기화 전에 어떤 변수도 사용할 수 없음을 정의합니다. 이는 빠른 성능 및 쉬운 디버깅을 위한 ECMAScript 5의 제한된 변형(variant)입니다.
+
JavaScript 형식화된 배열
+
JavaScript 형식화된 배열은 원시(raw) 이진 데이터에 접근하기 위한 메커니즘을 제공합니다.
+
메모리 관리
+
JavaScript에서 메모리 라이프 사이클 및 가비지 컬렉션.
+
동시성 모델 및 이벤트 루프
+
JavaScript "이벤트 루프"에 기반을 둔 동시성 모델이 있습니다.
+
+
+ +
+

참고서

+ +

전체 JavaScript 참고서를 훑어보세요.

+ +
+
표준 객체
+
{{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("RegExp")}}, {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}} 등 표준 내장 객체 알아가기.
+
표현식 및 연산자
+
JavaScript 연산자 {{jsxref("Operators/instanceof", "instanceof")}}, {{jsxref("Operators/typeof", "typeof")}}, {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}}의 행동, 연산자 우선순위 등에 대해 더 알아보기.
+
명령문 및 선언문
+
{{jsxref("Statements/do...while", "do-while")}}, {{jsxref("Statements/for...in", "for-in")}}, {{jsxref("Statements/for...of", "for-of")}}, {{jsxref("Statements/try...catch", "try-catch")}}, {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/var", "var")}}, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/if...else", "if-else")}}, {{jsxref("Statements/switch", "switch")}} 등의 JavaScript 명령문 및 키워드 작동 법 배우기.
+
함수
+
어플리케이션 개발에 JavaScript 함수로 작업하는 법 배우기.
+
+ +

도구 & 자원

+ +

JavaScript 코드 작성과 디버깅을 돕는 유용한 도구 모음입니다.

+ +
+
Firefox 개발자 도구
+
Web Console, JavaScript Profiler, Debugger 등.
+
JavaScript 쉘
+
빠르게 JavaScript 코드 조각(snippet)을 테스트할 수 있는 JavaScript 쉘.
+
TogetherJS
+
간편한 협업.
+
Stack Overflow
+
"JavaScript" 태그가 달린 Stack Overflow 질문.
+
JavaScript 버전 및 출시 노트
+
JavaScript 기능 역사 및 구현 상태 훑어보기.
+
JSFiddle
+
JavaScript, CSS, HTML 편집 및 실시간 결과 얻기. 외부 자원(resource)을 사용하며 온라인으로 팀과 협업하기.
+
Plunker
+
Plunker는 온라인에서 여러분의 웹 개발 아이디어를 실제로 만들거나 다른사람과 공유 협업하는 커뮤니티 입니다. 실시간으로 JavaScrip, CSS, HTML을 만들고 편집 할 수 있습니다.
+
+
+
diff --git a/files/ko/web/javascript/introduction_to_object-oriented_javascript/index.html b/files/ko/web/javascript/introduction_to_object-oriented_javascript/index.html new file mode 100644 index 0000000000..67b15b963d --- /dev/null +++ b/files/ko/web/javascript/introduction_to_object-oriented_javascript/index.html @@ -0,0 +1,289 @@ +--- +title: 객체지향 자바스크립트 개요 +slug: Web/JavaScript/Introduction_to_Object-Oriented_JavaScript +translation_of: Learn/JavaScript/Objects +--- +

비록 다른 객체지향적인 언어들과의 차이점에 대한 논쟁들이 있긴 하지만, JavaScript는 강력한 객체지향 프로그래밍 능력들을 지니고 있다.

+ +

이 글에서는 객체지향 프로그래밍에 대해 소개하는 것으로 시작해서 자바스크립트의 객체 모델, 그리고 자바스크립트에서의 객체지향 프로그래밍 개념에 대해 간단한 예제로 살펴볼 것이다.

+ +

자바스크립트 리뷰(JavaScript review)

+ +

만약 변수, 형, 함수, 스코프 등 자바스크립트의 개념에 대해 명확히 이해하고 있지 못하다면, A re-introduction to JavaScript를 참고해 보자. Core JavaScript 1.5 Guide라는 글도 도움이 될 것이다.

+ +

객체지향 프로그래밍(Object-oriented programming)

+ +

객체지향 프로그래밍은 실제 세계에 기반한 모델을 만들기 위해 추상화를 사용하는 프로그래밍 패러다임이다. 객체지향 프로그래밍은 modularity, polymorphism, encapsulation을 포함하여 이전에 정립된 패러다임들부터 여러가지 테크닉들을 사용한다. 오늘날 많은 유명한 프로그래밍 언어(자바, 자바스크립트, C#, C++, 파이썬, PHP, 루비, 오브젝트C)는 객체지향 프로그래밍을 지원한다.

+ +

객체지향 프로그래밍은 함수들의 집합 혹은 단순한 컴퓨터의 명령어들의 목록 이라는 기존의 프로그래밍에 대한 전통적인 관점에 반하여, 관계성있는 객체들의 집합이라는 관점으로 접근하는 소프트웨어 디자인으로 볼 수 있다. 객체지향 프로그래밍에서, 각 객체는 메시지를 받을 수도 있고, 데이터를 처리할 수도 있으며, 또다른 객체에게 메시지를 전달할 수도 있다. 각 객체는 별도의 역할이나 책임을 갖는 작은 독립적인 기계로 볼 수 있는 것이다.

+ +

객체지향 프로그래밍은 보다 유연하고 유지보수성이 높은 프로그래밍을 하도록 의도되었고, 대규모 소프트웨어 공학에서 널리 알려져 있다. 객체지향 프로그래밍이 갖는 modularity에 기반한 강력한 힘에 의해, 객체지향적인 코드는 개발을 보다 단순하게 했고, 시간이 흐른 뒤에도 보다 쉽게 이해할 수 있도록 했으며, 복잡한 상황이나 절차들을 덜 모듈화된 프로그래밍 방법들보다 더 직접적으로 분석하고, 코딩하고, 이해할 수 있도록 만들었다.2

+ +

용어(Terminology)

+ +
+
Class
+
객체의 특성을 정의
+
Object
+
Class의 인스턴스
+
Property
+
객체의 특성(예: 색깔)
+
Method
+
객체의 능력(예: 걷기)
+
Constructor
+
인스턴스화 되는 시점에서 호출되는 메서드
+
Inheritance
+
클래스는 다른 클래스로부터 특성들을 상속받을 수 있다.
+
Encapsulation
+
클래스는 해당 객체의 특성들만을 정의할 수 있고, 메서드는 그 메서드가 어떻게 실행되는지만 정의할 수 있다. (외부 접근 불가)
+
Abstraction
+
복잡한 상속, 메서드, 객체의 속성의 결합은 반드시 현실 세계를 시뮬레이션할 수 있어야 한다.
+
Polymorphism
+
다른 클래스들이 같은 메서드나 속성으로 정의될 수 있다.
+
+ +

객체지향 프로그래밍에 대한 보다 확장된 설명은 Object-oriented programming를 참고하면 된다.

+ +

프로토타입기반 프로그래밍(Prototype-based programming)

+ +

프로토타입 기반 프로그래밍은 클래스가 존재하지 않는 객체지향 프로그래밍의 한가지 스타일로, 동작 재사용(behavior reuse, 클래스기반 언어에서는 상속이라고함)은 프로토타입으로서 존재하는 객체를 데코레이팅하는 과정을 통해 수행된다.

+ +

프로토타입 기반 언어의 원형적인 예는 David Ungar과 Randall Smith가 개발한 'Self'라는 프로그래밍 언어이다. 그러나 클래스가 없는 프로그래밍 스타일이 최근 인기를 얻으며 성장하였고, 자바스크립트, Cecil, NewtonScript, Io, MOO, REBOL, Kevo, Squeak 등의 언어에서 채택되어 왔다.2

+ +

자바스크립트 객체지향 프로그래밍(JavaScript Object Oriented Programming)

+ +

Core Objects

+ +

자바스크립트는 코어(core)에 몇 개의 객체를 갖고 있다. 예를들면, Math, Object, Array, String과 같은 객체가 있다. 아래의 예제는 Math 객체를 사용해서 무작위 숫자를 만들어내는 것을 보여준다.

+ +
alert(Math.random());
+
+ +
Note: 여기와 다른 예제들 모두 alert 이라는 함수가 전역에 선언되어 있다고 가정하고 있다. alert 함수는 실제로 자바스크립트 그 자체에 포함되진 않았지만, 대부분의 브라우저에서 지원하고 있다.
+ +

자바스크립트의 core object들의 리스트는 Core JavaScript 1.5 Reference:Global Objects라는 글을 참고하면 자세히 알 수 있다.

+ +

자바스크립트의 모든 객체는 Object 객체의 인스턴스이므로 Object의 모든 속성과 메서드를 상속받는다.

+ +

Custom Objects

+ +

The Class

+ +

class문을 흔하게 볼 수 있는 C++이나 자바와는 달리 자바스크립트는 class문이 포함되지 않은 프로토타입 기반 언어이다. 이로인해 때때로 class 기반 언어에 익숙한 프로그래머들은 혼란을 일으킨다. 자바스크립트에서는 function을 class로서 사용한다. 클래스를 정의하는 것은 function을 정의하는 것만큼 쉽다. 아래 예제에서는 Person이라는 이름의 클래스를 새로 정의하고 있다.

+ +
function Person() { }
+
+ +

The Object (Class Instance)

+ +

obj라는 이름의 객체의 새로운 인스턴스를 만들 때에는 new obj라는 statement를 사용하고, 차후에 접근할 수 있도록 변수에 결과를 받는다.

+ +

아래의 예제에서 Person이라는 이름의 클래스를 정의한 후에, 두 개의 인스턴스를 생성하고 있다.

+ +
function Person() { }
+var person1 = new Person();
+var person2 = new Person();
+
+ +
Object.create 메서드 역시 새로운 인스턴스를 만들 때 사용할 수 있다.
+ +

The Constructor

+ +

생성자는 인스턴스화되는 순간(객체 인스턴스가 생성되는 순간) 호출된다. 생성자는 해당 클래스의 메서드이다. 자바스크립트에서는 함수 자체가 그 객체의 생성자 역할을 하기 때문에 특별히 생성자 메서드를 정의할 필요가 없다. 클래스 안에 선언된 모든 내역은 인스턴스화되는 그 시간에 실행된다. 생성자는 주로 객체의 속성을 설정하거나 사용하기 위해 객체를 준비시키는 메서드를 호출할 때 주로 사용된다. 클래스 메서드를 추가하고 정의하는 것은 나중에 설명한다.

+ +
아래의 예제에서, Person 클래스의 생성자는 Person 이 인스턴스화되었을 때 alert 을 보여주게 된다.
+ +
function Person() {
+  alert('Person instantiated');
+}
+
+var person1 = new Person();
+var person2 = new Person();
+
+ +

The Property (object attribute)

+ +
속성은 클래스 안에 있는 변수들을 말한다. 객체의 모든 인스턴스는 그 인스턴스의 속성을 갖는다. 속성들의 상속이 바르게 이루어지려면 해당 클래스(function)의 프로토타입에 선언되어 있어야 한다.
+ +
 
+ +
클래스 내에서 속성 작업은 현재 객체를 가리키는 this 키워드에 의해 이루어진다. 클래스의 외부에서 속성에 접근(읽기 혹은 쓰기)하는 것은 "인스턴스명.속성명" 의 형식으로 이루어진다. 이러한 문법은 C++, 자바나 다른 수많은 언어에서와 동일한 방식이다. (클래스 내부에서 "this.속성명" 은 해당 속성의 값을 읽거나 쓸 때 주로 사용된다)
+ +
 
+ +
아래의 예제에서 Person 클래스에 gender라는 속성을 정의하고 인스턴스화할 때 그 값을 설정한다.
+ +
function Person(gender) {
+  this.gender = gender;
+  alert('Person instantiated');
+}
+
+var person1 = new Person('Male');
+var person2 = new Person('Female');
+
+//display the person1 gender
+alert('person1 is a ' + person1.gender); // person1 is a Male
+
+ +

메서드(The methods)

+ +

메서드는 앞서 살펴본 속성과 같은 방식을 따른다. 차이점이 있다면 메서드는 function이기 때문에 function 형태로 정의된다는 것입니다. 메서드를 호출하는 것은 속성에 접근하는 것과 매우 유사한데 단지 끝에 ()를 추가하면 된다. argument가 있다면 괄호 안에 입력해준다. 메서드를 정의하기 위해서는 클래스의 prototype에 명명된 속성에 함수를 할당하면 된다. 이때 할당된 이름은 해당 객체의 메서드를 호출할 때 사용되는 이름이다.

+ +

아래의 예에서는 Person 클래스에 sayHello()라는 메서드를 정의하고 사용하고 있다.

+ +
function Person(gender) {
+  this.gender = gender;
+  alert('Person instantiated');
+}
+
+Person.prototype.sayHello = function()
+{
+  alert ('hello');
+};
+
+var person1 = new Person('Male');
+var person2 = new Person('Female');
+
+// call the Person sayHello method.
+person1.sayHello(); // hello
+
+ +

자바스크립트에서 메서드는 "컨텍스트에 관계 없이" 호출될 수 있는 속성으로서 클래스/객체에 연결되어 있다. 다음 예제의 코드를 살펴보자.

+ +
function Person(gender) {
+  this.gender = gender;
+}
+
+Person.prototype.sayGender = function()
+{
+  alert(this.gender);
+};
+
+var person1 = new Person('Male');
+var genderTeller = person1.sayGender;
+
+person1.sayGender(); // alerts 'Male'
+genderTeller(); // alerts undefined
+alert(genderTeller === person1.sayGender); // alerts true
+alert(genderTeller === Person.prototype.sayGender); // alerts true
+
+ +

위의 예제는 많은 개념들을 한꺼번에 보여주고 있다. 

+ +
먼저 이 예제는 자바스크립트에 "per-object methods" 가 존재하지 않는다는 것을 보여준다. JavaScript는 메서드에 대한 레퍼런스가 모두 똑같은 (프로토타입에 처음 정의한) 함수를 참조하고 있기 때문이다.
+ +
 
+ +
자바스크립트는 어떤 객체의 메서드로서 함수가 호출될 때 현재 "객체의 컨텍스트"를 특별한 "this" 변수에 "연결한다". 이는 아래와 같이 function 객체의 call 메서드를 호출하는 것과 동일하다.
+ +
 
+ +
(역자주: 참고로, genderTeller() 만 호출했을 때 undefined 가 나타난 것은 해당 메서드가 호출될 때 컨텍스트가 window 로 잡혔기 때문에 window.gender 는 존재하지 않으므로 undefined 가 나타난 것이다.)
+ +
 
+ +
genderTeller.call(person1); //alerts 'Male'
+
+ +
더 자세한 것은 Function.callFunction.apply 를 참고하자.
+ +

상속(Inheritance)

+ +

상속은 하나 이상의 클래스를 특별한 버전의 클래스로 생성하는 하나의 방법이다. (다만 자바스크립트는 오직 하나의 클래스를 상속받는 것만 지원한다.) 이 특별한 클래스는 흔히 자식 클래스(child)라고 불리우고 원본 클래스는 흔히 부모 클래스(parent)라고 불리운다. 자바스크립트에서는 부모 클래스의 인스턴스를 자식 클래스에 할당함으로써 상속이 이루어진다. 최신 브라우저에서는 Object.create 메서드를 사용해서 상속을 수행할 수도 있다.

+ +
+

Core JavaScript 1.5 Reference:Global Objects:Object:prototype 에 나와있는 설명과 같이 자바스크립트는 자식 클래스의 prototype.constructor 를 검색하지 않으므로 직접 명시해주어야 한다.

+
+ +

아래의 예제에서는, Student라는 클래스를 Person 클래스의 자식 클래스로 정의한다. 그 후에 우리는 sayHello() 메서드를 재정의하고 sayGoodBye() 메서드를 추가한다.

+ +
// define the Person Class
+function Person() {}
+
+Person.prototype.walk = function(){
+  alert ('I am walking!');
+};
+Person.prototype.sayHello = function(){
+  alert ('hello');
+};
+
+// define the Student class
+function Student() {
+  // Call the parent constructor
+  Person.call(this);
+}
+
+// inherit Person
+Student.prototype = new Person();
+
+// correct the constructor pointer because it points to Person
+Student.prototype.constructor = Student;
+
+// replace the sayHello method
+Student.prototype.sayHello = function(){
+  alert('hi, I am a student');
+}
+
+// add sayGoodBye method
+Student.prototype.sayGoodBye = function(){
+  alert('goodBye');
+}
+
+var student1 = new Student();
+student1.sayHello();
+student1.walk();
+student1.sayGoodBye();
+
+// check inheritance
+alert(student1 instanceof Person); // true
+alert(student1 instanceof Student); // true
+
+ +

Object.create 를 사용하면 상속을 아래와 같이 수행할 수 있다.

+ +
Student.prototype = Object.create(Person.prototype);
+ +

캡슐화(Encapsulation)

+ +

이전의 예제에서, Student 클래스는 Person 클래스의 walk() 메서드가 어떻게 실행되는지에 대해 알 필요가 없고, walk() 메서드를 사용하는데에도 전혀 문제가 없다. 또 Student 클래스에서는 walk() 메서드의 내용을 바꾸려는게 아니라면 walk() 메서드를 특별히 정의할 필요도 없다. 자식 클래스는 부모 클래스의 모든 메서드를 상속받고, 상속받은 메서드중 일부를 수정하고 싶은 경우에만 해당 메서드를 정의하는 것을 우리는 캡슐화(encapsulation)이라고 부른다.

+ +

추상화(Abstraction)

+ +

추상화는 작업 문제의 현재 부분을 모델링할 수 있도록 하는 매커니즘이다. 추상화는 상속(specialization, 추상의 수준을 낮추는 것)과 합성으로 구현할 수 있다. 자바스크립트는 상속에 의해 특별화(specialization)를, 클래스들의 인스턴스를 다른 객체의 속성값이 되게 함으로써 합성을 구현한다.

+ +

자바스크립트 Function 클래스는 Object 클래스를 상속받고(이는 모델의 특별화를 보여준다), Function.prototype 속성은 Object의 인스턴스이다(이는 합성을 보여준다).

+ +
var foo = function(){};
+alert( 'foo is a Function: ' + (foo instanceof Function) );
+alert( 'foo.prototype is an Object: ' + (foo.prototype instanceof Object) );
+
+ +

다형성(Polymorphism)

+ +

모든 메서드와 속성들은 prototype 속성에 선언되어 있고, 클래스가 다르다면 같은 이름의 메서드도 선언할 수 있다. 메서드들은 메서드가 선언된 클래스로 그 실행 영역이 한정된다. 물론 이건 두 개의 클래스들이 서로 부모-자식 관계가 아닐때에만 성립한다. 즉 다시 말해 부모-자식 관계의 상속 관계로 하나가 다른 하나에게서 상속받지 않았을 때에만 성립한다.

+ +

Notes

+ +

객체지향 프로그래밍을 구현하는데 있어서 자바스크립트는 매우 유연하기 때문에, 이 글에서 선보인 테크닉들은 자바스크립트에서 객체지향을 구현하는 유일한 방법들 중 일부일 뿐이다.

+ +

또, 여기에서 선보인 테크닉들은 어떤 hack도 사용하지 않았고 또한 다른 언어의 객체 이론 구현물들을 모방하지도 않았다.

+ +

자바스크립트의 객체지향 프로그래밍에 있어서 다른 보다 깊이있는 테크닉들이 많이 있지만, 소개하는 글이라는 이 글의 특성상 다루지 않기로 한다.

+ +

References

+ +
    +
  1. Mozilla. "Core JavaScript 1.5 Guide", http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide
  2. +
  3. Wikipedia. "Object-oriented programming", http://en.wikipedia.org/wiki/Object-...ed_programming
  4. +
+ +
+

Original Document Information

+ + +
+ +

 

diff --git a/files/ko/web/javascript/javascript_technologies_overview/index.html b/files/ko/web/javascript/javascript_technologies_overview/index.html new file mode 100644 index 0000000000..185a417001 --- /dev/null +++ b/files/ko/web/javascript/javascript_technologies_overview/index.html @@ -0,0 +1,83 @@ +--- +title: JavaScript 기술 개요 +slug: Web/JavaScript/JavaScript_technologies_overview +tags: + - Beginner + - DOM + - JavaScript +translation_of: Web/JavaScript/JavaScript_technologies_overview +--- +
{{JsSidebar("Introductory")}}
+ +

개요

+ +

HTML이 웹 페이지의 구조와 내용을, CSS가 서식과 외관을 결정한다면, JavaScript는 상호작용성을 추가하여 풍부한 웹 어플리케이션을 만듭니다.

+ +

그러나, 웹 브라우저 맥락에서 포괄적으로 쓰이는 용어로써의 "JavaScript"는 사실 매우 다른 요소 여럿을 포함하는 것입니다. 그 중 하나는 핵심 언어(ECMAScript)고, 다른 하나는 DOM(Document Object Model)을 포함한 Web API입니다.

+ +

핵심 언어, JavaScript(ECMAScript)

+ +

JavaScript의 핵심 언어는 ECMA TC39 위원회가 ECMAScript라는 이름으로 표준화했습니다.

+ +

핵심 언어는 Node.js 등 비브라우저 환경에서도 사용됩니다.

+ +

ECMAScript에 속하는 것

+ +

ECMAScript는 다음 항목을 포함하고 있습니다.

+ + + +

브라우저 지원

+ +

2016년 10월 기준 주요 브라우저의 현버전은 ECMAScript 5.1과 ECMAScript 2015를 구현하지만, (여전히 사용 중인) 오래된 브라우저는 ECMAScript 5만 구현합니다.

+ +

미래

+ +

2015년 7월 17일, ECMAScript 6판이 ECMA General Assembly에 의해 공식으로 채택되고 표준으로 출판됐습니다. 이후 ECMAScript는 매년 새로운 판을 출판하고 있습니다.

+ +

국제화 API

+ +

ECMAScript 국제화 API 명세는 ECMAScript 언어 명세의 부속이며, 마찬가지로 ECMA TC39가 표준화했습니다. 국제화 API는 JavaScript 어플리케이션에 콜레이션(문자열 비교), 숫자 서식, 날짜 및 시간 서식 기능을 제공하므로, 어플리케이션이 언어를 선택하고 필요에 맞춰 기능을 적용할 수 있는 방법입니다. 초기 표준안은 2012년 12월에 통과했으며 브라우저 구현 상태는 {{jsxref("Intl")}} 객체 문서에서 추적 중입니다. 최근에는 국제화 명세도 매년 비준하고 있으며 브라우저 구현도 계속하여 향상 중입니다.

+ +

DOM API

+ +

WebIDL

+ +

WebIDL 명세는 DOM 기술과 ECMAScript 사이를 연결하는 역할을 합니다.

+ +

DOM의 핵심

+ +

DOM(Document Object Model)은 HTML, XHTML, XML 문서의 객체를 나타내고 상호작용하기 위한, 언어에 제약되지 않는 크로스 플랫폼 협약입니다. DOM 트리의 객체는 해당 객체의 메서드를 사용해 조작할 수 있습니다. {{glossary("W3C")}}는 HTML와 XML 문서를 객체로 추상화하는 Core Document Object Model을 표준화하고, 추상화를 조작하기 위한 방법도 정의합니다. DOM에 정의된 내용 중 일부는 다음과 같습니다.

+ + + +

ECMAScript의 관점에서, DOM 명세에 정의된 객체는 "호스트 객체"라고 부릅니다.

+ +

HTML DOM

+ +

웹 마크업 언어인 HTML은 DOM 코어에 정의된 추상화 개념에 엘리먼트의 의미를 더한 레이어라고 할 수 있겠다. HTML DOM은 HTML 엘리먼트의 className 같은 속성과 {{ domxref("document.body") }} 같은 API도 포함한다.

+ +

HTML 명세는 문서의 제약도 정의한다. 예를들어 순서가 없는 리스트를 나타내는 ul 의 모든 자식들은 리스트 요소를 나타내는 li 엘리먼트여야 한다. 또한 표준에 정의되지 않은 엘리먼트와 속성을 사용하는것도 금지된다.

+ +

알아둘만한 다른 API

+ + diff --git a/files/ko/web/javascript/memory_management/index.html b/files/ko/web/javascript/memory_management/index.html new file mode 100644 index 0000000000..22cccc5e76 --- /dev/null +++ b/files/ko/web/javascript/memory_management/index.html @@ -0,0 +1,183 @@ +--- +title: 자바스크립트의 메모리관리 +slug: Web/JavaScript/Memory_Management +translation_of: Web/JavaScript/Memory_Management +--- +

{{JsSidebar("Advanced")}}
+ C 언어같은 저수준 언어에서는 메모리 관리를 위해 malloc() 과 free()를 사용한다. 반면, 자바스크립트는 객체가 생성되었을 때 자동으로 메모리를 할당하고 쓸모 없어졌을 때 자동으로 해제한다(가비지 컬렉션). 이러한 자동 메모리 관리는 잠재적 혼란의 원인이기도 한데, 개발자가 메모리 관리에 대해 고민할 필요가 없다는 잘못된 인상을 줄 수 있기 때문이다.

+ +

메모리 생존주기

+ +

메모리 생존주기는 프로그래밍 언어와 관계없이 비슷하다.

+ +
    +
  1. 필요할때 할당한다.
  2. +
  3. 사용한다. (읽기, 쓰기)
  4. +
  5. 필요없어지면 해제한다. 
  6. +
+ +

두 번째 부분은 모든 언어에서 명시적으로 사용된다. 그러나 첫 번째 부분과 마지막 부분은 저수준 언어에서는 명시적이며, 자바스크립트와 같은 대부분의 고수준 언어에서는 암묵적으로 작동한다. 

+ +

자바스크립트에서 메모리 할당

+ +

값 초기화

+ +

프로그래머를 할당 문제로 괴롭히지 않기 위해서, 자바스크립트는 값을 선언할 때 자동으로 메모리를 할당한다.

+ +
+
var n = 123; // 정수를 담기 위한 메모리 할당
+var s = 'azerty'; // 문자열을 담기 위한 메모리 할당
+
+var o = {
+  a: 1,
+  b: null
+}; // 오브젝트와 그 오브젝트에 포함된 값들을 담기 위한 메모리 할당
+
+// (오브젝트처럼) 배열과 배열에 담긴 값들을 위한 메모리 할당
+var a = [1, null, 'abra'];
+
+function f(a){
+  return a + 2;
+} // 함수를 위한 할당(함수는 호출 가능한 오브젝트이다)
+
+// 함수식 또한 오브젝트를 담기위한 메모리를 할당한다.
+someElement.addEventListener('click', function(){
+  someElement.style.backgroundColor = 'blue';
+}, false);
+
+
+ +

함수 호출을 통한 할당

+ +

함수 호출의 결과 메모리 할당이 일어나기도 한다. 

+ +
var d = new Date(); // Date 개체를 위해 메모리를 할당
+
+var e = document.createElement('div'); // DOM 엘리먼트를 위해 메모리를 할당한다.
+
+ +

메소드가 새로운 값이나 오브젝트를 할당하기도 한다.

+ +
var s = 'azerty';
+var s2 = s.substr(0, 3); // s2는 새로운 문자열
+// 자바스크립트에서 문자열은 immutable 값이기 때문에,
+// 메모리를 새로 할당하지 않고 단순히 [0, 3] 이라는 범위만 저장한다.
+
+var a = ['ouais ouais', 'nan nan'];
+var a2 = ['generation', 'nan nan'];
+var a3 = a.concat(a2);
+// a 와 a2 를 이어붙여, 4개의 원소를 가진 새로운 배열
+
+ +

값 사용

+ +

값 사용이란 기본적으로는 할당된 메모리를 읽고 쓰는 것을 의미한다. 변수나 오브젝트 속성 값을 읽고 쓸때 값 사용이 일어난다. 또 함수 호출시 함수에 인수를 넘길때도 일어난다. 

+ +

할당된 메모리가 더 이상 필요없을 때 해제하기

+ +

이 단계에서 대부분의 문제가 발생한다. "할당된 메모리가 더 이상 필요없을 때"를 알아내기가 어렵기 때문이다.

+ +

저수준 언어에서는 메모리가 필요없어질 때를 개발자가 직접 결정하고 해제하는 방식을 사용한다. 

+ +

자바스크립트와 같은 고수준 언어들은 "가비지 콜렉션(GC)"이라는 자동 메모리 관리 방법을 사용한다. 가비지 콜렉터의 목적은 메모리 할당을 추적하고 할당된 메모리 블록이 더 이상 필요하지 않게게 되었는지를 판단하여 회수하는 것이다. 이러한 자동 메모리 관리 프로세스는 궁극의 방법은 아니다. 왜냐하면 어떤 메모리가 여전히 필요한지 아닌지를 판단하는 것은 비결정적 문제이기 때문이다.

+ +

가비지 콜렉션

+ +

위에서 언급한 것처럼 "더 이상 필요하지 않은" 모든 메모리를 찾는건 비결정적 문제다. 따라서 가비지 컬렉터들은 이 문제에 대한 제한적인 해결책을 구현한다. 이 섹션에서는 주요한 가비지 컬렉션 알고리즘들과 그 한계를 이해하는데 필요한 개념을 설명한다.

+ +

참조

+ +

가비지 콜렉션 알고리즘의 핵심 개념은 참조이다. A라는 메모리를 통해 (명시적이든 암시적이든) B라는 메모리에 접근할 수 있다면 "B는 A에 참조된다" 라고 한다. 예를 들어 모든 자바스크립트 오브젝트는 prototype 을 암시적으로 참조하고 그 오브젝트의 속성을 명시적으로 참조한다.

+ +

앞으로 "오브젝트"라는 어휘의 의미를 넓혀서 기존의 자바스크립트 오브젝트뿐만 아니라 함수 스코프도 포괄하자.

+ +

참조-세기(Reference-counting) 가비지 콜렉션

+ +

참조-세기 알고리즘은 가장 소박한 알고리즘이다. 이 알고리즘은 "더 이상 필요없는 오브젝트"를 "어떤 다른 오브젝트도 참조하지 않는 오브젝트"라고 정의한다. 이 오브젝트를 "가비지"라 부르며, 이를 참조하는 다른 오브젝트가 하나도 없는 경우, 수집이 가능하다.

+ +

예제

+ +
var x = {
+  a: {
+    b:2
+  }
+};
+// 2개의 오브젝트가 생성되었다. 하나의 오브젝트는 다른 오브젝트의 속성으로 참조된다.
+// 나머지 하나는 'x' 변수에 할당되었다.
+// 명백하게 가비지 콜렉션 수행될 메모리는 하나도 없다.
+
+
+var y = x;    // 'y' 변수는 위의 오브젝트를 참조하는 두 번째 변수이다.
+x = 1;        // 이제 'y' 변수가 위의 오브젝트를 참조하는 유일한 변수가 되었다.
+
+var z = y.a;  // 위의 오브젝트의 'a' 속성을 참조했다.
+              // 이제 'y.a'는 두 개의 참조를 가진다.
+              // 'y'가 속성으로 참조하고 'z'라는 변수가 참조한다.
+
+y = "yo";     // 이제 맨 처음 'y' 변수가 참조했던 오브젝트를 참조하는 오브젝트는 없다.
+              // (역자: 참조하는 유일한 변수였던 y에 다른 값을 대입했다)
+              // 이제 오브젝트에 가비지 콜렉션이 수행될 수 있을까?
+              // 아니다. 오브젝트의 'a' 속성이 여전히 'z' 변수에 의해 참조되므로
+              // 메모리를 해제할 수 없다.
+
+z = null;     // 'z' 변수에 다른 값을 할당했다.
+              // 이제 맨 처음 'x' 변수가 참조했던 오브젝트를 참조하는
+              // 다른 변수는 없으므로 가비지 콜렉션이 수행된다.
+
+ +

한계: 순환 참조

+ +

순환 참조를 다루는 일에는 한계가 있다. 다음 예제에서는 두 객체가 서로 참조하는 속성으로 생성되어 순환 구조를 생성한다. 함수 호출이 완료되면 이 두 객체는 스코프를 벗어나게 될 것이며, 그 시점에서 두 객체는 불필요해지므로 할당된 메모리는 회수되어야 한다. 그러나 두 객체가 서로를 참조하고 있으므로, 참조-세기 알고리즘은 둘 다 가비지 컬렉션의 대상으로 표시하지 않는다. 이러한 순환 참조는 메모리 누수의 흔한 원인이다.

+ +
function f(){
+  var o = {};
+  var o2 = {};
+  o.a = o2; // o는 o2를 참조한다.
+  o2.a = o; // o2는 o를 참조한다.
+
+  return "azerty";
+}
+
+f();
+
+ +

실제 예제

+ +

인터넷 익스플로러 6, 7 은 DOM 오브젝트에 대해 참조-세기 알고리즘으로 가비지 콜렉션을 수행한다. 흔히, 이 두 브라우저에서는 다음과 같은 패턴의 메모리 누수가 발생한다. 

+ +
var div = document.createElement("div");
+div.onclick = function(){
+  doSomething();
+}; // div 오브젝트는 이벤트 핸들러를 'onclick' 속성을 통해 참조한다.
+// 이벤트 핸들러의 스코프에도 div 오브젝트가 있으므로 div 오브젝트에 접근할 수 있다. 따라서 이벤트 핸들러도 div 오브젝트를 참조한다.
+// 순환이 발생했고 메모리 누수가 일어난다.
+
+ +

표시하고-쓸기(Mark-and-sweep) 알고리즘

+ +

이 알고리즘은 "더 이상 필요없는 오브젝트"를 "닿을 수 없는 오브젝트"로 정의한다.

+ +

이 알고리즘은 roots 라는 오브젝트의 집합을 가지고 있다(자바스크립트에서는 전역 변수들을 의미한다). 주기적으로 가비지 콜렉터는 roots로 부터 시작하여 roots가 참조하는 오브젝트들, roots가 참조하는 오브젝트가 참조하는 오브젝트들... 을 닿을 수 있는 오브젝트라고 표시한다. 그리고 닿을 수 있는 오브젝트가 아닌 닿을 수 없는 오브젝트에 대해 가비지 콜렉션을 수행한다.

+ +

이 알고리즘은 위에서 설명한 참조-세기 알고리즘보다 효율적이다. 왜냐하면 "참조되지 않는 오브젝트"는 모두 "닿을 수 없는 오브젝트" 이지만 역은 성립하지 않기 때문이다. 위에서 반례인 순환 참조하는 오브젝트들을 설명했다.

+ +

2012년 기준으로 모든 최신 브라우저들은 가비지 콜렉션에서 표시하고-쓸기 알고리즘을 사용한다. 지난 몇 년간 연구된 자바스크립트 가비지 콜렉션 알고리즘의 개선들은 모두 이 알고리즘에 대한 것이다. 개선된 알고리즘도 여전히 "더 이상 필요없는 오브젝트"를 "닿을 수 없는 오브젝트"로 정의하고 있다.

+ +

순환 참조는 이제 문제가 되지 않는다.

+ +

첫 번째 예제에서 함수가 리턴되고 나서 두 오브젝트는 닿을 수 없다. 따라서 가비지 콜렉션이 일어난다.

+ +

두 번째 예제에서도 마찬가지다. div 변수와 이벤트 핸들러가 roots로 부터 닿을 수 없어지면 순환 참조가 일어났음에도 불구하고 가비지 콜렉션이 일어난다. (역자2: div 선언을 블럭안에다 넣어야 된다.(테스트는 못 해봤다.))

+ +

한계: 수동 메모리 해제.

+ +

어떤 메모리를 언제 해제할지에 대해 수동으로 결정하는 것이 편리할 때가 있습니다. 그리고 수동으로 객체의 메모리를 해제하려면, 객체 메모리에 도달할 수 없도록 명시하는 기능이 있어야 합니다.
+
+ 2019년 현재의 JavaScript에서는 명시적으로 또는 프로그래밍 방식으로 가비지 컬렉션을 작동할 수 없습니다.

+ +

더 보기

+ + diff --git a/files/ko/web/javascript/new_in_javascript/1.5/index.html b/files/ko/web/javascript/new_in_javascript/1.5/index.html new file mode 100644 index 0000000000..a34931d815 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/1.5/index.html @@ -0,0 +1,37 @@ +--- +title: New in JavaScript 1.5 +slug: Web/JavaScript/New_in_JavaScript/1.5 +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.5 +--- +
{{jsSidebar("New_in_JS")}}
+ +

다음은 JavaScript 1.5의 변경 내역입니다. 이 버전은 2000년 11월 14일에 출시된 Netscape Navigator 6.0과 그 이 후 버전 그리고 Firefox 1.0에 포함되어 있습니다. You can compare JavaScript 1.5 to JScript version 5.5 and Internet Explorer 5.5, which was released in July 2000. 해당하는 ECMA 표준은 ECMA-262 Edition 3(1999년 12월 이후) 입니디.

+ +

New features in JavaScript 1.5

+ + + +

Changed functionality in JavaScript 1.5

+ + diff --git a/files/ko/web/javascript/new_in_javascript/1.6/index.html b/files/ko/web/javascript/new_in_javascript/1.6/index.html new file mode 100644 index 0000000000..db92810578 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/1.6/index.html @@ -0,0 +1,85 @@ +--- +title: New in JavaScript 1.6 +slug: Web/JavaScript/New_in_JavaScript/1.6 +tags: + - E4X + - JavaScript + - JavaScript_version_overviews +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.6 +--- +
{{jsSidebar("New_in_JS")}}
+ +

JavaScript 1.6 여러 새 기능(E4X, 여러 새 Array 메소드, Array과 String generic)을 소개합니다.

+ +

JavaScript 1.6은 Firefox 1.5와 이후 버전에서 지원합니다.

+ +

E4X

+ +

ECMAScript for XML (E4X)는 JavaScript 안의 XML 컨텐트를 만들고 처리하는 강력한 기술입니다. 우리는 기존 DOM과의 transparent한 통합 추가를 포함하는 E4X 지원 향상을 계속할 예정이지만 XML 기반 웹 응용프로그램을 만드는(build) 개발자는 Firefox 1.5의 E4X 지원에서 이득을 얻을 수 있습니다.

+ +

아직은 E4X를 쓸 때 표준 MIME 형을 쓸 수 있습니다.

+ +
<script type="text/javascript">
+
+ +

그러나, E4X 구문이 옛날 브라우저에서 그것을 숨기기 위해 HTML 주석 (<!--...-->)에 스크립트를 넣는 흔한 관례(practice)와 충돌할지도 모릅니다. E4X 또한 스크립트에 기호 "<"와 ">"를 허용하는 XML CDATA 절 (<![CDATA{{ mediawiki.external('...') }}]>) 에 스크립트를 놓는 더 현대식 관례와 충돌할지도 모릅니다(이는 HTML에는 적용되지 않음을 주의하세요). 만약 설명할 수 없는 구문 에러를 보면, MIME 형에 "; e4x=1"를 보태세요.

+ +
<script type="text/javascript; e4x=1">
+
+ +

확장기능의 스크립트는 항상 HTML 주석을 E4X 상수(literal)로 다룸을 주의하세요. 즉, "e4x=1"을 묵시(implicit)로 적용합니다.

+ +

E4X는 Processing XML with E4X에서 설명합니다.

+ +

Array 추가분

+ +

두 갈래(item location 메소드와 iterative 메소드)로 구분할 수 있는 7가지 새 Array 메소드가 있습니다. item location 메소드는

+ + + +

iterative 메소드는

+ + + +

더 자세한 정보는 Working with Arrays나 Nicholas C. Zakas의 기사 Mozilla's New Array Methods를 보세요.

+ +

Array와 String generic

+ +

간혹 배열 메소드를 문자열에 쓰고 싶습니다. 이리하여, 문자열을 문자 배열로 다룹니다. 예를 들어, 변수 str의 모든 문자(character)가 문자(letter)인지 검사하기 위해, 당신은 작성합니다.

+ +
function isLetter(character) {
+  return (character >= "a" && character <= "z");
+}
+
+if (Array.prototype.every.call(str, isLetter))
+  alert("The string '" + str + "' contains only letters!");
+
+ +

이 표기(notation)는 약간 낭비라서 JavaScript 1.6은 generic 속기(shorthand)를 도입합니다.

+ +
if (Array.every(str, isLetter))
+  alert("The string '" + str + "' contains only letters!");
+
+ +

비슷하게 문자열 메소드를 어느 개체든지 쉽게 적용할 수 있습니다.

+ +
var num = 15;
+alert(String.replace(num, /5/, '2'));
+
+ +

같이 보기

+ +

Working with Array-like objects.

+ +
 
+ +

{{ languages( { "en": "en/New_in_JavaScript_1.6", "es": "es/Novedades_en_JavaScript_1.6", "fr": "fr/Nouveaut\u00e9s_dans_JavaScript_1.6", "ja": "ja/New_in_JavaScript_1.6", "pl": "pl/Nowo\u015bci_w_JavaScript_1.6", "ru": "ru/\u041d\u043e\u0432\u043e\u0435_\u0432_JavaScript_1.6", "zh-cn": "cn/New_in_JavaScript_1.6" } ) }}

diff --git a/files/ko/web/javascript/new_in_javascript/1.8.1/index.html b/files/ko/web/javascript/new_in_javascript/1.8.1/index.html new file mode 100644 index 0000000000..2a50e35cf7 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/1.8.1/index.html @@ -0,0 +1,26 @@ +--- +title: New in JavaScript 1.8.1 +slug: Web/JavaScript/New_in_JavaScript/1.8.1 +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.8.1 +--- +
{{jsSidebar("New_in_JS")}}
+ +

다음은  JavaScript 1.8.1의 변경사항입니다. Firefox 3.5 버전에 포함되었습니다.

+ +

JavaScript 1.8.1는 약간의 문법적인 업데이트가 있습니다. 이번 릴리즈의 주요 변경사항은 Tracemonkey just-in-time compiler(성능적인 향상이 포함된 릴리즈입니다)의 추가되어있습니다

+ +

JavaScript 1.8.1의 새로운 특징

+ + + +

JavaScript 1.8.1에서 변경된 기능

+ + diff --git a/files/ko/web/javascript/new_in_javascript/1.8.5/index.html b/files/ko/web/javascript/new_in_javascript/1.8.5/index.html new file mode 100644 index 0000000000..27853f0531 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/1.8.5/index.html @@ -0,0 +1,126 @@ +--- +title: New in JavaScript 1.8.5 +slug: Web/JavaScript/New_in_JavaScript/1.8.5 +tags: + - ECMAScript5 + - JavaScript + - JavaScript 1.8.5 +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.8.5 +--- +
{{jsSidebar("New_in_JS")}}
+ +

다음은 JavaScript 1.8.5에 대한 변경기록입니다. 이 버전은 Firefox 4에서 포함되었습니다.

+ +

JavaScript 1.8.5의 새로운 기능

+ +

새로운 함수

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
함수설명
{{jsxref("Object.create()")}}지정된 프로토타입 객체 및 속성을 갖는 새로운 객체 생성. {{bug("492840")}}
{{jsxref("Object.defineProperty()")}}객체에 주어진 설명자로 기술된 유명(named) 속성을 추가.
{{jsxref("Object.defineProperties()")}}객체에 주어진 설명자로 기술된 유명 속성을 추가.
{{jsxref("Object.getOwnPropertyDescriptor()")}}객체의 유명 속성에 대한 속성 설명자를 반환. {{bug("505587")}}
{{jsxref("Object.keys()")}}객체의 모든 열거가능 속성 배열을 반환. {{bug("307791")}}
{{jsxref("Object.getOwnPropertyNames()")}}객체의 모든 열거가능 및 열거불가 속성 배열을 반환. {{bug("518663")}}
{{jsxref("Object.preventExtensions()")}}객체 확장을 막음. {{bug("492849")}}
{{jsxref("Object.isExtensible()")}}객체 확장이 허용되는지 판단. {{bug("492849")}}
{{jsxref("Object.seal()")}}다른 코드가 객체의 속성을 삭제하는 것으로부터 막음. {{bug("492845")}}
{{jsxref("Object.isSealed()")}}객체가 봉인되었는지 판단. {{bug("492845")}}
{{jsxref("Object.freeze()")}}객체 동결: 다른 코드가 어떤 속성도 삭제 또는 변경할 수 없음. {{bug("492844")}}
{{jsxref("Object.isFrozen()")}}객체가 동결됐는지 판단. {{bug("492844")}}
{{jsxref("Array.isArray()")}}변수가 배열인지 확인. {{bug("510537")}}
{{jsxref("Date.prototype.toJSON()")}}Date 객체의 JSON 형식 문자열 반환.
{{jsxref("Function.prototype.bind()")}}호출될 때 그 자체가 (주어진 인수열과 함께) 주어진 문맥에서 이 함수를 호출하는 새로운 함수 생성 {{bug("429507")}}
+ +

ECMAScript5 새로운 기능

+ + + +

다른 표준화 작업

+ +

getter 및 setter를 정의하는 다양한 비표준 구문이 제거되었습니다; ECMAScript 5에서 정의된 구문은 변경되지 않았습니다. 이들은 모두 꽤 난해하고 거의 쓰이지 않았습니다; 영향을 미치는 경우, 자세한 사항은 이 블로그 게시글 참조.

+ +

새로운 객체

+ + + + + + + + + + + + + + +
객체설명
{{jsxref("Proxy")}}JavaScript에서 메타프로그래밍을 가능케 하는 ObjectFunction 프록시 생성 지원을 제공.
+ +

JavaScript 1.8.5에서 바뀐 기능

+ + diff --git a/files/ko/web/javascript/new_in_javascript/1.8/index.html b/files/ko/web/javascript/new_in_javascript/1.8/index.html new file mode 100644 index 0000000000..3372eeac27 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/1.8/index.html @@ -0,0 +1,138 @@ +--- +title: New in JavaScript 1.8 +slug: Web/JavaScript/New_in_JavaScript/1.8 +tags: + - JavaScript + - JavaScript_version_overviews +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.8 +--- +

{{jsSidebar("New_in_JS")}} 자바스크립트 1.8은 (Firefox 3에 포함될 예정인) Gecko 1.9의 일부분으로 계획되어 있습니다. 자바스크립트 1.8은 자바스크립트 1.7보다는 변경된 부분이 적습니다. 그러나, ECMAScript 4/JavaScript 2로 진행되는 과정의 몇몇 변경점이 있습니다. 이번 자바스크립트 1.8 릴리즈에는 자바스크립트 1.6자바스크립트 1.7에 있는 모든 부분이 포함될 것입니다.

+ +

자바스크립트 1.8가 개발되어지고 있는 상황은 {{ Bug(380236) }}을 참조하십시오.

+ +

자바스크립트 1.8의 사용

+ +

HTML에서 자바스크립트 1.8의 새로운 기능 몇 가지를 사용하려면 다음과 같이 사용하십시오.

+ +
 <script type="application/javascript;version=1.8"> ... your code ... </script>
+
+ +

자바스크립트 쉘, 자바스크립트 XPCOM 컴포넌트, 혹은 XUL의 <script> 엘리먼트를 사용할 때에는 자동적으로 가장 마지막의 자바스크립트 버전(모질라 1.9에서는 자바스크립트 1.8)이 사용되어 집니다({{ Bug(381031) }}, {{ Bug(385159) }}).

+ +

새로운 예약어 "yield"와 "let"를 사용하려면 버전을 1.8이나 그 이상으로 지정하여야 합니다. 왜냐하면 기존 코드에 변수나 함수의 이름으로 이런 키워드를 사용하고 있을 수 있기 때문입니다. (generator expressions처럼) 새로운 예약어로 소개되지 않는 것들은 자바스크립트 버전을 명시하지 않아도 사용할 수 있습니다.

+ +

closures 표현

+ +

추가된 closures 표현은 간단한 함수 작성을 쉽게 할 수 있는 것 뿐입니다. 문자 그대로인 Lambda notation과 유사한 어떤 것을 자바스크립트도 가능하도록 합니다.

+ +

자바스크립트 1.7과 그 이전 버전:

+ +
 function(x) { return x * x; }
+
+ +

자바스크립트 1.8:

+ +
 function(x) x * x
+
+ +

이런 문법은 괄호를 없애고 'return' 문을 쓰지 않아도 되도록 해줍니다. - 즉, 내용을 함축적으로 만들어 줍니다. 문법이 더 짧아진다는 것 외에 코드에 이 문법을 사용하여 얻을 수 있는 추가적인 이점은 없습니다.

+ +

예제:

+ +

이벤트 리스너 연결:

+ +
 document.addEventListener("click", function() false, true);
+
+ +

자바스크립트 1.6의 배열 함수의 some을 사용하면:

+ +
 elems.some(function(elem) elem.type == "text");
+
+ +

Generator expression

+ +

Generator expression은 (자바스크립트 1.7에서 소개된) generator를 간단하게 만들 수 있게 해줍니다. 문자 그대로 함수 내부에 yield를 포함한 사용자 함수를 생성할 수 있습니다. 그러나 동일한 generator 문법과 같은 것을 포함하고 있는 배열 역시 사용할 수 있습니다.

+ +

This addition allows you to simply create generators (which were introduced in JavaScript 1.7). Typically you would have to create a custom function which would have a yield in it, but this addition allows you to use array comprehension-like syntax to create an identical generator statement.

+ +

자바스크립트 1.7에서 오브젝트로부터 사용자 generator를 만드려면 다음과 같은 코드를 작성해야 했습니다:

+ +
 function add3(obj) {
+   for ( let i in obj )
+     yield i + 3;
+ }
+
+ let it = add3(someObj);
+ try {
+   while (true) {
+     document.write(it.next() + "<br>\n");
+   }
+ } catch (err if err instanceof StopIteration) {
+   document.write("End of record.<br>\n");
+ }
+
+ +

위의 코드 대신에 자바스크립트 1.8에서는 generator expression을 사용하여 순환문 안에 사용자 generator 함수를 생성하는 부분을 포함할 수 있습니다:

+ +
 let it = (i + 3 for (i in someObj));
+ try {
+   while (true) {
+     document.write(it.next() + "<br>\n");
+   }
+ } catch (err if err instanceof StopIteration) {
+   document.write("End of record.<br>\n");
+ }
+
+ +

generator 표현은 또한 값처럼 함수에 전달할 수 있습니다. generator 표현은 generator가 실행되지 않을 때부터 반드시 필요할 때까지 (배열이 맨 처음 생성되어지는 전형적인 상황과는 다르게) 특히 주목할만 합니다. 다른 예는 아래에서 볼 수 있습니다:

+ +

Generator expressions can also be passed in, as values, to a function. This is particularly noteworthy since generators aren't run until they are absolutely needed (unlike for typical array comprehension situations, where the arrays are constructed ahead of time). An example of the difference can be seen here:

+ +

자바스크립트 1.7 Array Comprehension 사용

+ +
 handleResults([ i for ( i in obj ) if ( i > 3 ) ]);
+
+ function handleResults( results ) {
+   for ( let i in results )
+     // ...
+ }
+
+ +

자바스크립트 1.8 Generator Expressions 사용

+ +
 handleResults( i for ( i in obj ) if ( i > 3 ) );
+
+ function handleResults( results ) {
+   for ( let i in results )
+     // ...
+ }
+
+ +

두 예제에서 generator expression을 사용함으로써 중요한 다른 점은 'obj' 하나에 대해서만 반복될 것이란 것과 전체에 대해서 반복될 것이라는 점입니다. 배열에 포함되었을 때 하나에 대해서만 반복될 것에 비해 generator expression은 전체에 대해 계속 반복됩니다.

+ +

The significant difference between the two examples being that by using the generator expressions, you would only have to loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it.

+ +

배열에 추가된 것들

+ +

자바스크립트 1.8에는 Array 객체에 배열 항목마다 반복 적용되는 두 가지 새로운 메소드가 포함되었습니다:

+ + + +

Changes in destructuring for..in

+ +

TBD: mention New_in_JavaScript_1.7#Looping_across_objects ({{ Bug(366941) }}).

+ +

곧 변경될 사항들

+ +

자바스크립트 1.8에 포함될 수 있을 것이라 기대되는 것들:

+ + diff --git a/files/ko/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html b/files/ko/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html new file mode 100644 index 0000000000..6662aee95b --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html @@ -0,0 +1,45 @@ +--- +title: ECMAScript 5 support in Mozilla +slug: Web/JavaScript/New_in_JavaScript/ECMAScript_5_support_in_Mozilla +tags: + - ECMAScript 5 + - JavaScript + - Versions +translation_of: Archive/Web/JavaScript/New_in_JavaScript/ECMAScript_5_support_in_Mozilla +--- +
{{jsSidebar("New_in_JS")}}
+ +

ECMAScript 5.1, 자바스크립트에 기반한, 더 오래된 표준이 2011년 6월에 허가되었습니다.

+ +

파이어폭스와 썬더버드를 포함하는 모질라 프로젝트들은 ECMAScript 5.1 의 기능들을 모두 지원합니다. 이 글은 모질라의 다양한 자바스크립트 런타임 버젼에 따라, 어떤 기능들이 지원되는지를 다룹니다.

+ +

지원 기능

+ +

자바스크립트 1.8.5에 추가(Gecko 2, Firefox 4 and later)

+ +

파이어폭스 4는 Object.* 와 Strict 모드를 포함한 ECMAScript 5의 모든 기능을 지원합니다. 자바스크립트 1.8.5의 새기능 보기.

+ +

자바스크립트 1.8.1에 추가 (Gecko 1.9.1, Firefox 3.5)

+ + + +

ECMAScript 5 는 특정한 상황에서 XTHML을 자바스크립트 코드로 판단하는 경우를 방지하는 파싱 알고리즘을 만들어냈습니다.

+ +

자바스크립트 1.6에 추가 (Gecko 1.8, Firefox 1.5)

+ +

새로운 배열 함수들은, 배열을 가공하기 위해 향상된 방법들을 제공합니다. -- 자바스크립트 1.6부터 자바스크립트의 일부였던 이 것은 이제 ECMAScript 5의 표준 기능으로 자리잡았습니다.

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html b/files/ko/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html new file mode 100644 index 0000000000..bafb603919 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/ecmascript_6_support_in_mozilla/index.html @@ -0,0 +1,285 @@ +--- +title: ECMAScript 2015 support in Mozilla +slug: Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla +tags: + - ECMAScript6 + - JavaScript +translation_of: Archive/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla +--- +
{{jsSidebar("New_in_JS")}}
+ +
+

ECMAScript 2015는 ECMAScript 언어의 6번째 표준 스펙(Spec)입니다. 파이어폭스와 모질라 애플리케이션에서 사용되는 SpiderMonkey 엔진의 표준 자바스크립트를 정의하고 있습니다.

+ +

"ES.next", "Harmony", or "ECMAScript 6" 등의 코드네임으로 불린 이 표준은 2011년 7월 12일에 "ES.next"라는 명칭으로 초안이 발표되었습니다. 2014년 8월 드디어 ECMAScript 2015 초안의 기능들이 확정되고 안정화와 버그 수정 작업에 들어갔습니다. 그리고 2015년 6월 17일, 드디어 ECMA-262 Edition 6은 ECMA 총회(General Assembly)의 공식 승인을 받아 배포되었습니다. 이 표준은 국제 산업 규격 ISO/IEC 16262:2016이기도 합니다.

+ +

PDF와   HTML 버전의 표준을 ecma-international.org 에서 무료로 다운로드 할 수 있습니다.

+
+ +

ECMAScript 표준에 대한 피드백 채널은 es-discuss을 이용하시면 됩니다.

+ +

표준 라이브러리

+ +

Array 객체 추가사항

+ + + +

새로운 MapSet 객체 그리고 WeakMap과 WeakSet 객체

+ + + +

새로운 Math 함수

+ + + +

Number 객체 추가사항

+ + + +

Object 객체 추가사항

+ + + + + +

Date 객체 추가사항

+ + + + + +

새로운 Promise 객체

+ + + + + +

새로운 Proxy 객체

+ + + + + +

새로운 Reflect 객체

+ + + + + + + +

RegExp 객체 추가사항

+ + + +

String 객체 추가사항

+ + + +

새로운 Symbol 객체

+ + + +

형식화된 배열

+ +

형식화된 배열은 ECMAScript 2015의 일부로 지정되었고, 더 이상 자신의 기존 명세서를 따르지 않습니다.

+ + + +

표현식과 연산자

+ + + +

문(문장)

+ + + +

함수

+ + + +

그 밖의 기능

+ + + +

같이 보기

+ + diff --git a/files/ko/web/javascript/new_in_javascript/index.html b/files/ko/web/javascript/new_in_javascript/index.html new file mode 100644 index 0000000000..0972eba4d0 --- /dev/null +++ b/files/ko/web/javascript/new_in_javascript/index.html @@ -0,0 +1,71 @@ +--- +title: New in JavaScript +slug: Web/JavaScript/New_in_JavaScript +tags: + - JavaScript + - Versions +translation_of: Archive/Web/JavaScript/New_in_JavaScript +--- +
{{jsSidebar("New_in_JS")}}
+ +

이 장은 JavaScript 버전 이력에 관한 정보 및 Mozilla/SpiderMonkey 기반 JavaScript 애플리케이션, 가령 Firefox의 구현 상태를 포함합니다.

+ +

ECMAScript 버전

+ +
+
언어 리소스
+
JavaScript 언어의 기반이 된 ECMAScript 표준에 대해 자세히 알아보세요.
+
ECMAScript 5 지원
+
Mozilla 기반 엔진 및 제품에서 현재 표준 ECMA-262 Edition 5.1의 구현 상태.
+
ECMAScript 6 지원
+
Mozilla 기반 엔진 및 제품에서 초안 ECMA-262 Edition 6 (ES2015/ES6)의 구현 상태.
+
ECMAScript Next 지원
+
Mozilla 기반 엔진 및 제품에서 연간 (ES2016/ES2017/ES2018/...) 출시 계획에 따라 예정된 ECMA-262 기능의 구현 상태.
+
+ +

JavaScript 출시 기록

+ +
+
Firefox JavaScript changelog
+
Firefox 5 이상에서 구현된 JavaScript 기능은 이 changelog 참조.
+
+ +

JavaScript 버전

+ +

사라짐 ({{deprecated_inline}}). 명백한 버전 관리 및 언어 기능의 채택은 Mozilla 전용이었고 제거되는 과정에 있습니다. Firefox 4는 JavaScript 버전 (1.8.5)에 참조되었던 마지막 버전이었습니다. 새로운 ECMA 표준이 있다면, JavaScript 언어 기능은 이제 종종 ECMA-262 Edition 가령 Edition 6 (ES2015/ES6) 내 그들의 초기 정의에 언급됩니다.

+ +

JavaScript는 Netscape Navigator 2.0 및 Internet Explorer 2.0에서 March 1996에 버전 1.0으로 출시되었습니다.

+ +
+
JavaScript 1.1
+
Netscape Navigator 3.0에 실린 버전. August 19, 1996에 출시됨.
+
JavaScript 1.2
+
Netscape Navigator 4.0-4.05에 실린 버전. June 11, 1997에 출시됨.
+
JavaScript 1.3
+
Netscape Navigator 4.06-4.7x에 실린 버전. October 19, 1998에 출시됨.
+ ECMA-262 1st 및 2nd Edition을 따르는 표준화 작업.
+
JavaScript 1.4
+
Netscape의 서버측 JavaScript에 실린 버전. 1999에 출시됨.
+
JavaScript 1.5
+
Netscape Navigator 6.0 및 Firefox 1.0에 실린 버전. November 14, 2000에 출시됨.
+ ECMA-262 3rd Edition을 따르는 표준화 작업.
+
JavaScript 1.6
+
Firefox 1.5에 실린 버전. November 2005에 출시됨.
+ ECMAScript for XML (E4X), 새로운 Array 메서드 더하기 StringArray generics 포함.
+
JavaScript 1.7
+
Firefox 2에 실린 버전. October 2006에 출시됨.
+ 생성기, 반복기, 배열 내포(comprehension), let 식 및 해체 할당 포함.
+
JavaScript 1.8
+
Firefox 3에 실린 버전. June 2008에 출시됨.
+ 식 클로저, 생성기 식 및 Array.reduce() 포함
+
JavaScript 1.8.1
+
Firefox 3.5에 실린 버전. June 30, 2009에 출시됨.
+ TraceMonkey JIT 포함 및 native JSON 지원.
+
JavaScript 1.8.2
+
Firefox 3.6에 실린 버전. June 22, 2009에 출시됨.
+ minor changes만 포함.
+
JavaScript 1.8.5
+
Firefox 4에 실린 버전. July 27, 2010에 출시됨.
+ ECMA-262 Edition 5를 따르는 많은 새 기능 포함.
+ 이게 마지막 JavaScript 버전입니다.
+
diff --git a/files/ko/web/javascript/reference/about/index.html b/files/ko/web/javascript/reference/about/index.html new file mode 100644 index 0000000000..f558451826 --- /dev/null +++ b/files/ko/web/javascript/reference/about/index.html @@ -0,0 +1,51 @@ +--- +title: 소개 +slug: Web/JavaScript/Reference/About +translation_of: Web/JavaScript/Reference/About +--- +

{{JsSidebar}}
+ The JavaScript reference serves as a repository of facts about the JavaScript language. The entire language is described here in detail. As you write JavaScript code, you'll refer to these pages often (thus the title "JavaScript reference"). If you're learning JavaScript, or need help understanding some of its capabilities or features, check out the JavaScript guide.

+ +

The JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment.

+ +

Where to find JavaScript information

+ +

JavaScript documentation of core language features (pure ECMAScript, for the most part) includes the following:

+ + + +

If you are new to JavaScript, start with the guide. Once you have a firm grasp of the fundamentals, you can use the reference to get more details on individual objects and language constructs.

+ +

Structure of the reference

+ +

In the JavaScript reference you can find the following chapters:

+ +
+
Standard built-in objects
+
This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.
+
Statements and declarations
+
JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.
+
Expressions and operators
+
This chapter documents all the JavaScript language operators, expressions and keywords.
+
Functions
+
Chapter about JavaScript functions.
+
Classes
+
Chapter about JavaScript classes introduced in ECMAScript 2015.
+
Errors
+
Chapter about specific errors, exceptions and warnings thrown by JavaScript.
+
New in JavaScript
+
Chapter about JavaScript version history.
+
+ +

More reference pages

+ + + +

 

diff --git a/files/ko/web/javascript/reference/classes/class_fields/index.html b/files/ko/web/javascript/reference/classes/class_fields/index.html new file mode 100644 index 0000000000..959c65fada --- /dev/null +++ b/files/ko/web/javascript/reference/classes/class_fields/index.html @@ -0,0 +1,396 @@ +--- +title: Class fields +slug: Web/JavaScript/Reference/Classes/Class_fields +translation_of: Web/JavaScript/Reference/Classes/Public_class_fields +--- +
{{JsSidebar("Classes")}}
+ +
+

This page describes experimental features.

+ +

Both Public and private field declarations are an experimental feature (stage 3) proposed at TC39, the JavaScript standards committee.

+ +

Support in browsers is limited, but the feature can be used through a build step with systems like Babel. See the compat information below.

+
+ +

Public fields

+ +

static fields와 instance의 public fields 는 둘 다 writable, enumerable, configurable 한 프로퍼티들이다. 예를들면, 정 반대인 private 과는 다르게, unlike their private counterparts, static fields는 프로토타입 상속에 관여한다.

+ +

Public static fields

+ +

Public static fields 는 클래스에서 생성하는 모든 인스턴스에 대한 필드가 아닌, 클래스마다 단 한개의 필드가 존재하기를 원할 때 유용하게 사용할 수 있다. Public fields는 캐시, 고정된 설정값, 또는 인스턴스 간 복제할 필요가 없는 어떤 데이터 등에 유용하게 쓰일 수 있다.

+ +

Public static fields are declared using the static keyword. They are added to the class constructor at the time of class evaluation using {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}}. They are accessed again from the class constructor.

+ +
class ClassWithStaticField {
+  static staticField = 'static field'
+}
+
+console.log(ClassWithStaticField.staticField)
+// expected output: "static field"​
+
+ +

Fields without initializers are initialized to undefined.

+ +
class ClassWithStaticField {
+  static staticField
+}
+
+console.assert(ClassWithStaticField.hasOwnProperty('staticField'))
+console.log(ClassWithStaticField.staticField)
+// expected output: "undefined"
+ +

Public static fields are not reinitialized on subclasses, but can be accessed via the prototype chain.

+ +
class ClassWithStaticField {
+  static baseStaticField = 'base field'
+}
+
+class SubClassWithStaticField extends ClassWithStaticField {
+  static subStaticField = 'sub class field'
+}
+
+console.log(SubClassWithStaticField.subStaticField)
+// expected output: "sub class field"
+
+console.log(SubClassWithStaticField.baseStaticField)
+// expected output: "base field"
+ +

When initializing fields, this refers to the class constructor. You can also reference it by name, and use super to get the superclass constructor (if one exists).

+ +
class ClassWithStaticField {
+  static baseStaticField = 'base static field'
+  static anotherBaseStaticField = this.baseStaticField
+
+  static baseStaticMethod() { return 'base static method output' }
+}
+
+class SubClassWithStaticField extends ClassWithStaticField {
+  static subStaticField = super.baseStaticMethod()
+}
+
+console.log(ClassWithStaticField.anotherBaseStaticField)
+// expected output: "base static field"
+
+console.log(SubClassWithStaticField.subStaticField)
+// expected output: "base static method output"
+
+ +

Public instance fields

+ +

Public instance fields exist on every created instance of a class. By declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting.

+ +

Public instance fields are added with {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} either at construction time in the base class (before the constructor body runs), or just after super() returns in a subclass.

+ +
class ClassWithInstanceField {
+  instanceField = 'instance field'
+}
+
+const instance = new ClassWithInstanceField()
+console.log(instance.instanceField)
+// expected output: "instance field"
+ +

Fields without initializers are initialized to undefined.

+ +
class ClassWithInstanceField {
+  instanceField
+}
+
+const instance = new ClassWithInstanceField()
+console.assert(instance.hasOwnProperty('instanceField'))
+console.log(instance.instanceField)
+// expected output: "undefined"
+ +

Like properties, field names may be computed.

+ +
const PREFIX = 'prefix'
+
+class ClassWithComputedFieldName {
+    [`${PREFIX}Field`] = 'prefixed field'
+}
+
+const instance = new ClassWithComputedFieldName()
+console.log(instance.prefixField)
+// expected output: "prefixed field"
+ +

When initializing fields this refers to the class instance under construction. Just as in public instance methods, if you're in a subclass you can access the superclass prototype using super.

+ +
class ClassWithInstanceField {
+  baseInstanceField = 'base field'
+  anotherBaseInstanceField = this.baseInstanceField
+  baseInstanceMethod() { return 'base method output' }
+}
+
+class SubClassWithInstanceField extends ClassWithInstanceField {
+  subInstanceField = super.baseInstanceMethod()
+}
+
+const base = new ClassWithInstanceField()
+const sub = new SubClassWithInstanceField()
+
+console.log(base.anotherBaseInstanceField)
+// expected output: "base field"
+
+console.log(sub.subInstanceField)
+// expected output: "base method output"
+ +

Public methods

+ +

Public static methods

+ +

The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.

+ +

{{EmbedInteractiveExample("pages/js/classes-static.html")}}

+ + + +

The static methods are added to the class constructor with {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} at class evaluation time. These methods are writable, non-enumerable, and configurable.

+ +

Public instance methods

+ +

As the name implies, public instance methods are methods available on class instances.

+ +
class ClassWithPublicInstanceMethod {
+  publicMethod() {
+    return 'hello world'
+  }
+}
+
+const instance = new ClassWithPublicInstanceMethod()
+console.log(instance.publicMethod())
+// expected output: "hello worl​d"
+ +

Public instance methods are added to the class prototype at the time of class evaluation using {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}}. They are writable, non-enumerable, and configurable.

+ +

You may make use of generator, async, and async generator functions.

+ +
class ClassWithFancyMethods {
+  *generatorMethod() { }
+  async asyncMethod() { }
+  async *asyncGeneratorMethod() { }
+}
+ +

Inside instance methods, this refers to the instance itself. In subclasses, super lets you access the superclass prototype, allowing you to call methods from the superclass.

+ +
class BaseClass {
+  msg = 'hello world'
+  basePublicMethod() {
+    return this.msg
+  }
+}
+
+class SubClass extends BaseClass {
+  subPublicMethod() {
+    return super.basePublicMethod()
+  }
+}
+
+const instance = new SubClass()
+console.log(instance.subPublicMethod())
+// expected output: "hello worl​d"
+
+ +

Getters and setters are special methods that bind to a class property and are called when that property is accessed or set. Use the get and set syntax to declare a public instance getter or setter.

+ +
class ClassWithGetSet {
+  #msg = 'hello world'
+  get msg() {
+    return this.#msg
+  }
+  set msg(x) {
+    this.#msg = `hello ${x}`
+  }
+}
+
+const instance = new ClassWithGetSet()
+console.log(instance.msg)
+// expected output: "hello worl​d"
+
+instance.msg = 'cake'
+console.log(instance.msg)
+// expected output: "hello cake"
+
+ +

Private fields

+ +

Private static fields 

+ +

Private fields are accessible on the class constructor from inside the class declaration itself.

+ +

The limitation of static variables being called by only static methods still holds. 

+ +
class ClassWithPrivateStaticField {
+  static #PRIVATE_STATIC_FIELD
+
+  static publicStaticMethod() {
+    ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD = 42
+    return ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD
+  }
+}
+
+assert(ClassWithPrivateStaticField.publicStaticMethod() === 42)
+ +

Private static fields are added to the class constructor at class evaluation time.

+ +

There is a provenance restriction on private static fields. Only the class which defines the private static field can access the field.

+ +

This can lead to unexpected behaviour when using this.

+ +
class BaseClassWithPrivateStaticField {
+  static #PRIVATE_STATIC_FIELD
+
+  static basePublicStaticMethod() {
+    this.#PRIVATE_STATIC_FIELD = 42
+    return this.#PRIVATE_STATIC_FIELD
+  }
+}
+
+class SubClass extends BaseClassWithPrivateStaticField { }
+
+assertThrows(() => SubClass.basePublicStaticMethod(), TypeError)
+
+ +

Private instance fields

+ +

Private instance fields are declared with # names (pronounced "hash names"), which are identifiers prefixed with #. The # is a part of the name itself. It is used for declaration and accessing as well.

+ +

The encapsulation is enforced by the language. It is a syntax error to refer to # names from out of scope.

+ +
class ClassWithPrivateField {
+  #privateField
+
+  constructor() {
+    this.#privateField = 42
+    this.#randomField = 666 // Syntax error
+  }
+}
+
+const instance = new ClassWithPrivateField()
+instance.#privateField === 42 // Syntax error
+
+ +

Private Methods

+ +

Private static methods

+ +

Like their public equivalent, private static methods are called on the class itself, not instances of the class. Like private static fields, they are only accessible from inside the class declaration.

+ +

Private static methods may be generator, async, and async generator functions.

+ +
class ClassWithPrivateStaticMethod {
+    static #privateStaticMethod() {
+        return 42
+    }
+
+    static publicStaticMethod1() {
+        return ClassWithPrivateStaticMethod.#privateStaticMethod();
+    }
+
+    static publicStaticMethod2() {
+        return this.#privateStaticMethod();
+    }
+}
+
+assert(ClassWithPrivateStaticField.publicStaticMethod1() === 42);
+assert(ClassWithPrivateStaticField.publicStaticMethod2() === 42);
+
+ +

This can lead to unexpected behaviour when using this(because this binding rule applies).

+ +
class Base {
+    static #privateStaticMethod() {
+        return 42;
+    }
+    static publicStaticMethod1() {
+        return Base.#privateStaticMethod();
+    }
+    static publicStaticMethod2() {
+        return this.#privateStaticMethod();
+    }
+}
+
+class Derived extends Base {}
+
+console.log(Derived.publicStaticMethod1()); // 42
+console.log(Derived.publicStaticMethod2()); // TypeError
+
+ +

Private instance methods

+ +

Private instance methods are methods available on class instances whose access is restricted in the same manner as private instance fields.

+ +
class ClassWithPrivateMethod {
+  #privateMethod() {
+    return 'hello world'
+  }
+
+  getPrivateMessage() {
+      return this.#privateMethod()
+  }
+}
+
+const instance = new ClassWithPrivateMethod()
+console.log(instance.getPrivateMessage())
+// expected output: "hello worl​d"
+ +

Private instance methods may be generator, async, or async generator functions. Private getters and setters are also possible:

+ +
class ClassWithPrivateAccessor {
+  #message
+
+  get #decoratedMessage() {
+    return `✨${this.#message}✨`
+  }
+  set #decoratedMessage(msg) {
+    this.#message = msg
+  }
+
+  constructor() {
+    this.#decoratedMessage = 'hello world'
+    console.log(this.#decoratedMessage)
+  }
+}
+
+new ClassWithPrivateAccessor();
+// expected output: "✨hello worl​d✨"
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
FieldDefinition productionStage 3
+ +

Browser compatibility

+ +

Public class fields

+ + + +

{{Compat("javascript.classes.public_class_fields")}}

+ +

Private class fields

+ + + +

{{Compat("javascript.classes.private_class_fields")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/classes/constructor/index.html b/files/ko/web/javascript/reference/classes/constructor/index.html new file mode 100644 index 0000000000..f07dbd43b9 --- /dev/null +++ b/files/ko/web/javascript/reference/classes/constructor/index.html @@ -0,0 +1,128 @@ +--- +title: constructor +slug: Web/JavaScript/Reference/Classes/constructor +tags: + - Classes + - ECMAScript 2015 + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +
{{jsSidebar("Classes")}}
+ +

constructor 메서드는 {{jsxref("Statements/class", "class")}} 내에서 객체를 생성하고 초기화하기 위한 특별한 메서드입니다.

+ +
{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}
+ + + +

구문

+ +
constructor([arguments]) { ... }
+
+ +

설명

+ +

클래스는 constructor라는 이름을 가진 특별한 메서드를 하나씩만 가질 수 있습니다. 두 개 이상의 constructor 메서드는 {{jsxref("SyntaxError")}}를 유발합니다.

+ +

생성자 메서드는 {{jsxref("Operators/super", "super")}} 키워드를 사용하여 상위 클래스의 생성자 메서드를 호출할 수 있습니다.

+ +

생성자 메서드를 지정하지 않은 경우엔 기본 생성자 메서드를 사용합니다.

+ +

예제

+ +

constructor 메서드 사용하기

+ +
class Square extends Polygon {
+  constructor(length) {
+    // length로 다각형의 넓이와 높이를 정의하기 위해 부모클래스의 생성자를 호출합니다.
+    super(length, length);
+    // Note: 파생 클래스에서, 'this'를 사용하기 전에는 반드시 super()를
+    // 호출하여야 합니다. 그렇지 않을 경우 참조에러가 발생합니다.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.area = value;
+  }
+}
+ +

다른예제

+ +
class Polygon {
+    constructor() {
+        this.name = "Polygon";
+    }
+}
+
+class Square extends Polygon {
+    constructor() {
+        super();
+    }
+}
+
+class Rectangle {}
+
+Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
+
+console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false
+console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true
+
+let newInstance = new Square();
+console.log(newInstance.name); //Polygon
+ +

여기서 Square 클래스의 프로토 타입이 변경되었지만 사각형의 새 인스턴스가 만들어 질 때 이전 기본 클래스 인 Polygon의 생성자가 호출됩니다.

+ +

기본 생성자

+ +

만약 생성자를 지정하지 않을 경우 기본 생성자 메서드를 사용합니다. 기본 클래스(즉, 아무것도 상속하지 않는 클래스)의 기본 생성자 메서드는 다음과 같습니다.

+ +
constructor() {}
+
+ +

파생 클래스의 경우, 기본 생성자는 다음과 같습니다.

+ +
constructor(...args) {
+  super(...args);
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.classes.constructor")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/classes/extends/index.html b/files/ko/web/javascript/reference/classes/extends/index.html new file mode 100644 index 0000000000..e1ae2eac31 --- /dev/null +++ b/files/ko/web/javascript/reference/classes/extends/index.html @@ -0,0 +1,112 @@ +--- +title: extends +slug: Web/JavaScript/Reference/Classes/extends +tags: + - Classes + - ECMAScript6 + - JavaScript +translation_of: Web/JavaScript/Reference/Classes/extends +--- +
{{jsSidebar("Classes")}}
+ +

extends 키워드는 클래스를 다른 클래스의 자식으로 만들기 위해 class 선언 또는 class 식에 사용됩니다.

+ +

{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}

+ + + +

구문

+ +
class ChildClass extends ParentClass { ... }
+ +

설명

+ +

extends 키워드는 내장 객체뿐만 아니라 사용자 정의 클래스를 하위 클래스로 만들기 위해 사용될 수 있습니다.

+ +

확장( 클래스)의 .prototype은 {{jsxref("Object")}} 또는 {{jsxref("null")}}이어야 합니다.

+ +

+ +

extends 사용하기

+ +

첫 번째 예는 Polygon 클래스로부터 Square 클래스를 만듭니다. 이 예는 live demo (source)에서 발췌했습니다.

+ +
class Square extends Polygon {
+  constructor(length) {
+    // 여기서, length와 함께 부모 클래스의 생성자를 호출
+    // Polygon의 너비 및 높이가 제공됨
+    super(length, length);
+    // 주의: 파생 클래스에서, super()가 먼저 호출되어야 'this'를
+    // 사용할 수 있습니다. 이를 빼먹으면 참조 오류가 발생합니다.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.area = value;
+  }
+}
+ +

내장 객체에 extends 사용하기

+ +

이 예제는 내장 객체 {{jsxref("Date")}}를 확장합니다. 이 예제는 live demo (source)에서 발췌했습니다.

+ +
class myDate extends Date {
+  constructor() {
+    super();
+  }
+
+  getFormattedDate() {
+    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
+    return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
+  }
+}
+ +

null 확장

+ +

{{jsxref("null")}}에서 확장은 prototype 객체가 {{jsxref("Object.prototype")}}으로부터 상속받지 않은 것을 제외하면 보통 클래스처럼 동작합니다.

+ +
class nullExtends extends null {
+  constructor() {}
+}
+
+Object.getPrototypeOf(nullExtends); // Function.prototype
+Object.getPrototypeOf(nullExtends.prototype) // null
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES2015', '#sec-class-definitions', 'extends')}}{{Spec2('ES2015')}}초기 정의.
{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.classes.extends")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/classes/index.html b/files/ko/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..59f72f7652 --- /dev/null +++ b/files/ko/web/javascript/reference/classes/index.html @@ -0,0 +1,402 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +translation_of: Web/JavaScript/Reference/Classes +--- +
{{JsSidebar("Classes")}}
+ +

Class는 객체를 생성하기 위한 템플릿입니다. 클래스는 데이터와 이를 조작하는 코드를 하나로 추상화합니다. 자바스크립트에서 클래스는 프로토타입을 이용해서 만들어졌지만 ES5의 클래스 의미와는 다른 문법과 의미를 가집니다.

+ +

Class 정의

+ +

Class는 사실 "특별한 {{jsxref("Functions", "함수", "", "true")}}"입니다. 함수를 {{jsxref("Operators/function", "함수 표현식", "", "true")}}과 {{jsxref("Statements/function", "함수 선언", "", "true")}}으로 정의할 수 있듯이 class 문법도 {{jsxref("Operators/class", "class 표현식", "", "true")}} and {{jsxref("Statements/class", "class 선언", "", "true")}} 두 가지 방법을 제공합니다.

+ +

Class 선언

+ +

Class를 정의하는 한 가지 방법은 class 선언을 이용하는 것입니다. class를 선언하기 위해서는 클래스의 이름(여기서 "Rectangle")과 함께 class 키워드를 사용해야 합니다.

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

Hoisting

+ +

함수 선언과 클래스 선언의 중요한 차이점은 함수 선언의 경우 {{Glossary("Hoisting", "호이스팅")}}이 일어나지만, 클래스 선언은 그렇지 않다는 것입니다. 클래스를 사용하기 위해서는 클래스를 먼저 선언 해야 합니다. 그렇지 않으면, 다음 코드는 {{jsxref("ReferenceError")}}를 던질 것입니다. :

+ +
const p = new Rectangle(); // ReferenceError
+
+class Rectangle {}
+
+ +

Class 표현식

+ +

Class 표현식은 class를 정의하는 또 다른 방법입니다. Class 표현식은 이름을 가질 수도 있고, 갖지 않을 수도 있습니다. 이름을 가진 class 표현식의 이름은 클래스 body의 local scope에 한해 유효합니다. (하지만, 클래스의 (인스턴스 이름이 아닌) {{jsxref("Function.name", "name")}} 속성을 통해 찾을 수 있습니다).

+ +
// unnamed
+let Rectangle = class {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+console.log(Rectangle.name);
+// 출력: "Rectangle"
+
+// named
+let Rectangle = class Rectangle2 {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+console.log(Rectangle.name);
+// 출력: "Rectangle2"
+
+ +
+

참고: 클래스 표현식에는 {{anch ( "Class 선언")}} 섹션에 설명된 것과 동일한 호이스팅 제한이 적용됩니다.

+
+ +

Class body 와 메서드 정의

+ +

Class body는 중괄호 {} 로 묶여 있는 안쪽 부분입니다. 이곳은 여러분이 메서드나 constructor와 같은 class 멤버를 정의할 곳입니다.

+ +

Strict mode

+ +

클래스의 본문(body)은 {{jsxref("Strict_mode", "strict mode", "", "true")}}에서 실행됩니다. 즉, 여기에 적힌 코드는 성능 향상을 위해 더 엄격한 문법이 적용됩니다. 그렇지 않으면, 조용히 오류가 발생할 수 있습니다. 특정 키워드는 미래의 ECMAScript 버전용으로 예약됩니다.

+ +

Constructor (생성자)

+ +

{{jsxref("Classes/constructor", "constructor", "", "true")}} 메서드는 class 로 생성된 객체를 생성하고 초기화하기 위한 특수한 메서드입니다.  "constructor" 라는 이름을 가진 특수한 메서드는 클래스 안에 한 개만 존재할 수 있습니다. 만약 클래스에 여러 개의 constructor 메서드가 존재하면 {{jsxref("SyntaxError")}} 가 발생할 것입니다.

+ +

constructor는 부모 클래스의 constructor를 호출하기 위해 super 키워드를 사용할 수 있습니다.

+ +

프로토타입 메서드

+ +

{{jsxref("Functions/Method_definitions", "메서드 정의", "", "true")}}도 참조해보세요.

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+  // Getter
+  get area() {
+    return this.calcArea();
+  }
+  // 메서드
+  calcArea() {
+    return this.height * this.width;
+  }
+}
+
+const square = new Rectangle(10, 10);
+
+console.log(square.area); // 100
+ +

정적 메서드와 속성

+ +

{{jsxref("Classes/static", "static", "", "true")}} 키워드는 클래스를 위한 정적(static) 메서드를 정의합니다. 정적 메서드는 클래스의 인스턴스화(instantiating) 없이 호출되며, 클래스의 인스턴스에서는 호출할 수 없습니다. 정적 메서드는 어플리케이션(application)을 위한 유틸리티(utility) 함수를 생성하는 데 주로 사용됩니다. 반면, 정적 속성은 캐시, 고정 환경설정 또는 인스턴스 간에 복제할 필요가 없는 기타 데이터에 유용합니다.

+ +
class Point {
+  constructor(x, y) {
+    this.x = x;
+    this.y = y;
+  }
+
+  static displayName = "Point";
+  static distance(a, b) {
+    const dx = a.x - b.x;
+    const dy = a.y - b.y;
+
+    return Math.hypot(dx, dy);
+  }
+}
+
+const p1 = new Point(5, 5);
+const p2 = new Point(10, 10);
+p1.displayName; // undefined
+p1.distance;    // undefined
+p2.displayName; // undefined
+p2.distance;    // undefined
+
+console.log(Point.displayName);      // "Point"
+console.log(Point.distance(p1, p2)); // 7.0710678118654755
+ +

프로토타입 및 정적 메서드를 사용한 this 바인딩

+ +

메서드를 변수에 할당 한 다음 호출하는 것과 같이, 정적 메서드나 프로토타입 메서드가 {{jsxref("Operators/this", "this")}} 값 없이 호출될 때, this 값은 메서드 안에서 undefined가 됩니다. 이 동작은 {{jsxref("Strict_mode", "\"use strict\"")}} 명령어 없이도 같은 방식으로 동작하는데, class 문법 안에 있는 코드는 항상 strict mode 로 실행되기 때문입니다.

+ +
class Animal {
+  speak() {
+    return this;
+  }
+  static eat() {
+    return this;
+  }
+}
+
+let obj = new Animal();
+obj.speak(); // the Animal object
+let speak = obj.speak;
+speak(); // undefined
+
+Animal.eat() // class Animal
+let eat = Animal.eat;
+eat(); // undefined
+ +

위에 작성된 코드를 전통적 방식의 함수기반의 non–strict mode 구문으로 재작성하면, this 메서드 호출은 기본적으로 {{Glossary("Global_object", "전역 객체")}}인 초기 this 값에 자동으로 바인딩 됩니다. Strict mode에서는 자동 바인딩이 발생하지 않습니다; this 값은 전달된 대로 유지됩니다.

+ +
function Animal() { }
+
+Animal.prototype.speak = function() {
+  return this;
+}
+
+Animal.eat = function() {
+  return this;
+}
+
+let obj = new Animal();
+let speak = obj.speak;
+speak(); // global object (in non–strict mode)
+
+let eat = Animal.eat;
+eat(); // global object (in non-strict mode)
+ +

인스턴스 속성

+ +

인스턴스 속성은 반드시 클래스 메서드 내에 정의되어야 합니다:

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

정적 (클래스사이드) 속성과 프로토타입 데이터 속성은 반드시 클래스 선언부 바깥쪽에서 정의되어야 합니다. 

+ +
Rectangle.staticWidth = 20;
+Rectangle.prototype.prototypeWidth = 25;
+
+ +

Field 선언

+ +
+

public과  private 필드 선언은 자바스크립트 표준화 위원회에 실험적 기능 (stage 3)  TC39 로 제안되어있습니다.  현재 이를 지원하는 브라우져는 제한적인 상태입니다만, Babel 과 같은 build 시스템을 사용한다면 이 기능을 사용해볼 수 있습니다.

+
+ +

Public 필드 선언

+ +

자바스크립트의 필드 선언 문법을 사용해서 위의 예제는 아래와 같이 다시 쓰여질 수 있습니다.

+ +
class Rectangle {
+  height = 0;
+  width;
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

필드를 먼저 선언함으로서 클래스 정의는 self-documenting에 가까워졌고 필드는 언제나 존재하는 상태가 됩니다.

+ +

위의 예에서 봤듯이 필드 선언은 기본 값과 같이 선언될 수도 있습니다.

+ +

자세한 내용은 {{jsxref("Classes/Public_class_fields", "public class fields", "", "true")}}를 참조하세요.

+ +

Private 필드 선언

+ +

private 필드를 사용하면 아래와 같이 예제를 개선할 수 있습니다.

+ +
class Rectangle {
+  #height = 0;
+  #width;
+  constructor(height, width) {
+    this.#height = height;
+    this.#width = width;
+  }
+}
+ +

클래스의 바깥에서 private 필드를 접근하려고 하면 에러가 발생합니다. private필드는 클래스 내부에서만 읽고 쓰기가 가능합니다. 클래스 외부에서 보이지 않도록 정의하였으므로 클래스가 버젼업 되면서 내부 구현이 바뀌더라도 클래스 사용자 입장에서는 이에 아무런 영항을 받지 않도록 할 수 있습니다.

+ +
+

Private 필드는 사용전에 선언되어야 합니다.

+
+ +

일반적인 프로퍼티와는 다르게 private 필드는 값을 할당하면서 만들어질 수 없습니다.

+ +

자세한 내용은 {{jsxref("Classes/Private_class_fields", "private class fields", "", "true")}}를 참조하세요.

+ +

extends를 통한 클래스 상속(sub classing)

+ +

{{jsxref("Classes/extends", "extends")}} 키워드는 클래스 선언이나 클래스 표현식에서 다른 클래스의 자식 클래스를 생성하기 위해 사용됩니다.

+ +
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(`${this.name} makes a noise.`);
+  }
+}
+
+class Dog extends Animal {
+  constructor(name) {
+    super(name); // super class 생성자를 호출하여 name 매개변수 전달
+  }
+
+  speak() {
+    console.log(`${this.name} barks.`);
+  }
+}
+
+let d = new Dog('Mitzie');
+d.speak(); // Mitzie barks.
+ +

subclass에 constructor가 있다면, "this"를 사용하기 전에 가장 먼저 super()를 호출해야 합니다.

+ +

또한 es5에서 사용되던 전통적인 함수 기반의 클래스를 통하여 확장할 수도 있습니다.

+ +
function Animal (name) {
+  this.name = name;
+}
+
+Animal.prototype.speak = function () {
+  console.log(`${this.name} makes a noise.`);
+}
+
+class Dog extends Animal {
+  speak() {
+    console.log(`${this.name} barks.`);
+  }
+}
+
+let d = new Dog('Mitzie');
+d.speak(); // Mitzie barks.
+
+// 유사한 메서드의 경우, 자식의 메서드가 부모의 메서드보다 우선합니다
+ +

클래스는 생성자가 없는 객체(non-constructible)을 확장할 수 없습니다. 만약 기존의 생성자가 없는 객체을 확장하고 싶다면, 이 메서드를 사용하세요. {{jsxref("Object.setPrototypeOf()")}}:

+ +
const Animal = {
+  speak() {
+    console.log(`${this.name} makes a noise.`);
+  }
+};
+
+class Dog {
+  constructor(name) {
+    this.name = name;
+  }
+}
+
+// 이 작업을 수행하지 않으면 speak를 호출할 때 TypeError가 발생합니다
+Object.setPrototypeOf(Dog.prototype, Animal);
+
+let d = new Dog('Mitzie');
+d.speak(); // Mitzie makes a noise.
+ +

Species

+ +

배열을 상속 받은 MyArray 클래스에서 {{jsxref("Array")}} Object를 반환하고 싶을 수도 있을 것입니다. 그럴때 Species 패턴은 기본 생성자를 덮어쓰도록 해줍니다.

+ +

예를 들어, {{jsxref("Array.map", "map()")}}과 같은 기본 생성자를 반환하는 메서드를 사용할 때 이 메서드가 MyArray 객체 대신 Array 객체가 반환하도록 하고 싶을 것입니다. {{jsxref("Symbol.species")}} 심볼은 이러한 것을 가능하게 해줍니다:

+ +
class MyArray extends Array {
+  // 부모 Array 생성자로 species 덮어쓰기
+  static get [Symbol.species]() { return Array; }
+}
+var a = new MyArray(1,2,3);
+var mapped = a.map(x => x * x);
+
+console.log(mapped instanceof MyArray); // false
+console.log(mapped instanceof Array);   // true
+ +

super 를 통한 상위 클래스 호출

+ +

{{jsxref("Operators/super", "super")}} 키워드는 객체의 부모가 가지고 있는 메서드를 호출하기 위해 사용됩니다. 이는 프로토타입 기반 상속보다 좋은 점 중 하나입니다.

+ +
class Cat {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(`${this.name} makes a noise.`);
+  }
+}
+
+class Lion extends Cat {
+  speak() {
+    super.speak();
+    console.log(`${this.name} roars.`);
+  }
+}
+
+let l = new Lion('Fuzzy');
+l.speak();
+// Fuzzy makes a noise.
+// Fuzzy roars.
+ +

Mix-ins

+ +

추상 서브 클래스 또는 믹스-인은 클래스를 위한 템플릿입니다. ECMAScript 클래스는 하나의 단일 슈퍼클래스만을 가질 수 있으며, 예를 들어 툴링 클래스로부터의 다중 상속은 불가능합니다. 기능은 반드시 슈퍼클래스에서 제공되어야 합니다.

+ +

슈퍼클래스를 인자로 받고 이 슈퍼클래스를 확장하는 서브클래스를 생성하여 반환하는 함수를 사용하여 ECMAScript에서 믹스-인을 구현할 수 있습니다:

+ +
var calculatorMixin = Base => class extends Base {
+  calc() { }
+};
+
+var randomizerMixin = Base => class extends Base {
+  randomize() { }
+};
+ +

위 믹스-인을 사용하는 클래스는 다음과 같이 작성할 수 있습니다:

+ +
class Foo { }
+class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
+ +

클래스 재정의

+ +

클래스는 재정의될 수 없습니다. 재정의를 시도하면 SyntaxError 가 발생합니다.

+ +

이를 실험해보고 싶으면 FireFox Web Console (Tools > Web Developer > Web Console) 에서 같은 이름으로 클래스를 두번 정의하려고 해보세요. 다음과 같은 오류를 보게 될 겁니다. SyntaxError: redeclaration of let ClassName;. (See further discussion of this issue in {{Bug(1428672)}}.) Doing something similar in Chrome Developer Tools gives you a message like Uncaught SyntaxError: Identifier 'ClassName' has already been declared at <anonymous>:1:1.

+ +

명세서

+ + + + + + + + + + +
명세서
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.classes")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/classes/private_class_fields/index.html b/files/ko/web/javascript/reference/classes/private_class_fields/index.html new file mode 100644 index 0000000000..ea5508ab27 --- /dev/null +++ b/files/ko/web/javascript/reference/classes/private_class_fields/index.html @@ -0,0 +1,201 @@ +--- +title: Private class fields +slug: Web/JavaScript/Reference/Classes/Private_class_fields +tags: + - Class + - JavaScript + - Private Field +translation_of: Web/JavaScript/Reference/Classes/Private_class_fields +--- +
{{JsSidebar("Classes")}}
+ +

class 의 속성(property)들은 기본적으로 public 하며 class 외부에서 읽히고 수정될 수 있다. 하지만, ES2019 에서는 해쉬 # prefix 를 추가해 private class 필드를 선언할 수 있게 되었다.

+ +

Syntax

+ +
class ClassWithPrivateField {
+  #privateField
+}
+
+class ClassWithPrivateMethod {
+  #privateMethod() {
+    return 'hello world'
+  }
+}
+
+class ClassWithPrivateStaticField {
+  static #PRIVATE_STATIC_FIELD
+}
+ +

Examples

+ +

Private static fields

+ +

private 필드는 class 선언문 내부의 class 생성자(class constructor)에서 접근이 가능하다.

+ +

static 메소드에서만 static 변수들을 호출할 수 있다는 제약은 그대로 유지된다.

+ +
class ClassWithPrivateStaticField {
+  static #PRIVATE_STATIC_FIELD
+
+  static publicStaticMethod() {
+    ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD = 42
+    return ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD
+  }
+}
+
+console.assert(ClassWithPrivateStaticField.publicStaticMethod() === 42)
+ +

Private static 필드는 class evaluation 시 class 생성자(class constructor)에 추가된다.

+ +

Private static 필드는 해당 필드를 선언한 class 에서만 접근할 수 있다.

+ +

이는 this 를 사용함에 있어 예상치 못한 동작을 야기할 수 있다.

+ +
class BaseClassWithPrivateStaticField {
+  static #PRIVATE_STATIC_FIELD
+
+  static basePublicStaticMethod() {
+    this.#PRIVATE_STATIC_FIELD = 42
+    return this.#PRIVATE_STATIC_FIELD
+  }
+}
+
+class SubClass extends BaseClassWithPrivateStaticField { }
+
+let error = null
+
+try {
+  SubClass.basePublicStaticMethod()
+} catch(e) { error = e}
+
+console.assert(error instanceof TypeError)
+ +

Private instance fields

+ +

private 인스턴스 필드는 # 이름 ('해쉬 이름' 으로 발음), # prefix 를 가진 식별자로 선언된다. # 은 그 이름 자체의 일부이며 선언과 접근 시에 모두 사용된다.

+ +

캡슐화(encapsulation) 는 언어로부터 강제된다(enforced by the language). 즉, scope 밖에서 # 이름에 접근하는 것은 syntax error 이다.

+ +
class ClassWithPrivateField {
+  #privateField
+
+  constructor() {
+    this.#privateField = 42
+    this.#randomField = 444 // Syntax error
+  }
+}
+
+const instance = new ClassWithPrivateField()
+instance.#privateField === 42 // Syntax error
+ +

Private Methods

+ +

Private static methods

+ +

private static 메소드는 public static 메소드처럼 인스턴스가 아닌 class 로부터 호출된다. 그리고 private static 필드처럼 class 선언문 내부에서만 접근 가능하다. 

+ +

private static 메소드는 generator, async 그리고 async generator 함수가 될 수 있다.

+ +
class ClassWithPrivateStaticMethod {
+  static #privateStaticMethod() {
+    return 42
+  }
+
+  static publicStaticMethod1() {
+    return ClassWithPrivateStaticMethod.#privateStaticMethod();
+  }
+
+  static publicStaticMethod2() {
+    return this.#privateStaticMethod();
+  }
+}
+
+console.assert(ClassWithPrivateStaticMethod.publicStaticMethod1() === 42);
+console.assert(ClassWithPrivateStaticMethod.publicStaticMethod2() === 42);
+ +

이는 this 를 사용할 때 예상치 못한 동작을 발생시킬 수 있다. (이는 this binding rule 이 적용되기 때문이다.) 다음 예시에서 Derived.publicStaticMethod2() 를 호출할 때, this 는 class Derived (Base 가 아니라) 를 가리킨다. 

+ +
class Base {
+  static #privateStaticMethod() {
+    return 42;
+  }
+  static publicStaticMethod1() {
+    return Base.#privateStaticMethod();
+  }
+  static publicStaticMethod2() {
+    return this.#privateStaticMethod();
+  }
+}
+
+class Derived extends Base {}
+
+console.log(Derived.publicStaticMethod1()); // 42
+console.log(Derived.publicStaticMethod2()); // TypeError
+ +

Private instance methods

+ +

private 인스턴스 메소드는 private 인스턴스 필드와는 다르게 class 인스턴스로부터 접근 가능하다.

+ +
class ClassWithPrivateMethod {
+  #privateMethod() {
+    return 'hello world'
+  }
+
+  getPrivateMessage() {
+    return this.#privateMethod()
+  }
+}
+
+const instance = new ClassWithPrivateMethod()
+console.log(instance.getPrivateMessage())
+// expected output: "hello worl​d"
+ +

private 인스턴스 메소드는 generator, async 그리고 async generator 함수가 될 수 있다. private getter 와 setter 또한 가능하다:

+ +
class ClassWithPrivateAccessor {
+  #message
+
+  get #decoratedMessage() {
+    return `✨${this.#message}✨`
+  }
+  set #decoratedMessage(msg) {
+    this.#message = msg
+  }
+
+  constructor() {
+    this.#decoratedMessage = 'hello world'
+    console.log(this.#decoratedMessage)
+  }
+}
+
+new ClassWithPrivateAccessor();
+// expected output: "✨hello worl​d✨"
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('Public and private instance fields', '#prod-FieldDefinition', 'FieldDefinition')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.classes.private_class_fields")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/classes/static/index.html b/files/ko/web/javascript/reference/classes/static/index.html new file mode 100644 index 0000000000..02701e550d --- /dev/null +++ b/files/ko/web/javascript/reference/classes/static/index.html @@ -0,0 +1,136 @@ +--- +title: static +slug: Web/JavaScript/Reference/Classes/static +tags: + - Classes + - ECMAScript 2015 + - JavaScript + - 자바스크립트 + - 클래스 +translation_of: Web/JavaScript/Reference/Classes/static +--- +
{{jsSidebar("Classes")}}
+ +

static 키워드는 클래스의 정적 메서드를 정의합니다.

+ +

{{EmbedInteractiveExample("pages/js/classes-static.html")}}

+ + + +

문법

+ +
static methodName() { ... }
+ +

설명

+ +

정적 메서드는 클래스의 인스턴스 없이 호출이 가능하며 클래스가 인스턴스화되면 호출할 수 없다. 정적 메서드는 종종 어플리케이션의 유틸리티 함수를 만드는데 사용된다.

+ +

정적 메서드의 호출

+ +

다른 정적 메서드에서의 호출

+ +

동일한 클래스 내의 다른 정적 메서드 내에서 정적 메서드를 호출하는 경우 키워드 this를 사용할 수 있다.

+ +
class StaticMethodCall {
+  static staticMethod() {
+    return 'Static method has been called';
+  }
+  static anotherStaticMethod() {
+    return this.staticMethod() + ' from another static method';
+  }
+}
+StaticMethodCall.staticMethod();
+// 'Static method has been called'
+
+StaticMethodCall.anotherStaticMethod();
+// 'Static method has been called from another static method'
+
+ +

클래스 생성자 및 다른 메서드에서의 호출

+ +

정적 메서드가 비정적 메서드에서 키워드this 를 써서는 직접적인 접근을 할 수 없다. 바른 호출 방법은  클래스 명칭을 쓰거나, 즉 CLASSNAME.STATIC_METHOD_NAME() 을 이용하거나 혹은 그 메서드를 생성자의 한 속성으로 부르는 것으로, 즉 constructor : this.constructor.STATIC_METHOD_NAME()를 이용한다.

+ +
class StaticMethodCall {
+  constructor() {
+    console.log(StaticMethodCall.staticMethod());
+    // 'static method has been called.'
+
+    console.log(this.constructor.staticMethod());
+    // 'static method has been called.'
+  }
+
+  static staticMethod() {
+    return 'static method has been called.';
+  }
+}
+
+ +

예제

+ +

아래 예제는 여러가지 내용을 설명합니다.

+ +
    +
  1. 어떻게 정적 메서드가 클래스에서 구현되는지
  2. +
  3. 클래스의 정적 맴버가 서브클래스화 되는 것을 보여줍니다.
  4. +
  5. 정적 메서드가 어떤 경우에 호출 될 수 있는지와 없는지를 설명합니다.
  6. +
+ +
class Triple {
+  static triple(n) {
+    n = n || 1; //비트연산이 아니어야 합니다.
+    return n * 3;
+  }
+}
+
+class BiggerTriple extends Triple {
+  static triple(n) {
+    return super.triple(n) * super.triple(n);
+  }
+}
+
+console.log(Triple.triple());        // 3
+console.log(Triple.triple(6));       // 18
+console.log(BiggerTriple.triple(3)); // 81
+var tp = new Triple();
+console.log(BiggerTriple.triple(3)); // 81 (부모의 인스턴스에 영향을 받지 않습니다.)
+console.log(tp.triple()); // 'tp.triple은 함수가 아닙니다.'.
+console.log(tp.constructor.triple(4)); // 12
+
+ +

 

+ +

명세서

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.classes.static")}}

+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/deprecated_and_obsolete_features/index.html b/files/ko/web/javascript/reference/deprecated_and_obsolete_features/index.html new file mode 100644 index 0000000000..deffbf4caa --- /dev/null +++ b/files/ko/web/javascript/reference/deprecated_and_obsolete_features/index.html @@ -0,0 +1,290 @@ +--- +title: Deprecated and obsolete features +slug: Web/JavaScript/Reference/Deprecated_and_obsolete_features +tags: + - Deprecated + - JavaScript + - Obsolete +translation_of: Web/JavaScript/Reference/Deprecated_and_obsolete_features +--- +
{{JsSidebar("More")}}
+ +

본 페이지는 자바스크립트의 제외 예정인(즉, 아직 사용할 수 있지만 제거 계획이 있는) 기능과 제외된(즉, 더 이상 사용할 수 없는) 기능을 나열합니다.

+ +

제외 예정 기능

+ +

아래 기능은 아직 사용할 수 있지만, 언젠가 제거될 예정이므로 주의를 기울여야 합니다. 작성한 코드가 항목 중 하나를 포함하고 있다면 제거해야 합니다.

+ +

RegExp 속성

+ +

아래 속성은 제외 예정입니다. 이는 {{jsxref("String.replace")}} 사용에 영향을 주지 않습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescription
{{jsxref("RegExp.n", "$1-$9")}} +

Parenthesized substring matches, if any.
+ Warning: Using these properties can result in problems, since browser extensions can modify them. Avoid them!

+
{{jsxref("RegExp.input", "$_")}}See input.
{{jsxref("RegExp.multiline", "$*")}}See multiline.
{{jsxref("RegExp.lastMatch", "$&")}}See lastMatch.
{{jsxref("RegExp.lastParen", "$+")}}See lastParen.
{{jsxref("RegExp.leftContext", "$`")}}See leftContext.
{{jsxref("RegExp.rightContext", "$'")}}See rightContext.
{{jsxref("RegExp.input", "input")}}The string against which a regular expression is matched.
{{jsxref("RegExp.lastMatch", "lastMatch")}}The last matched characters.
{{jsxref("RegExp.lastParen", "lastParen")}}The last parenthesized substring match, if any.
{{jsxref("RegExp.leftContext", "leftContext")}}The substring preceding the most recent match.
{{jsxref("RegExp.rightContext", "rightContext")}}The substring following the most recent match.
+ +

The following are now properties of RegExp instances, no longer of the RegExp object:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescription
{{jsxref("RegExp.global", "global")}}Whether or not to test the regular expression against all possible matches in a string, or only against the first.
{{jsxref("RegExp.ignoreCase", "ignoreCase")}}Whether or not to ignore case while attempting a match in a string.
{{jsxref("RegExp.lastIndex", "lastIndex")}}The index at which to start the next match.
{{jsxref("RegExp.multiline", "multiline")}}Whether or not to search in strings across multiple lines.
{{jsxref("RegExp.source", "source")}}패턴의 텍스트.
+ +

RegExp 메서드

+ + + +

Function 속성

+ + + +

Legacy generator

+ + + +

Iterator

+ + + +

Object methods

+ + + +

Date methods

+ + + +

Functions

+ + + +

Proxy

+ + + +

Escape sequences

+ + + +

String methods

+ + + +

Obsolete features

+ +

These obsolete features have been entirely removed from JavaScript and can no longer be used as of the indicated version of JavaScript.

+ +

Object

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescription
{{jsxref("Global_Objects/Object/count", "__count__")}}Returns the number of enumerable properties directly on a user-defined object.
{{jsxref("Global_Objects/Object/Parent", "__parent__")}}Points to an object's context.
{{jsxref("Global_Objects/Object/eval", "Object.prototype.eval()")}}Evaluates a string of JavaScript code in the context of the specified object.
{{jsxref("Object.observe()")}}Asynchronously observing the changes to an object.
{{jsxref("Object.unobserve()")}}Remove observers.
{{jsxref("Object.getNotifier()")}}Creates an object that allows to synthetically trigger a change.
+ +

Function

+ + + + + + + + + + + + +
PropertyDescription
{{jsxref("Global_Objects/Function/arity", "arity")}}Number of formal arguments.
+ +

Array

+ + + + + + + + + + + + + + + + +
PropertyDescription
{{jsxref("Array.observe()")}}Asynchronously observing changes to Arrays.
{{jsxref("Array.unobserve()")}}Remove observers.
+ +

Number

+ + + +

ParallelArray

+ + + +

Statements

+ + + +

E4X

+ +

See E4X for more information.

+ +

Sharp variables

+ +

See Sharp variables in JavaScript for more information.

diff --git a/files/ko/web/javascript/reference/errors/bad_octal/index.html b/files/ko/web/javascript/reference/errors/bad_octal/index.html new file mode 100644 index 0000000000..8a4590e668 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/bad_octal/index.html @@ -0,0 +1,45 @@ +--- +title: 'SyntaxError: "x" is not a legal ECMA-262 octal constant' +slug: Web/JavaScript/Reference/Errors/Bad_octal +translation_of: Web/JavaScript/Reference/Errors/Bad_octal +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
Warning: SyntaxError: 08 is not a legal ECMA-262 octal constant.
+Warning: SyntaxError: 09 is not a legal ECMA-262 octal constant.
+
+ +

에러 형식

+ +

{{jsxref("SyntaxError")}}엄격 모드(strict mode)에서만 경고 됨.

+ +

무엇이 잘못되었을까?

+ +

10진법의 리터럴은 0을 가장 앞 자리에 표시하고 뒤따라 다른 10진 숫자가 오게 할 수 있지만, 0으로 시작하여 그 뒤를 따르는 모든 숫자들이 8보다 작다면, 그 수는 8진수로 해석됩니다. 이런 경우에는 08 09는 허용되지 않기 때문에 JavaScript는 경고를 띄웁니다. 

+ +

8진 리터럴과 8진 escape sequence는 사라지고 추가적인 경고가 나타날 것임을 알아 두세요. ECMAScript 6와 그 이후 버전의 구문은, 맨 앞자리에 위치하는 0의 뒤에 소문자 또는 대문자의 라틴 문자 "O" 를 위치시키도록 합니다 (0o or 0O). 더 자세한 설명은 lexical grammar 페이지를 보세요.

+ +

+ +

유효하지 않은 8진수

+ +
08;
+09;
+// SyntaxError: 08 is not a legal ECMA-262 octal constant
+// SyntaxError: octal literals and octal escape sequences are deprecated
+ +

유효한 8진수

+ +

선두로 사용된 0의 뒤에는 문자 "o"가 오도록 한다. 

+ +
0O755;
+0o644;
+
+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/errors/bad_radix/index.html b/files/ko/web/javascript/reference/errors/bad_radix/index.html new file mode 100644 index 0000000000..3ea98bf1eb --- /dev/null +++ b/files/ko/web/javascript/reference/errors/bad_radix/index.html @@ -0,0 +1,57 @@ +--- +title: 'RangeError: radix must be an integer' +slug: Web/JavaScript/Reference/Errors/Bad_radix +translation_of: Web/JavaScript/Reference/Errors/Bad_radix +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
RangeError: radix must be an integer at least 2 and no greater than 36 (Firefox)
+RangeError: toString() radix argument must be between 2 and 36 (Chrome)
+
+ +

에러 형식

+ +

{{jsxref("RangeError")}}

+ +

무엇이 잘못되었을까?

+ +

{{jsxref("Number.prototype.toString()")}} 메소드는 선택적 파라메터인 radix(기수:진수를 지정하는 값)와 함께 사용되어 왔습니다. 이 파라메터는 반드시 수의 값을 나타내는 진법의 2와 36 사이로 지정된 정수(숫자)여야 합니다. 

+ +

왜 36으로 제한이 되었을까요? radix는 digit(밑기수) 알파벳 글자로 사용되는 10보다는 큽니다. 그렇기 때문에, radix는 라틴 알파벳 26글자를 가졌을 때, 36보다 클 수 없습니다.  

+ +

보통 아래의 radix 중 하나를 사용하게 될 것입니다.

+ + + +

+ +

허용되지 않는 경우

+ +
(42).toString(0);
+(42).toString(1);
+(42).toString(37);
+(42).toString(150);
+//포맷팅하기 위해 string을 이런 식으로 사용할 수는 없습니다. :
+(12071989).toString("MM-dd-yyyy");
+
+ +

허용된 경우

+ +
(42).toString(2);     // "101010" (2진수)
+(13).toString(8);     // "15"     (8진수)
+(0x42).toString(10);  // "66"     (10진수)
+(100000).toString(16) // "186a0"  (16진수)
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/bad_regexp_flag/index.html b/files/ko/web/javascript/reference/errors/bad_regexp_flag/index.html new file mode 100644 index 0000000000..2c8d12289d --- /dev/null +++ b/files/ko/web/javascript/reference/errors/bad_regexp_flag/index.html @@ -0,0 +1,107 @@ +--- +title: 'SyntaxError: invalid regular expression flag "x"' +slug: Web/JavaScript/Reference/Errors/Bad_regexp_flag +tags: + - 구문 에러 + - 자바스크립트 + - 정규식 + - 플래그 +translation_of: Web/JavaScript/Reference/Errors/Bad_regexp_flag +--- +
{{jsSidebar("Errors")}}
+ +

메세지

+ +
SyntaxError: Syntax error in regular expression (Edge)
+SyntaxError: invalid regular expression flag "x" (Firefox)
+SyntaxError: Invalid regular expression flags (Chrome)
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘못되었을까?

+ +

코드에 잘못된 정규 표현식 플래그가 있습니다. 슬래시로 묶인 패턴으로 구성되어 있는 정규 표현식 문자에서 플래그는 두 번째 플래그 뒤에 정의됩니다. 플래그는 또한 {{jsxref("RegExp")}} 객체의 생성자 함수에서도 정의될 수 있습니다(두 번째 매개변수). 정규 표현식 플래그는 따로 또는 순서에 상관 없이 같이 사용될 수 있지만 ECMAScript에는 오직 5개만 있습니다.

+ +

정규 표현식에 플래그를 포함시키려면 아래의 문법을 사용하세요:

+ +
var re = /pattern/flags;
+
+ +

또는

+ +
var re = new RegExp('pattern', 'flags');
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
정규 표현식 플래그
플래그설명
g전역 검색.
i대소문자 구별 없이 검색.
m여러 줄(Multi-line) 검색.
u유니코드; 패턴을 유니코드 코드 포인트의 나열로 취급.
y현재 위치에서 검색. ("sticky" 검색). {{jsxref("RegExp.sticky", "sticky")}} 참조.
+ +

예제

+ +

5개의 플래그만이 유효합니다.

+ +
/foo/bar;
+
+// SyntaxError: invalid regular expression flag "b"
+
+ +

정규 표현식을 만들려고 했나요? 두 개의 슬래시가 포함된 표현식은 정규 표현식 문자로 해석됩니다.

+ +
let obj = {
+  url: /docs/Web
+};
+
+// SyntaxError: invalid regular expression flag "W"
+
+ +

아니면 문자열로 만들려고 했나요? 작은 따옴표 또는 큰 따옴표를 추가하여 문자열을 만듭니다.

+ +
let obj = {
+  url: '/docs/Web'
+};
+ +

유효한 정규 표현식 플래그

+ +

자바스크립트에서 허용하는 5개의 유효한 정규 표현식 플래그를 위의 표에서 확인하세요.

+ +
/foo/g;
+/foo/gim;
+/foo/uy;
+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/bad_return_or_yield/index.html b/files/ko/web/javascript/reference/errors/bad_return_or_yield/index.html new file mode 100644 index 0000000000..1239fa27f4 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/bad_return_or_yield/index.html @@ -0,0 +1,51 @@ +--- +title: 'SyntaxError: return not in function' +slug: Web/JavaScript/Reference/Errors/Bad_return_or_yield +translation_of: Web/JavaScript/Reference/Errors/Bad_return_or_yield +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
SyntaxError: return not in function
+SyntaxError: yield not in function
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}.

+ +

뭐가 잘못된 걸까요?

+ +

return 또는 yield 문장이 function 밖에서 호출되었기 때문입니다. 혹시 어딘가에 중괄호를 빠트리신 건 아닌가요? return 과 yield function 내에 있어야 합니다, 왜냐하면 이것들은 function의 실행 종료 (또는 일시정지 및 재개)를 의미하고 function 호출자에게 특정 값을 반환하기 위해 사용되기 때문입니다.

+ +

예제

+ +
var cheer = function(score) {
+  if (score === 147)
+    return 'Maximum!';
+  };
+  if (score > 100) {
+    return 'Century!';
+  }
+}
+
+// SyntaxError: return not in function
+ +

처음 볼 때는 중괄호가 제대로 있는 것처럼 보인다, 하지만 이 코드 조각에는 if 문장 다음에 중괄호가 하나 빠져 있다. 다음처럼 고쳐야 한다:

+ +
var cheer = function(score) {
+  if (score === 147) {
+    return 'Maximum!';
+  }
+  if (score > 100) {
+    return 'Century!';
+  }
+};
+ +

또 다른 내용

+ + diff --git a/files/ko/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html b/files/ko/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html new file mode 100644 index 0000000000..593e8cca13 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html @@ -0,0 +1,56 @@ +--- +title: 'ReferenceError: can''t access lexical declaration`X'' before initialization' +slug: Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init +translation_of: Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
ReferenceError: can't access lexical declaration `X' before initialization (Firefox)
+ReferenceError: 'x' is not defined (Chrome)
+
+ +

Error type

+ +

{{jsxref("ReferenceError")}}

+ +

무엇이 잘못 되었을까요?

+ +

변수가 초기화 되기 전에 엑세스가 되어버립니다. 이 문제는 let 또는 const 선언이 정의 되기 전에 엑세스되는 모든 block 문에서 발생합니다.

+ +

Examples

+ +

잘못된 경우

+ +

이 경우에 변수 "foo"는 let 을 사용하여 block 문에서 다시 선언됩니다.

+ +
function test() {
+  let foo = 33;
+  if (true) {
+    let foo = (foo + 55);
+    // ReferenceError: can't access lexical
+    // declaration `foo' before initialization
+  }
+}
+test();
+
+ +

올바른 경우

+ +

if 문에서 "foo"를 변경하려면 재 선언을 발생시키는 let 을 제거해야합니다.

+ +
function test(){
+   let foo = 33;
+   if (true) {
+      foo = (foo + 55);
+   }
+}
+test();
+
+ +

그밖에 볼 것

+ + diff --git a/files/ko/web/javascript/reference/errors/delete_in_strict_mode/index.html b/files/ko/web/javascript/reference/errors/delete_in_strict_mode/index.html new file mode 100644 index 0000000000..138384bcac --- /dev/null +++ b/files/ko/web/javascript/reference/errors/delete_in_strict_mode/index.html @@ -0,0 +1,71 @@ +--- +title: >- + SyntaxError: applying the 'delete' operator to an unqualified name is + deprecated +slug: Web/JavaScript/Reference/Errors/Delete_in_strict_mode +tags: + - 가비지 컬렉터 + - 구문 에러 + - 변수 삭제 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Delete_in_strict_mode +--- +
{{jsSidebar("Errors")}}
+ +

메세지

+ +
SyntaxError: Calling delete on expression not allowed in strict mode (Edge)
+SyntaxError: applying the 'delete' operator to an unqualified name is deprecated (Firefox)
+SyntaxError: Delete of an unqualified identifier in strict mode. (Chrome)
+
+ +

에러 타입

+ +

엄격(Strict) 모드에서의 {{jsxref("SyntaxError")}}

+ +

무엇이 잘못되었을까?

+ +

자바스크립트에서 일반 변수는 delete 연산자를 사용하여 삭제할 수 없습니다. 엄격 모드에서 변수를 삭제하는 접근은 허용되지 않으므로 에러가 발생합니다.

+ +

delete 연산자는 오직 객체의 속성만을 삭제할 수 있습니다. 객체 속성은 설정할 수 있는 경우 "수식"될 수 있습니다.

+ +

일반적인 생각과 다르게 delete 연산자는 메모리 해제와 직접적인 연관이 없습니다. 메모리 관리는 참조가 깨짐에 따라 간접적으로 수행됩니다. 자세한 내용은 메모리 관리 페이지와 delete 연산자 페이지를 참조하십시오.

+ +

이 에러는 오직 엄격 모드 코드에서만 발생합니다. 엄격하지 않은 모드에서 해당 연산자는 단순히 false 를 반환합니다.

+ +

예제

+ +

자바스크립트에서 일반 변수를 삭제하려고 하면 동작하지 않습니다. 그리고 엄격 모드에서는 에러가 발생합니다:

+ +
'use strict';
+
+var x;
+
+// ...
+
+delete x;
+
+// SyntaxError: applying the 'delete' operator to an unqualified name
+// is deprecated
+
+ +

변수의 내용을 비우려면 {{jsxref("null")}}을 설정하면 됩니다:

+ +
'use strict';
+
+var x;
+
+// ...
+
+x = null;
+
+// x는 가비지 컬렉터에 의해 메모리에서 해제됩니다
+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html b/files/ko/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html new file mode 100644 index 0000000000..fc613db1d0 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.html @@ -0,0 +1,70 @@ +--- +title: 'ReferenceError: deprecated caller or arguments usage' +slug: Web/JavaScript/Reference/Errors/Deprecated_caller_or_arguments_usage +translation_of: Web/JavaScript/Reference/Errors/Deprecated_caller_or_arguments_usage +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
Warning: ReferenceError: deprecated caller usage (Firefox)
+Warning: ReferenceError: deprecated arguments usage (Firefox)
+TypeError: 'callee' and 'caller' cannot be accessed in strict mode. (Safari)
+
+ +

에러 형식

+ +

엄격 모드에서만 {{jsxref("ReferenceError")}} 경고가 발생합니다. JavaScript 실행이 중단되지는 않을 것입니다.   

+ +

무엇이 잘못되었을까?

+ +

엄격모드에서, {{jsxref("Function.caller")}} 나 {{jsxref("Function.arguments")}} 속성이 사용되었고, 그러지 말아야 했습니다. 이 속성들은 사라지게 되었는데, 함수 호출자를 흘려보내거나, 비 표준이었으며, 최적화 하기 어렵고, 잠재적으로 퍼포먼스에 무리를 주었기 때문입니다.

+ +

+ +

function.caller or arguments.callee.caller

+ +

{{jsxref("Function.caller")}} 와 arguments.callee.caller 는 사라지게 되었습니다. (자세한 정보는 레퍼런스 문서를 확인해 보세요.)

+ +
"use strict";
+
+function myFunc() {
+  if (myFunc.caller == null) {
+    return 'The function was called from the top!';
+  } else {
+    return 'This function\'s caller was ' + myFunc.caller;
+  }
+}
+
+myFunc();
+// Warning: ReferenceError: deprecated caller usage
+// "The function was called from the top!"
+ +

Function.arguments

+ +

{{jsxref("Function.arguments")}} 는 사라졌습니다. (자세한 정보는 레퍼런스 문서를 확인해 주세요.) 

+ +
"use strict";
+
+function f(n) { g(n - 1); }
+
+function g(n) {
+  console.log('before: ' + g.arguments[0]);
+  if (n > 0) { f(n); }
+  console.log('after: ' + g.arguments[0]);
+}
+
+f(2);
+
+console.log('returned: ' + g.arguments);
+// Warning: ReferenceError: deprecated arguments usage
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/deprecated_octal/index.html b/files/ko/web/javascript/reference/errors/deprecated_octal/index.html new file mode 100644 index 0000000000..55d85cf7eb --- /dev/null +++ b/files/ko/web/javascript/reference/errors/deprecated_octal/index.html @@ -0,0 +1,64 @@ +--- +title: 'SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated' +slug: Web/JavaScript/Reference/Errors/Deprecated_octal +translation_of: Web/JavaScript/Reference/Errors/Deprecated_octal +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
SyntaxError: Octal numeric literals and escape characters not allowed in strict mode (Edge)
+SyntaxError:
+"0"-prefixed octal literals and octal escape sequences are deprecated;
+for octal literals use the "0o" prefix instead
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}} strict mode 내에서만.

+ +

무엇이 잘 못 되었을까?

+ +

8진 리터럴과 8진수 이스케이프 시퀀스는 더 이상 사용하지 않으며, 엄격 모드(strict mode) 내에서는 {{jsxref("SyntaxError")}} 에러를 던질 것입니다. ECMAScript 2015와 이 후의 버전의 표준화된 구문은 0을 맨 앞자리에 두고 그 뒤를 대문자 또는 소문자의 라틴 문자 "O" 를 사용하도록 합니다. (0o 또는 0O)

+ +

예제

+ +

"0"이 접두인 8진 리터럴

+ +
"use strict";
+
+03;
+
+// SyntaxError: "0"-prefixed octal literals and octal escape sequences
+// are deprecated (0으로 시작하는 8진수와 8진 이스케이프 시퀀스는 더 이상 사용되지 않습니다. )
+
+ +

8진수 이스케이프 시퀀스

+ +
"use strict";
+
+"\251";
+
+// SyntaxError: "0"-prefixed octal literals and octal escape sequences
+// are deprecated (0으로 시작하는 8진수와 8진 이스케이프 시퀀스는 더 이상 사용되지 않습니다. )
+
+ +

유효한 8진 수들

+ +

0뒤에 "o" 또는 "O"를 사용합니다. :

+ +
0o3;
+
+ +

8진수 이스케이프 시퀀스 대신 16진수 이스케이프 시퀀스를 사용할 수도 있습니다. :

+ +
'\xA9';
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/errors/identifier_after_number/index.html b/files/ko/web/javascript/reference/errors/identifier_after_number/index.html new file mode 100644 index 0000000000..14e5b336c7 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/identifier_after_number/index.html @@ -0,0 +1,57 @@ +--- +title: 'SyntaxError: identifier starts immediately after numeric literal' +slug: Web/JavaScript/Reference/Errors/Identifier_after_number +tags: + - 구문 에러 + - 변수 이름 + - 식별자 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Identifier_after_number +--- +
{{JSSidebar("Errors")}}
+ +

메세지

+ +
SyntaxError: Unexpected identifier after numeric literal (Edge)
+SyntaxError: identifier starts immediately after numeric literal (Firefox)
+SyntaxError: Unexpected number (Chrome)
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘못되었을까?

+ +

{{Glossary("식별자", "식별자")}}라고 불리는 변수의 이름은 반드시 지켜야 하는 특정 규칙을 따라야 합니다.

+ +

자바스크립트의 식별자는 반드시 문자, 언더스코어(_), 또는 달러 표시($)로 시작돼야 합니다. 숫자로 시작될 수 없습니다. 글자 뒤에만 숫자(0-9)가 올 수 있습니다.

+ +

예제

+ +

숫자로 시작하는 변수 이름

+ +

자바스크립트에서 변수 이름은 숫자로 시작될 수 없습니다. 아래 예제는 에러가 발생합니다:

+ +
var 1life = 'foo';
+// SyntaxError: identifier starts immediately after numeric literal
+
+var foo = 1life;
+// SyntaxError: identifier starts immediately after numeric literal
+
+alert(1.foo);
+// SyntaxError: identifier starts immediately after numeric literal
+
+ +

숫자가 뒤에 오도록 변수 이름을 변경해야 합니다.

+ +
var life1 = 'foo';
+var foo = life1;
+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/illegal_character/index.html b/files/ko/web/javascript/reference/errors/illegal_character/index.html new file mode 100644 index 0000000000..b3cd3a9750 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/illegal_character/index.html @@ -0,0 +1,81 @@ +--- +title: 'SyntaxError: illegal character' +slug: Web/JavaScript/Reference/Errors/Illegal_character +tags: + - ZWSP + - 구문 에러 + - 자바스크립트 + - 폭 없는 공백 +translation_of: Web/JavaScript/Reference/Errors/Illegal_character +--- +

{{jsSidebar("Errors")}}

+ +

메세지

+ +
SyntaxError: Invalid character (Edge)
+SyntaxError: illegal character (Firefox)
+SyntaxError: Invalid or unexpected token (Chrome)
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘못되었을까?

+ +

코드에 해당 구문에 맞지 않거나 예기치 않은 토큰이 있습니다. 마이너스 기호( - )와 대시() 또는 따옴표( " )와 비표준 따옴표() 등이 잘못 사용된 경우에 대해 문법 체크를 해주는 편집기를 사용하여 코드를 주의 깊게 확인해야 합니다.

+ +

예제

+ +

잘못 사용된 문자

+ +

일부 문자들은 비슷하게 보이지만 파서가 코드 해석을 실패하게 만듭니다. 유명한 예로 따옴표, 마이너스 또는 세미콜론(greek questionmark (U+37e)과 동일하게 보입니다)이 있습니다.

+ +
“This looks like a string”;  // SyntaxError: illegal character
+                             // 비슷해 보이지만 “와 ”는 "이 아닙니다
+
+42 – 13;                     // SyntaxError: illegal character
+                             // 비슷해 보이지만 –은 -이 아닙니다
+
+var foo = 'bar';             // SyntaxError: illegal character
+                             // 비슷해 보이지만 <37e>은 ;이 아닙니다
+
+ +

아래 예제는 정상적으로 동작합니다:

+ +
"This is actually a string";
+42 - 13;
+var foo = 'bar';
+
+ +

일부 편집기와 IDE는 문제가 있는 부분을 알려주거나 적어도 강조 표시를 해주지만 전부는 아닙니다. 이런 에러가 발생했을 때 무엇이 문제인지 찾을 수 없는 경우, 문제가 있는 줄을 지우고 다시 작성하는 것 가장 좋습니다.

+ +

문자 빠트리기

+ +

앞이나 뒤에 오는 문자를 잊어버리기 쉽습니다.

+ +
var colors = ['#000', #333', '#666'];
+// SyntaxError: illegal character
+
+ +

 '#333'에 빠진 작은따옴표를 추가합니다.

+ +
var colors = ['#000', '#333', '#666'];
+ +

숨겨진 문자

+ +

다른 곳에서 코드를 복사하여 붙여넣은 경우 잘못된 문자가 포함돼 있을 수 있습니다. 주의하세요!

+ +
var foo = 'bar';​
+// SyntaxError: illegal character
+
+ +

Vim과 같은 편집기에서 아래 코드를 체크하면 폭 없는 공백(zero-width space (ZWSP) (U+200B)) 문자가 있는 것을 확인할 수 있습니다.

+ +
var foo = 'bar';​<200b>
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/index.html b/files/ko/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..79e24cc575 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/index.html @@ -0,0 +1,12 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Errors +--- +

{{jsSidebar("Errors")}}

+ +

오류, 사방에 오류.

+ +

{{ListSubPages("/ko/docs/Web/JavaScript/Reference/Errors")}}

diff --git a/files/ko/web/javascript/reference/errors/invalid_array_length/index.html b/files/ko/web/javascript/reference/errors/invalid_array_length/index.html new file mode 100644 index 0000000000..6ddeb58f06 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/invalid_array_length/index.html @@ -0,0 +1,73 @@ +--- +title: 'RangeError: invalid array length' +slug: Web/JavaScript/Reference/Errors/Invalid_array_length +translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length +--- +
{{jsSidebar("Errors")}}
+ +

메세지

+ +
RangeError: invalid array length (Firefox)
+RangeError: Invalid array length (Chrome)
+RangeError: Invalid array buffer length (Chrome)
+
+ +

에러 형식

+ +

{{jsxref("RangeError")}}

+ +

무엇이 잘못 된 것일까?

+ +

다음과 같은 원인 때문이다:

+ + + +

Array와 ArrayBuffer의 길이에 제한을 둔 이유는, Array나 ArrayBuffer의 length 속성은 사인되지 않은(unsigned) 32 비트 정수로 반영되기 때문이다.Array나 ArrayBuffer는 오직 0 ~ 232-1 사이의 값만을 저장할 수 있다.

+ +

Array의 length로 해석되는 첫번째 argument로서 문자열 표기를 통해 contructor를 사용하여 Array를 생성할 수 있다.

+ +

다른 방법으로는, length 속성을 설정하기 전에 length의 길이에 제한을 두거나, constructor의 aurgment로서 사용할 수 있다.

+ +

예제

+ +

잘못된 예제

+ +
new Array(Math.pow(2, 40))
+new Array(-1)
+new ArrayBuffer(Math.pow(2, 32))
+new ArrayBuffer(-1)
+
+let a = [];
+a.length = a.length - 1;         // set -1 to the length property
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = b.length + 1;         // set 2^32 to the length property
+
+ +

올바른 예제

+ +
[ Math.pow(2, 40) ]                     // [ 1099511627776 ]
+[ -1 ]                                  // [ -1 ]
+new ArrayBuffer(Math.pow(2, 32) - 1)
+new ArrayBuffer(0)
+
+let a = [];
+a.length = Math.max(0, a.length - 1);
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = Math.min(0xffffffff, b.length + 1);
+
+// 0xffffffff is the hexadecimal notation for 2^32 - 1
+// which can also be written as (-1 >>> 0)
+
+ +

 

+ + diff --git a/files/ko/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html b/files/ko/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html new file mode 100644 index 0000000000..7a7acf3ca2 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html @@ -0,0 +1,50 @@ +--- +title: 'ReferenceError: invalid assignment left-hand side' +slug: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side +translation_of: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
ReferenceError: invalid assignment left-hand side
+
+ +

에러 타입

+ +

{{jsxref("ReferenceError")}}.

+ +

무엇이 잘못되었을까?

+ +

예상치 못한 할당이 일어났습니다. 이것은 할당 연산자(assignment operator)와 비교 연산자(comparison operator) 간의 불일치로 인한 것일 겁니다.  예를 들면, "=" 부호는 값을 변수에 할당합니다.  "==" 나  "==="는 값을 비교하는 연산을 합니다.

+ +

+ +
if (Math.PI = 3 || Math.PI = 4) {
+  console.log('no way!');
+}
+// ReferenceError: invalid assignment left-hand side
+
+var str = 'Hello, '
++= 'is it me '
++= 'you\'re looking for?';
+// ReferenceError: invalid assignment left-hand side
+
+ +

if 구문에서, 비교 연산자 ("==")로 비교하려 할 때, 문자열의 연속적인 결합의 경우에는, 플러스("+") 연산자가 필요합니다.

+ +
if (Math.PI == 3 || Math.PI == 4) {
+  console.log('no way!');
+}
+
+var str = 'Hello, '
++ 'from the '
++ 'other side!';
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/invalid_date/index.html b/files/ko/web/javascript/reference/errors/invalid_date/index.html new file mode 100644 index 0000000000..32cf041e7e --- /dev/null +++ b/files/ko/web/javascript/reference/errors/invalid_date/index.html @@ -0,0 +1,50 @@ +--- +title: 'RangeError: invalid date' +slug: Web/JavaScript/Reference/Errors/Invalid_date +translation_of: Web/JavaScript/Reference/Errors/Invalid_date +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
RangeError: invalid date (Firefox)
+RangeError: invalid time value (Chrome)
+RangeError: Provided date is not in valid range (Chrome)
+
+ +

에러 종류

+ +

{{jsxref("RangeError")}}

+ +

무엇이 잘못 된 걸까?

+ +

유효하지 않은 String이 {{jsxref("Date")}} 나 {{jsxref("Date.parse()")}}에 입력되었습니다.

+ +

예시

+ +

올바르지 않은 사용 예시

+ +

인식 할 수 없는 string이나 잘못된 요소 값을 포함하는 ISO 형식의 날짜 string은 일반적으로 {{jsxref ( "NaN")}}을 반환합니다. 그러나 구현 방식에 따라 ISO 형식 string을 따르지 않는 경우 RangeError: invalid date가 표시 될 수 있습니다. Firefox의 경우:

+ +
new Date('foo-bar 2014');
+new Date('2014-25-23').toISOString();
+new Date('foo-bar 2014').toString();
+
+ +

그러나 이 경우, Firefox에서는 {{jsxref("NaN")}} 을 반환합니다:

+ +
Date.parse('foo-bar 2014'); // NaN
+ +

더 자세한 사항은  {{jsxref("Date.parse()")}} 문서를 참고하세요.

+ +

올바른 사용 예시

+ +
new Date('05 October 2011 14:48 UTC');
+ +

더 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/invalid_for-in_initializer/index.html b/files/ko/web/javascript/reference/errors/invalid_for-in_initializer/index.html new file mode 100644 index 0000000000..7dd5e15a9a --- /dev/null +++ b/files/ko/web/javascript/reference/errors/invalid_for-in_initializer/index.html @@ -0,0 +1,75 @@ +--- +title: 'SyntaxError: for-in loop head declarations may not have initializers' +slug: Web/JavaScript/Reference/Errors/Invalid_for-in_initializer +tags: + - for...in 구문 + - 구문 에러 + - 배열 반복 + - 자바스크립트 + - 초기화 +translation_of: Web/JavaScript/Reference/Errors/Invalid_for-in_initializer +--- +
{{jsSidebar("Errors")}}
+ +

메세지

+ +
SyntaxError: for-in loop head declarations cannot have an initializer (Edge)
+SyntaxError: for-in loop head declarations may not have initializers (Firefox)
+SyntaxError: for-in loop variable declaration may not have an initializer. (Chrome)
+
+ +

에러 타입

+ +

엄격(Strict) 모드에서의 {{jsxref("SyntaxError")}}.

+ +

무엇이 잘못되었을까?

+ +

for...in 반복문의 선언부에 초기화 구문이 포함되어 있습니다. 즉, |for (var i = 0 in obj)| 구문을 통해 변수가 정의되고 값이 할당된 것을 말합니다. 비엄격 모드(non-strict) 모드에서는 이 초기화 구문이 무시되어 |for (var i in obj)| 처럼 동작합니다. 하지만 엄격 모드에서는 SyntaxError 가 발생합니다.

+ +

예제

+ +

이 예제는 SyntaxError를 발생시킵니다.

+ +
"use strict";
+
+var obj = {a: 1, b: 2, c: 3 };
+
+for (var i = 0 in obj) {
+  console.log(obj[i]);
+}
+
+// SyntaxError: for-in loop head declarations may not have initializers
+
+ +

올바른 for-in 반복문

+ +

for-in 반복문의 선언부에서 초기화 구문(i = 0)을 삭제합니다.

+ +
"use strict";
+
+var obj = {a: 1, b: 2, c: 3 };
+
+for (var i in obj) {
+  console.log(obj[i]);
+}
+
+ +

배열 반복

+ +

for...in 반복문은 배열을 반복하는데에는 사용하지 않습니다. 배열({{jsxref("Array")}})을 반복하기 위해 for-in 반복문 대신에 for 반복문을 사용하려고 한 적이 있습니까? for 반복문은 선언부에서 초기화도 할 수 있습니다:

+ +
var arr = [ "a", "b", "c" ]
+
+for (var i = 2; i < arr.length; i++) {
+  console.log(arr[i]);
+}
+
+// "c"
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/invalid_for-of_initializer/index.html b/files/ko/web/javascript/reference/errors/invalid_for-of_initializer/index.html new file mode 100644 index 0000000000..0e60e242e8 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/invalid_for-of_initializer/index.html @@ -0,0 +1,64 @@ +--- +title: >- + SyntaxError: a declaration in the head of a for-of loop can't have an + initializer +slug: Web/JavaScript/Reference/Errors/Invalid_for-of_initializer +tags: + - For문 초기화 + - 구문 에러 + - 반복문 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Invalid_for-of_initializer +--- +
{{jsSidebar("Errors")}}
+ +

메세지

+ +
SyntaxError: for-of loop head declarations cannot have an initializer (Edge)
+SyntaxError: a declaration in the head of a for-of loop can't have an initializer (Firefox)
+SyntaxError: for-of loop variable declaration may not have an initializer. (Chrome)
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘못되었을까?

+ +

for...of 반복문의 식이 초기화 구문을 포함한 것이 문제입니다. 즉, |for (var i = 0 of iterable)| 구문을 통해 변수가 정의되고 값이 할당된 것을 말합니다. 이 구문은 for-of 반복문에서 허용되지 않습니다. 이 경우 초기화를 할 수 있는 for 반복문이 필요합니다.

+ +

예제

+ +

잘못된 for-of 반복문

+ +
let iterable = [10, 20, 30];
+
+for (let value = 50 of iterable) {
+  console.log(value);
+}
+
+// SyntaxError: a declaration in the head of a for-of loop can't
+// have an initializer
+ +

올바른 for-of 반복문

+ +

for-of 반복문에서 초기화 구문(value = 50)을 삭제해야 합니다. 50을 더하고 싶다면 다음 예제와 같이 반복문 안에 추가할 수 있습니다.

+ +
let iterable = [10, 20, 30];
+
+for (let value of iterable) {
+  value += 50;
+  console.log(value);
+}
+// 60
+// 70
+// 80
+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/is_not_iterable/index.html b/files/ko/web/javascript/reference/errors/is_not_iterable/index.html new file mode 100644 index 0000000000..8e00501d54 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/is_not_iterable/index.html @@ -0,0 +1,106 @@ +--- +title: 'TypeError: ''x'' is not iterable' +slug: Web/JavaScript/Reference/Errors/is_not_iterable +tags: + - JavaScript + - 레퍼런스 + - 에러 + - 타입에러 +translation_of: Web/JavaScript/Reference/Errors/is_not_iterable +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
TypeError: 'x' is not iterable (Firefox, Chrome)
+TypeError: 'x' is not a function or its return value is not iterable (Chrome)
+
+ +

에러 타입

+ +

{{jsxref("TypeError")}}

+ +

무엇이 문제인가요?

+ +

{{jsxref("Promise.all")}} 또는 {{jsxref("TypedArray.from")}} 과 같은 함수의 아규먼트 또는 for…of 의 right hand-side 로 주어진 값이 iterable 객체가 아닙니다. iterable 은 {{jsxref("Array")}}, {{jsxref("String")}} 또는 {{jsxref("Map")}}, 생성자 결과, 또는 iterable protocol 구현 객체와 같은 내장 iterable 타입이 될 수 있습니다.

+ +

예제

+ +

모든 객체 프로퍼티 iterating

+ +

JavaScript 에서 iterable protocol 을 구현하지 않은 {{jsxref("Object")}} 는 iterable 이 아닙니다.
+ 그러므로, 객체의 프로퍼티를 반복하기 위해 for…of 를 사용하면 안됩니다.

+ +
var obj = { 'France': 'Paris', 'England': 'London' };
+for (let p of obj) { // TypeError: obj is not iterable
+    // …
+}
+
+ +

객체의 모든 항목 또는 프로퍼티를 반복하려면 대신 {{jsxref("Object.keys")}} 또는 {{jsxref("Object.entries")}} 를 사용해야 합니다.

+ +
var obj = { 'France': 'Paris', 'England': 'London' };
+// 모든 프로퍼티 이름을 iterate:
+for (let country of Object.keys(obj)) {
+    var capital = obj[country];
+    console.log(country, capital);
+}
+
+for (const [country, capital] of Object.entries(obj))
+    console.log(country, capital);
+
+
+
+ +

이 유즈 케이스에 대한 다른 옵션은 {{jsxref("Map")}} 을 사용하는 것입니다.

+ +
var map = new Map;
+map.set('France', 'Paris');
+map.set('England', 'London');
+// 모든 프로퍼티 이름 iterate
+for (let country of map.keys()) {
+    let capital = map[country];
+    console.log(country, capital);
+}
+
+for (let capital of map.values())
+    console.log(capital);
+
+for (const [country, capital] of map.entries())
+    console.log(country, capital);
+
+ +

Generator iterating

+ +

Generators 는 iterable 객체를 생성하기 위해 호출하는 함수입니다.

+ +
function* generate(a, b) {
+  yield a;
+  yield b;
+}
+
+for (let x of generate) // TypeError: generate is not iterable
+    console.log(x);
+
+ +

generator 가 호출되지 않으면, generator 에 해당하는 {{jsxref("Function")}} 객체를 호출할수는 있지만 interable 하지는 않습니다. generator 호출은 generator 실행동안 yield 된 모든 값을 iterate 하는 iterable 객체를 생성합니다.

+ +
function* generate(a, b) {
+    yield a;
+    yield b;
+}
+
+for (let x of generate(1,2))
+    console.log(x);
+
+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/json_bad_parse/index.html b/files/ko/web/javascript/reference/errors/json_bad_parse/index.html new file mode 100644 index 0000000000..c73b082dbb --- /dev/null +++ b/files/ko/web/javascript/reference/errors/json_bad_parse/index.html @@ -0,0 +1,105 @@ +--- +title: 'SyntaxError: JSON.parse: bad parsing' +slug: Web/JavaScript/Reference/Errors/JSON_bad_parse +translation_of: Web/JavaScript/Reference/Errors/JSON_bad_parse +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
SyntaxError: JSON.parse: unterminated string literal
+SyntaxError: JSON.parse: bad control character in string literal
+SyntaxError: JSON.parse: bad character in string literal
+SyntaxError: JSON.parse: bad Unicode escape
+SyntaxError: JSON.parse: bad escape character
+SyntaxError: JSON.parse: unterminated string
+SyntaxError: JSON.parse: no number after minus sign
+SyntaxError: JSON.parse: unexpected non-digit
+SyntaxError: JSON.parse: missing digits after decimal point
+SyntaxError: JSON.parse: unterminated fractional number
+SyntaxError: JSON.parse: missing digits after exponent indicator
+SyntaxError: JSON.parse: missing digits after exponent sign
+SyntaxError: JSON.parse: exponent part is missing a number
+SyntaxError: JSON.parse: unexpected end of data
+SyntaxError: JSON.parse: unexpected keyword
+SyntaxError: JSON.parse: unexpected character
+SyntaxError: JSON.parse: end of data while reading object contents
+SyntaxError: JSON.parse: expected property name or '}'
+SyntaxError: JSON.parse: end of data when ',' or ']' was expected
+SyntaxError: JSON.parse: expected ',' or ']' after array element
+SyntaxError: JSON.parse: end of data when property name was expected
+SyntaxError: JSON.parse: expected double-quoted property name
+SyntaxError: JSON.parse: end of data after property name when ':' was expected
+SyntaxError: JSON.parse: expected ':' after property name in object
+SyntaxError: JSON.parse: end of data after property value in object
+SyntaxError: JSON.parse: expected ',' or '}' after property value in object
+SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal
+SyntaxError: JSON.parse: property names must be double-quoted strings
+SyntaxError: JSON.parse: expected property name or '}'
+SyntaxError: JSON.parse: unexpected character
+SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}

+ +

뭐가 잘못됬나요?

+ +

{{jsxref("JSON.parse()")}} 는 문자열을 JSON으로 파싱한다. 이 문자열은 유효한 JSON 형태의 문자열이어야 하며, 유효하지 않을 경우 에러가 발생한다.

+ +

예제

+ +

JSON.parse() 는 여분의 콤마를 허용하지 않는다.

+ +

다음 두 줄은 SyntaxError를 발생시킨다:

+ +
JSON.parse('[1, 2, 3, 4,]');
+JSON.parse('{"foo": 1,}');
+// SyntaxError JSON.parse: unexpected character
+// at line 1 column 14 of the JSON data
+
+ +

끝에 오는 콤마를 제거하면 정확하게 JSON으로 파싱한다:

+ +
JSON.parse('[1, 2, 3, 4]');
+JSON.parse('{"foo": 1}');
+ +

프로퍼티 이름은 반드시 쌍따옴표로 표현해야 한다.

+ +

'foo'처럼 프로퍼티를 작은 따옴표로 감싸서는 안된다.

+ +
JSON.parse("{'foo': 1}");
+// SyntaxError: JSON.parse: expected property name or '}'
+// at line 1 column 2 of the JSON data
+ +

대신에 "foo" 처럼 써야 한다:

+ +
JSON.parse('{"foo": 1}');
+ +

리딩 제로와 십진 소수점

+ +

01 처럼 리딩제로를 사용할 수 없고, 십진 소수점 뒤에는 최소한 하나의 숫자는 등장해야 한다.

+ +
JSON.parse('{"foo": 01}');
+// SyntaxError: JSON.parse: expected ',' or '}' after property value
+// in object at line 1 column 2 of the JSON data
+
+JSON.parse('{"foo": 1.}');
+// SyntaxError: JSON.parse: unterminated fractional number
+// at line 1 column 2 of the JSON data
+
+ +

대신에 리딩제로를 없애고 1 이라고 쓰고, 십진 소수점 뒤에는 반드시 하나 이상의 숫자를 적도록 한다:

+ +
JSON.parse('{"foo": 1}');
+JSON.parse('{"foo": 1.0}');
+
+ +

또다른 내용

+ + diff --git a/files/ko/web/javascript/reference/errors/malformed_formal_parameter/index.html b/files/ko/web/javascript/reference/errors/malformed_formal_parameter/index.html new file mode 100644 index 0000000000..e258ba49e6 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/malformed_formal_parameter/index.html @@ -0,0 +1,57 @@ +--- +title: 'SyntaxError: Malformed formal parameter' +slug: Web/JavaScript/Reference/Errors/Malformed_formal_parameter +translation_of: Web/JavaScript/Reference/Errors/Malformed_formal_parameter +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
SyntaxError: malformed formal parameter (Firefox)
+
+ +

Error type

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘못 되었을까요?

+ +

코드에는 최소한 두 개의 인수가 전달 된 Function() 생성자가 있습니다. 마지막 인수는 작성중인 새 함수의 소스코드 입니다.  나머지는 모두 새 함수의 인수 목록을 구성합니다.

+ +

인수 목록이 어딘가 잘못되었습니다. 아마도 실수로 인수 이름으로 if 또는 var와 같은 키워드를 선택했거나 인수 목록에 갈곳 잃은 구두점이 있을 수 있습니다. 또는 실수로 숫자나 개체와 같은 잘못된 값을 전달한 것일 수 있습니다.

+ +

그래, 내 문제가 해결됐어. 근데 왜 말 안해줬어?

+ +

틀림 없이 오류 메세지의 표현은 다소 이상한 부분이 있습니다. "공식 매개 변수"는 "함수 인수"를 말하는 좋은 방법입니다. 우리는 "잘못된 형식의 단어를 사용했다"라고 표현 합니다.

+ +

Examples

+ +

Invalid cases

+ +
var f = Function('x y', 'return x + y;');
+// SyntaxError (missing a comma)
+
+var f = Function('x,', 'return x;');
+// SyntaxError (extraneous comma)
+
+var f = Function(37, "alert('OK')");
+// SyntaxError (numbers can't be argument names)
+
+ +

Valid cases

+ +
var f = Function('x, y', 'return x + y;');  // correctly punctuated
+
+var f = Function('x', 'return x;');
+
+// if you can, avoid using Function - this is much faster
+var f = function(x) { return x; };
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/errors/missing_bracket_after_list/index.html b/files/ko/web/javascript/reference/errors/missing_bracket_after_list/index.html new file mode 100644 index 0000000000..b9149ac159 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_bracket_after_list/index.html @@ -0,0 +1,56 @@ +--- +title: 'SyntaxError: missing ] after element list' +slug: Web/JavaScript/Reference/Errors/Missing_bracket_after_list +tags: + - 구문 에러 + - 배열 초기자 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Missing_bracket_after_list +--- +
{{jsSidebar("Errors")}}
+ +

메세지

+ +
SyntaxError: missing ] after element list
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}.

+ +

무엇이 잘못되었을까?

+ +

배열 초기자 구문에 오류가 있습니다. 닫는 대괄호("]") 또는 콤마(",")가 빠진 것 같습니다.

+ +

예제

+ +

완성되지 않은 배열 초기자

+ +
var list = [1, 2,
+
+var instruments = [
+  'Ukulele',
+  'Guitar',
+  'Piano'
+};
+
+var data = [{foo: 'bar'} {bar: 'foo'}];
+
+ +

바르게 고치면:

+ +
var list = [1, 2];
+
+var instruments = [
+ 'Ukulele',
+ 'Guitar',
+ 'Piano'
+];
+
+var data = [{foo: 'bar'}, {bar: 'foo'}];
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/missing_colon_after_property_id/index.html b/files/ko/web/javascript/reference/errors/missing_colon_after_property_id/index.html new file mode 100644 index 0000000000..4fe7865664 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_colon_after_property_id/index.html @@ -0,0 +1,78 @@ +--- +title: 'SyntaxError: missing : after property id' +slug: Web/JavaScript/Reference/Errors/Missing_colon_after_property_id +tags: + - 객체 초기자 + - 계산된 속성 + - 구문 에러 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Missing_colon_after_property_id +--- +
{{jsSidebar("Errors")}}
+ +

메세지

+ +
SyntaxError: Expected ':' (Edge)
+SyntaxError: missing : after property id (Firefox)
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 문제일까?

+ +

객체 초기자 구문으로 객체를 만들 때 콜론(:)은 객체의 속성을 키와 값으로 분리합니다.

+ +
var obj = { propertyKey: 'value' };
+
+ +

예제

+ +

콜론 vs. 등호

+ +

객체 초기자 구문에는 등호를 사용할 수 없으므로 아래 예제는 실패합니다.

+ +
var obj = { propertyKey = 'value' };
+// SyntaxError: missing : after property id
+
+ +

콜론을 사용하거나 객체를 생성한 뒤에 대괄호를 사용하여 새로운 속성을 할당하는 것이 바릅니다.

+ +
var obj = { propertyKey: 'value' };
+
+// 또는
+
+var obj = { };
+obj['propertyKey'] = 'value';
+
+ +

빈 속성

+ +

아래와 같이 빈 속성을 만들 수 없습니다:

+ +
var obj = { propertyKey; };
+// SyntaxError: missing : after property id
+
+ +

만약 값 없이 속성을 정의해야 한다면 값으로 {{jsxref("null")}}을 지정할 수 있습니다.

+ +
var obj = { propertyKey: null };
+ +

계산된 속성

+ +

식으로 속성의 키를 만드는 경우 대괄호를 사용해야 합니다. 그렇지 않으면 속성 이름에 계산된 값을 사용할 수 없습니다:

+ +
var obj = { 'b'+'ar': 'foo' };
+// SyntaxError: missing : after property id
+
+ +

식에 대괄호를 넣으세요 []:

+ +
var obj = { ['b'+'ar']: 'foo' };
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/missing_curly_after_property_list/index.html b/files/ko/web/javascript/reference/errors/missing_curly_after_property_list/index.html new file mode 100644 index 0000000000..8e0abf94db --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_curly_after_property_list/index.html @@ -0,0 +1,47 @@ +--- +title: 'SyntaxError: missing } after property list' +slug: Web/JavaScript/Reference/Errors/Missing_curly_after_property_list +translation_of: Web/JavaScript/Reference/Errors/Missing_curly_after_property_list +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
SyntaxError: missing } after property list
+
+ +

에러 유형

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘못 된 걸까?

+ +

객체를 초기화 하는 부분 어딘가에 구문에 실수가 있습니다. 실제로 빠진 중괄호 일 수도 있지만, 누락 된 쉼표 일 수도 있습니다. 또한 닫는 중괄호나 괄호가 올바른 순서인지 확인하세요. 코드를 들여쓰기하거나 서식을 지정하면 좀 더 보기 쉽습니다.

+ +

예시

+ +

쉼표를 까먹은 경우

+ +

종종 객체 초기화 과정에서 쉼표를 빠트리는 경우가 있습니다:

+ +
var obj = {
+  a: 1,
+  b: { myProp: 2 }
+  c: 3
+};
+
+ +

올바른 예시는 다음과 같습니다:

+ +
var obj = {
+  a: 1,
+  b: { myProp: 2 },
+  c: 3
+};
+
+ +

더 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/missing_initializer_in_const/index.html b/files/ko/web/javascript/reference/errors/missing_initializer_in_const/index.html new file mode 100644 index 0000000000..be116cf3a4 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_initializer_in_const/index.html @@ -0,0 +1,55 @@ +--- +title: 'SyntaxError: missing = in const declaration' +slug: Web/JavaScript/Reference/Errors/Missing_initializer_in_const +translation_of: Web/JavaScript/Reference/Errors/Missing_initializer_in_const +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
SyntaxError: Const must be initalized (Edge)
+SyntaxError: missing = in const declaration (Firefox)
+SyntaxError: Missing initializer in const declaration (Chrome)
+
+ +

에러 유형

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘못되었나요?

+ +

상수는 일반적인 실행 중에 프로그램에 의해 변경될 수 없는 값입니다. 상수는 재할당되거나 재선언될 수 없습니다. 자바스크립트에서 상수는 const 키워드를 사용해 선언됩니다. 상수는 이니셜라이저가 필요합니다. 다시말해, 한 문장 안에 선언과 동시에 초기화가 이루어져야 합니다 (따라서 추후 수정 불가).

+ +

예제

+ +

const 이니셜라이저가 빠진 경우

+ +

var 또는 let과 달리, const 선언에서는 반드시 값을 정의해야 합니다.

+ +
const COLUMNS;
+// SyntaxError: missing = in const declaration
+ +

에러 수정

+ +

해당 에러를 수정하기 위해서 여러가지 방법이 존재합니다. 문제 상황에서 상수를 사용해 무엇을 하려 했는지 확인해보세요.

+ +

상수 값 추가

+ +

선언과 같은 문장에 상수 값을 정의합니다.

+ +
const COLUMNS = 80;
+ +

const, letvar?

+ +

상수를 선언할 목적이 아니었다면 const를 사용하지 마세요. let 키워드를 이용한 블록범위 변수, 또는 var 키워드를 이용한 전역 변수를 사용할 수 있습니다. 두 가지 경우 모두 초기값을 요구하지 않습니다.

+ +
let columns;
+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/missing_name_after_dot_operator/index.html b/files/ko/web/javascript/reference/errors/missing_name_after_dot_operator/index.html new file mode 100644 index 0000000000..a549e48e51 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_name_after_dot_operator/index.html @@ -0,0 +1,63 @@ +--- +title: 'SyntaxError: missing name after . operator' +slug: Web/JavaScript/Reference/Errors/Missing_name_after_dot_operator +translation_of: Web/JavaScript/Reference/Errors/Missing_name_after_dot_operator +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
SyntaxError: missing name after . operator
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘 못 되었을까?

+ +

점 연산자 (.)는 프로퍼티 접근을 위해 사용합니다. 접근해야 하는 프로퍼티 명은 제대로 명시 해야 합니다. 연산 프로퍼티에 접근하려면, 점 연산자를 사용하지 않고 대괄호를 사용하는 것으로 프로퍼티 접근 방식을 바꿔야 합니다. 이런 방식들이 표현식의 계산을 수행시켜줄 것입니다. 아마 당신은 연결을 하려고 했을 것입니다. 이 경우에는 더하기 연산자(+)가 필요합니다. 아래의 예제를 봐주세요. 

+ +

예제

+ +

프로퍼티 접근

+ +

JavaScript 프로퍼티 접근자는 점(.) 또는 대괄호([]) 중 하나만 사용한다. 대괄호는 연산 프로퍼티에 접근을 허용합니다.   

+ +
var obj = { foo: { bar: "baz", bar2: "baz2" } };
+var i = 2;
+
+obj.[foo].[bar]
+// SyntaxError: missing name after . operator
+
+obj.foo."bar"+i;
+// SyntaxError: missing name after . operator
+
+ +

이 코드를 고치려면, 오브젝트에 이런 식으로 접근해야 합니다.:

+ +
obj.foo.bar; // "baz"
+// 또는 대신에
+obj["foo"]["bar"]; // "baz"
+
+// 연산 프로퍼티는 대괄호가 필요합니다.
+obj.foo["bar" + i]; // "baz2"
+
+ +

프로퍼티 접근 vs. 연결

+ +

다른 프로그램 언어를 사용하다 왔다면 ( {{Glossary("PHP")}} 같은), 점 연산자(.)와 연결 연산자(+)를 혼동해서 쓰기가 더 쉬울 것입니다.

+ +
console.log("Hello" . "world");
+
+// SyntaxError: missing name after . operator
+ +

대신에 결합을 위해서는 더하기 표식을 사용해야 합니다.:

+ +
console.log("Hello" + "World");
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html b/files/ko/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html new file mode 100644 index 0000000000..1f28ac1104 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html @@ -0,0 +1,38 @@ +--- +title: 'SyntaxError: missing ) after argument list' +slug: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list +translation_of: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
SyntaxError: missing ) after argument list
+
+ +

Error type

+ +

{{jsxref("SyntaxError")}}.

+ +

What went wrong?

+ +

function을 호출하는 방식에 에러가 있는 것입니다. 맞춤법, 연산자 누락 또는 이스케이프 처리를 하지 않는 문자열과 같은 것으로 발생될 수 있습니다.

+ +

Examples

+ +

문자열을 합치는 "+" 연산자가 없기 때문에, Javascript는 log function에 대한 인수를 "PI: "로 인식을 합니다. 이 경우, 닫침 괄호가 누락된 것으로 인식을 합니다.

+ +
console.log('PI: ' Math.PI);
+// SyntaxError: missing ) after argument list
+
+ +

You can correct the log call by adding the "+" operator:

+ +
console.log('PI: ' + Math.PI);
+// "PI: 3.141592653589793"
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html b/files/ko/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html new file mode 100644 index 0000000000..cd7b368aa4 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_parenthesis_after_condition/index.html @@ -0,0 +1,65 @@ +--- +title: 'SyntaxError: missing ) after condition' +slug: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_condition +translation_of: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_condition +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
SyntaxError: missing ) after condition
+
+ +

에러 유형

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘못 된 걸까?

+ +

if조건문에 에러가 있습니다. 어떠한 프로그래밍 언어에서든 코드는 입력값에 따라 의사를 결정하고 행동을 수행해야합니다. 지정된 조건이 true이면 if 문이 명령문을 실행합니다. 자바스크립트에서는 이 조건이 if문 다음의 괄호에 있어야 합니다. 다음은 그 예시입니다.

+ +
if (condition) {
+  // do something if the condition is true
+}
+ +

예시

+ +

실수가 있을 수 있으니, 모든 괄호를 주의깊게 확인하세요.

+ +
if (3 > Math.PI {
+  console.log("wait what?");
+}
+
+// SyntaxError: missing ) after condition
+
+ +

이 코드를 고치기 위해선, 조건문을 괄호로 닫아야 합니다.

+ +
if (3 > Math.PI) {
+  console.log("wait what?");
+}
+ +

다른 프로그래밍 언어를 배운 경우, 자바스크립트에서는 다르게 쓰이거나, 쓰이지 않는 키워드를 사용하기 쉽습니다.

+ +
if (done is true) {
+ console.log("we are done!");
+}
+
+// SyntaxError: missing ) after condition
+
+ +

이 경우 올바른 비교연산자를 사용해야 합니다. 그 예시로:

+ +
if (done === true) {
+ console.log("we are done!");
+}
+ +

더 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/ko/web/javascript/reference/errors/missing_semicolon_before_statement/index.html new file mode 100644 index 0000000000..ec3334b52f --- /dev/null +++ b/files/ko/web/javascript/reference/errors/missing_semicolon_before_statement/index.html @@ -0,0 +1,63 @@ +--- +title: 'SyntaxError: missing ; before statement' +slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
SyntaxError: missing ; before statement
+
+ +

오류 타입

+ +

{{jsxref("SyntaxError")}}.

+ +

무엇이 잘 못 되었나?

+ +

어딘가에 세미 콜론(;)이 빠져 있습니다.  JavaScript 구문은 반드시 세미 콜론으로 끝나야 합니다. 일부는 자동 세미콜론 삽입 (automatic semicolon insertion (ASI))의 영향을 받습니다. 그러나 이 경우에는 직접 세미 콜론을 써주어야 합니다. 그래야 JavaScript가 올바르게 해석 될 수 있기 때문입니다.

+ +

그러나, 가끔, 이 오류는 또 다른 오류의 결과로도 나타날 수도 있습니다. 문자열을 escape 문자로 적절히 처리해 주지 않았을 때, 또는 var 키워드를 잘 못 사용했을 때와 같은 경우 입니다. 또한 어딘가에 너무 많은 괄호 기호를 사용했을 것입니다. 이 오류가 발생했을 때에는 문법을 신중히 검토해야 합니다. 

+ +

예제

+ +

Escape 처리되지 않은 문자열

+ +

이 오류는 문자열을 escape 처리 하지 않았을 때, JavaScript 엔진이 문자열 끝을 미리 예측하여 발생합니다. 예를 들자면 아래와 같습니다. :

+ +
var foo = 'Tom's bar';
+// SyntaxError: missing ; before statement
+ +

문자열을 묶어줄 때 쌍 따옴표를 사용하거나, 역슬래시를 이용해서 홑따옴표를 사용 할 수 있습니다. :

+ +
var foo = "Tom's bar";
+var foo = 'Tom\'s bar';
+
+ +

var와 함께 선언하는 것

+ +

이미 var 선언된 object나 array의 요소를 새로 선언 할 수 없습니다.

+ +
var obj = {};
+var obj.foo = 'hi'; // SyntaxError missing ; before statement
+
+var array = [];
+var array[0] = 'there'; // SyntaxError missing ; before statement
+
+ +

대신에, var  키워드를 생략하고 정의합니다. :

+ +
var obj = {};
+obj.foo = 'hi';
+
+var array = [];
+array[0] = 'there';
+
+ +

참조 문서

+ + diff --git a/files/ko/web/javascript/reference/errors/more_arguments_needed/index.html b/files/ko/web/javascript/reference/errors/more_arguments_needed/index.html new file mode 100644 index 0000000000..41137d2f63 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/more_arguments_needed/index.html @@ -0,0 +1,45 @@ +--- +title: 'TypeError: More arguments needed' +slug: Web/JavaScript/Reference/Errors/More_arguments_needed +translation_of: Web/JavaScript/Reference/Errors/More_arguments_needed +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
TypeError: argument is not an Object and is not null (Edge)
+TypeError: Object.create requires at least 1 argument, but only 0 were passed
+TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 0 were passed
+TypeError: Object.defineProperties requires at least 1 argument, but only 0 were passed
+
+ +

에러 타입

+ +

{{jsxref("TypeError")}}.

+ +

무엇이 잘 못 되었을까?

+ +

함수 호출 시 에러가 있습니다. 더 많은 인수가 주어져야 합니다.

+ +

예제

+ +

{{jsxref("Object.create()")}} 메서드는 적어도 1개의 인자가 필요하며, {{jsxref("Object.setPrototypeOf()")}} 메서드는 적어도 2개의 인자가 필요합니다.:

+ +
var obj = Object.create();
+// TypeError: Object.create requires at least 1 argument, but only 0 were passed
+
+var obj = Object.setPrototypeOf({});
+// TypeError: Object.setPrototypeOf requires at least 2 arguments, but only 1 were passed
+
+ +

예를 들면, 이렇게 프로토 타입으로  {{jsxref("null")}}를 세팅해서 고칠 수 있습니다.:

+ +
var obj = Object.create(null);
+
+var obj = Object.setPrototypeOf({}, null);
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/negative_repetition_count/index.html b/files/ko/web/javascript/reference/errors/negative_repetition_count/index.html new file mode 100644 index 0000000000..b2437c9ad8 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/negative_repetition_count/index.html @@ -0,0 +1,40 @@ +--- +title: 'RangeError: repeat count must be non-negative' +slug: Web/JavaScript/Reference/Errors/Negative_repetition_count +translation_of: Web/JavaScript/Reference/Errors/Negative_repetition_count +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
RangeError: repeat count must be non-negative (Firefox)
+RangeError: Invalid count value (Chrome)
+
+ +

에러 형식

+ +

{{jsxref("RangeError")}}

+ +

무엇이 잘못되었을까?

+ +

{{jsxref("String.prototype.repeat()")}} 메소드가 사용되었습니다. 이 메소드는 문자열이 반복되는 수를 예측하는 카운트 파라메터를 가지고 있었습니다. 이 파라메터는 0보다 크고, 양의 {{jsxref("Infinity")}} 보다는 작으며, 음수는 될수 없습니다. 이 범위는 이렇게 표현 될 수 있습니다. : [0, +∞)

+ +

+ +

허용되지 않는 경우

+ +
'abc'.repeat(-1); // RangeError 
+ +

허용되는 경우

+ +
'abc'.repeat(0);    // ''
+'abc'.repeat(1);    // 'abc'
+'abc'.repeat(2);    // 'abcabc'
+'abc'.repeat(3.5);  // 'abcabcabc' (수는 정수로 변환될 것입니다.)
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/no_variable_name/index.html b/files/ko/web/javascript/reference/errors/no_variable_name/index.html new file mode 100644 index 0000000000..e9d6ec6ee7 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/no_variable_name/index.html @@ -0,0 +1,79 @@ +--- +title: 'SyntaxError: missing variable name' +slug: Web/JavaScript/Reference/Errors/No_variable_name +translation_of: Web/JavaScript/Reference/Errors/No_variable_name +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
SyntaxError: missing variable name (Firefox)
+SyntaxError: Unexpected token = (Chrome)
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘 못 되었을까?

+ +

변수에 이름이 없습니다. 이것은 코드 내의 구문 에러 때문일 수도 있습니다. 어쩌면 콤마를 잘 못 된 곳에 찍었거나, 변수명을 지을 때 애를 먹었을 수도 있습니다. 그럴 수도 있죠! 작명은 너무 어려우니까요. 

+ +

예제

+ +

이름을 잃은 변수

+ +
var = "foo";
+
+ +

좋은 이름을 떠올리기 어려웠을 거예요. 우리 모두 겪는 일이죠.

+ +
var ohGodWhy = "foo";
+ +

예약어는 변수명이 될 수 없어요

+ +

예약어로 지정된 이름들이 변수로 쓰여 있습니다. 이것들은 사용할 수 없어요. 미안합니다. :(

+ +
var debugger = "whoop";
+// SyntaxError: missing variable name
+
+ +

여러 변수를 선언하기

+ +

여러 변수를 한 번에 선언할 때에는 콤마에 주의를 기울여야 합니다. 쓸 데없는 콤마를 더 찍지는 않았는지? 무심코 세미콜론 대신 콤마를 찍지는 않았는지? 

+ +
var x, y = "foo",
+var x, = "foo"
+
+var first = document.getElementById('one'),
+var second = document.getElementById('two'),
+
+// SyntaxError: missing variable name
+
+ +

올바르게 수정한 버전:

+ +
var x, y = "foo";
+var x = "foo";
+
+var first = document.getElementById('one');
+var second = document.getElementById('two');
+ +

배열

+ +

JavaScript 의 {{jsxref("Array")}} 리터럴은 대괄호로 감싸주어야 합니다. 이건 동작하지 않아요.

+ +
var arr = 1,2,3,4,5;
+// SyntaxError: missing variable name
+
+ +

이렇게 해야 맞습니다:

+ +
var arr = [1,2,3,4,5];
+ +

더 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/not_a_codepoint/index.html b/files/ko/web/javascript/reference/errors/not_a_codepoint/index.html new file mode 100644 index 0000000000..782cea10f2 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/not_a_codepoint/index.html @@ -0,0 +1,51 @@ +--- +title: 'RangeError: argument is not a valid code point' +slug: Web/JavaScript/Reference/Errors/Not_a_codepoint +translation_of: Web/JavaScript/Reference/Errors/Not_a_codepoint +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
RangeError: {0} is not a valid code point (Firefox)
+RangeError: Invalid code point {0} (Chrome)
+
+ +

에러 형식

+ +

{{jsxref("RangeError")}}

+ +

무엇이 잘못되었을까?

+ +

{{jsxref("String.fromCodePoint()")}} 메소드는 유효한 코드 포인트(code point)만을 받아들입니다.

+ +

code point는 유니코드의 코드 스페이스 값으로, 0부터 0x10FFFF까지의 정수 범위입니다.

+ +

{{jsxref("NaN")}}을 사용하는 값, 음수 (-1),  정수가 아닌 수(3.14), 또는 0x10FFFF (1114111) 보다 큰 값은 이 함수에 적용될 수 없습니다.

+ +

+ +

유효하지 않은 경우

+ +
String.fromCodePoint('_');      // RangeError
+String.fromCodePoint(Infinity); // RangeError
+String.fromCodePoint(-1);       // RangeError
+String.fromCodePoint(3.14);     // RangeError
+String.fromCodePoint(3e-2);     // RangeError
+String.fromCodePoint(NaN);      // RangeError
+ +

유효한 경우

+ +
String.fromCodePoint(42);       // "*"
+String.fromCodePoint(65, 90);   // "AZ"
+String.fromCodePoint(0x404);    // "\u0404"
+String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
+String.fromCodePoint(194564);   // "\uD87E\uDC04"
+String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/not_a_constructor/index.html b/files/ko/web/javascript/reference/errors/not_a_constructor/index.html new file mode 100644 index 0000000000..80bc235779 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/not_a_constructor/index.html @@ -0,0 +1,91 @@ +--- +title: 'TypeError: "x" is not a constructor' +slug: Web/JavaScript/Reference/Errors/Not_a_constructor +translation_of: Web/JavaScript/Reference/Errors/Not_a_constructor +--- +
{{jsSidebar("Errors")}}
+ +

메세지

+ +
TypeError: "x" is not a constructor
+
+TypeError: Math is not a constructor
+TypeError: JSON is not a constructor
+TypeError: Symbol is not a constructor
+TypeError: Reflect is not a constructor
+TypeError: Intl is not a constructor
+TypeError: SIMD is not a constructor
+TypeError: Atomics is not a constructor
+
+ +

오류 유형

+ +

{{jsxref("TypeError")}}

+ +

뭐가 잘못된 거죠?

+ +

객체 혹은 변수를 생성자로 사용하려고 했습니다, 하지만 객체(혹은 변수)가 생성자가 아닙니다. 생성자가 무엇인지에 대한 자세한 정보는 {{Glossary("constructor")}} 혹은 new operator 를 참조하시기 바랍니다.

+ +

{{jsxref("String")}} 혹은 {{jsxref("Array")}}와 같이 new,를 사용하여 생성할 수 있는 전역 객체들이 있습니다. 하지만 일부 전역 객체들은 그렇지 않고 속성과 메서드가 정적입니다. 다음의 자바스크립트 표준 내장 객체들은 생성자가 아닙니다: {{jsxref("Math")}}, {{jsxref("JSON")}}, {{jsxref("Symbol")}}, {{jsxref("Reflect")}}, {{jsxref("Intl")}}, {{jsxref("SIMD")}}, {{jsxref("Atomics")}}.

+ +

Generator functions 또한 생성자로 사용될 수 없습니다.

+ +

예시

+ +

유효하지 않은 경우

+ +
var Car = 1;
+new Car();
+// TypeError: Car is not a constructor
+
+new Math();
+// TypeError: Math is not a constructor
+
+new Symbol();
+// TypeError: Symbol is not a constructor
+
+function* f() {};
+var obj = new f;
+// TypeError: f is not a constructor
+
+ +

car 생성자

+ +

자동차(car) 객체를 만들고자 한다고 가정합니다. 이 객체의 타입을 car라 하고 make, model, and year 세 개의 프로퍼티를 갖습니다. 이를 위해 다음과 같은 함수를 작성할 것입니다:

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+
+ +

이제 다음과 같이 mycar 라 불리는 객체를 생성할 수 있습니다:

+ +
var mycar = new Car('Eagle', 'Talon TSi', 1993);
+ +

프라미스 이용

+ +

즉시 실행되는 프라미스를 반환하는 경우에는 새로운 Promise(...)를 생성할 필요가 없습니다.

+ +

아래는 올바른 방법이 아닙니다(프라미스 생성자가 제대로 호출되고 있지 않습니다). TypeError: this is not a constructor 예외를 던지게 됩니다:

+ +
return new Promise.resolve(true);
+
+ +

대신, Promise.resolve() 혹은 Promise.reject() 정적 메서드를 사용하십시오:

+ +
// This is legal, but unnecessarily long:
+return new Promise((resolve, reject) => { resolve(true); })
+
+// Instead, return the static method:
+return Promise.resolve(true);
+return Promise.reject(false);
+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/not_defined/index.html b/files/ko/web/javascript/reference/errors/not_defined/index.html new file mode 100644 index 0000000000..6b403dd848 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/not_defined/index.html @@ -0,0 +1,66 @@ +--- +title: 'ReferenceError: "x" is not defined' +slug: Web/JavaScript/Reference/Errors/Not_defined +translation_of: Web/JavaScript/Reference/Errors/Not_defined +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
ReferenceError: "x" is not defined
+
+ +

에러 타입

+ +

{{jsxref("ReferenceError")}}.

+ +

무엇이 잘못되었을까?

+ +

존재하지 않는 변수를 참조하는 곳이 있습니다. 이 변수는 선언되어야 합니다. 또는, 현재 스크립트나 {{Glossary("scope")}} 에서 사용이 가능하도록 해야합니다.

+ +
+

Note: 라이브러리(예를 들면 jQuery와 같은)의 로딩은, 반드시 코드에서  "$"와 같은 라이브러리 변수에 접근하기 이전에 수행되어야 합니다. 라이브러리를 로딩하는 {{HTMLElement("script")}} 태그가 그 변수를 사용하는 코드보다 앞에 위치하도록 하세요.

+
+ +

+ +

선언되지 않은 변수

+ +
foo.substring(1); // ReferenceError: foo is not defined
+
+ +

"foo" 변수는 어디에도 선언되지 않았습니다. {{jsxref("String.prototype.substring()")}} 메소드가 작동하도록 하기 위해서는 문자열을 필요로 합니다.

+ +
var foo = "bar";
+foo.substring(1); // "ar"
+ +

잘못된 스코프

+ +

변수는 현재의 실행 흐름 내에서 이용 가능해야합니다. 함수 내부에 정의된 변수는 다른 외부의 함수에서는 접근할 수 없습니다. 그 때문에, 변수는 함수의 스코프 내부에서만 정의 됩니다.

+ +
function numbers () {
+  var num1 = 2,
+      num2 = 3;
+  return num1 + num2;
+}
+
+console.log(num1); // ReferenceError: num1 is not defined
+ +

그러나, 함수는 모든 변수와 정의된 스코프 안에 정의된 함수에 접근할 수 있습니다. 따라서, 전역으로 정의된 함수는 전역에 정의된 모든 변수에도 접근할 수 있습니다.

+ +
var num1 = 2,
+    num2 = 3;
+
+function numbers () {
+  return num1 + num2;
+}
+
+console.log(num1); // 2
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/precision_range/index.html b/files/ko/web/javascript/reference/errors/precision_range/index.html new file mode 100644 index 0000000000..43ab7392e4 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/precision_range/index.html @@ -0,0 +1,92 @@ +--- +title: 'RangeError: precision is out of range' +slug: Web/JavaScript/Reference/Errors/Precision_range +translation_of: Web/JavaScript/Reference/Errors/Precision_range +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
RangeError: precision {0} out of range (Firefox)
+RangeError: toExponential() argument must be between 0 and 20 (Chrome)
+RangeError: toFixed() digits argument must be between 0 and 20 (Chrome)
+RangeError: toPrecision() argument must be between 1 and 21 (Chrome)
+
+ +

에러 형식

+ +

{{jsxref("RangeError")}}

+ +

무엇이 잘못되었을까?

+ +

아래의 메소드들 중 하나에서,  실행 인자(argument)가 정확도의 범위를 벗어났습니다. :

+ + + +

이 메소드들에게 허용된 범위는 0부터 20 (또는 21)까지 입니다. 하지만, ECMAScript 스펙은 아래의 범위까지 확장하여 허용하고 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodFirefox (SpiderMonkey)Chrome, Opera (V8)
{{jsxref("Number.prototype.toExponential()")}}0 부터 1000 부터 20
{{jsxref("Number.prototype.toFixed()")}}-20 부터 1000 부터 20
{{jsxref("Number.prototype.toPrecision()")}}1 부터 1001 부터 21
+ +

+ +

유효하지 않은 경우

+ +
77.1234.toExponential(-1);  // RangeError
+77.1234.toExponential(101); // RangeError
+
+2.34.toFixed(-100);         // RangeError
+2.34.toFixed(1001);         // RangeError
+
+1234.5.toPrecision(-1);     // RangeError
+1234.5.toPrecision(101);    // RangeError
+
+ +

유효한 경우

+ +
77.1234.toExponential(4); // 7.7123e+1
+77.1234.toExponential(2); // 7.71e+1
+
+2.34.toFixed(1); // 2.3
+2.35.toFixed(1); // 2.4 (note that it rounds up in this case)
+
+5.123456.toPrecision(5); // 5.1235
+5.123456.toPrecision(2); // 5.1
+5.123456.toPrecision(1); // 5
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/property_access_denied/index.html b/files/ko/web/javascript/reference/errors/property_access_denied/index.html new file mode 100644 index 0000000000..2468d0221a --- /dev/null +++ b/files/ko/web/javascript/reference/errors/property_access_denied/index.html @@ -0,0 +1,42 @@ +--- +title: 'Error: Permission denied to access property "x"' +slug: Web/JavaScript/Reference/Errors/Property_access_denied +translation_of: Web/JavaScript/Reference/Errors/Property_access_denied +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
Error: Permission denied to access property "x"
+
+ +

에러 형식

+ +

{{jsxref("Error")}}.

+ +

무엇이 잘못되었을까?

+ +

접근이 허가되지 않은 객체에 접근하기 위한 시도가 있었습니다. 아마 동일 출처 정책(same-origin policy)을 침해하여 다른 도메인으로부터 로드된 {{HTMLElement("iframe")}} 엘리먼트에 대한 것이었을 겁니다.

+ +

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe>
+    <script>
+      onload = function() {
+        console.log(frames[0].document);
+        // Error: Permission denied to access property "document"
+      }
+    </script>
+  </head>
+  <body></body>
+</html>
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/read-only/index.html b/files/ko/web/javascript/reference/errors/read-only/index.html new file mode 100644 index 0000000000..7260fd71f8 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/read-only/index.html @@ -0,0 +1,77 @@ +--- +title: 'TypeError: "x" is read-only' +slug: Web/JavaScript/Reference/Errors/Read-only +translation_of: Web/JavaScript/Reference/Errors/Read-only +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
TypeError: "x" is read-only (Firefox)
+TypeError: 0 is read-only (Firefox)
+TypeError: Cannot assign to read only property 'x' of #<Object> (Chrome)
+TypeError: Cannot assign to read only property '0' of [object Array] (Chrome)
+
+ +

에러 유형

+ +

{{jsxref("TypeError")}}

+ +

무엇이 잘못 된 걸까?

+ +

전역변수 또는 객체 프로퍼티가 읽기 전용으로 할당된 경우입니다.(엄밀히 따지자면 쓰기가 불가능한 데이터 속성입니다.)

+ +

이 에러는 엄격모드에서만 등장합니다.  엄격하지 않은 모드에서는 읽기전용 속성은 묵시적으로 무시됩니다.

+ +

예시

+ +

적절하지 않은 예

+ +

읽기 전용 속성은 아주 흔한 것은 아니지만, {{jsxref("Object.defineProperty()")}} 나 {{jsxref("Object.freeze()")}} 를 이용해 만들어 질 수 있습니다.

+ +
'use strict';
+var obj = Object.freeze({name: 'Elsa', score: 157});
+obj.score = 0;  // TypeError
+
+'use strict';
+Object.defineProperty(this, 'LUNG_COUNT', {value: 2, writable: false});
+LUNG_COUNT = 3;  // TypeError
+
+'use strict';
+var frozenArray = Object.freeze([0, 1, 2]);
+frozenArray[0]++;  // TypeError
+
+ +

자바 스크립트에는 몇 가지 읽기 전용 속성이 내장되어 있습니다. 아마도 수학적 상수를 재정의하려고 한 것 같습니다.

+ +
'use strict';
+Math.PI = 4;  // TypeError
+
+ +

이렇게는 불가능합니다.

+ +

전역변수 undefined  또한 읽기전용으로, 사람들이 모두 좋아하지 않는 "undefined is not a function" 에러가 다음과 같은 경우 등장합니다:

+ +
'use strict';
+undefined = function() {};  // TypeError: "undefined" is read-only
+
+ +

적절한 예

+ +
'use strict';
+var obj = Object.freeze({name: 'Score', points: 157});
+obj = {name: obj.name, points: 0};   // replacing it with a new object works
+
+'use strict';
+var LUNG_COUNT = 2;  // a `var` works, because it's not read-only
+LUNG_COUNT = 3;  // ok (anatomically unlikely, though)
+
+ +

더보기

+ + diff --git a/files/ko/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html b/files/ko/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html new file mode 100644 index 0000000000..53796ea87f --- /dev/null +++ b/files/ko/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.html @@ -0,0 +1,83 @@ +--- +title: 'TypeError: Reduce of empty array with no initial value' +slug: Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value +translation_of: Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
TypeError: 초기값이 없는 빈 배열에 대한 recude는 에러
+
+ +

Error type

+ +

{{jsxref("TypeError")}}

+ +

What went wrong?

+ +

자바스크립크에서 몇 몇의 reduce 함수들:

+ + + +

이러한 함수들은 선택적으로 초기값(initialValue)을 사용합니다.(콜백(callback)의 첫번째 호출에 대한 첫번째 인수로 사용됩니다.) 그러나, 만약에 초기값을 설정하지 않는다면, {{jsxref("Array")}} or {{jsxref("TypedArray")}}에 대한 첫번째 엘리먼트를 초기값으로 사용 합니다. 이런 경우에 초기값이 없기 때문에 빈 배열이 제공될 경우 오류가 발생 합니다.

+ +

Examples

+ +

Invalid cases

+ +

This problem appears frequently when combined with a filter ({{jsxref("Array.prototype.filter()")}}, {{jsxref("TypedArray.prototype.filter()")}}) which will remove all elements of the list. Thus leaving none to be used as the initial value.

+ +
var ints = [0, -1, -2, -3, -4, -5];
+ints.filter(x => x > 0)         // removes all elements
+    .reduce((x, y) => x + y)    // no more elements to use for the initial value.
+ +

Similarly, the same issue can happen if there is a typo in a selector, or an unexpected number of elements in a list:

+ +
var names = document.getElementsByClassName("names");
+var name_list = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name);
+
+ +

Valid cases

+ +

These problems can be solved in two different ways.

+ +

One way is to actually provide an initialValue  as the neutral element of the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for a concatenation.

+ +
var ints = [0, -1, -2, -3, -4, -5];
+ints.filter(x => x > 0)         // removes all elements
+    .reduce((x, y) => x + y, 0) // the initial value is the neutral element of the addition
+
+ +

Another way would be two to handle the empty case, either before calling reduce, or in the callback after adding an unexpected dummy initial value.

+ +
var names = document.getElementsByClassName("names");
+
+var name_list1 = "";
+if (names1.length >= 1)
+  name_list1 = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name);
+// name_list1 == "" when names is empty.
+
+var name_list2 = Array.prototype.reduce.call(names, (acc, name) => {
+  if (acc == "") // initial value
+    return name;
+  return acc + ", " + name;
+}, "");
+// name_list2 == "" when names is empty.
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/errors/reserved_identifier/index.html b/files/ko/web/javascript/reference/errors/reserved_identifier/index.html new file mode 100644 index 0000000000..8a1932d9cc --- /dev/null +++ b/files/ko/web/javascript/reference/errors/reserved_identifier/index.html @@ -0,0 +1,80 @@ +--- +title: 'SyntaxError: "x" is a reserved identifier' +slug: Web/JavaScript/Reference/Errors/Reserved_identifier +tags: + - 구문 에러 + - 예약어 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Reserved_identifier +--- +
{{jsSidebar("Errors")}}
+ +

메세지

+ +
SyntaxError: The use of a future reserved word for an identifier is invalid (Edge)
+SyntaxError: "x" is a reserved identifier (Firefox)
+SyntaxError: Unexpected reserved word (Chrome)
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘못되었을까?

+ +

예약어가 식별자로 쓰인 경우 발생하는 에러입니다. 이 키워드는 엄격(Strict) 모드와 느슨한(Sloppy) 모드에서 모두 예약어로 취급됩니다.

+ + + +

다음은 엄격 모드의 코드에서만 예약어로 취급됩니다:

+ + + +

예제

+ +

엄격 모드와 엄격하지 않은 모드에서의 예약어

+ +

enum 식별자는 일반적으로 예약되어 있습니다.

+ +
var enum = { RED: 0, GREEN: 1, BLUE: 2 };
+// SyntaxError: enum is a reserved identifier
+
+ +

엄격 모드의 코드에선 더 많은 식별자들이 예약되어 있습니다.

+ +
"use strict";
+var package = ["potatoes", "rice", "fries"];
+// SyntaxError: package is a reserved identifier
+
+ +

이 변수들의 이름을 변경해야 합니다.

+ +
var colorEnum = { RED: 0, GREEN: 1, BLUE: 2 };
+var list = ["potatoes", "rice", "fries"];
+ +

오래된 브라우저의 업데이트

+ +

새로운 구문을 사용하기 위해서는 최근 버전의 브라우저로 업데이트 해야 합니다. 예를 들어, 오래된 브라우저를 사용하고 있다면 let 또는 class 구현할 수 없습니다.

+ +
"use strict";
+class DocArchiver {}
+
+// SyntaxError: class is a reserved identifier
+// (오래된 버전의 브라우저에서만 에러가 발생합니다. 예) Firefox 44 이하)
+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/errors/resulting_string_too_large/index.html b/files/ko/web/javascript/reference/errors/resulting_string_too_large/index.html new file mode 100644 index 0000000000..20e28cbe2b --- /dev/null +++ b/files/ko/web/javascript/reference/errors/resulting_string_too_large/index.html @@ -0,0 +1,46 @@ +--- +title: 'RangeError: repeat count must be less than infinity' +slug: Web/JavaScript/Reference/Errors/Resulting_string_too_large +translation_of: Web/JavaScript/Reference/Errors/Resulting_string_too_large +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
RangeError: repeat count must be less than infinity and not overflow maximum string size (Firefox)
+(repeat count는 infinity보다 작아야하며, 최대 문자열 크기를 넘길 수 없습니다.)
+
+RangeError: Invalid count value (Chrome)
+
+ +

에러 형식

+ +

{{jsxref("RangeError")}}

+ +

무엇이 잘못되었을까?

+ +

 {{jsxref("String.prototype.repeat()")}} 메소드가 사용되었습니다. 이 메소드는 문자열을 반복하는 수를 예측하는 카운트 파라메터를 가지고 있었습니다. 그리고 이 파라메터는 0보다 커야하며, 양의 {{jsxref("Infinity")}} 보다 작아야 했으며, 음수는 허용되지 않았습니다. 이 값의 허용 범위는 이렇게 표현될 수 있습니다. : [0, +∞). 

+ +

결과인 문자열은 최대 문자열 크기보다 클 수 없지만, JavaScript 에서는 다를 수 있습니다. Firefox (SpiderMonkey) 에서의 최대 문자열 크기는 228 -1 (0xFFFFFFF)입니다.

+ +

+ +

허용되지 않는 경우

+ +
'abc'.repeat(Infinity); // RangeError
+'a'.repeat(2**28);      // RangeError
+
+ +

허용되는 경우

+ +
'abc'.repeat(0);    // ''
+'abc'.repeat(1);    // 'abc'
+'abc'.repeat(2);    // 'abcabc'
+'abc'.repeat(3.5);  // 'abcabcabc' (숫자는 정수로 변환될 것입니다.)
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/strict_non_simple_params/index.html b/files/ko/web/javascript/reference/errors/strict_non_simple_params/index.html new file mode 100644 index 0000000000..8c07f4b46a --- /dev/null +++ b/files/ko/web/javascript/reference/errors/strict_non_simple_params/index.html @@ -0,0 +1,107 @@ +--- +title: 'SyntaxError: "use strict" not allowed in function with non-simple parameters' +slug: Web/JavaScript/Reference/Errors/Strict_Non_Simple_Params +translation_of: Web/JavaScript/Reference/Errors/Strict_Non_Simple_Params +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
Firefox:
+SyntaxError: "use strict" not allowed in function with default parameter
+SyntaxError: "use strict" not allowed in function with rest parameter
+SyntaxError: "use strict" not allowed in function with destructuring parameter
+
+Chrome:
+SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list
+
+ +

Error type

+ +

{{jsxref("SyntaxError")}}.

+ +

무엇이 잘못 되었을까요?

+ +

 "use strict" 지시문은 다음 매개변수 중 한 개가 있는 함수의 맨 위에 작성됩니다:

+ + + +

"use strict" 지시문은 ECMAScript 동작에 따라 이러한 함수의 맨 위에 허용되지 않습니다.

+ +

Examples

+ +

기능 명세서

+ +

다음은 함수 sum 에는 기본 매개 변수 a=1b=2가 있는 경우입니다:

+ +
function sum(a = 1, b = 2) {
+  // SyntaxError: "use strict" not allowed in function with default parameter
+  'use strict';
+  return a + b;
+}
+
+ +

함수가 strict mode 모드에 있어야 하고 전체 스크립트 또는 포함된 함수가 strict mode에 있어도 괜찮으면 함수 외부에서 "use strict" 지시문을 이동할 수 있습니다:

+ +
'use strict';
+function sum(a = 1, b = 2) {
+  return a + b;
+}
+
+ +

함수 표현식

+ +

함수 표현식은 또 다른 해결방법을 사용할 수 있습니다:

+ +
var sum = function sum([a, b]) {
+  // SyntaxError: "use strict" not allowed in function with destructuring parameter
+  'use strict';
+  return a + b;
+};
+
+ +

이것은 다음 표현식으로 변환 될 수 있습니다:

+ +
var sum = (function() {
+  'use strict';
+  return function sum([a, b]) {
+    return a + b;
+  };
+})();
+
+ +

화살표 함수

+ +

화살표 함수가 this에 접근해야 하는 경우에는,  둘러싼 함수로 화살표 함수를 사용할 수 있습니다:

+ +
var callback = (...args) => {
+  // SyntaxError: "use strict" not allowed in function with rest parameter
+  'use strict';
+  return this.run(args);
+};
+
+ +

이것은 다음 표현식과 같이 변환될 수 있습니다:

+ +
var callback = (() => {
+  'use strict';
+  return (...args) => {
+    return this.run(args);
+  };
+})();
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/errors/too_much_recursion/index.html b/files/ko/web/javascript/reference/errors/too_much_recursion/index.html new file mode 100644 index 0000000000..90495a359b --- /dev/null +++ b/files/ko/web/javascript/reference/errors/too_much_recursion/index.html @@ -0,0 +1,50 @@ +--- +title: 'InternalError: too much recursion' +slug: Web/JavaScript/Reference/Errors/Too_much_recursion +translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
InternalError: too much recursion
+
+ +

에러 형식

+ +

InternalError.

+ +

무엇이 잘못되었을까?

+ +

자신을 호출하는 함수를 재귀 함수라고 합니다. 어떤 면에서, 재귀는 반복과 유사합니다. 둘 다 같은 코드를 여러 번 실행하며, 조건(무한 반복 피하기, 더 정확히 여기서 말하는 무한 재귀)이 있습니다. 너무 많거나 무한 번의 재귀가 발생할 경우, JavaScript는 이 에러를 던질 것입니다.

+ +

+ +

이 재귀 함수는 exit 조건에 따라 10번을 실행합니다.

+ +
function loop(x) {
+  if (x >= 10) // "x >= 10" is the exit condition
+    return;
+  // do stuff
+  loop(x + 1); // the recursive call
+}
+loop(0);
+ +

이 조건에 대하여 너무 높은 값을 설정 하면 작동하지 않게 됩니다.

+ +
function loop(x) {
+  if (x >= 1000000000000)
+    return;
+  // do stuff
+  loop(x + 1);
+}
+loop(0);
+
+// InternalError: too much recursion
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/undeclared_var/index.html b/files/ko/web/javascript/reference/errors/undeclared_var/index.html new file mode 100644 index 0000000000..688c92473d --- /dev/null +++ b/files/ko/web/javascript/reference/errors/undeclared_var/index.html @@ -0,0 +1,62 @@ +--- +title: 'ReferenceError: assignment to undeclared variable "x"' +slug: Web/JavaScript/Reference/Errors/Undeclared_var +translation_of: Web/JavaScript/Reference/Errors/Undeclared_var +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
ReferenceError: assignment to undeclared variable "x" (Firefox)
+ReferenceError: "x" is not defined (Chrome)
+ReferenceError: Variable undefined in strict mode (Edge)
+
+ +

에러 형식

+ +

엄격 모드(strict mode)에서만 발생하는 {{jsxref("ReferenceError")}} 경고.

+ +

무엇이 잘못되었을까?

+ +

선언되지 않은 변수로 값은 할당되었습니다. var 키워드가 없이 할당이 된 것입니다. 선언된 변수와 선언되지 않은 변수 사이에는 차이가 있는데, 이는 예상치 못한 결과를 가져오며, 때문에 JavaScript 엄격모드에서는 에러를 발생시키고 있습니다.

+ +

선언된 변수와 선언되지 않은 변수에 대하여 기억해야 할 세 가지:

+ + + +

더 많은 설명과 예제를 필요로 한다면 이 var 참조문서 페이지를 보세요.

+ +

선언되지 않은 변수 할당에 대한 에러는 엄격 모드(strict mode code)에서만 발생합니다. 비-엄격 코드에서는 조용히 묵인됩니다.

+ +

+ +

허용되지 않는 경우

+ +

이런 경우에는, 변수 "bar"는 선언되지 않은 변수가 됩니다.

+ +
function foo() {
+  "use strict";
+  bar = true;
+}
+foo(); // ReferenceError: assignment to undeclared variable bar
+
+ +

허용되는 경우

+ +

"bar" 를 선언된 변수로 만들기 위해서, var 키워드를 변수명 앞에 붙여줍니다.

+ +
function foo() {
+  "use strict";
+  var bar = true;
+}
+foo();
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/undefined_prop/index.html b/files/ko/web/javascript/reference/errors/undefined_prop/index.html new file mode 100644 index 0000000000..7919ca877d --- /dev/null +++ b/files/ko/web/javascript/reference/errors/undefined_prop/index.html @@ -0,0 +1,58 @@ +--- +title: 'ReferenceError: reference to undefined property "x"' +slug: Web/JavaScript/Reference/Errors/Undefined_prop +translation_of: Web/JavaScript/Reference/Errors/Undefined_prop +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
ReferenceError: reference to undefined property "x" (Firefox)
+
+ +

에러 형식

+ +

엄격 모드(strict mode)에서만 발생하는 {{jsxref("ReferenceError")}} 경고.

+ +

무엇이 잘못되었을까?

+ +

이 스크립트는 존재하지 않는 객체의 속성에 접근을 시도했습니다. 요소에 접근하는 방법에는 두 가지가 있습니다.; 더 자세히 알고 싶으시다면, 속성 접근자(property accessors) 참조 문서를 봐주세요. 

+ +

정의되지 않은 속성 참조에 대한 에러는 엄격 모드 코드(strict mode code)에서만 발생합니다. 비-엄격모드의 코드에서는 존재하지 않는 속성에 대한 접근은 조용히 무시됩니다.

+ +

+ +

허용되지 않는 경우

+ +

이 경우에는, 속성 bar 는 정의되지 않은 속성으로, ReferenceError 가 발생합니다.

+ +
"use strict";
+
+var foo = {};
+foo.bar; // ReferenceError: reference to undefined property "bar"
+
+ +

허용되는 경우

+ +

에러를 피하기 위해서는, 접근을 시도하기 앞서, 객체에 bar 에 대한 정의를 추가하거나 bar 속성의 존재 여부를 확인해야 합니다.; 아래와 같이 {{jsxref("Object.prototype.hasOwnProperty()")}} method)를 사용하는 것이 하나의 방법이 될 수 있습니다.:

+ +
"use strict";
+
+var foo = {};
+
+// bar 속성을 정의한다.
+
+foo.bar = "moon";
+console.log(foo.bar); // "moon"
+
+// bar에 접근하기 전에 존재 하는지 확인한다.
+
+if (foo.hasOwnProperty("bar") {
+  console.log(foo.bar);
+}
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/unexpected_token/index.html b/files/ko/web/javascript/reference/errors/unexpected_token/index.html new file mode 100644 index 0000000000..91704a6006 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/unexpected_token/index.html @@ -0,0 +1,49 @@ +--- +title: 'SyntaxError: Unexpected token' +slug: Web/JavaScript/Reference/Errors/Unexpected_token +tags: + - 에러 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Errors/Unexpected_token +--- +
{{jsSidebar("Errors")}}
+ +

메시지

+ +
SyntaxError: expected expression, got "x"
+SyntaxError: expected property name, got "x"
+SyntaxError: expected target, got "x"
+SyntaxError: expected rest argument name, got "x"
+SyntaxError: expected closing parenthesis, got "x"
+SyntaxError: expected '=>' after argument list, got "x"
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘못되었나요?

+ +

특정 언어 구조를 예상했지만 무언가 다른 것이 있었습니다. 아마도, 간단한 오타일 것입니다.

+ +

예제

+ +

예상하지 못한 표현식

+ +

예를 들어, 함수를 호출할 때, 인수에서 마지막 부분에 콤마는 허용되지 않습니다. 자바스크립트는 계속해서 다른 인자가 있을 것이라고 기대하기 때문입니다.

+ +
Math.max(2, 42,);
+// SyntaxError: expected expression, got ')'
+
+ +

콤마를 생략하거나 다른 인수를 추가해 수정할 수 있습니다.

+ +
Math.max(2, 42);
+Math.max(2, 42, 13+37);
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/errors/unexpected_type/index.html b/files/ko/web/javascript/reference/errors/unexpected_type/index.html new file mode 100644 index 0000000000..527411ab9a --- /dev/null +++ b/files/ko/web/javascript/reference/errors/unexpected_type/index.html @@ -0,0 +1,67 @@ +--- +title: 'TypeError: "x" is (not) "y"' +slug: Web/JavaScript/Reference/Errors/Unexpected_type +tags: + - Errors + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Unexpected_type +--- +
{{jsSidebar("Errors")}}
+ +

Message

+ +
TypeError: "x" is (not) "y"
+
+Examples:
+TypeError: "x" is undefined
+TypeError: "x" is null
+TypeError: "undefined" is not an object
+TypeError: "x" is not an object or null
+TypeError: "x" is not a symbol
+
+ +

Error type

+ +

{{jsxref("TypeError")}}.

+ +

What went wrong?

+ +

그것은 정확하지 않은 형태이다. 그것은 가끔{{jsxref("undefined")}} 나 {{jsxref("null")}} 값을 발생한다.

+ +

또한, {{jsxref("Object.create()")}} 또는 {{jsxref("Symbol.keyFor()")}}와 같은 메서드는 반드시 제공되어야하는 특별한 형태를 요구한다.

+ +

Examples

+ +

Invalid cases

+ +
// undefined and null cases on which the substring method won't work
+var foo = undefined;
+foo.substring(1); // TypeError: foo is undefined
+
+var foo = null;
+foo.substring(1); // TypeError: foo is null
+
+
+// Certain methods might require a specific type
+var foo = {}
+Symbol.keyFor(foo); // TypeError: foo is not a symbol
+
+var foo = 'bar'
+Object.create(foo); // TypeError: "foo" is not an object or null
+
+ +

Fixing the issue

+ +

undefined 나 null 값을 가진 null 포인터를 고치기 위해서 아래 예제와 같이 typeof 연산자를 사용할 수 있다.

+ +
if (typeof foo !== 'undefined') {
+  // Now we know that foo is defined, we are good to go.
+}
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/errors/unnamed_function_statement/index.html b/files/ko/web/javascript/reference/errors/unnamed_function_statement/index.html new file mode 100644 index 0000000000..b7afe67563 --- /dev/null +++ b/files/ko/web/javascript/reference/errors/unnamed_function_statement/index.html @@ -0,0 +1,118 @@ +--- +title: 'SyntaxError: function statement requires a name' +slug: Web/JavaScript/Reference/Errors/Unnamed_function_statement +tags: + - IIEF + - 객체 메소드 + - 구문 에러 + - 자바스크립트 + - 콜백 함수 + - 함수 이름 +translation_of: Web/JavaScript/Reference/Errors/Unnamed_function_statement +--- +
{{jsSidebar("Errors")}}
+ +

메세지

+ +
Syntax Error: Expected identifier (Edge)
+SyntaxError: function statement requires a name [Firefox]
+SyntaxError: Unexpected token ( [Chrome]
+
+ +

에러 타입

+ +

{{jsxref("SyntaxError")}}

+ +

무엇이 잘못되었을까?

+ +

함수 구문(Function statement)은 이름이 필수입니다. 함수가 정의된 방법에 따라 함수의 이름을 짓거나 함수 표현식(Function expression) {{Glossary("IIFE")}}으로 작성하거나, 함수가 맥락에 맞게 제대로 작성되었는지 확인해야 합니다.

+ +

예제

+ +

구문 vs 표현식

+ +

함수 구문(또는 함수 선언)은 이름이 필요하므로 아래 예제는 동작하지 않습니다:

+ +
function () {
+  return 'Hello world';
+}
+// SyntaxError: function statement requires a name
+
+ +

대신 함수 표현식을 사용할 수 있습니다:

+ +
var greet = function() {
+  return 'Hello world';
+};
+ +

또는, 선언하자마자 바로 실행되는 IIFE (Immediately Invoked Function Expression)를 사용할 수 있습니다. 이 경우 몇 개의 괄호가 더 필요합니다:

+ +
(function () {
+
+})();
+ +

레이블을 붙인 함수

+ +

만약 함수 레이블을 사용하는 경우 function 키워드 뒤에 함수 이름이 필요하므로 아래 예제는 동작하지 않습니다:

+ +
function Greeter() {
+  german: function () {
+    return "Moin";
+  }
+}
+// SyntaxError: function statement requires a name
+
+ +

아래 예제는 동작합니다:

+ +
function Greeter() {
+  german: function g() {
+    return "Moin";
+  }
+}
+ +

객체 메소드

+ +

만약 객체 메소드를 만드는 경우 먼저 객체를 만들어야 합니다. 객체 메소드의 경우 아래 예제와 같이 function 키워드 뒤에 이름이 없어도 정상적으로 동작합니다.

+ +
var greeter = {
+  german: function () {
+    return "Moin";
+  }
+};
+ +

콜백 구문

+ +

콜백을 사용하는 경우 구문을 확인해야 합니다. 괄호와 쉼표는 구문을 어렵게 만듭니다.

+ +
promise.then(
+  function() {
+    console.log("success");
+  });
+  function() {
+    console.log("error");
+}
+// SyntaxError: function statement requires a name
+
+ +

올바르게 변경하면:

+ +
promise.then(
+  function() {
+    console.log("success");
+  },
+  function() {
+    console.log("error");
+  }
+);
+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/functions/arguments/@@iterator/index.html b/files/ko/web/javascript/reference/functions/arguments/@@iterator/index.html new file mode 100644 index 0000000000..454c8111b8 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/arguments/@@iterator/index.html @@ -0,0 +1,78 @@ +--- +title: 'arguments[@@iterator]()' +slug: Web/JavaScript/Reference/Functions/arguments/@@iterator +tags: + - Deprecated + - Functions + - JavaScript + - Property + - arguments +translation_of: Web/JavaScript/Reference/Functions/arguments/@@iterator +--- +
{{jsSidebar("Functions")}}
+ +

@@iterator 속성의 초기값은 {{jsxref("Array.prototype.values")}} 속성의 초기값과 같은 함수 객체입니다.

+ +

구문

+ +
arguments[Symbol.iterator]()
+ +

예제

+ +

for...of 반복문을 사용한 반복

+ +
function f() {
+  // 브라우저가 for...of 반복문과
+  // for 반복문 안의 let 범위의 변수를 지원해야 합니다.
+  for (let letter of arguments) {
+    console.log(letter);
+  }
+}
+f('w', 'y', 'k', 'o', 'p');
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-createunmappedargumentsobject', ' CreateUnmappedArgumentsObject')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ES6', '#sec-createmappedargumentsobject', ' CreateMappedArgumentsObject')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-createunmappedargumentsobject', 'CreateUnmappedArgumentsObject')}}{{Spec2('ESDraft')}} 
{{SpecName('ESDraft', '#sec-createmappedargumentsobject', 'CreateMappedArgumentsObject')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.functions.arguments.@@iterator")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/functions/arguments/callee/index.html b/files/ko/web/javascript/reference/functions/arguments/callee/index.html new file mode 100644 index 0000000000..13ab0c948d --- /dev/null +++ b/files/ko/web/javascript/reference/functions/arguments/callee/index.html @@ -0,0 +1,203 @@ +--- +title: arguments.callee +slug: Web/JavaScript/Reference/Functions/arguments/callee +tags: + - Deprecated + - Functions + - JavaScript + - Property + - arguments +translation_of: Web/JavaScript/Reference/Functions/arguments/callee +--- +
{{jsSidebar("Functions")}}
+ +

arguments.callee 속성(property)은 현재 실행 중인 함수를 포함합니다.

+ +

설명

+ +

calleearguments 객체의 속성입니다. 그 함수의 몸통(body) 내에서 현재 실행 중인 함수를 참조하는 데 쓰일 수 있습니다. 이는 함수의 이름을 알 수 없는 경우에 유용합니다, 가령 이름 없는 함수 식(또한 "익명 함수"라 함) 내에서.

+ +
경고: ECMAScript 제5판(ES5) 은 엄격 모드에서 arguments.callee()의 사용을 금합니다. function 식(expression)에 이름을 주거나 함수 자체를 호출해야 하는 곳에 function 선언을 사용하여 arguments.callee() 사용을 피하세요.
+ +

arguments.callee는 왜 ES5 엄격 모드에서 제거되었나요?

+ +

(olliej의 Stack Overflow 답변에서 고쳐씀)

+ +

초기 버전 JavaScript는 유명(named) 함수 식을 허용하지 않습니다. 그리고 이 때문에 재귀(recursive) 함수 식을 만들 수 없습니다.

+ +

예를 들어, 이 구문은 작동됩니다:

+ +
function factorial (n) {
+    return !(n > 1) ? 1 : factorial(n - 1) * n;
+}
+
+[1,2,3,4,5].map(factorial);
+ +

하지만 다음은:

+ +
[1,2,3,4,5].map(function (n) {
+    return !(n > 1) ? 1 : /* what goes here? */ (n - 1) * n;
+});
+ +

아닙니다. 이를 우회하기 위해 arguments.callee가 추가되었고 이와 같이 할 수 있습니다

+ +
[1,2,3,4,5].map(function (n) {
+    return !(n > 1) ? 1 : arguments.callee(n - 1) * n;
+});
+ +

그러나, 이는 실로 정말 나쁜 해결책이었습니다. 이는 (다른 arguments, calleecaller 문제와 함께) 일반적인 경우에 인라인 및 tail 재귀를 불가능케 하기에 (tracing 등을 통해 선택한 경우에 그것을 달성할 수 있지만 최고의 코드는 검사가 달리 필요하지 않기에 차선입니다.) 다른 주요 문제는 그 재귀 호출이 다른 this 값을 갖는 것입니다. 가령:

+ +
var global = this;
+
+var sillyFunction = function (recursed) {
+    if (!recursed) { return arguments.callee(true); }
+    if (this !== global) {
+        alert("This is: " + this);
+    } else {
+        alert("This is the global");
+    }
+}
+
+sillyFunction();
+ +

ECMAScript 3은 유명(named) 함수 식을 허용해서 이 문제를 해결했습니다. 예를 들면:

+ +
[1,2,3,4,5].map(function factorial (n) {
+    return !(n > 1) ? 1 : factorial(n-1)*n;
+});
+ +

이는 많은 이점이 있습니다:

+ + + +

사라지게 됐던 또 다른 기능은 arguments.callee.caller 또는 더 명확하게 Function.caller였습니다. 이는 왜일까요? 자, 어느 시점에서든 당신은 모든 함수의 스택 상 가장 깊은 caller를 찾을 수 있고 위에서 말했듯이 호출 스택 보기는 한 가지 주요 효과가 있습니다: 이는 큰 수의 최적화를 불가능 또는 훨씬 훨씬 더 어렵게 합니다. 예를 들어, 함수 f가 익명(unknown) 함수를 호출하지 않음을 보장할 수 없는 경우, f를 인라인하는 게 가능하지 않습니다. 원래 사소하게 인라인 가능했을 지도 모를 모든 호출 사이트가 다수의 guard를 축적함을 뜻합니다:

+ +
function f (a, b, c, d, e) { return a ? b * c : d * e; }
+ +

JavaScript 인터프리터가 제공된 모든 인수가 호출이 행해진 그 시점에 숫자임을 보장할 수 없다면, 인라인된 코드 앞에 모든 인수에 대한 검사 삽입이 필요합니다. 그렇지 않으면 그 함수를 인라인할 수 없습니다. 이제 이 특정한 경우에 스마트 인터프리터는 더 최적이고 사용되지 않을 값은 확인하지 않을 검사를 재배열할 수 있어야 합니다. 그러나 많은 경우에 그건 그냥 가능하지 않고 그러므로 인라인은 불가능하게 됩니다.

+ +

+ +

익명 재귀 함수에서 arguments.callee 사용하기

+ +

재귀 함수는 자신을 참조할 수 있어야 합니다. 보통, 함수는 그 이름으로 자신을 참조합니다. 그러나, 익명 함수(함수 식 또는 Function 생성자로 생성될 수 있는)는 이름이 없습니다. 그러므로 그를 참조하는 액세스 가능한 변수가 없는 경우, 함수가 자신을 참조할 수 있는 유일한 방법은 arguments.callee에 의해서입니다.

+ +

다음 예는 차례로 팩토리얼 함수를 정의하고 반환하는 함수를 정의합니다. 이 예는 매우 실용적이지 않고 같은 결과가 유명 함수 식으로 달성될 수 없는 경우가 거의 없습니다.

+ +
function create() {
+   return function(n) {
+      if (n <= 1)
+         return 1;
+      return n * arguments.callee(n - 1);
+   };
+}
+
+var result = create()(5); // 반환값 120 (5 * 4 * 3 * 2 * 1)
+ +

좋은 대안 없는 arguments.callee의 사용

+ +

그러나, 다음과 같은 경우에는 arguments.callee에 대안이 없습니다. 그래서 그 사라짐(deprecation)은 버그가 될 수 있습니다 ({{Bug("725398")}} 참조):

+ +
function createPerson (sIdentity) {
+    var oPerson = new Function("alert(arguments.callee.identity);");
+    oPerson.identity = sIdentity;
+    return oPerson;
+}
+
+var john = createPerson("John Smith");
+
+john();
+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.2에서 구현됨
{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/functions/arguments/caller/index.html b/files/ko/web/javascript/reference/functions/arguments/caller/index.html new file mode 100644 index 0000000000..bcdc54c7dc --- /dev/null +++ b/files/ko/web/javascript/reference/functions/arguments/caller/index.html @@ -0,0 +1,93 @@ +--- +title: arguments.caller +slug: Web/JavaScript/Reference/Functions/arguments/caller +translation_of: Archive/Web/JavaScript/arguments.caller +--- +
{{jsSidebar("Functions")}}
+ +

이전의 arguments.caller 속성은 현재 실행한 함수를 적용하여 제공했었습니다. 이 속성은 삭제되었으며 더 이상 작동하지 않습니다.

+ +

설명

+ +

이 속성은 더 이상 이용할 수 없습니다. 하지만 {{jsxref("Function.caller")}} 는 사용할 수 있습니다.

+ +
function whoCalled() {
+   if (whoCalled.caller == null)
+      console.log('I was called from the global scope.');
+   else
+      console.log(whoCalled.caller + ' called me!');
+}
+ +

+ +

다음의 코드는 함수 내에서 arguments.caller 값을 확인하기 위해 사용되었지만, 더 이상 작동하지 않습니다.

+ +
function whoCalled() {
+   if (arguments.caller == null)
+      console.log('I was called from the global scope.');
+   else
+      console.log(arguments.caller + ' called me!');
+}
+
+ +

스펙

+ +

초기 정의된 부분이 아닙니다. JavaScript 1.1에서 구현되었으며, 잠재적인 보안 취약의 우려로 ({{bug(7224)}}) 삭제되었습니다.

+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/functions/arguments/index.html b/files/ko/web/javascript/reference/functions/arguments/index.html new file mode 100644 index 0000000000..98b5f1385b --- /dev/null +++ b/files/ko/web/javascript/reference/functions/arguments/index.html @@ -0,0 +1,189 @@ +--- +title: arguments 객체 +slug: Web/JavaScript/Reference/Functions/arguments +tags: + - Functions + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Functions/arguments +--- +
+
{{jsSidebar("Functions")}}
+
+ +

arguments 객체는 함수에 전달된 인수에 해당하는 Array 형태의 객체입니다.

+ +
+

Note: ES6 호환 코드를 작성 중이라면 되도록 나머지 매개변수 구문을 사용해야 합니다.

+
+ +
+

참고: "Array 형태"란 arguments가 {{jsxref("Array.length", "length")}} 속성과 더불어 0부터 인덱스 된 다른 속성을 가지고 있지만, {{jsxref("Array")}}의 {{jsxref("Array.prototype.forEach()", "forEach")}}, {{jsxref("Array.prototype.map()", "map")}}과 같은 내장 메서드를 가지고 있지 않다는 뜻입니다.

+
+ +
{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}
+ + + +

구문

+ +
arguments
+ +

설명

+ +

arguments 객체는 모든 함수 내에서 이용 가능한 지역 변수입니다. arguments 객체를 사용하여 함수 내에서 모든 인수를 참조할 수 있으며, 호출할 때 제공한 인수 각각에 대한 항목을 갖고 있습니다. 항목의 인덱스는 0부터 시작합니다.

+ +

예를 들어, 함수가 세 개의 인수를 받은 경우 다음과 같이 접근할 수 있습니다.

+ +
arguments[0]
+arguments[1]
+arguments[2]
+
+ +

각 인수를 설정하거나 재할당할 수도 있습니다.

+ +
arguments[1] = 'new value';
+
+ +

arguments 객체는 {{jsxref("Array")}}가 아닙니다. Array와 비슷하지만, {{jsxref("Array.prototype.length", "length")}} 빼고는 {{jsxref("Array.prototype.pop", "pop()")}}과 같은 어떤 Array 속성도 없습니다. 그러나 실제 Array로 변환할 수 있습니다:

+ +
var args = Array.prototype.slice.call(arguments);
+var args = [].slice.call(arguments);
+
+ +

arguments를 실제 Array로 변환하기 위해 ES2015의 {{jsxref("Array.from()")}} 메서드 또는 전개 연산자를 사용할 수도 있습니다.

+ +
var args = Array.from(arguments);
+var args = [...arguments];
+
+ +

당신이 형식상 받기로 선언된 것보다 많은 인수로 함수를 호출하는 경우 arguments 객체를 사용할 수 있습니다. 이 기법은 가변 인수가 전달될 수 있는 함수에 유용합니다. 함수에 전달된 인수의 수를 결정하기 위해 arguments.length를 쓰세요, 그 뒤에 arguments 객체를 사용하여 각 인수를 처리하세요. 함수 signature에 매개변수의 수를 결정하기 위해서는, Function.length 속성을 쓰세요.

+ +

속성

+ +
+
arguments.callee
+
현재 실행 중인 함수를 가리킵니다.
+
arguments.caller {{ Obsolete_inline() }}
+
현재 실행 중인 함수를 호출한 함수를 가리킵니다.
+
arguments.length
+
함수에 전달된 인수의 수를 가리킵니다.
+
arguments[@@iterator]
+
arguments의 각 인덱스 값을 포함하는 새로운 Array Iterator 객체를 반환합니다.
+
+ +

예제

+ +

여러 문자열을 연결하는 함수 정의하기

+ +

이 예는 여러 문자열을 연결하는 함수를 정의합니다. 함수의 유일한 형식 인수는 연결할 항목을 구분하는 문자를 지정하는 문자열입니다. 함수는 다음과 같이 정의됩니다:

+ +
function myConcat(separator) {
+  var args = Array.prototype.slice.call(arguments, 1);
+  return args.join(separator);
+}
+ +

이 함수에 인수를 얼마든지 전달할 수 있으며 리스트 내 항목처럼 각 인수를 사용하여 리스트를 만듭니다.

+ +
// "red, orange, blue" 반환
+myConcat(", ", "red", "orange", "blue");
+
+// "elephant; giraffe; lion; cheetah" 반환
+myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
+
+// "sage. basil. oregano. pepper. parsley" 반환
+myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
+ +

HTML 리스트를 만드는 함수 정의하기

+ +

이 예는 리스트 HTML을 포함하는 문자열을 만드는 함수를 정의합니다. 함수의 유일한 형식 인수는 리스트가 정렬되지 않은(bulluet(글 머리 기호)가 붙는) 경우 "u" 또는 정렬된(번호가 매겨진) 경우 "o"인 문자열입니다. 함수는 다음과 같이 정의됩니다:

+ +
function list(type) {
+  var result = "<" + type + "l><li>";
+  var args = Array.prototype.slice.call(arguments, 1);
+  result += args.join("</li><li>");
+  result += "</li></" + type + "l>"; // end list
+
+  return result;
+}
+ +

이 함수에 인수를 얼마든지 전달할 수 있고, 표시된 유형의 리스트에 항목으로 각 인수를 추가합니다. 예를 들면:

+ +
var listHTML = list("u", "One", "Two", "Three");
+
+/* listHTML은:
+
+"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
+
+*/
+ +

나머지, 기본 및 비구조화된 매개변수

+ +

arguments 객체는 나머지 매개변수, 기본 매개변수 또는 비구조화된 매개변수와 함께 사용될 수 있습니다.

+ +
function foo(...args) {
+  return arguments;
+}
+foo(1, 2, 3); // { "0": 1, "1": 2, "2": 3 }
+
+ +

그러나, 비엄격 함수에서는 mapped arguments 객체는 함수가 어떤 나머지 매개변수, 기본 매개변수 또는 비구조화된 매개변수든 포함하지 않는 경우에만 제공됩니다. 예를 들어, 기본 매개변수를 사용하는 다음 함수에서는, 100 대신에 10이 반환됩니다:

+ +
function bar(a=1) {
+  arguments[0] = 100;
+  return a;
+}
+bar(10); // 10
+
+ +

이 예에서, 어떤 나머지 매개변수, 기본 매개변수 또는 비구조화된 매개변수가 없는 경우에는, 100이 반환됩니다:

+ +
function zoo(a) {
+  arguments[0] = 100;
+  return a;
+}
+zoo(10); // 100
+
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.1에서 구현됨
{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.functions.arguments")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/functions/arguments/length/index.html b/files/ko/web/javascript/reference/functions/arguments/length/index.html new file mode 100644 index 0000000000..d8ea3f0da4 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/arguments/length/index.html @@ -0,0 +1,74 @@ +--- +title: arguments.length +slug: Web/JavaScript/Reference/Functions/arguments/length +translation_of: Web/JavaScript/Reference/Functions/arguments/length +--- +
{{jsSidebar("Functions")}}
+ +

arguments.length 속성은 함수에 전달된 인수의 수를 포함하고 있습니다.

+ +

구문

+ +
arguments.length
+ +

설명

+ +

arguments.length 속성은 실제로 함수에 전달된 arguments 의 수를 제공합니다. 이것은 정의된 매개변수의 수보다 작을 수도 클 수도 있습니다. ({{jsxref("Function.length")}} 보기).

+ +

예제

+ +

arguments.length 사용하기

+ +

이 예시에서는 둘 또는 그 이상의 수를 더할 수 있는 함수를 정의합니다.

+ +
function adder(base /*, n2, ... */) {
+  base = Number(base);
+  for (var i = 1; i < arguments.length; i++) {
+    base += Number(arguments[i]);
+  }
+  return base;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.1에서 구현됨.
{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.functions.arguments.length")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/functions/default_parameters/index.html b/files/ko/web/javascript/reference/functions/default_parameters/index.html new file mode 100644 index 0000000000..2783b65844 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/default_parameters/index.html @@ -0,0 +1,239 @@ +--- +title: 기본값 매개변수 +slug: Web/JavaScript/Reference/Functions/Default_parameters +tags: + - ECMAScript2015 + - ECMAScript6 + - Functions + - JavaScript + - 기본값 매개변수 +translation_of: Web/JavaScript/Reference/Functions/Default_parameters +--- +
{{jsSidebar("Functions")}}
+ +

 기본값 함수 매개변수 (default function parameter)를 사용하면 값이 없거나 undefined가 전달될 경우 이름붙은 매개변수를 기본값으로 초기화할 수 있습니다.

+ +

{{EmbedInteractiveExample("pages/js/functions-default.html")}}

+ + + +

구문

+ +
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
+   statements
+}
+
+ +

설명

+ +

JavaScript에서, 함수의 매개변수는 {{jsxref("undefined")}}가 기본입니다. 그러나, 일부 상황에서는 다른 기본 값을 설정하는 것이 유용할 수 있습니다. 이때가 바로 기본값 매개변수 가 필요할 때 입니다.

+ +

과거에 기본값 설정을 위한 일반적인 방법은 함수 내부(body)에서 매개변수 값을 검사해 undefined인 경우 값을 할당하는 것이었습니다.

+ +

다음 예제에서, multiply호출시 b에 할당된  값이 없다면, b 값은 a*b를 평가할 때 undefined일 거고 multiply 호출은 NaN이 반환됩니다. 

+ +
function multiply(a, b) {
+  return a * b
+}
+
+multiply(5, 2)  // 10
+multiply(5)     // NaN !
+ +

이를 방지하기 위해서, 아래 두번째 줄과 같이  multiply 함수가 오직 한 개의 인수만 있다면  b를  1로 설정하는 방식을 사용하곤 했습니다.

+ +
function multiply(a, b) {
+  b = (typeof b !== 'undefined') ?  b : 1
+  return a*b
+}
+
+multiply(5, 2)   // 10
+multiply(5)      // 5
+
+ +

ES2015의 기본값 매개변수로 함수 내부 에서의 검사는 더 이상 필요치 않습니다. 이제, 간단히 함수 머리(head)에서 b의 기본값으로 1 로 설정할 수 있습니다:

+ +
function multiply(a, b = 1) {
+  return a*b
+}
+
+multiply(5, 2)          // 10
+multiply(5)             // 5
+multiply(5, undefined)  // 5
+
+ +

예제

+ +

undefined vs. 다른 거짓같은 값(falsy values) 전달하기

+ +

아래 예제중 두 번째 호출에서, 설사 두 번째 인수를 호출할 때 명시해서 undefined (null 혹은 {{glossary("falsy")}} 값이 아니긴 하지만 )로 설정하더라도 , num 인수의 값은 여전히 기본값입니다.

+ +
function test(num = 1) {
+  console.log(typeof num)
+}
+
+test()            // 'number' (num 은 1로 설정됨)
+test(undefined)   // 'number' (num 이 역시 1로 설정됨)
+
+// 다른 falsy values로 테스트 하기:
+test('')          // 'string' (num 은 ''로 설정됨)
+test(null)        // 'object' (num 은 null로 설정됨)
+
+ +

호출 시 평가

+ +

기본 인수는 호출 시 에 평가됩니다, 그래서 Python의 경우 와는 달리, 함수가 호출될 때마다 새로운 객체가 생성됩니다.

+ +
function append(value, array = []) {
+  array.push(value)
+  return array
+}
+
+append(1)  // [1]
+append(2)  // [2], [1, 2]가 아니라
+
+
+ +

이는 심지어 함수 및 변수에도 적용됩니다:

+ +
function callSomething(thing = something()) {
+  return thing
+}
+
+let numberOfTimesCalled = 0
+function something(){
+  numberOfTimesCalled += 1
+  return numberOfTimesCalled
+}
+
+callSomething()  // 1
+callSomething()  // 2
+
+ +

앞쪽 매개변수는 뒷쪽의 매개변수 기본값에 사용할 수 있습니다

+ +

매개 변수가 여러개일 때 앞쪽에( 왼쪽 부분) 정의된 매개변수는 뒷쪽에 정의된 매개변수의 기본값에  바로 사용할 수 있습니다.

+ +
function greet(name, greeting, message = greeting + ' ' + name) {
+  return [name, greeting, message]
+}
+
+greet('David', 'Hi')                      // ["David", "Hi", "HiDavid"]
+greet('David', 'Hi', 'Happy Birthday!')   // ["David", "Hi", "Happy Birthday!"]
+
+ +

이 기능은,  얼마나 많은 경계 조건(edge case)를 다룰수 있는지 보여주는, 아래 예제로 거의 설명 가능합니다.

+ +
function go() {
+  return ':P'
+}
+
+// 함수 정의가 간단해짐
+function withDefaults(a, b = 5, c = b, d = go(), e = this,
+                      f = arguments, g = this.value) {
+  return [a,b,c,d,e,f,g]
+}
+
+// 함수 정의가 길고 장황함
+function withoutDefaults(a, b, c, d, e, f, g){
+  switch(arguments.length){
+    case 0:
+      a;
+    case 1:
+      b = 5;
+    case 2:
+      c = b;
+    case 3:
+      d = go();
+    case 4:
+      e = this;
+    case 5:
+      f = arguments;
+    case 6:
+      g = this.value;
+    default:
+  }
+  return [a,b,c,d,e,f,g];
+}
+
+// 아래와 같이 함수 호출하면 동일한 결과를 보임
+
+withDefaults.call({value:"=^_^="});
+// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
+
+withoutDefaults.call({value:"=^_^="});
+// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
+
+ +

유효범위 효과 (Scope Effects)

+ +

한개 이상의 매개변수에 기본값이 지정되면 특별히 매개변수 목록내의 식별자들(identifiers) 대상으로, 두번째 스코프 (Environment Record) 가 생성됩니다.

+ +

이 말은 함수 내부에 선언된 함수와 변수들은 매개변수 기본값 초기화시에 참조할 수  없다는 말입니다; 그렇게 하려고 하면 실행시간 에러인 {{jsxref("ReferenceError")}} 를 유발합니다.

+ +

이 말은 또한 함수 내부에서 var 로 선언된 변수는 동일한 이름을 가진 매개변수를 가리게 되는, 중첩 var 선언 으로 인한 일반적인 동작이 일어나지 않는다는 말입니다.

+ +

아래 함수는 호출되면 ReferenceError 를 발생시킵니다. 매개변수 기본값이 함수 내부의 자식 유효범위를 참조할 수 없기 때문입니다.

+ +
function f(a = go()) { // `f`가 호출 되면 `ReferenceError` 발생
+  function go() { return ':P' }
+}
+ +

...그리고 아래 함수는 undefined 를 프린트 하는데,  var a 가 함수 내부 대상의 유효범위내에서만 효과를 가지기 때문입니다. ( 매개변수 목록이 대상인 부모 스코프가 아니라)

+ +
function f(a, b = () => console.log(a)) {
+  var a = 1
+  b() // `undefined`를 인쇄하는데, 매개변수 기본값이 자체 스코프에 있기 때문입니다
+} 
+ +

기본값 매개변수 뒤쪽의 기본값 없는 매개변수

+ +

매개변수는 여전히 왼쪽에서 오른쪽으로 설정됩니다. 아래 예제에서 뒷쪽에 기본값이 없는 매개변수가 있지만 기본값 매개변수를 덮어씁니다.

+ +
function f(x=1, y) {
+  return [x, y];
+}
+
+f()   // [1, undefined]
+f(2)  // [2, undefined]
+
+ +

기본값 할당 있는 해체된 매개변수

+ +

기본값 할당을 {{jsxref("Operators/Destructuring_assignment", "destructuring assignment", "", 1)}} 표기와 함께 사용할 수 있습니다:

+ +
function f([x, y] = [1, 2], {z: z} = {z: 3}) {
+  return x + y + z
+}
+
+f()  // 6
+ +

스펙

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.functions.default_parameters")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/functions/get/index.html b/files/ko/web/javascript/reference/functions/get/index.html new file mode 100644 index 0000000000..fb64206dff --- /dev/null +++ b/files/ko/web/javascript/reference/functions/get/index.html @@ -0,0 +1,179 @@ +--- +title: getter +slug: Web/JavaScript/Reference/Functions/get +tags: + - 자바스크립트 + - 함수 +translation_of: Web/JavaScript/Reference/Functions/get +--- +
{{jsSidebar("Functions")}}
+ +

get 구문은 객체의 프로퍼티를 그 프로퍼티를 가져올 때 호출되는 함수로 바인딩합니다.

+ +

{{EmbedInteractiveExample("pages/js/functions-getter.html")}}

+ + + +

구문

+ +
{get prop() { ... } } {get [expression]() { ... } }
+ +

매개변수

+ +
+
prop
+
주어진 함수를 바인딩할 프로퍼티의 이름입니다.
+
expression
+
ECMAScript 2015가 도입되면서, 함수의 이름을 계산하기 위해 표현식을 사용할 수 있습니다.
+
+ +

설명

+ +

어떤 프로퍼티에 접근할 때마다 그 값을 계산하도록 해야 하거나, 내부 변수의 상태를 명시적인 함수 호출 없이 보여주고 싶을 때, JavaScript의 getter를 이용할 수 있습니다. getter가 바인딩된 프로퍼티는 동시에 실제 값을 가질 수는 없지만, getter와 setter를 동시에 바인딩해 일종의 유사 프로퍼티(pseudo-property)를 만들 수는 있습니다.

+ +

get 구문을 이용할 때는 다음을 유의하세요.

+ +
+ +
+ +

getter는 delete 연산자를 이용해 삭제할 수 있습니다.

+ +

+ +

getter를 객체 초기자에서 정의하기

+ +

객체 obj에 유사 프로퍼티 latest를 생성합니다. latest는 배열 log의 마지막 요소를 반환합니다.

+ +
var obj = {
+  log: ['example','test'],
+  get latest() {
+    if (this.log.length == 0) return undefined;
+    return this.log[this.log.length - 1];
+  }
+}
+console.log(obj.latest); // "test".
+ +

latest에 어떤 값을 할당하려고 시도해도 그 값이 바뀌지 않는다는 점을 유의하세요.

+ +

delete연산자를 이용해 getter 삭제하기

+ +

getter를 삭제하고 싶다면, delete를 이용하면 됩니다.

+ +
delete obj.latest;
+
+ +

defineProperty를 이용해 이미 존재하는 객체에 getter 정의하기

+ +

이미 존재하는 객체에 getter를 추가하고자 한다면, {{jsxref("Object.defineProperty()")}}를 이용하면 됩니다.

+ +
var o = { a:0 }
+
+Object.defineProperty(o, "b", { get: function () { return this.a + 1; } });
+
+console.log(o.b) // getter를 실행합니다. a + 1 (= 1)이 반환됩니다.
+ +

계산된 (computed) 프로퍼티 이름

+ +
var expr = "foo";
+
+var obj = {
+  get [expr]() { return "bar"; }
+};
+
+console.log(obj.foo); // "bar"
+ +

똑똑한(Smart) / 스스로 덮어쓰는(self-overwriting) / 느긋한(lazy) getter

+ +

Getter는 객체에 프로퍼티를 정의할 수 있도록 하지만, 그 프로퍼티에 접근하기 전까지는 값을 계산하지 않습니다. getter는 값을 계산하는 비용을 실제 값이 필요할 때까지 미루며, 그 값이 필요없다면 계산 비용도 들지 않습니다.

+ +

또다른 최적화 기법으로는 계산 미루기와 함께 프로퍼티 값을 나중에 접근하기 위해 캐싱하는 것이 있습니다. 이를 똑똑한(smart), 혹은 메모화된(memoized) getter라고 부릅니다. 값은 getter가 호출될 때 처음 계산되며, 캐싱됩니다. 이후의 호출에는 다시 계산하지 않고 이 캐시값을 반환합니다. 이는 다음과 같은 상황에 유용합니다.

+ + + +

똑똑한 getter는 값을 다시 계산하지 않기 때문에, 값의 변경이 예상되는 경우에는 똑똑한 getter를 이용해서는 안 됩니다.

+ +

다음 예제에서, 객체는 원래 프로퍼티로 getter를 가집니다. 프로퍼티를 가져올 때, getter는 삭제되며 대신 명시적인 값이 저장됩니다. 최종적으로 값을 반환합니다.

+ +
get notifier() {
+  delete this.notifier;
+  return this.notifier = document.getElementById("bookmarked-notification-anchor");
+},
+ +

Firefox 코드의 경우,  defineLazyGetter() 함수를 정의하고 있는 XPCOMUtils.jsm 모듈을 참조하세요.

+ +

get Vs. defineProperty

+ +

While using the get 키워드와 {{jsxref("Object.defineProperty()")}}를 사용하면 비슷한 결과를 얻지만, {{jsxref("classes")}}에서 사용되는 두 가지 경우에는 미묘한 차이가 있습니다.

+ +

get을 사용할 때 속성은 {{jsxref("Object.defineProperty()")}} 를 사용하는 동안 객체의 프로토 타입에 정의 될 것이고, 속성은 그것이 적용되는 인스턴스에 정의 될 것입니다.

+ +
class Example {
+  get hello() {
+    return 'world';
+  }
+}
+
+const obj = new Example();
+console.log(obj.hello);
+// "world"
+console.log(Object.getOwnPropertyDescriptor(obj, 'hello'));
+// undefined
+console.log(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), 'hello'));
+// { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined }
+ +

 

+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}{{Spec2('ES5.1')}}최초로 정의되었습니다.
{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ES6')}}계산된 프로퍼티 이름이 추가되었습니다.
{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.functions.get")}}

+ +

 

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/functions/index.html b/files/ko/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..2052b67a93 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/index.html @@ -0,0 +1,596 @@ +--- +title: 함수 +slug: Web/JavaScript/Reference/Functions +tags: + - 생성자 + - 인자 + - 파라미터 + - 함수 +translation_of: Web/JavaScript/Reference/Functions +--- +
{{jsSidebar("Functions")}}
+ +

일반적으로, 함수는 함수 외부 (또는 재귀(recursion)의 경우엔 내부) 코드에 의해 호출될 수 있는 "하위프로그램"입니다. 프로그램 그 자체처럼, 함수는 함수 몸통(function body)이라고 하는 일련의 구문(statement)으로 구성됩니다. 값은 함수에 전달될 수 있고 함수는 값을 반환합니다.

+ +

JavaScript에서, 함수는 다른 객체처럼 속성 및 메서드를 가질 수 있기에 일급(first-class) 객체입니다. 다른 객체와 함수를 구별하는 것은 함수는 호출될 수 있다는 것입니다. 간단히 말해, 함수는 Function 객체입니다.

+ +

더 많은 예제와 설명은, JavaScript 함수 안내서를 참조하세요.

+ +

설명

+ +

JavaScript에서 모든 함수는 Function 객체입니다. Function 객체의 속성(property) 및 메서드에 관한 정보는 {{jsxref("Function")}} 참조.

+ +

기본값 이외의 값을 반환하려면, 함수는 반환할 값을 지정하는 return 문이 있어야 합니다. return 문이 없는 함수는 기본값을 반환합니다. new 키워드로 호출되는 생성자의 경우에, 기본값은 자신의 this 매개변수 값입니다. 다른 모든 함수의 경우, 기본 반환값은 {{jsxref("undefined")}}입니다.

+ +

함수 호출의 매개변수는 함수의 인수입니다. 인수는 함수에 값으로 전달됩니다. 함수가 인수값을 바꾸면, 이 변화는 전역 또는 호출한 함수에 반영되지 않습니다. 그러나, 객체 참조(reference)는 값이지만 특별합니다: 함수가 참조된 객체의 속성을 바꾸면, 그 변화는 다음 예에서와 같이 함수 밖에서도 바뀌는 것을 볼 수 있습니다:

+ +
/* 함수 'myFunc' 선언 */
+function myFunc(theObject) {
+   theObject.brand = "Toyota";
+ }
+
+ /*
+  * 변수 'mycar' 선언;
+  * 새 객체를 만들고 초기화;
+  * 'mycar'에 객체 참조를 할당
+  */
+ var mycar = {
+   brand: "Honda",
+   model: "Accord",
+   year: 1998
+ };
+
+ /* Logs 'Honda' */
+ console.log(mycar.brand);
+
+ /* 객체 참조를 함수에 전달 */
+ myFunc(mycar);
+
+ /*
+  * 함수에 의해 바뀌었기에 객체의
+  * 'brand' 속성의 값으로 'Toyota' 출력.
+  */
+ console.log(mycar.brand);
+
+ +

this 키워드는 현재 실행 중인 함수를 참조하지 않습니다, 그래서 심지어 함수 몸통 내에서도 이름으로 Function 객체를 참조해야 합니다.

+ +

함수 정의하기

+ +

함수를 정의하는 여러 방법이 있습니다:

+ +

함수 선언 (function 문)

+ +

함수 선언을 위한 특별한 구문이 있습니다 (자세한 사항은 function 문 참조):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
함수 이름.
+
+ +
+
param
+
함수에 전달되는 인수의 이름. 함수는 255개까지 인수를 가질 수 있습니다.
+
+ +
+
statements
+
함수의 몸통을 구성하는 문.
+
+ +

함수 표현식 (function 식)

+ +

함수 식(expression)은 함수 선언과 비슷하고 구문이 같습니다 (자세한 사항은 function 식 참조):

+ +

함수 표현식(expression)은 함수 선언과 비슷하고 구문이 같습니다 (자세한 내용은 function expression 참조). 함수 표현식은 더 큰 표현식의 일부일 수 있습니다. "이름이 붙은(named)"함수 표현식 (예 : 호출 스택에서 표현식 이름 사용하는경우) 또는 "익명"함수 표현식을 정의 할 수 있습니다. 함수 표현식은 선언이 되지 않은 상태에서 사용할 수 없기 때문에 함수를 사용하기 전에 코드에 함수코드가 존제해야 사용 할 수 있습니다.

+ +
function [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
함수 이름. 함수가 익명(anonymous) 함수로 알려진 경우, 생략될 수 있음.
+
+ +
+
param
+
함수에 전달되는 인수의 이름. 함수는 255개까지 인수를 가질 수 있습니다.
+
statements
+
함수의 몸통을 구성하는 문.
+
+ +

다음은 익명 함수 표현식의 예입니다 (이름 이 사용되지 않음):

+ +
var myFunction = function() {
+    statements
+}
+ +

It is also possible to provide a name inside the definition in order to create a named function expression:

+ +
var myFunction = function namedFunction(){
+    statements
+}
+ +

One of the benefits of creating a named function expression is that in case we encountered an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

+ +

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

+ +

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

+ +
(function() {
+    statements
+})();
+ +

IIFE are function expressions that are invoked as soon as the function is declared.

+ +

생성기 함수 선언 (function* 문)

+ +

생성기 함수 선언을 위한 특별한 구문이 있습니다 (자세한 사항은 {{jsxref('Statements/function*', 'function* statement')}} 참조):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
함수 이름.
+
+ +
+
param
+
함수에 전달되는 인수의 이름.
+
+ +
+
statements
+
함수의 몸통을 구성하는 문.
+
+ +

생성기 함수 식 (function* 식)

+ +

생성기 함수 식은 생성기 함수 선언과 비슷하고 구문이 같습니다 (자세한 사항은 {{jsxref('Operators/function*', 'function* expression')}} 참조):

+ +
function* [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
함수 이름. 함수가 익명 함수인 경우 생략될 수 있음.
+
+ +
+
param
+
함수에 전달되는 인수의 이름.
+
statements
+
함수의 몸통을 구성하는 문.
+
+ +

화살표 함수 표현식 (=>)

+ +

화살표 함수 식은 구문이 더 짧고 어휘상(lexically) this 값을 바인딩합니다 (자세한 사항은 화살표 함수 참조):

+ +
([param[, param]]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
인수의 이름. 0개 인수는 ()로 표시돼야 합니다. 인수가 1개뿐이면, 괄호는 필요치 않습니다. (foo => 1처럼)
+
statements or expression
+
선언문이 여러개인 경우 괄호로 묶여야 합니다. 단일 식(expression)은 괄호가 필요 없습니다. 그리고 식은 암시적으로(implicit) 함수의 반환값이 됩니다.
+
+ +

Function constructor

+ +
+

참고 : Function constructor를 사용하여 함수를 만드는 것은 권장되지 않습니다. 함수 본문을 일부 JS 엔진 최적화를 방해 할 수있는 문자열로 사용해야하고 다른 문제를 유발할 수 있기 때문입니다.

+
+ +

다른 모든 객체처럼, {{jsxref("Function")}} 객체는 new 연산자를 사용하여 생성될 수 있습니다:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
형식 매개변수로 함수에 의해 사용되는 0개 이상의 이름. 각각은 알맞은 JavaScript 식별자(identifier)여야 합니다.
+
+ +
+
functionBody
+
함수 몸통을 구성하는 JavaScript 문을 포함하는 문자열.
+
+ +

함수로 Function 생성자 호출(new 연산자 사용 없이)하는 것은 생성자로 호출하는 것과 같습니다.

+ +

GeneratorFunction 생성자

+ +
+

주의: GeneratorFunction은 전역 객체가 아니지만 생성기 함수 인스턴스로부터 얻을 수 있습니다(자세한 사항은 {{jsxref("GeneratorFunction")}} 참조).

+
+ +
+

주의: GeneratorFunction 생성자를 사용하여 함수를 만드는 것은 권장되지 않습니다. 함수 본문을 일부 JS 엔진 최적화를 방해 할 수있는 문자열로 사용해야하고 다른 문제를 유발할 수 있기 때문입니다.

+
+ +

다른 모든 객체처럼, {{jsxref("GeneratorFunction")}} 객체는 new 연산자를 사용하여 생성될 수 있습니다:

+ +
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
형식 인수명으로 함수에 의해 사용되는 0개 이상의 이름. 각각은 유효한 JavaScript 식별자 규칙을 따르는 문자열 또는 콤마로 구분된 그러한 문자열 목록이어야 합니다; 예를 들어 "x", "theValue" 또는 "a,b".
+
+ +
+
functionBody
+
함수 정의를 구성하는 JavaScript 문을 포함하는 문자열.
+
+ +

함수로서 Function 생성자 호출(new 연산자 사용 없이)은 생성자로서 호출하는 것과 같은 효과입니다.

+ +

Function 매개변수

+ +

기본 매개변수

+ +

기본(default) 함수 매개변수는 전달된 값이 없거나 undefined인 경우 기본값으로 초기화되는 형식 매개변수를 허용합니다. 자세한 사항은, 기본 매개변수 참조.

+ +

나머지 매개변수

+ +

나머지(rest) 매개변수 구문은 부정(indefinite)수인 인수를 배열로 나타내는 것을 허용합니다. 자세한 사항은, 나머지 매개변수 참조.

+ +

arguments 객체

+ +

arguments 객체를 사용하여 함수 내에서 함수의 인수를 참조할 수 있습니다. arguments 참조.

+ + + +

메서드 함수 정의하기

+ +

getter 및 setter 함수

+ +

모든 표준 내장 객체 또는 새로운 속성 추가를 지원하는 사용자 정의 객체에 getter(accessor 메서드) 및 setter(mutator 메서드)를 정의할 수 있습니다. getter 및 setter를 정의하는 구문은 객체 리터럴 구문을 사용합니다.

+ +
+
get
+
+

객체 속성을 그 속성이 검색되는 경우 호출되는 함수에 바인딩합니다.

+
+
set
+
객체 속성을 그 속성을 설정하려는 시도가 있는 경우 호출되는 함수에 바인딩합니다.
+
+ +

메서드 정의 구문

+ +

ECMAScript 2015를 시작으로, getter 및 setter와 비슷한 단축 구문으로 자신의 메서드를 정의할 수 있습니다. 더 자세한 정보는 메서드 정의 참조.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

생성자 vs. 선언문 vs. 표현식

+ +

다음을 비교해보세요:

+ +

Function constructor로 정의된 함수를 변수multiply에 할당.

+ +
var multiply = new Function('x', 'y', 'return x * y');
+ +

이름이 multiply인 함수 선언:

+ +
function multiply(x, y) {
+   return x * y;
+}
+
+ +

변수 multiply에 할당된 익명(anonymous) 함수의 function 식:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

변수 multiply에 할당된 이름이 func_name인 함수의 function 식:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

차이

+ +

모두 거의 같은 일을 하지만 약간 미묘한 차이가 있습니다:

+ +

함수 이름과 함수가 할당 된 변수 사이에는 차이가 있습니다. 함수 이름을 변경할 수 없으며 함수가 할당 된 변수는 다시 할당 할 수 있습니다. 함수 이름은 함수 본문(body)내에서만 사용할 수 있습니다. 함수 본문(body) 외부에서 사용하려고 하면 오류가 발생합니다. (함수 이름이 var 문을 통해 이전에 선언 된 경우에는 정의되지 않습(undefined)니다.

+ +

예를 들어:

+ +
var y = function x() {};
+alert(x); // 오류 발생
+
+ +

함수 이름은 Function의 toString 메서드를 통해 직렬화되는 경우에도 보입니다.

+ +

반면에 함수가 할당 된 변수는 함수의 범위(scope)가 포함되도록 보장 된 범위로만 제한됩니다.

+ +

예제 4에서 볼 수 있듯이 함수 이름은 함수가 할당 된 변수와 다를 수 있습니다. 그들은 서로에게 아무런 관련이 없습니다. 함수 선언은 함수 이름과 동일한 이름의 변수도 만듭니다. 따라서 함수 표현식으로 정의 된 함수와 달리 함수 선언으로 정의 된 함수는 정의 된 범위에서 함수 선언의 이름으로 액세스 할 수 있습니다.

+ +

'new Function'으로 정의된 함수는 함수 이름이 없습니다. 그러나, SpiderMonkey JavaScript 엔진에서는, 함수의 직렬화된 형태가 마치 그 이름이 "anonymous"인 것처럼 보입니다. 예를 들어, alert(new Function())은 다음을 출력합니다:

+ +
function anonymous() {
+}
+
+ +

함수가 실제로는 이름이 없기에, anonymous는 함수 내에서 액세스될 수 있는 변수가 아닙니다.

+ +

다음 코드는 오류가 날 것입니다:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

function 식 또는 Function 생성자에 의해 정의된 함수와는 달리, function 선언으로 정의된 함수는 function 자체의 선언 전에 사용될 수 있습니다. 예를 들어:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

함수 표현식(function expression)이나 함수 선언(function declaration)에 의해 정의 된 함수는 현재 범위를 상속합니다. 즉,이 함수는 클로저를 형성합니다. 반면에 Function 생성자가 정의한 함수는 전역 범위 (모든 함수가 상속) 이외의 다른 범위를 상속하지 않습니다.

+ +
/*
+ * Declare and initialize a variable 'p' (global)
+ * and a function 'myFunc' (to change the scope) inside which
+ * declare a varible with same name 'p' (current) and
+ * define three functions using three different ways:-
+ *     1. function declaration
+ *     2. function expression
+ *     3. function constructor
+ * each of which will log 'p'
+ */
+var p = 5;
+function myFunc() {
+    var p = 9;
+
+    function decl() {
+        console.log(p);
+    }
+    var expr = function() {
+        console.log(p);
+    };
+    var cons = new Function('\tconsole.log(p);');
+
+    decl();
+    expr();
+    cons();
+}
+myFunc();
+
+/*
+ * Logs:-
+ * 9  - for 'decl' by function declaration (current scope)
+ * 9  - for 'expr' by function expression (current scope)
+ * 5  - for 'cons' by Function constructor (global scope)
+ */
+ +

function 식 및 function 선언에 의해 정의된 함수는 한 번만 구문 분석됩니다, 반면에 Function 생성자에 의해 정의된 함수는 아닙니다. 즉, Function 생성자에 전달된 함수 몸통 문자열은 생성자가 호출될 때마다 구문 분석되어야 합니다. function 식이 매번 closure를 만들더라도, 함수 몸통은 다시 구문 분석되지 않습니다, 그래서 function 식은 "new Function(...)"보다 여전히 더 빠릅니다. 따라서 Function 생성자는 보통 가능한 한 피해야 합니다.

+ +

함수 식과 함수 선언으로 정의 된 함수는 한 번만 구문 분석되지만 Function 생성자로 정의 된 함수는 구문 분석되지 않습니다. 즉, Function 생성자에 전달 된 함수 본문 문자열은 생성자가 호출 될 때마다 파싱되어야합니다. 함수식이 매번 클로저(closure)를 만들지만 함수 본문은 다시 파싱되지 않으므로 함수 식은 여전히 ​​"new Function (...)"보다 빠릅니다. 따라서 Function 생성자는 가능한 피하는 것이 좋습니다.

+ +

그러나 Function constructor의 문자열을 구문 분석하여 생성된 함수 내에 중첩된 function 식 및 function 선언은 반복해서 구문 분석되지 않음에 주의해야 합니다. 예를 들면:

+ +
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
+foo(); // 함수 몸통 문자열의 "function() {\n\talert(bar);\n}" 부분은 다시 구문 분석되지 않습니다.
+ +

function 선언은 매우 쉽게 (그리고 종종 무심코) function 식으로 바뀝니다. function 선언은 다음 어느 쪽이든 function 식이 되는 것을 중단합니다:

+ + + +
var x = 0;               // source 요소
+if (x == 0) {            // source 요소
+   x = 10;               // source 요소가 아님
+   function boo() {}     // source 요소가 아님
+}
+function foo() {         // source 요소
+   var y = 20;           // source 요소
+   function bar() {}     // source 요소
+   while (y == 10) {     // source 요소
+      function blah() {} // source 요소가 아님
+      y++;               // source 요소가 아님
+   }
+}
+
+ +

+ +
// function 선언
+function foo() {}
+
+// function 식
+(function bar() {})
+
+// function 식
+x = function hello() {}
+
+
+if (x) {
+   // function 식
+   function world() {}
+}
+
+
+// function 선언
+function a() {
+   // function 선언
+   function b() {}
+   if (0) {
+      // function 식
+      function c() {}
+   }
+}
+
+ +

블록 레벨 함수

+ +

ES2015 (ES6)를 시작으로 엄격 모드에서, 블록 내부 함수는 이제 그 블록 범위가 됩니다. ES6 이전에, 블록 레벨 함수는 엄격 모드에서 금지됐습니다.

+ +
'use strict';
+
+function f() {
+  return 1;
+}
+
+{
+  function f() {
+    return 2;
+  }
+}
+
+f() === 1; // true
+
+// 비엄격 모드에서는 f() === 2
+
+ +

비엄격 코드에서 블록 레벨 함수

+ +

한 마디로: 안됩니다.

+ +

비엄격 코드에서, 블록 내부 function 선언은 이상하게 동작합니다. 예를 들면:

+ +
if (shouldDefineZero) {
+   function zero() {     // 위험: 호환성 위험
+      console.log("This is zero.");
+   }
+}
+
+ +

ES2015는 shouldDefineZero가 false인 경우, 그러면 zero는 결코 정의되어서는 안된다고 합니다, 그 블록이 실행된 적이 없기에. 그러나, 이는 표준의 새로운 일부입니다. 역사상, 이는 지정되지 않은 채 방치되었고 일부 브라우저는 블록이 실행됐든 아니든 zero를 정의할 겁니다.

+ +

엄격 모드에서, ES2015를 지원하는 모든 브라우저는 이를 같은 식으로 다룹니다: zeroshouldDefineZero가 true이고 if 블록 범위인 경우에만 정의됩니다.

+ +

조건부 함수를 정의하는 더 안전한 방법은 function 식을 변수에 할당하는 것입니다:

+ +
var zero;
+if (0) {
+   zero = function() {
+      console.log("This is zero.");
+   };
+}
+
+ +

예제

+ +

형식 갖춘 숫자 반환하기

+ +

다음 함수는 선행 0으로 채워진 형식 갖춘(formatted) 숫자 표현을 포함하는 문자열을 반환합니다.

+ +
// 이 함수는 선행 0으로 채워진 문자열을 반환
+function padZeros(num, totalLen) {
+   var numStr = num.toString();             // 문자열로 반환값을 초기화
+   var numZeros = totalLen - numStr.length; // 0의 개수 계산
+   for (var i = 1; i <= numZeros; i++) {
+      numStr = "0" + numStr;
+   }
+   return numStr;
+}
+
+ +

다음 문은 padZeros 함수를 호출합니다.

+ +
var result;
+result = padZeros(42,4); // 반환값 "0042"
+result = padZeros(42,2); // 반환값 "42"
+result = padZeros(5,4);  // 반환값 "0005"
+
+ +

함수 존재 여부 결정하기

+ +

typeof 연산자를 사용하여 함수가 존재하는지 여부를 결정할 수 있습니다. 다음 예에서, window 객체가 함수인 noFunc이라고 하는 속성이 있는지 결정하기 위해 테스트가 수행됩니다. 있으면, 사용됩니다; 그렇지 않으면 무언가 다른 행동을 취합니다.

+ +
 if ('function' == typeof window.noFunc) {
+   // noFunc() 사용
+ } else {
+   // 뭔가 다른 것 수행
+ }
+
+ +

if 테스트에는, noFunc에 대한 참조가 사용되고—실제 함수가 호출되지 않도록 함수 이름 뒤에 괄호 "()"가 없음을 주의하세요.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.0에서 구현됨
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}신규: 화살표 함수, 생성기 함수, 기본 매개변수, 나머지 매개변수.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.functions")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/functions/method_definitions/index.html b/files/ko/web/javascript/reference/functions/method_definitions/index.html new file mode 100644 index 0000000000..ff1b67956a --- /dev/null +++ b/files/ko/web/javascript/reference/functions/method_definitions/index.html @@ -0,0 +1,230 @@ +--- +title: 메서드 정의 +slug: Web/JavaScript/Reference/Functions/Method_definitions +tags: + - ECMAScript 2015 + - Functions + - JavaScript + - Object + - Syntax +translation_of: Web/JavaScript/Reference/Functions/Method_definitions +--- +
{{JsSidebar("Functions")}}
+ +

ECMAScript 2015 를 시작으로, 객체 초기자(initializer)에 메서드 정의를 위한 더 짧은 구문이 도입되었습니다. 이는 메서드 명에 할당된 함수를 위한 단축입니다.

+ +

구문

+ +
var obj = {
+  property( parameters… ) {},
+  *generator( parameters… ) {},
+// 키(속성) 계산값과도 함께:
+  [property]( parameters… ) {},
+  *[generator]( parameters… ) {},
+// ES5 getter/setter 구문과 비교해 보세요:
+  get property() {},
+  set property(value) {}
+};
+
+ +

설명

+ +

단축 구문은 ECMAScript 5에 도입된 gettersetter 구문과 비슷합니다.

+ +

다음 코드가 주어지면:

+ +
var obj = {
+  foo: function() {},
+  bar: function() {}
+};
+ +

이제 이를 아래로 줄일 수 있습니다:

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +
+

주의 : 단축 구문은 익명(anonymous) 함수 (…foo: function() {}… 에서처럼) 대신 유명(named) 함수를 사용합니다. 유명 함수는 함수 본체에서 호출될 수 있습니다 (이는 참조할 식별자가 없기에 익명 함수에게는 불가능합니다). 자세한 사항은, {{jsxref("Operators/function","function","#Examples")}} 참조.

+
+ +

단축 생성기 메서드

+ +

생성기 메서드는 단축 구문을 사용해서도 정의될 수 있습니다. 단축 구문 내 별표(*)는 생성기 속성명 앞에 와야 함을 주의하세요. 즉, * g(){}는 작동하지만 g *(){}는 아닙니다.

+ +
// 유명 속성 사용 (ES2015 이전)
+var obj2 = {
+  g: function*() {
+    var index = 0;
+    while(true)
+      yield index++;
+  }
+};
+
+// 단축 구문을 쓰는 같은 객체
+var obj2 = {
+  * g() {
+    var index = 0;
+    while(true)
+      yield index++;
+  }
+};
+
+var it = obj2.g();
+console.log(it.next().value); // 0
+console.log(it.next().value); // 1
+ +

메서드 정의는 생성 불가능합니다

+ +

모든 메서드 정의는 생성자가 아니고 인스턴스화하려고 하는 경우 {{jsxref("TypeError")}} 예외가 발생합니다.

+ +
var obj = {
+  method() {},
+};
+new obj.method; // TypeError: obj.method는 생성자가 아닙니다
+
+var obj = {
+  * g() {}
+};
+new obj.g; // TypeError: obj.g는 생성자가 아닙니다 (ES2016에서 바뀜)
+
+ +

+ +

간단한 테스트 사례

+ +
var obj = {
+  a : "foo",
+  b(){ return this.a; }
+};
+console.log(obj.b()); // "foo"
+
+ +

속성 계산명

+ +

단축 구문은 속성 계산명(computed property name)도 지원합니다.

+ +
var bar = {
+  foo0 : function (){return 0;},
+  foo1(){return 1;},
+  ["foo" + 2](){return 2;},
+};
+
+console.log(bar.foo0()); // 0
+console.log(bar.foo1()); // 1
+console.log(bar.foo2()); // 2
+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES2015', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ES2015')}}초기 정의.
{{SpecName('ES7', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ES7')}}생성기 메서드 역시 [[Construct]] 트랩이 없어야 하고 new와 함께 사용되는 경우 예외 발생으로 바뀜.
{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Method definition shorthand{{CompatChrome("39")}}{{CompatGeckoDesktop("34")}}{{CompatNo}}{{CompatOpera("26")}}{{CompatNo}}
Generator methods are not constructable (ES2016){{CompatUnknown}}{{CompatGeckoDesktop("43")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Method definition shorthand{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("34")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Generator methods are not constructable (ES2016){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("43")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

SpiderMonkey 전용 주의사항

+ + + +

참조

+ + diff --git a/files/ko/web/javascript/reference/functions/rest_parameters/index.html b/files/ko/web/javascript/reference/functions/rest_parameters/index.html new file mode 100644 index 0000000000..eee5528b38 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/rest_parameters/index.html @@ -0,0 +1,223 @@ +--- +title: Rest 파라미터 +slug: Web/JavaScript/Reference/Functions/rest_parameters +tags: + - Functions + - JavaScript + - Rest + - Rest parameters +translation_of: Web/JavaScript/Reference/Functions/rest_parameters +--- +
{{jsSidebar("Functions")}}
+ +

Rest 파라미터 구문은 정해지지 않은 수(an indefinite number, 부정수) 인수를 배열로 나타낼 수 있게 합니다.

+ +

{{EmbedInteractiveExample("pages/js/functions-restparameters.html")}}

+ + + +

 

+ +

구문

+ +
function f(a, b, ...theArgs) {
+  // ...
+}
+
+ +

설명

+ +

함수의 마지막 파라미터의 앞에 ... 를 붙여 (사용자가 제공한) 모든 나머지 인수를 "표준" 자바스크립트 배열로 대체합니다. 마지막 파라미터만 "Rest 파라미터" 가 될 수 있습니다.

+ +
function myFun(a, b, ...manyMoreArgs) {
+  console.log("a", a);
+  console.log("b", b);
+  console.log("manyMoreArgs", manyMoreArgs);
+}
+
+myFun("one", "two", "three", "four", "five", "six");
+
+// Console Output:
+// a, one
+// b, two
+// manyMoreArgs, [three, four, five, six]
+ +

 

+ +

Rest 파라미터 및 arguments 객체간 차이

+ +

Rest 파라미터와 arguments 객체 사이에 세 가지 주요 차이점이 있습니다:

+ + + +

arguments에서 배열까지

+ +

Rest 파라미터는 인수에 의해 유발된 상용구(boilerplate) 코드를 줄이기 위해 도입되었습니다.

+ +
// Rest 파라미터 이전에, "arguments" 는 다음을 사용해 일반적인 배열로 변환될 수 있음
+
+function f(a, b) {
+
+  var normalArray = Array.prototype.slice.call(arguments);
+  // -- 또는 --
+  var normalArray = [].slice.call(arguments);
+  // -- 또는 --
+  var normalArray = Array.from(arguments);
+
+  var first = normalArray.shift(); // OK, 첫 번째 인수를 반환
+  var first = arguments.shift(); // ERROR (arguments 가 일반적인 배열이 아님)
+
+}
+
+// 이제 rest 파라미터를 사용해 쉽게 일반적인 배열에 접근할 수 있음
+
+function f(...args) {
+  var normalArray = args;
+  var first = normalArray.shift(); // OK, 첫 번째 인수를 반환
+}
+ +

Rest 파라미터 해체

+ +

Rest 파라미터는 해체될 수 있습니다(배열로만). 이는 데이터가 구분된 변수로 해체될 수 있음을 의미합니다. 구조 분해 할당 문서를 보세요.

+ +
function f(...[a, b, c]) {
+  return a + b + c;
+}
+
+f(1)          // NaN (b 와 c 는 undefined)
+f(1, 2, 3)    // 6
+f(1, 2, 3, 4) // 6 (4번 째 파라미터는 해체되지 않음)
+ +

예제

+ +

이 예제에서, 첫 번째 인수는 "a", 두 번째 인수는 "b" 로 매핑되어, 일반적인 유명 인수와 같이 사용됩니다. 반면에 3번 째 인수 "manyMoreArgs" 는 사용자가 포함시킨 인수를 포함하는 배열이 됩니다.

+ +
function myFun(a, b, ...manyMoreArgs) {
+  console.log("a", a);
+  console.log("b", b);
+  console.log("manyMoreArgs", manyMoreArgs);
+}
+
+myFun("one", "two", "three", "four", "five", "six");
+
+// a, one
+// b, two
+// manyMoreArgs, [three, four, five, six]
+ +

아래를 보면, 하나의 값만 있더라도 마지막 인수는 여전히 배열을 갖습니다.

+ +
// 위 예제와 동일한 함수 정의를 사용
+
+myFun("one", "two", "three");
+
+// a, one
+// b, two
+// manyMoreArgs, [three]
+ +

아래를 보면, 3번 째 인수가 제공되지 않더라도, "manyMoreArgs" 는 여전히 배열입니다(비어있긴하지만).

+ +
// 위 예제와 동일한 함수 정의를 사용
+
+myFun("one", "two");
+
+// a, one
+// b, two
+// manyMoreArgs, []
+ +

theArgs 가 배열이므로, length 프로퍼티를 사용해 엘리먼트의 수를 얻을 수 있습니다.

+ +
function fun1(...theArgs) {
+  console.log(theArgs.length);
+}
+
+fun1();  // 0
+fun1(5); // 1
+fun1(5, 6, 7); // 3
+ +

다음 예제에서, rest 파라미터는 첫 번째 인수 다음의 모든 인수를 배열로 모으는데 사용됩니다. 각각은 첫 번째 파라미터와 곱해져 배열로 반환됩니다.

+ +
function multiply(multiplier, ...theArgs) {
+  return theArgs.map(function(element) {
+    return multiplier * element;
+  });
+}
+
+var arr = multiply(2, 1, 2, 3);
+console.log(arr); // [2, 4, 6]
+ +

Array 메소드는 rest 파라미터에서 사용될 수 있지만, arguments 객체에서는 그렇지 않습니다.

+ +
function sortRestArgs(...theArgs) {
+  var sortedArgs = theArgs.sort();
+  return sortedArgs;
+}
+
+console.log(sortRestArgs(5, 3, 7, 1)); // 1, 3, 5, 7
+
+function sortArguments() {
+  var sortedArgs = arguments.sort();
+  return sortedArgs; // this will never happen
+}
+
+
+console.log(sortArguments(5, 3, 7, 1)); // TypeError (arguments.sort is not a function)
+ +

arguments 객체에서 Array 메소드를 사용하려면, 이를 먼저 실제 배열로 변환해야합니다.

+ +
function sortArguments() {
+  var args = Array.from(arguments);
+  var sortedArgs = args.sort();
+  return sortedArgs;
+}
+console.log(sortArguments(5, 3, 7, 1)); // 1, 3, 5, 7
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

 

+ + + +

{{Compat("javascript.functions.rest_parameters")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/functions/set/index.html b/files/ko/web/javascript/reference/functions/set/index.html new file mode 100644 index 0000000000..248a218c37 --- /dev/null +++ b/files/ko/web/javascript/reference/functions/set/index.html @@ -0,0 +1,208 @@ +--- +title: setter +slug: Web/JavaScript/Reference/Functions/set +translation_of: Web/JavaScript/Reference/Functions/set +--- +
{{jsSidebar("Functions")}}
+ +

set syntax는 어떤 객체의 속성에 이 속성을 설정하려고 할 때 호출되는 함수를 바인드한다.

+ +

구문

+ +
{set prop(val) { . . . }}
+{set [expression](val) { . . . }}
+ +

매개변수

+ +
+
prop
+
주어진 함수를 바인드할 속성의 이름
+
+ +
+
val
+
prop에 설정될 값을 가지고 있는 변수의 별명.
+
expression
+
ECMAScript 6부터는, 주어진 함수에 바인드 되는 속성 이름은 계산(computed)을 통해 얻을 수 있고 이것을 위한 expressions을 사용할 수 있다.
+
+ +

설명

+ +

 자바스크립트에서, setter는 특정한 속성에 값이 변경되어 질 때마다 함수를 실행하는데 사용될 수 있다. Setter는 유사(pseudo)-property 타입을 생성하는 getter와 함께 가장 자주 사용된다. 실제 값을 가지는 property와 이  property의 setter 를  동시에 갖는 것은 불가능하다.

+ +

set 문법을 사용할 때 다음을 주의한다:

+ +
+ +
+ +

setter는   delete operator를 사용하여 제거할 수 있다.

+ +

+ +

새로운 객체의 setter를 객체의 initializer에서 정의하기 

+ +

다음은 객체 o의 유사 프로러티(pseudo-property )인 current를 정의한다. 이것은 값이 설정될 때, 이 값으로 로그를 갱신 한다.

+ +
var o = {
+  set current (str) {
+    this.log[this.log.length] = str;
+  },
+  log: []
+}
+
+ +

다음 사항에 주의한다. current는 정의 되지 않았고 이것에 접근하는 모든 시도는 undefined 값을 얻게될 것이다.

+ +

delete operator로 setter를 제거하기

+ +

만약 setter를 제거하기 원한다면, 그냥 그것을 delete 하면 된다:

+ +
delete o.current;
+
+ +

defineProperty를 사용하여 이미 존재하는 객체에 setter를 정의하기

+ +

setter를 이미 존재하는 object에 나중에 언제라도 추가하기 위해서, {{jsxref("Object.defineProperty()")}}를 사용한다.

+ +
var o = { a:0 };
+
+Object.defineProperty(o, "b", { set: function (x) { this.a = x / 2; } });
+
+o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
+console.log(o.a) // 5
+ +

연산된(computed) property name 사용하기

+ +
+

Note: 계산된(Computed) properties는 실험적인 기술이고,  ECMAScript 6 proposal의 부분이다. 아직 많은 브라우저가 지원하지 않는다. 이것 때문에 지원하지 않는 환경에서는  문법 오류가 발생할 것이다.

+
+ +
var expr = "foo";
+
+var obj = {
+  baz: "bar",
+  set [expr](v) { this.baz = v; }
+};
+
+console.log(obj.baz); // "bar"
+obj.foo = "baz";      // run the setter
+console.log(obj.baz); // "baz"
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}{{Spec2('ES5.1')}}Initial definition.
{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ES6')}}Added computed property names.
{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(1)}}{{ CompatGeckoDesktop("1.8.1") }}{{ CompatIE(9) }}9.53
Computed property names{{CompatNo}}{{ CompatGeckoDesktop("34") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("1.8.1") }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Computed property names{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("34.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

SpiderMonkey-specific notes

+ + + +

See also

+ + diff --git "a/files/ko/web/javascript/reference/functions/\354\225\240\353\241\234\354\232\260_\355\216\221\354\205\230/index.html" "b/files/ko/web/javascript/reference/functions/\354\225\240\353\241\234\354\232\260_\355\216\221\354\205\230/index.html" new file mode 100644 index 0000000000..02dc0d55e4 --- /dev/null +++ "b/files/ko/web/javascript/reference/functions/\354\225\240\353\241\234\354\232\260_\355\216\221\354\205\230/index.html" @@ -0,0 +1,465 @@ +--- +title: 화살표 함수 +slug: Web/JavaScript/Reference/Functions/애로우_펑션 +tags: + - ECMAScript6 + - Functions + - Intermediate + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +
{{jsSidebar("Functions")}}
+ +

화살표 함수 표현(arrow function expression)은 function 표현에 비해 구문이 짧고  자신의 this, arguments, super 또는 new.target을 바인딩 하지 않습니다. 화살표 함수는 항상 익명입니다. 이  함수 표현은 메소드 함수가 아닌 곳에 가장 적합합니다. 그래서 생성자로서 사용할 수 없습니다.

+ +

{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}

+ +

구문

+ +

기본 구문

+ +
(param1, param2, …, paramN) => { statements }
+(param1, param2, …, paramN) => expression
+// 다음과 동일함:  => { return expression; }
+
+// 매개변수가 하나뿐인 경우 괄호는 선택사항:
+(singleParam) => { statements }
+singleParam => { statements }
+
+// 매개변수가 없는 함수는 괄호가 필요:
+() => { statements }
+ +

고급 구문

+ +
// 객체 리터럴 표현을 반환하기 위해서는 함수 본문(body)을 괄호 속에 넣음:
+params => ({foo: bar})
+
+// 나머지 매개변수기본 매개변수를 지원함
+(param1, param2, ...rest) => { statements }
+(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }
+
+// 매개변수 목록 내 구조분해할당도 지원됨
+var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
+f();  // 6
+
+ +

상세한 구문 예는 여기에서 볼 수 있습니다.

+ +

설명

+ +

Hacks 블로그 "ES6 In Depth: Arrow functions" 포스트 참조.

+ +

화살표 함수 도입에 영향을 준 두 요소: 보다 짧아진 함수 및  바인딩하지 않은 this.

+ +

짧은 함수

+ +

일부 함수 패턴에서는, 짧은 함수가 환영받습니다. 비교해 보세요:

+ +
var elements = [
+  'Hydrogen',
+  'Helium',
+  'Lithium',
+  'Beryllium'
+];
+
+// 이 문장은 배열을 반환함: [8, 6, 7, 9]
+elements.map(function(element) {
+  return element.length;
+});
+
+// 위의 일반적인 함수 표현은 아래 화살표 함수로 쓸 수 있다.
+elements.map((element) => {
+  return element.length;
+}); // [8, 6, 7, 9]
+
+// 파라미터가 하나만 있을 때는 주변 괄호를 생략할 수 있다.
+elements.map(element => {
+  return element.length;
+}); // [8, 6, 7, 9]
+
+// 화살표 함수의 유일한 문장이 'return'일 때 'return'과
+// 중괄호({})를 생략할 수 있다.
+elements.map(element => element.length); // [8, 6, 7, 9]
+
+// 이 경우 length 속성만 필요하므로 destructuring 매개변수를 사용할 수 있다.
+// 'length'는 우리가 얻고자 하는 속성에 해당하는 반면,
+// lengthFooBArX'는 변경 가능한 변수의 이름일 뿐이므로
+// 원하는 유효한 변수명으로 변경할 수 있다.
+elements.map(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9]
+
+// destructuring 파라미터 할당도 아래와 같이 작성할 수 있습니다.
+// 이 예에서 정의한 객체내의 'length'에 값을 지정하지 않은 점에 주목하세요. 대신, "length" 변수의
+// 리터럴 이름은 우리가 해당 객체에서 꺼내오고 싶은 속성이름 자체로 사용됩니다.
+elements.map(({ length }) => length); // [8, 6, 7, 9] 
+ +

바인딩 되지 않은 this

+ +

화살표 함수가 나오기 전까지는, 모든 새로운 함수는, 어떻게 그 함수가 호출되는지에 따라  자신의 this 값을 정의했습니다:

+ + + +

이는 객체 지향 스타일로 프로그래밍할 때 별로 좋지않습니다.

+ +
function Person() {
+  // Person() 생성자는 `this`를 자신의 인스턴스로 정의.
+  this.age = 0;
+
+  setInterval(function growUp() {
+    // 비엄격 모드에서, growUp() 함수는 `this`를
+    // 전역 객체로 정의하고, 이는 Person() 생성자에
+    // 정의된 `this`와 다름.
+    this.age++;
+  }, 1000);
+}
+
+var p = new Person();
+ +

ECMAScript 3/5 에서는, 이 문제를 this 값을 폐쇄될 수 있는 (비전역) 변수에 할당하여 해결했습니다.

+ +
function Person() {
+  var that = this;
+  that.age = 0;
+
+  setInterval(function growUp() {
+    // 콜백은  `that` 변수를 참조하고 이것은 값이 기대한 객체이다.
+    that.age++;
+  }, 1000);
+}
+ +

이렇게 하는 대신에, 바인딩한 함수는 적절한 this 값이 growUp() 함수에 전달될 수 있도록 생성될 수 있습니다.

+ +

화살표 함수는 자신의 this가 없습니다.  대신 화살표 함수를 둘러싸는 렉시컬 범위(lexical scope)의 this가 사용됩니다; 화살표 함수는 일반 변수 조회 규칙(normal variable lookup rules)을 따릅니다. 때문에 현재 범위에서 존재하지 않는 this를 찾을 때, 화살표 함수는 바로 바깥 범위에서 this를 찾는것으로 검색을 끝내게 됩니다.

+ +

따라서 다음 코드에서 setInterval에 전달 된 함수 내부의 thissetInterval을 포함한 function의 this와 동일한 값을 갖습니다.

+ +
function Person(){
+  this.age = 0;
+
+  setInterval(() => {
+    this.age++; // |this|는 Person 객체를 참조
+  }, 1000);
+}
+
+var p = new Person();
+ +

엄격 모드와의 관계

+ +

this가 렉시컬(lexical, 정적)임을 감안하면, this에 관한 엄격 모드 규칙은 그냥 무시됩니다.

+ +
var f = () => { 'use strict'; return this; };
+f() === window; // 혹은 전역객체
+ +

엄격 모드의 나머지 규칙은 평소대로 적용합니다.

+ +

CORRECTION: START

+ +

NOTE: the previous statement seems false.

+ +

Strict mode should prevent creating global variables when assigning to an undeclared identifier in a function.

+ +

This code sample using Chrome 81 demonstrates that arrow functions allow the creation of global variables in such situations (both for a concise body and for a normal function body):

+ +
> f1 = x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; }
+x => { y = x; console.log(`x: ${x}, y: ${y}`); return x + 1; }
+
+> y
+VM51587:1 Uncaught ReferenceError: y is not defined
+    at <anonymous>:1:1
+(anonymous) @ VM51587:1
+
+> f1(3)
+VM51533:1 x: 3, y: 3
+4
+
+> y
+3
+
+> f2 = x => { 'use strict'; z = x; console.log(`x: ${x}, z: ${z}`); return x + 1; }
+x => { 'use strict'; z = x; console.log(`x: ${x}, z: ${z}`); return x + 1; }
+
+> z
+VM51757:1 Uncaught ReferenceError: z is not defined
+    at <anonymous>:1:1
+(anonymous) @ VM51757:1
+
+> f2(4)
+VM51712:1 Uncaught ReferenceError: z is not defined
+    at f2 (<anonymous>:1:29)
+    at <anonymous>:1:1
+f2 @ VM51712:1
+(anonymous) @ VM51800:1
+
+> f3 = x => (z1 = x + 1)
+x => (z1 = x + 1)
+
+> z1
+VM51891:1 Uncaught ReferenceError: z1 is not defined
+    at <anonymous>:1:1
+(anonymous) @ VM51891:1
+
+> f3(10)
+11
+
+> z1
+11
+
+ +

f2 illustrates that when explicitly setting the arrow function to apply strict mode, it does throw an error when attempting to assign an undeclared variable.

+ +

https://www.ecma-international.org/ecma-262/10.0/index.html#sec-strict-mode-code

+ +

https://www.ecma-international.org/ecma-262/10.0/index.html#sec-arrow-function-definitions-runtime-semantics-evaluation

+ +

CORRECTION: END

+ +

call 또는 apply를 통한 피호출

+ +

화살표 함수에서는 this가 바인딩되지 않았기 때문에, call() 또는 apply() 메서드는  인자만 전달 할 수 있습니다. this는 무시됩니다.

+ +
var adder = {
+  base : 1,
+
+  add : function(a) {
+    var f = v => v + this.base;
+    return f(a);
+  },
+
+  addThruCall: function(a) {
+    var f = v => v + this.base;
+    var b = {
+      base : 2
+    };
+
+    return f.call(b, a);
+  }
+};
+
+console.log(adder.add(1));         // 이는 2가 콘솔에 출력될 것임
+console.log(adder.addThruCall(1)); // 이도 2가 콘솔에 출력될 것임
+ +

바인딩 되지 않은 arguments

+ +

화살표 함수는 arguments 객체를 바인드 하지 않습니다.  때문에, arguments는  그저 둘러싸는 범위(scope) 내 이름에 대한 참조입니다.

+ +
var arguments = [1, 2, 3];
+var arr = () => arguments[0];
+
+arr(); // 1
+
+function foo(n) {
+  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
+  return f();
+}
+
+foo(1); // 2
+ +

화살표 함수는 자신의 arguments 객체가 없지만, 대부분의 경우에 나머지 매개변수가 좋은 대안입니다:

+ +
function foo(n) {
+  var f = (...args) => args[0] + n;
+  return f(2);
+}
+
+foo(1); // 3
+ +

메소드로 사용되는 화살표 함수

+ +

이야기 했듯이, 화살표 함수 표현은 메소드 함수가 아닌 형태로 사용 할 수 있습니다. 메소드로 사용하려고 한면 무슨일이 발생하는지 봅시다.

+ +
'use strict';
+
+var obj = { // does not create a new scope
+  i: 10,
+  b: () => console.log(this.i, this),
+  c: function() {
+    console.log( this.i, this)
+  }
+}
+obj.b(); // prints undefined, Window {...} (or the global object)
+obj.c(); // prints 10, Object {...}
+
+ +

화살표 함수는 자신의 this를 가지고("bind" 바인드)있지 않습니다.{{jsxref("Object.defineProperty()")}}

+ +
'use strict';
+
+var obj = {
+  a: 10
+};
+
+Object.defineProperty(obj, 'b', {
+  get: () => {
+    console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object)
+    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
+  }
+});
+ +

new 연산자 사용

+ +

화살표 함수는 생성자로서 사용될 수 없으며 new와 함께 사용하면 오류가 발생합니다.

+ +
var Foo = () => {};
+var foo = new Foo(); // TypeError: Foo is not a constructor
+ +

prototype 속성 사용

+ +

화살표 함수는 prototype 속성이 없습니다.

+ +
var Foo = () => {};
+console.log(Foo.prototype); // undefined
+ +

yield 키워드 사용

+ +

yield 키워드는 화살표 함수의 본문(그 안에 더 중첩된 함수 내에서 허용한 경우를 제외하고)에 사용될 수 없습니다. 그 결과, 화살표 함수는 생성기(generator)로서 사용될 수 없습니다.

+ +

함수 본문

+ +

화살표 함수는 "concise 바디"든 보통 "block 바디"든 하나를 가질 수 있습니다.

+ +
+

concise바디는 중괄호'{}'로 묶이지않은 한줄짜리 바디이고 block바디는 중괄호로 묶인 바디입니다. 보통 여러줄 쓸때 block바디를 사용합니다.

+
+ +

block바디는 자동으로 값을 반환하지 않습니다. return을 사용해서 값을 반환해야 합니다.

+ +
var func = x => x * x;                  // concise 바디, 생략된 "return" 여기서는 x * x
+var func = (x, y) => { return x + y; }; // block 바디, "return"이 필요
+
+ +

객체 리터럴 반환

+ +

간결한 구문 params => {object:literal}을 사용한 객체 리터럴 반환은 예상대로 작동하지 않음을 명심하세요:

+ +
var func = () => {  foo: 1  };
+// func() 호출은 undefined를 반환!
+
+var func = () => {  foo: function() {}  };
+// SyntaxError: function 문은 이름이 필요함
+ +

이는 중괄호({}) 안 코드가 일련의 문(즉 foo는 라벨처럼 취급됩니다, 객체 리터럴 내 키가 아니라)으로 파싱(parse, 구문 분석)되기 때문입니다.

+ +

객체 리터럴를 괄호로 감싸는 것을 기억하세요:

+ +
var func = () => ({ foo: 1 });
+ +

줄바꿈

+ +

화살표 함수는 파라메터와 화살표 사이에 개행 문자를 포함 할 수 없습니다.

+ +
var func = (a, b, c)
+           => 1;
+// SyntaxError: expected expression, got '=>'
+ +

하지만, 보기 좋은 코드를 유지하고 싶다면, 아래에 보는 것처럼 괄호나 개행을 둠으로써 이를 수정할 수 있습니다.

+ +
var func = (a, b, c) =>
+  1;
+
+var func = (a, b, c) => (
+  1
+);
+
+var func = (a, b, c) => {
+  return 1
+};
+
+var func = (
+  a,
+  b,
+  c
+) => 1;
+
+// SyntaxError가 발생하지 않습니다.
+ +

파싱순서

+ +

화살표 함수 내의 화살표는 연산자가 아닙니다. 그러나 화살표 함수는 평범한 함수와 비교했을 때 operator precedence와 다르게 반응하는 특별한 파싱룰을 가지고 있습니다.

+ +
let callback;
+
+callback = callback || function() {}; // ok
+
+callback = callback || () => {};
+// SyntaxError: invalid arrow-function arguments
+
+callback = callback || (() => {});    // ok
+
+ +

다른 예

+ +

기본 사용법

+ +
//  empty 화살표 함수는 undefined를 반환 
+let empty = () => {};
+
+(() => 'foobar')();
+// "foobar" 반환
+// (this is an Immediately Invoked Function Expression
+
+var simple = a => a > 15 ? 15 : a;
+simple(16); // 15
+simple(10); // 10
+
+let max = (a, b) => a > b ? a : b;
+
+// Easy array filtering, mapping, ...
+
+var arr = [5, 6, 13, 0, 1, 18, 23];
+
+var sum = arr.reduce((a, b) => a + b);
+// 66
+
+var even = arr.filter(v => v % 2 == 0);
+// [6, 0, 18]
+
+var double = arr.map(v => v * 2);
+// [10, 12, 26, 0, 2, 36, 46]
+
+// 더 간결한 promise 체인
+promise.then(a => {
+  // ...
+}).then(b => {
+  // ...
+});
+
+// 매개변수가 없는 경우에도 더 읽기 쉬움
+setTimeout( () => {
+  console.log('I happen sooner');
+  setTimeout( () => {
+    // deeper code
+    console.log('I happen later');
+  }, 1);
+}, 1);
+ +

스펙

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.functions.arrow_functions")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/aggregateerror/index.html b/files/ko/web/javascript/reference/global_objects/aggregateerror/index.html new file mode 100644 index 0000000000..b83db1139e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/aggregateerror/index.html @@ -0,0 +1,87 @@ +--- +title: AggregateError +slug: Web/JavaScript/Reference/Global_Objects/AggregateError +tags: + - AggregateError + - 실험적 + - 인터페이스 + - 자바스크립트 + - 클래스 +translation_of: Web/JavaScript/Reference/Global_Objects/AggregateError +--- +
{{JSRef}}
+ +

AggregateError 객체는 다수의 에러가 한 에러로 랩핑되어야 할 때의 오류를 나타냅니다. 한 작업에서 여러개의 오류가 보고될 때 발생하는데, 대표적으로 {{JSxRef("Promise.any()")}}에 전달된 모든 promise들이 거부되었을 때 발생합니다.

+ +

Constructor

+ +
+
{{jsxref("Global_Objects/AggregateError/AggregateError", "AggregateError()")}}
+
새로운 AggregateError 객체를 생성합니다.
+
+ +

Instance properties

+ +
+
{{JSxRef("Error.prototype.message", "AggregateError.prototype.message")}}
+
에러 메시지, 기본값 "".
+
{{JSxRef("Error.prototype.name", "AggregateError.prototype.name")}}
+
에러 이름, 기본값 AggregateError.
+
+ +

Examples

+ +

AggregateError 다루기

+ +
Promise.any([
+  Promise.reject(new Error("some error")),
+]).catch(e => {
+  console.log(e instanceof AggregateError); // true
+  console.log(e.message);                   // "All Promises rejected"
+  console.log(e.name);                      // "AggregateError"
+  console.log(e.errors);                    // [ Error: "some error" ]
+});
+
+ +

AggregateError 발생시키기

+ +
try {
+  throw new AggregateError([
+    new Error("some error"),
+  ], 'Hello');
+} catch (e) {
+  console.log(e instanceof AggregateError); // true
+  console.log(e.message);                   // "Hello"
+  console.log(e.name);                      // "AggregateError"
+  console.log(e.errors);                    // [ Error: "some error" ]
+}
+
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('Promise.any', '#sec-aggregate-error-objects', 'AggregateError')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.AggregateError")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html b/files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html new file mode 100644 index 0000000000..89e08aa41e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/@@iterator/index.html @@ -0,0 +1,84 @@ +--- +title: 'Array.prototype[@@iterator]()' +slug: Web/JavaScript/Reference/Global_Objects/Array/@@iterator +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/@@iterator +--- +
{{JSRef}}
+ +

 @@iterator 속성의 초기 값은 {{jsxref("Array.prototype.values()", "values()")}} 속성의 초기 값과 같은 함수 객체입니다.

+ +

구문

+ +
arr[Symbol.iterator]()
+ +

반환 값

+ +

{{jsxref("Array.prototype.values()", "values()")}} 반복기가 반환하는 초기 값. arr[Symbol.iterator]의 기본값은 {{jsxref("Array.prototype.values()", "values()")}} 입니다.

+ +

예제

+ +

for…of 반복문을 이용한 순회

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr[Symbol.iterator]();
+// your browser must support for..of loop
+// and let-scoped variables in for loops
+// const and var could also be used
+for (let letter of eArr) {
+  console.log(letter);
+}
+ +

다른 방법

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr[Symbol.iterator]();
+console.log(eArr.next().value); // w
+console.log(eArr.next().value); // y
+console.log(eArr.next().value); // k
+console.log(eArr.next().value); // o
+console.log(eArr.next().value); // p
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES6', '#sec-array.prototype-@@iterator', 'Array.prototype[@@iterator]()')}}{{Spec2('ES2015')}}초기 정의.
{{SpecName('ESDraft', '#sec-array.prototype-@@iterator', 'Array.prototype[@@iterator]()')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.@@iterator")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/@@species/index.html b/files/ko/web/javascript/reference/global_objects/array/@@species/index.html new file mode 100644 index 0000000000..7b1bda0ca6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/@@species/index.html @@ -0,0 +1,75 @@ +--- +title: 'get Array[@@species]' +slug: Web/JavaScript/Reference/Global_Objects/Array/@@species +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/@@species +--- +
{{JSRef}}
+ +

Array[@@species] 접근자 속성은 Array 생성자를 반환합니다.

+ +

구문

+ +
Array[Symbol.species]
+
+ +

반환 값

+ +

{{jsxref("Array")}} 생성자.

+ +

설명

+ +

species 접근자 속성은 Array 객체의 기본 생성자를 반환합니다. 서브클래스 생성자는 생성자 할당을 변경하기 위해 이 속성을 재정의할 수 있습니다.

+ +

예제

+ +

species 속성은 Array 객체의 Array 생성자를 반환합니다.

+ +
Array[Symbol.species]; // function Array()
+ +

파생 콜렉션 개체(예시: 사용자 설정 배열인 MyArray)에서, MyArrayspeciesMyArray 생성자입니다. 그러나 이 속성을 재정의하면 파생 클래스 메서드에서 상위 Array 객체를 반환할 수 있습니다.

+ +
class MyArray extends Array {
+  // MyArray species를 부모 Array 생성자로 재설정
+  static get [Symbol.species]() { return Array; }
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES6', '#sec-get-array-@@species', 'get Array [ @@species ]')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-get-array-@@species', 'get Array [ @@species ]')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.@@species")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html b/files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html new file mode 100644 index 0000000000..1ac7f0b29b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/@@unscopables/index.html @@ -0,0 +1,72 @@ +--- +title: 'Array.prototype[@@unscopables]' +slug: Web/JavaScript/Reference/Global_Objects/Array/@@unscopables +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/@@unscopables +--- +
{{JSRef}}
+ +

@@unscopable 기호 속성은 ES2015 이전 ECMAScript 표준에 포함되지 않은 속성 이름을 포함합니다. 해당 속성들은 {{jsxref("Statements/with", "with")}} 바인딩에서 제외됩니다.

+ +

구문

+ +
arr[Symbol.unscopables]
+ +

설명

+ +

with 바인딩에서 제외되는 배열의 기본 속성은 copyWithin, entries, fill, find, findIndex, includes, keys, values입니다.

+ +

자신의 객체에 대해 unscopables를 설정하는 방법은 {{jsxref("Symbol.unscopables")}}를 참고하세요.

+ +

{{js_property_attributes (0,0,1)}}

+ +

예제

+ +

아래 코드는 ES5 이하에서 잘 작동합니다. 그러나 ECMAScript 2015 이후 {{jsxref("Array.prototype.keys()")}} 메서드가 도입되었습니다. 이는 with 내부에서 "keys"가 변수가 아니라 메서드임을 의미합니다. 여기서 Array.prototype[@@unscopables]가 개입하여 일부 배열 메서드가 with 범위에 묶이는 일을 방지합니다.

+ +
var keys = [];
+
+with (Array.prototype) {
+  keys.push("something");
+}
+
+Object.keys(Array.prototype[Symbol.unscopables]);
+// ["copyWithin", "entries", "fill", "find", "findIndex",
+//  "includes", "keys", "values"]
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.prototype-@@unscopables', 'Array.prototype[@@unscopables]')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype-@@unscopables', 'Array.prototype[@@unscopables]')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.@@unscopables")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/array/index.html b/files/ko/web/javascript/reference/global_objects/array/array/index.html new file mode 100644 index 0000000000..3f3d60a4ec --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/array/index.html @@ -0,0 +1,86 @@ +--- +title: Array() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/Array/Array +tags: + - Array + - Constructor + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Array +--- +
{{JSRef}}
+ +

Array() 생성자는 새로운 {{jsxref("Array")}} 객체를 생성할 때 사용합니다.

+ +

구문

+ +
[element0, element1, ..., elementN]
+
+new Array(element0, element1[, ...[, elementN]])
+new Array(arrayLength)
+ +

매개변수

+ +
+
elementN
+
JavaScript 배열을 초기화할 때 채워넣을 요소. 단, 항목이 하나 뿐이며 그 항목의 자료형이 숫자일 경우 아래의 arrayLength 매개변수로 간주합니다.
+
arrayLength
+
Array 생성자에 제공한 유일한 매개변수가 0에서 232-1 이하의 정수인 경우, length 속성이 해당 값인 새로운 JavaScript 배열을 생성합니다. (참고: 이렇게 생성한 배열은 arrayLength 만큼의 빈 슬롯을 가지는 것으로, 실제 {{jsxref("undefined")}}를 채우는 것이 아닙니다.) 값이 범위 밖이거나 정수가 아닌 경우 {{jsxref("RangeError")}}가 발생합니다.
+
+ +

예제

+ +

배열 리터럴 표기법

+ +

배열은 리터럴 표기법으로 생성할 수도 있습니다.

+ +
let fruits = ['사과', '바나나']
+
+console.log(fruits.length) // 2
+console.log(fruits[0])     // "사과"
+
+ +

단일 매개변수 배열 생성자

+ +

배열을 생성자와 하나의 숫자 매개변수로 생성할 수 있습니다. 그 결과는 length가 매개변수고, 길이만큼의 빈 슬롯을 가진 배열입니다.

+ +
let fruits = new Array(2)
+
+console.log(fruits.length) // 2
+console.log(fruits[0])     // undefined
+
+ +

복수 매개변수 배열 생성자

+ +

생성자에 두 개 이상의 매개변수를 제공할 경우, 매개변수를 원소로 하는 새로운 배열을 생성합니다.

+ +
let fruits = new Array('사과', '바나나')
+
+console.log(fruits.length) // 2
+console.log(fruits[0])     // "사과"
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array-constructor', 'Array constructor')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.Array")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/concat/index.html b/files/ko/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..b35f040632 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,138 @@ +--- +title: Array.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +
{{JSRef}}
+ +

concat() 메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다. 

+ + + +
{{EmbedInteractiveExample("pages/js/array-concat.html")}}
+ + + +

구문

+ +
array.concat([value1[, value2[, ...[, valueN]]]])
+ +

매개변수

+ + + +
+
valueN {{optional_inline}}
+
자세한 내용은 아래 설명을 참고하세요.
+
+ +

반환값

+ +

새로운 {{jsxref("Array")}} 객체.

+ +

설명

+ +

concat은 메서드를 호출한 배열 뒤에 각 인수를 순서대로 붙여 새로운 배열을 만듭니다. 인수가 배열이면 그 구성요소가 순서대로 붙고, 배열이 아니면 인수 자체가 붙습니다. 중첩 배열 내부로 재귀하지 않습니다.

+ +

concatthis나 인수로 넘겨진 배열의 내용을 바꾸지 않고, 대신 주어진 배열을 합친 뒤 그 얕은 사본을 반환합니다. 새 배열에는 원본 배열의 요소를 다음과 같은 방법으로 복사합니다.

+ + + +
+

참고: 배열이나 값을 이어붙여도 원본은 변하지 않으며, 새로운 배열이나 원본 배열을 조작해도 서로 영향을 받지 않습니다.

+
+ +

예제

+ +

배열 두 개 이어붙이기

+ +

다음 예제는 두 개의 배열을 이어붙입니다.

+ +
const alpha = ['a', 'b', 'c'];
+const numeric = [1, 2, 3];
+
+alpha.concat(numeric);
+// 결과: ['a', 'b', 'c', 1, 2, 3]
+
+ +

배열 세 개 이어붙이기

+ +

다음 예제는 세 개의 배열을 이어붙입니다.

+ +
const num1 = [1, 2, 3];
+const num2 = [4, 5, 6];
+const num3 = [7, 8, 9];
+
+num1.concat(num2, num3);
+// 결과: [1, 2, 3, 4, 5, 6, 7, 8, 9]
+
+ +

배열에 값 이어붙이기

+ +

다음 코드는 배열에 세 개의 값을 이어붙입니다.

+ +
const alpha = ['a', 'b', 'c'];
+
+alpha.concat(1, [2, 3]);
+// 결과: ['a', 'b', 'c', 1, 2, 3]
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES3')}}{{Spec2('ES3')}}최초 정의. JavaScript 1.2에서 구현됨.
{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.concat")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/copywithin/index.html b/files/ko/web/javascript/reference/global_objects/array/copywithin/index.html new file mode 100644 index 0000000000..7d6c2cdf8b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/copywithin/index.html @@ -0,0 +1,183 @@ +--- +title: Array.prototype.copyWithin() +slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +--- +
{{JSRef}}
+ +

copyWithin() 메서드는 배열의 일부를 얕게 복사한 뒤, 동일한 배열의 다른 위치에 덮어쓰고 그 배열을 반환합니다. 이 때, 크기(배열의 길이)를 수정하지 않고 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}

+ +

구문

+ +
arr.copyWithin(target[, start[, end]])
+
+ +

매개변수

+ +
+
target
+
복사한 시퀀스(값)를 넣을 위치를 가리키는 0 기반 인덱스. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산합니다.
+
+ targetarr.length보다 크거나 같으면 아무것도 복사하지 않습니다. targetstart 이후라면 복사한 시퀀스를 arr.length에 맞춰 자릅니다.
+
start {{optional_inline}}
+
복사를 시작할 위치를 가리키는 0 기반 인덱스. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산합니다.
+
+ 기본값은 0으로, start를 지정하지 않으면 배열의 처음부터 복사합니다.
+
end {{optional_inline}}
+
복사를 끝낼 위치를 가리키는 0 기반 인덱스. copyWithinend 인덱스 이전까지 복사하므로 end 인덱스가 가리키는 요소는 제외합니다. 음수를 지정하면 인덱스를 배열의 끝에서부터 계산합니다.
+
+ 기본값은 arr.length로, end를 지정하지 않으면 배열의 끝까지 복사합니다.
+
+ +

반환 값

+ +

수정한 배열.

+ +

설명

+ +

copyWithin은 C와 C++의 memmove처럼 작동하고, 복사와 대입이 하나의 연산에서 이루어지므로 {{jsxref("Array")}}의 데이터를 이동할 때 사용할 수 있는 고성능 메서드입니다. {{jsxref("TypedArray.prototype.copyWithin()", "TypedArray")}}의 동명 메서드에서 이 특징이 두드러집니다. 붙여넣은 시퀀스의 위치가 복사한 범위와 겹치더라도 최종 결과는 원본 배열에서 복사한 것과 같습니다.

+ +

copyWithin 함수는 제네릭 함수로, this 값이 {{jsxref("Array")}} 객체일 필요는 없습니다.

+ +

copyWithin 메서드는 변경자 메서드로, this의 길이는 바꾸지 않지만 내용을 바꾸며 필요하다면 새로운 속성을 생성합니다.

+ +

예제

+ +
[1, 2, 3, 4, 5].copyWithin(-2);
+// [1, 2, 3, 1, 2]
+
+[1, 2, 3, 4, 5].copyWithin(0, 3);
+// [4, 5, 3, 4, 5]
+
+[1, 2, 3, 4, 5].copyWithin(0, 3, 4);
+// [4, 2, 3, 4, 5]
+
+[1, 2, 3, 4, 5].copyWithin(-2, -3, -1);
+// [1, 2, 3, 3, 4]
+
+[].copyWithin.call({length: 5, 3: 1}, 0, 3);
+// {0: 1, 3: 1, length: 5}
+
+// ES2015 TypedArray는 Array의 하위 클래스
+var i32a = new Int32Array([1, 2, 3, 4, 5]);
+
+i32a.copyWithin(0, 2);
+// Int32Array [3, 4, 5, 4, 5]
+
+// 아직 ES2015를 사용할 수 없는 환경에서
+[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
+// Int32Array [4, 2, 3, 4, 5]
+
+ +

폴리필

+ +
if (!Array.prototype.copyWithin) {
+  Array.prototype.copyWithin = function(target, start/*, end*/) {
+    // Steps 1-2.
+    if (this == null) {
+      throw new TypeError('this is null or not defined');
+    }
+
+    var O = Object(this);
+
+    // Steps 3-5.
+    var len = O.length >>> 0;
+
+    // Steps 6-8.
+    var relativeTarget = target >> 0;
+
+    var to = relativeTarget < 0 ?
+      Math.max(len + relativeTarget, 0) :
+      Math.min(relativeTarget, len);
+
+    // Steps 9-11.
+    var relativeStart = start >> 0;
+
+    var from = relativeStart < 0 ?
+      Math.max(len + relativeStart, 0) :
+      Math.min(relativeStart, len);
+
+    // Steps 12-14.
+    var end = arguments[2];
+    var relativeEnd = end === undefined ? len : end >> 0;
+
+    var final = relativeEnd < 0 ?
+      Math.max(len + relativeEnd, 0) :
+      Math.min(relativeEnd, len);
+
+    // Step 15.
+    var count = Math.min(final - from, len - to);
+
+    // Steps 16-17.
+    var direction = 1;
+
+    if (from < to && to < (from + count)) {
+      direction = -1;
+      from += count - 1;
+      to += count - 1;
+    }
+
+    // Step 18.
+    while (count > 0) {
+      if (from in O) {
+        O[to] = O[from];
+      } else {
+        delete O[to];
+      }
+
+      from += direction;
+      to += direction;
+      count--;
+    }
+
+    // Step 19.
+    return O;
+  };
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ES7', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ES7')}} 
{{SpecName('ESDraft', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.copyWithin")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/entries/index.html b/files/ko/web/javascript/reference/global_objects/array/entries/index.html new file mode 100644 index 0000000000..316886c261 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/entries/index.html @@ -0,0 +1,89 @@ +--- +title: Array.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Array/entries +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries +--- +
{{JSRef}}
+ +

entries() 메서드는 배열의 각 인덱스에 대한 키/값 쌍을 가지는 새로운 Array Iterator 객체를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-entries.html")}}

+ + + +

구문

+ +
arr.entries()
+
+ +

반환 값

+ +

{{jsxref("Array")}} 반복자 인스턴스 객체.

+ +

예시

+ +

인덱스와 요소 이터레이팅

+ +
const a = ['a', 'b', 'c'];
+
+for (const [index, element] of a.entries())
+  console.log(index, element);
+
+// 0 'a'
+// 1 'b'
+// 2 'c'
+ +

for…of 루프 사용

+ +
var a = ['a', 'b', 'c'];
+var iterator = a.entries();
+
+for (let e of iterator) {
+  console.log(e);
+}
+// [0, 'a']
+// [1, 'b']
+// [2, 'c']
+
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Array.entries")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/every/index.html b/files/ko/web/javascript/reference/global_objects/array/every/index.html new file mode 100644 index 0000000000..827b81e760 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/every/index.html @@ -0,0 +1,191 @@ +--- +title: Array.prototype.every() +slug: Web/JavaScript/Reference/Global_Objects/Array/every +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/every +--- +
{{JSRef}}
+ +

every() 메서드는 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트합니다.

+ +
+

참고: 빈 배열에서 호출하면 무조건 true를 반환합니다.

+
+ +
{{EmbedInteractiveExample("pages/js/array-every.html")}}
+ + + +

구문

+ +
arr.every(callback[, thisArg])
+ +

매개변수

+ +
+
callback
+
각 요소를 시험할 함수. 다음 세 가지 인수를 받습니다. +
+
currentValue
+
처리할 현재 요소.
+
index {{Optional_inline}}
+
처리할 현재 요소의 인덱스.
+
array {{Optional_inline}}
+
every를 호출한 배열.
+
+
+
thisArg {{Optional_inline}}
+
callback을 실행할 때 this로 사용하는 값.
+
+ +

반환 값

+ +

callback이 모든 배열 요소에 대해 참({{Glossary("truthy")}})인 값을 반환하는 경우 true, 그 외엔 false.

+ +

설명

+ +

everycallback이 {{glossary("falsy", "거짓")}}을 반환하는 요소를 찾을 때까지 배열에 있는 각 요소에 대해 한 번씩 callback 함수를 실행합니다. 해당하는 요소를 발견한 경우 every는 즉시 false를 반환합니다. 그렇지 않으면, 즉 모든 값에서 참을 반환하면 true를 반환합니다. 할당한 값이 있는 배열의 인덱스에서만 callback을 호출합니다. 삭제했거나 값을 할당한 적이 없는 인덱스에서는 호출하지 않습니다.

+ +

callback은 요소의 값, 해당 요소의 인덱스 및 순회하고 있는 배열 세 가지 인수와 함께 호출됩니다.

+ +

thisArg 매개변수를 every에 제공한 경우 callbackthis로 사용됩니다. 그 외엔 {{jsxref("undefined")}}값을 사용합니다. 최종적으로 callback이 볼 수 있는 this의 값은 함수가 볼 수 있는 this를 결정하는 평소 규칙을 따릅니다.

+ +

every는 호출한 배열을 변형하지 않습니다.

+ +

every가 처리하는 요소의 범위는 callback의 첫 호출 전에 설정됩니다. every 호출 이후로 배열에 추가하는 요소는 callback이 방문하지 않습니다. 배열에 원래 있었지만 아직 방문하지 않은 요소가 callback에 의해 변경된 경우, 그 인덱스를 방문하는 시점의 값을 사용합니다. 삭제한 요소는 방문하지 않습니다.

+ +

every는 (이산)수학에서 전칭(∀) 정량자quantifier(한정자)처럼 행동합니다. 특히, 빈 배열에 대해서는 true를 반환합니다. (이는 공집합의 모든 요소가 어떠한 주어진 조건도 만족하는 공허한 참입니다.)

+ +

예제

+ +

모든 배열 요소의 크기 테스트

+ +

다음 예는 배열의 모든 요소가 10보다 더 큰지 테스트합니다.

+ +
function isBigEnough(element, index, array) {
+  return element >= 10;
+}
+[12, 5, 8, 130, 44].every(isBigEnough);   // false
+[12, 54, 18, 130, 44].every(isBigEnough); // true
+
+ +

화살표 함수 사용

+ +

화살표 함수는 같은 테스트에 대해 더 짧은 구문을 제공합니다.

+ +
[12, 5, 8, 130, 44].every(elem => elem >= 10); // false
+[12, 54, 18, 130, 44].every(elem => elem >= 10); // true
+ +

폴리필

+ +

every는 ECMA-262 표준 제5판에 추가됐으므로 어떤 표준 구현체에서는 사용하지 못할 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 every를 지원하지 않는 환경에서도 사용할 수 있습니다. 아래 알고리즘은 {{jsxref("Object")}}와 {{jsxref("TypeError")}}가 변형되지 않고, callbackfn.call의 계산 값이 원래의 {{jsxref("Function.prototype.call()")}}과 같은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.

+ +
if (!Array.prototype.every) {
+  Array.prototype.every = function(callbackfn, thisArg) {
+    'use strict';
+    var T, k;
+
+    if (this == null) {
+      throw new TypeError('this is null or not defined');
+    }
+
+    // 1. Let O be the result of calling ToObject passing the this
+    //    value as the argument.
+    var O = Object(this);
+
+    // 2. Let lenValue be the result of calling the Get internal method
+    //    of O with the argument "length".
+    // 3. Let len be ToUint32(lenValue).
+    var len = O.length >>> 0;
+
+    // 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
+    if (typeof callbackfn !== 'function') {
+      throw new TypeError();
+    }
+
+    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
+    if (arguments.length > 1) {
+      T = thisArg;
+    }
+
+    // 6. Let k be 0.
+    k = 0;
+
+    // 7. Repeat, while k < len
+    while (k < len) {
+
+      var kValue;
+
+      // a. Let Pk be ToString(k).
+      //   This is implicit for LHS operands of the in operator
+      // b. Let kPresent be the result of calling the HasProperty internal
+      //    method of O with argument Pk.
+      //   This step can be combined with c
+      // c. If kPresent is true, then
+      if (k in O) {
+
+        // i. Let kValue be the result of calling the Get internal method
+        //    of O with argument Pk.
+        kValue = O[k];
+
+        // ii. Let testResult be the result of calling the Call internal method
+        //     of callbackfn with T as the this value and argument list
+        //     containing kValue, k, and O.
+        var testResult = callbackfn.call(T, kValue, k, O);
+
+        // iii. If ToBoolean(testResult) is false, return false.
+        if (!testResult) {
+          return false;
+        }
+      }
+      k++;
+    }
+    return true;
+  };
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.6에서 구현됨.
{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.every")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/fill/index.html b/files/ko/web/javascript/reference/global_objects/array/fill/index.html new file mode 100644 index 0000000000..5a18af7d24 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/fill/index.html @@ -0,0 +1,146 @@ +--- +title: Array.prototype.fill() +slug: Web/JavaScript/Reference/Global_Objects/Array/fill +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill +--- +
{{JSRef}}
+ +

fill() 메서드는 배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채웁니다.

+ +

{{EmbedInteractiveExample("pages/js/array-fill.html")}}

+ +

구문

+ +
arr.fill(value[, start[, end]])
+ +

매개변수

+ +
+
value
+
배열을 채울 값.
+
start {{optional_inline}}
+
시작 인덱스, 기본 값은 0.
+
end {{optional_inline}}
+
끝 인덱스, 기본 값은 this.length.
+
+ +

반환 값

+ +

변형한 배열.

+ +

설명 

+ +

fill 메서드는 value, startend의 3개 인자를 가집니다. startend 인자는 선택 사항으로써 기본값으로 각각 0과, this 객체의 length를 가집니다.

+ +

length가 배열의 길이일 때, start가 음수이면 시작 인덱스는 length+start입니다. end가 음수이면 끝 인덱스는 length+end입니다.

+ +

fill은 일반 함수이며, this 값이 배열 객체일 필요는 없습니다.

+ +

fill 메서드는 변경자 메서드로, 복사본이 아니라 this 객체를 변형해 반환합니다.

+ +

value에 객체를 받을 경우 그 참조만 복사해서 배열을 채웁니다.

+ +

예제

+ +
[1, 2, 3].fill(4);               // [4, 4, 4]
+[1, 2, 3].fill(4, 1);            // [1, 4, 4]
+[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
+[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
+[1, 2, 3].fill(4, 3, 3);         // [1, 2, 3]
+[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]
+[1, 2, 3].fill(4, NaN, NaN);     // [1, 2, 3]
+[1, 2, 3].fill(4, 3, 5);         // [1, 2, 3]
+Array(3).fill(4);                // [4, 4, 4]
+[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}
+
+// Objects by reference.
+var arr = Array(3).fill({}); // [{}, {}, {}]
+arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
+
+ +

폴리필

+ +
if (!Array.prototype.fill) {
+  Object.defineProperty(Array.prototype, 'fill', {
+    value: function(value) {
+
+      // Steps 1-2.
+      if (this == null) {
+        throw new TypeError('this is null or not defined');
+      }
+
+      var O = Object(this);
+
+      // Steps 3-5.
+      var len = O.length >>> 0;
+
+      // Steps 6-7.
+      var start = arguments[1];
+      var relativeStart = start >> 0;
+
+      // Step 8.
+      var k = relativeStart < 0 ?
+        Math.max(len + relativeStart, 0) :
+        Math.min(relativeStart, len);
+
+      // Steps 9-10.
+      var end = arguments[2];
+      var relativeEnd = end === undefined ?
+        len : end >> 0;
+
+      // Step 11.
+      var final = relativeEnd < 0 ?
+        Math.max(len + relativeEnd, 0) :
+        Math.min(relativeEnd, len);
+
+      // Step 12.
+      while (k < final) {
+        O[k] = value;
+        k++;
+      }
+
+      // Step 13.
+      return O;
+    }
+  });
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.fill', 'Array.prototype.fill')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.fill', 'Array.prototype.fill')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.fill")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/filter/index.html b/files/ko/web/javascript/reference/global_objects/array/filter/index.html new file mode 100644 index 0000000000..9d1b623fd0 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,231 @@ +--- +title: Array.prototype.filter() +slug: Web/JavaScript/Reference/Global_Objects/Array/filter +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter +--- +
{{JSRef}}
+ +

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-filter.html")}}
+ + + +

구문

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

매개변수

+ +
+
callback
+
각 요소를 시험할 함수. true를 반환하면 요소를 유지하고, false를 반환하면 버립니다. 다음 세 가지 매개변수를 받습니다.
+
+
+
element
+
처리할 현재 요소.
+
index {{optional_inline}}
+
처리할 현재 요소의 인덱스.
+
array {{optional_inline}}
+
filter를 호출한 배열.
+
+
+
thisArg {{optional_inline}}
+
callback을 실행할 때 this로 사용하는 값.
+
+ +

반환 값

+ +

테스트를 통과한 요소로 이루어진 새로운 배열. 어떤 요소도 테스트를 통과하지 못했으면 빈 배열을 반환합니다.

+ +

설명

+ +

filter()는 배열 내 각 요소에 대해 한 번 제공된 callback 함수를 호출해, callbacktrue로 강제하는 값을 반환하는 모든 값이 있는 새로운 배열을 생성합니다. callback은 할당된 값이 있는 배열의 인덱스에 대해서만 호출됩니다; 삭제됐거나 값이 할당된 적이 없는 인덱스에 대해서는 호출되지 않습니다. callback 테스트를 통과하지 못한 배열 요소는 그냥 건너뛰며 새로운 배열에 포함되지 않습니다.

+ +

callback은 다음 세 인수와 함께 호출됩니다:

+ +
    +
  1. 요소값
  2. +
  3. 요소 인덱스
  4. +
  5. 순회(traverse)되는 배열 객체
  6. +
+ +

thisArg 매개변수가 filter에 제공된 경우, 호출될 때 그 값은 callbackthis 값으로 전달됩니다.  그 이외에, undefined값도 callback의 this 값으로 쓰기 위해 전달됩니다. 결국 callback에 의해 관찰될 수 있는 this 값은 this를 결정하는 함수의 평소 규칙에 따라 결정됩니다.

+ +

filter()는 호출되는 배열을 변화시키지(mutate) 않습니다.

+ +

filter()에 의해 처리되는 요소의 범위는 callback의 첫 호출 전에 설정됩니다. filter() 호출 시작 이후로 배열에 추가된 요소는 callback에 의해 방문되지 않습니다. 배열의 기존 요소가 변경 또는 삭제된 경우, callback에 전달된 그 값은 filter()가 그 요소를 방문한 시점에 값이 됩니다; 삭제된 요소는 반영되지 않습니다.

+ +

예제

+ +

모든 작은 값 걸러내기

+ +

다음 예는 값이 10 이하인 모든 요소가 제거된 걸러진 배열을 만들기 위해 filter()를 사용합니다.

+ +
function isBigEnough(value) {
+  return value >= 10;
+}
+
+var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
+// filtered 는 [12, 130, 44]
+
+ +

JSON에서 무효한 항목 거르기

+ +

다음 예는 0이 아닌, 숫자 id인 모든 요소의 걸러진 json을 만들기 위해 filter()를 사용합니다.

+ +
var arr = [
+  { id: 15 },
+  { id: -1 },
+  { id: 0 },
+  { id: 3 },
+  { id: 12.2 },
+  { },
+  { id: null },
+  { id: NaN },
+  { id: 'undefined' }
+];
+
+var invalidEntries = 0;
+
+function isNumber(obj) {
+  return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
+}
+
+function filterByID(item) {
+  if (isNumber(item.id) && item.id !== 0) {
+    return true;
+  }
+  invalidEntries++;
+  return false;
+}
+
+var arrByID = arr.filter(filterByID);
+
+console.log('Filtered Array\n', arrByID);
+// Filtered Array
+// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
+
+console.log('Number of Invalid Entries = ', invalidEntries);
+// Number of Invalid Entries = 5
+
+ +

배열 내용 검색

+ +

다음 예는 배열 내용을 조건에 따라 검색하기 위해 filter() 를 사용합니다.

+ +
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
+
+/**
+ * 검색 조건에 따른 배열 필터링(쿼리)
+ */
+function filterItems(query) {
+  return fruits.filter(function(el) {
+      return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
+  })
+}
+
+console.log(filterItems('ap')); // ['apple', 'grapes']
+console.log(filterItems('an')); // ['banana', 'mango', 'orange']
+ +

ES2015로 구현

+ +
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
+
+/**
+ * 검색 조건에 따른 배열 필터링(쿼리)
+ */
+const filterItems = (query) => {
+  return fruits.filter((el) =>
+    el.toLowerCase().indexOf(query.toLowerCase()) > -1
+  );
+}
+
+console.log(filterItems('ap')); // ['apple', 'grapes']
+console.log(filterItems('an')); // ['banana', 'mango', 'orange']
+ +

폴리필

+ +

filter는 ECMA-262 표준 제5판에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 환경에서도 filter를 사용할 수 있습니다. 아래 알고리즘은 fn.call의 계산 값이 원래의 Function.prototype.call()과 같고, {{jsxref("Array.prototype.push()")}}가 변형되지 않은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.

+ +
if (!Array.prototype.filter){
+  Array.prototype.filter = function(func, thisArg) {
+    'use strict';
+    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
+        throw new TypeError();
+
+    var len = this.length >>> 0,
+        res = new Array(len), // preallocate array
+        t = this, c = 0, i = -1;
+    if (thisArg === undefined){
+      while (++i !== len){
+        // checks to see if the key was set
+        if (i in this){
+          if (func(t[i], i, t)){
+            res[c++] = t[i];
+          }
+        }
+      }
+    }
+    else{
+      while (++i !== len){
+        // checks to see if the key was set
+        if (i in this){
+          if (func.call(thisArg, t[i], i, t)){
+            res[c++] = t[i];
+          }
+        }
+      }
+    }
+
+    res.length = c; // shrink down array to proper size
+    return res;
+  };
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.6에서 구현됨.
{{SpecName('ES6', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.filter")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/find/index.html b/files/ko/web/javascript/reference/global_objects/array/find/index.html new file mode 100644 index 0000000000..92a0208a6b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,226 @@ +--- +title: Array.prototype.find() +slug: Web/JavaScript/Reference/Global_Objects/Array/find +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/find +--- +
{{JSRef}}
+ +

find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소을 반환합니다. 그런 요소가 없다면 {{jsxref("undefined")}}를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-find.html")}}
+ + + +

찾은 요소의 값 대신 인덱스를 반환하는 {{jsxref("Array.findIndex", "findIndex()")}} 메서드도 살펴보세요.

+ +

배열 요소의 위치를 찾고자 하는 경우에는 {{jsxref("Array.prototype.indexOf()")}}를 사용하세요.

+ +

배열 요소가 해당 배열에 존재하는지 확인하고자 하는 경우에는 {{jsxref("Array.prototype.indexOf()")}} 또는 {{jsxref("Array.prototype.includes()")}}를 사용세요.

+ +

구문

+ +
arr.find(callback[, thisArg])
+ +

매개변수

+ +
+
callback
+
배열의 각 값에 대해 실행할 함수. 아래의 세 인자를 받습니다. +
+
element
+
콜백함수에서 처리할 현재 요소.
+
index{{optional_inline}}
+
콜백함수에서 처리할 현재 요소의 인덱스.
+
array{{optional_inline}}
+
find 함수를 호출한 배열.
+
+
+
thisArg
+
선택 항목. 콜백이 호출될 때 this로 사용할 객체.
+
+ +

반환 값

+ +

주어진 판별 함수를 만족하는 첫 번째 요소. 그 외에는 {{jsxref("undefined")}}.

+ +

설명

+ +

find 메서드는 callback 함수가 참을 반환 할 때까지 해당 배열의 각 요소에 대해서 callback 함수를 실행합니다. 만약 어느 요소를 찾았다면 find 메서드는 해당 요소의 값을 즉시 반환하고, 그렇지 않았다면 {{jsxref("undefined")}}를 반환합니다. callback0 부터 length - 1 까지 배열의 모든 인덱스에 대해 호출되며, 값이 지정되지 않은 요소도 포함하여 모든 인덱스에 대해 호출됩니다. 따라서, 희소 배열 (sparse arrays)의 경우에는 값이 지정된 요소만 탐색하는 다른 메소드에 비해 더 비효율적입니다.

+ +

callback은 다음의 세가지 인자를 가지고 호출됩니다: 요소의 값, 요소의 인덱스, 순회의 대상이 되는 배열. 

+ +

thisArg 파라미터가 주어진 경우에는 제공되었다면  thisArgcallback안에서 this로 사용되고, 그렇지 않은 경우 {{jsxref("undefined")}} 가 this로 사용됩니다. 

+ +

find는 호출의 대상이 된 배열을 변경(mutate)하지 않습니다.

+ +

find가 처리할 배열 요소의 범위는 첫 callback이 호출되기 전에 먼저 결정됩니다. find메서드가 실행 된 이후에 배열에 추가된 요소들에 대해서는 callback이 호출되지 않습니다. 아직 callback이 호출되지 않았던 배열 요소가 callback에 의해서 변경된 경우, find가 해당 요소의 인덱스를 방문할 때의 값으로 callback함수에 전달될 것입니다. 즉, 삭제된 요소에도 callback이 호출됩니다.

+ +

예제

+ +

속성 중 하나를 사용하여 배열에서 객체 찾기

+ +
var inventory = [
+    {name: 'apples', quantity: 2},
+    {name: 'bananas', quantity: 0},
+    {name: 'cherries', quantity: 5}
+];
+
+function findCherries(fruit) {
+    return fruit.name === 'cherries';
+}
+
+console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
+
+ +

ES2015 화살표 함수 사용하기

+ +

 

+ +
const inventory = [
+    {name: 'apples', quantity: 2},
+    {name: 'bananas', quantity: 0},
+    {name: 'cherries', quantity: 5}
+];
+
+const result = inventory.find(fruit => fruit.name === 'cherries');
+
+console.log(result) // { name: 'cherries', quantity: 5 }
+ +

 

+ +

배열에서 소수 찾기

+ +

다음 예제에서는 배열의 요소 중 소수인 요소를 찾습니다(소수가 없는 경우에는 {{jsxref("undefined")}}를 반환).

+ +
function isPrime(element, index, array) {
+  var start = 2;
+  while (start <= Math.sqrt(element)) {
+    if (element % start++ < 1) {
+      return false;
+    }
+  }
+  return element > 1;
+}
+
+console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
+console.log([4, 5, 8, 12].find(isPrime)); // 5
+
+ +

탐색 중 삭제된 배열 요소

+ +

다음 예제에서는 삭제되어 존재하지 않는 배열의 요소에도 callback이 호출되어 해당 시점의 값이 callback에 전달되는 것을 보여줍니다.

+ +
// Declare array with no element at index 2, 3 and 4
+var a = [0,1,,,,5,6];
+
+// Shows all indexes, not just those that have been assigned values
+a.find(function(value, index) {
+  console.log('Visited index ' + index + ' with value ' + value);
+});
+// Shows all indexes, including deleted
+  a.find(function(value, index) {
+  // Delete element 5 on first iteration
+  if (index == 0) {
+    console.log('Deleting a[5] with value ' + a[5]);
+    delete a[5];
+  }
+  // Element 5 is still visited even though deleted
+  console.log('Visited index ' + index + ' with value ' + value);
+});
+
+ +

폴리필

+ +

find는 ECMAScript 2015 명세에 추가됐으므로 어떤 표준 구현체에서는 사용지 못할 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 find를 지원하지 않는 환경에서도 사용할 수 있습니다.

+ +
// https://tc39.github.io/ecma262/#sec-array.prototype.find
+if (!Array.prototype.find) {
+  Object.defineProperty(Array.prototype, 'find', {
+    value: function(predicate) {
+     // 1. Let O be ? ToObject(this value).
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
+      if (typeof predicate !== 'function') {
+        throw new TypeError('predicate must be a function');
+      }
+
+      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
+      var thisArg = arguments[1];
+
+      // 5. Let k be 0.
+      var k = 0;
+
+      // 6. Repeat, while k < len
+      while (k < len) {
+        // a. Let Pk be ! ToString(k).
+        // b. Let kValue be ? Get(O, Pk).
+        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
+        // d. If testResult is true, return kValue.
+        var kValue = o[k];
+        if (predicate.call(thisArg, kValue, k, o)) {
+          return kValue;
+        }
+        // e. Increase k by 1.
+        k++;
+      }
+
+      // 7. Return undefined.
+      return undefined;
+    },
+    configurable: true,
+    writable: true
+  });
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.find")}}
+ +
 
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/findindex/index.html b/files/ko/web/javascript/reference/global_objects/array/findindex/index.html new file mode 100644 index 0000000000..9406439e6a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/findindex/index.html @@ -0,0 +1,146 @@ +--- +title: Array.prototype.findIndex() +slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex +--- +
{{JSRef}}
+ +

findIndex() 메서드는 주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다. 만족하는 요소가 없으면 -1을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-findindex.html")}}
+ + + +

인덱스 대신 을 반환하는 {{jsxref("Array.prototype.find", "find()")}} 메서드도 참고하세요.

+ +

구문

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

매개변수

+ +
+
callback
+
3개의 인수를 취하여 배열의 각 값에 대해 실행할 함수입니다.
+
+
+
element
+
배열에서 처리중인 현재 요소입니다.
+
index
+
배열에서 처리중인 현재 요소의 인덱스입니다.
+
array
+
findIndex 함수가 호출된 배열입니다.
+
+
+
thisArg
+
선택 사항. 콜백을 실행할 때 this로 사용할 객체입니다.
+
+ +

반환 값

+ +

요소가 테스트를 통과하면 배열의 인덱스. 그렇지 않으면 -1입니다.

+ +

설명

+ +

findIndex 메서드는 콜백 함수가 진리 값 (true를 반환하는 값)을 반환 할 때까지 배열의 모든 배열 인덱스 0..length-1 (포함)에 대해 한 번씩 콜백 함수를 실행합니다. 이러한 요소가 발견되면 findIndex는 해당 반복에 대한 색인을 즉시 반환합니다. 콜백이 진리 값을 반환하지 않거나 배열의 길이가 0 인 경우 findIndex는 -1을 반환합니다. Array # some과 같은 다른 배열 메소드와는 달리, 배열에 존재하지 않는 엔트리의 인덱스에 대해서조차 콜백이 호출됩니다.

+ +

콜백은 요소의 값, 요소의 인덱스 및 가로 지르는 Array 객체의 세 가지 인수로 호출됩니다.

+ +

thisArg 매개 변수가 findIndex에 제공되면 콜백 호출마다 thisArg 매개 변수가 사용됩니다. 제공되지 않으면 {{jsxref ( "undefined")}}가 사용됩니다.

+ +

findIndex는 호출 된 배열을 변경하지 않습니다.

+ +

findIndex에 의해 처리되는 요소의 범위는 콜백의 첫 번째 호출 전에 설정됩니다. findIndex 호출이 시작된 후 배열에 추가되는 요소는 콜백에 의해 방문되지 않습니다. 배열의 기존의 방문하지 않은 요소가 콜백에 의해 변경되면 방문 콜백에 전달 된 값은 findIndex가 해당 요소의 인덱스를 방문 할 때의 값이됩니다. 삭제된 요소도 방문합니다.

+ +

예제

+ +

배열에서 소수의 색인 찾기

+ +

다음 예제에서는 배열에서 소수 (소수가없는 경우 -1을 반환) 인 요소의 인덱스를 찾습니다.

+ +
function isPrime(element, index, array) {
+  var start = 2;
+  while (start <= Math.sqrt(element)) {
+    if (element % start++ < 1) {
+      return false;
+    }
+  }
+  return element > 1;
+}
+
+console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
+console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
+
+ +

폴리필

+ +
if (!Array.prototype.findIndex) {
+  Object.defineProperty(Array.prototype, 'findIndex', {
+    value: function(predicate) {
+      'use strict';
+      if (this == null) {
+        throw new TypeError('Array.prototype.findIndex called on null or undefined');
+      }
+      if (typeof predicate !== 'function') {
+        throw new TypeError('predicate must be a function');
+      }
+      var list = Object(this);
+      var length = list.length >>> 0;
+      var thisArg = arguments[1];
+      var value;
+
+      for (var i = 0; i < length; i++) {
+        value = list[i];
+        if (predicate.call(thisArg, value, i, list)) {
+          return i;
+        }
+      }
+      return -1;
+    },
+    enumerable: false,
+    configurable: false,
+    writable: false
+  });
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.findIndex")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/flat/index.html b/files/ko/web/javascript/reference/global_objects/array/flat/index.html new file mode 100644 index 0000000000..4d4af6dc36 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/flat/index.html @@ -0,0 +1,160 @@ +--- +title: Array.prototype.flat() +slug: Web/JavaScript/Reference/Global_Objects/Array/flat +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat +--- +
{{JSRef}}
+ +

flat() 메서드는 모든 하위 배열 요소를 지정한 깊이까지 재귀적으로 이어붙인 새로운 배열을 생성합니다.

+ +

구문

+ +
const newArr = arr.flat([depth])
+ +

매개변수

+ +
+
depth {{optional_inline}}
+
중첩 배열 구조를 평탄화할 때 사용할 깊이 값. 기본값은 1입니다.
+
+ +

반환 값

+ +

하위 배열을 이어붙인 새로운 배열.

+ +

예제

+ +

중첩 배열 평탄화

+ +
const arr1 = [1, 2, [3, 4]];
+arr1.flat();
+// [1, 2, 3, 4]
+
+const arr2 = [1, 2, [3, 4, [5, 6]]];
+arr2.flat();
+// [1, 2, 3, 4, [5, 6]]
+
+const arr3 = [1, 2, [3, 4, [5, 6]]];
+arr3.flat(2);
+// [1, 2, 3, 4, 5, 6]
+
+const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
+arr4.flat(Infinity);
+// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+ +

배열 구멍 제거

+ +

flat 메서드는 배열의 구멍도 제거합니다.

+ +
const arr5 = [1, 2, , 4, 5];
+arr5.flat();
+// [1, 2, 4, 5]
+ +

대안

+ +

reduce와 concat

+ +
const arr = [1, 2, [3, 4]];
+
+// To flat single level array
+arr.flat();
+// is equivalent to
+arr.reduce((acc, val) => acc.concat(val), []);
+// [1, 2, 3, 4]
+
+// or with decomposition syntax
+const flattened = arr => [].concat(...arr);
+ +

reduce + concat + isArray + 재귀

+ +
const arr = [1, 2, [3, 4, [5, 6]]];
+
+// to enable deep level flatten use recursion with reduce and concat
+function flatDeep(arr, d = 1) {
+   return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
+                : arr.slice();
+};
+
+flatDeep(arr, Infinity);
+// [1, 2, 3, 4, 5, 6]
+ +

스택

+ +
// non recursive flatten deep using a stack
+// note that depth control is hard/inefficient as we will need to tag EACH value with its own depth
+// also possible w/o reversing on shift/unshift, but array OPs on the end tends to be faster
+function flatten(input) {
+  const stack = [...input];
+  const res = [];
+  while(stack.length) {
+    // pop value from stack
+    const next = stack.pop();
+    if(Array.isArray(next)) {
+      // push back array items, won't modify the original input
+      stack.push(...next);
+    } else {
+      res.push(next);
+    }
+  }
+  // reverse to restore input order
+  return res.reverse();
+}
+
+const arr = [1, 2, [3, 4, [5, 6]]];
+flatten(arr);
+// [1, 2, 3, 4, 5, 6]
+ +

Generator 함수

+ +
function* flatten(array, depth) {
+    if(depth === undefined) {
+      depth = 1;
+    }
+    for(const item of array) {
+        if(Array.isArray(item) && depth > 0) {
+          yield* flatten(item, depth - 1);
+        } else {
+          yield item;
+        }
+    }
+}
+
+const arr = [1, 2, [3, 4, [5, 6]]];
+const flattened = [...flatten(arr, Infinity)];
+// [1, 2, 3, 4, 5, 6]
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.flat', 'Array.prototype.flat')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Array.flat")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/flatmap/index.html b/files/ko/web/javascript/reference/global_objects/array/flatmap/index.html new file mode 100644 index 0000000000..9d762001e8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/flatmap/index.html @@ -0,0 +1,148 @@ +--- +title: Array.prototype.flatMap() +slug: Web/JavaScript/Reference/Global_Objects/Array/flatMap +tags: + - Array + - Experimental + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/flatMap +--- +
{{JSRef}} {{SeeCompatTable}}
+ +

flatMap() 메서드는 먼저 매핑함수를 사용해 각 엘리먼트에 대해 map 수행 후, 결과를 새로운 배열로 평탄화합니다. 이는 깊이 1의 flat 이 뒤따르는 map 과 동일하지만, flatMap 은 아주 유용하며 둘을 하나의 메소드로 병합할 때 조금 더 효율적입니다.

+ + + + + +

구문

+ +
arr.flatMap(callback(currentValue[, index[, array]])[, thisArg])
+ +

매개변수

+ +
+
callback
+
새로운 배열의 엘리먼트를 생성하는 함수. 3개의 아규먼트를 갖습니다. +
+
+
currentValue
+
배열에서 처리되는 현재 엘리먼트.
+
index{{optional_inline}}
+
배열에서 처리되고 있는 현재 엘리먼트의 인덱스.
+
array{{optional_inline}}
+
map 이 호출된 배열.
+
+
+
thisArg{{optional_inline}}
+
callback 실행에서 this 로 사용할 값.
+
+ +

반환 값

+ +

각 엘리먼트가 callback 함수의 결과이고, 깊이 1로 평탄화된 새로운 배열.

+ +

설명

+ +

callback 함수의 상세 설명은 {{jsxref("Array.prototype.map()")}} 문서를 보시기 바랍니다. flatMap 메소드는 깊이 1의 flat 이 뒤따르는 map 과 동일합니다.

+ +

예제

+ +

mapflatMap

+ +
let arr1 = [1, 2, 3, 4];
+
+arr1.map(x => [x * 2]);
+// [[2], [4], [6], [8]]
+
+arr1.flatMap(x => [x * 2]);
+// [2, 4, 6, 8]
+
+// 한 레벨만 평탄화됨
+arr1.flatMap(x => [[x * 2]]);
+// [[2], [4], [6], [8]]
+
+ +

위 코드는 map 자체만을 사용해서 구현할 수 있지만, 다음은 flatMap 의 유즈케이스를 더 잘 보여주는 예시입니다.

+ +

문장의 리스트로부터 단어의 리스트를 생성해봅시다.

+ +
let arr1 = ["it's Sunny in", "", "California"];
+
+arr1.map(x=>x.split(" "));
+// [["it's","Sunny","in"],[""],["California"]]
+
+arr1.flatMap(x => x.split(" "));
+// ["it's","Sunny","in","California"]
+ +

출력 리스트의 길이는 입력 리스트의 길이와 다를 수 있습니다.

+ +

flatMap() 을 이용한 아이템 추가 및 제거

+ +

flatMapmap을 하는 과정에서 아이템을 추가하거나 제거하여 아이템 개수를 바꿀 수 있습니다. 다른 말로는 각각의 아이템에 대하여 1:1대응관계 뿐만 아니라 다대다 대응도 가능하다는 것입니다. 이러한 측면에서 filter가 하는 역할의 반대역할을 한다고 볼 수 있습니다. 단순히 아무런 변화를 주고 싶지 않을때에는 원소 하나를 가진 배열을 반환할 수도, 아이템을 추가하고 싶을 때는 다-원소 배열을 반환할 수도, 아이템을 제거하고 싶을 때에는 빈 배열을 반환할 수도 있습니다.

+ +
// 다음은 음수는 제거하고 홀수는 1과 짝수로 분리하는 예시입니다.
+let a = [5, 4, -3, 20, 17, -33, -4, 18]
+//       |\  \  x   |  | \   x   x   |
+//      [4,1, 4,   20, 16, 1,       18]
+
+a.flatMap( (n) =>
+  (n < 0) ?      [] :
+  (n % 2 == 0) ? [n] :
+                 [n-1, 1]
+)
+
+// expected output: [4, 1, 4, 20, 16, 1, 18]
+ +
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ +

대안

+ +

reduceconcat

+ +
var arr1 = [1, 2, 3, 4];
+
+arr1.flatMap(x => [x * 2]);
+// 다음과 동일합니다
+arr1.reduce((acc, x) => acc.concat([x * 2]), []);
+// [2, 4, 6, 8]
+
+ +
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
Array.prototype.flatMap proposalFinished (4)
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Array.flatMap")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/foreach/index.html b/files/ko/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..809bc4d269 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,264 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Referennce +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +
{{JSRef}}
+ +

forEach() 메서드는 주어진 함수를 배열 요소 각각에 대해 실행합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-foreach.html")}}
+ + + +

구문

+ +
arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])
+ +

매개변수

+ +
+
callback
+
각 요소에 대해 실행할 함수. 다음 세 가지 매개변수를 받습니다.
+
+
+
currentValue
+
처리할 현재 요소.
+
index {{optional_inline}}
+
처리할 현재 요소의 인덱스.
+
array {{optional_inline}}
+
forEach()를 호출한 배열.
+
+
+
thisArg {{optional_inline}}
+
callback을 실행할 때 this로 사용할 값.
+
+ +

반환 값

+ +

{{jsxref("undefined")}}.

+ +

설명

+ +

forEach()는 주어진 callback을 배열에 있는 각 요소에 대해 오름차순으로 한 번씩 실행합니다. 삭제했거나 초기화하지 않은 인덱스 속성에 대해서는 실행하지 않습니다. (예: 희소 배열)

+ +

callback은 다음 세 인수와 함께 호출됩니다.

+ + + +

thisArg 매개변수를 forEach()에 제공한 경우 callback을 호출할 때 전달해 this의 값으로 쓰입니다. 전달하지 않으면 undefined를 사용하며, 최종 this 값은 {{jsxref("Operators/this", "함수의 this를 결정하는 평소 규칙", "", 0)}}을 따릅니다.

+ +

forEach()로 처리할 요소의 범위는 최초 callback 호출 전에 설정됩니다. forEach() 호출을 시작한 뒤 배열에 추가한 요소는 callback이 방문하지 않습니다. 배열의 기존 요소값이 바뀐 경우, callback에 전달하는 값은 forEach()가 요소를 방문한 시점의 값을 사용합니다. 방문하기 전에 삭제한 요소는 방문하지 않습니다.

+ +

forEach()는 각 배열 요소에 대해 한 번씩 callback 함수를 실행합니다. {{jsxref("Array.prototype.map()", "map()")}}과 {{jsxref("Array.prototype.reduce()", "reduce()")}}와는 달리 {{jsxref("undefined")}}를 반환하기 때문에 메서드 체인의 중간에 사용할 수 없습니다. 대표적인 사용처는 메서드 체인 끝에서 부작용side effect을 실행하는 겁니다.

+ +

forEach()는 배열을 변형하지 않습니다. 그러나 callback이 변형할 수는 있습니다.

+ +
+

예외를 던지지 않고는 forEach()를 중간에 멈출 수 없습니다. 중간에 멈춰야 한다면 forEach()가 적절한 방법이 아닐지도 모릅니다.

+ +

다음 방법으로는 조기에 반복을 종료할 수 있습니다.

+ + + +

다른 배열 메서드 {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, {{jsxref("Array.prototype.findIndex()", "findIndex()")}}는 배열 요소를 판별 함수에 전달하고, 그 결과의 참/거짓 여부에 따라 반복의 종료 여부를 결정합니다.

+
+ +

예제

+ +

초기화하지 않은 값의 반복 생략

+ +
const arraySparse = [1,3,,7]
+let numCallbackRuns = 0
+
+arraySparse.forEach(function(element){
+  console.log(element)
+  numCallbackRuns++
+})
+
+console.log("numCallbackRuns: ", numCallbackRuns)
+
+// 1
+// 3
+// 7
+// numCallbackRuns: 3
+// comment: as you can see the missing value between 3 and 7 didn't invoke callback function.
+ +

for 반복문을 forEach()로 바꾸기

+ +
const items = ['item1', 'item2', 'item3'];
+const copy = [];
+
+// 이전
+for (let i=0; i<items.length; i++) {
+  copy.push(items[i]);
+}
+
+// 이후
+items.forEach(function(item){
+  copy.push(item);
+});
+ +

배열 콘텐츠 출력

+ +
+

참고: {{domxref("console.table()")}}을 사용하면 배열 내용물을 서식에 맞춰 출력할 수 있습니다.

+ +

다음 예제는 forEach()를 사용한 다른 방법을 소개합니다.

+
+ +

다음 코드는 배열의 각 요소에 대해 한 줄을 기록합니다:

+ +
function logArrayElements(element, index, array) {
+  console.log('a[' + index + '] = ' + element);
+}
+
+// 인덱스 2는 배열의 그 위치에 항목이 없기에
+// 건너뜀을 주의하세요.
+[2, 5, , 9].forEach(logArrayElements);
+// 기록:
+// a[0] = 2
+// a[1] = 5
+// a[3] = 9
+
+ +

thisArg 사용

+ +

다음 예제는 배열의 각 항목에서 객체의 속성을 갱신합니다:

+ +
function Counter() {
+  this.sum = 0
+  this.count = 0
+}
+Counter.prototype.add = function(array) {
+  array.forEach(function(entry) {
+    this.sum += entry
+    ++this.count
+  }, this)
+  // ^---- 주의
+}
+
+const obj = new Counter()
+obj.add([2, 5, 9])
+obj.count
+// 3
+obj.sum
+// 16
+ +

thisArg 매개변수(this)를 forEach()에 제공했기에, callback은 전달받은 this의 값을 자신의 this 값으로 사용할 수 있습니다. 

+ +
+

화살표 함수 표현식을 사용하여 함수 인수를 전달하는 경우 thisArg 매개변수는 화살표 함수가 {{jsxref("Operators/this", "this")}} 값을 렉시컬(lexical, 정적) 바인딩하기에 생략될 수 있습니다.

+
+ +

객체 복사 함수

+ +

다음 코드는 주어진 객체의 사본을 만듭니다.

+ +

객체 사본을 만드는 방법에는 여러가지가 있습니다, 다음은 그 중 한 방법으로, ECMAScript 5 Object.* 메타 속성 함수를 사용하여 Array.prototype.forEach()가 작동하는 법을 설명하기 위한 코드입니다.

+ +
function copy(obj) {
+  const copy = Object.create(Object.getPrototypeOf(obj))
+  const propNames = Object.getOwnPropertyNames(obj)
+
+  propNames.forEach(function(name) {
+    const desc = Object.getOwnPropertyDescriptor(obj, name)
+    Object.defineProperty(copy, name, desc)
+  })
+
+  return copy
+}
+
+const obj1 = { a: 1, b: 2 }
+const obj2 = copy(obj1)      // obj2 looks like obj1 now
+ +

반복 중 배열이 변경으로 인한 반복 생략

+ +

다음 예제에서는 "one", "two", "four"를 기록합니다.

+ +

forEach()가 값 "two"를 포함하는 항목에 도달하면 전체 배열의 첫 번째 항목을 제거하여, 나머지 모든 항목이 한 위치 앞으로 이동합니다. 요소 "four"는 이제 배열에서 보다 앞에 위치하므로 "three"는 건너 뜁니다.

+ +

forEach()는 반복 전에 배열의 복사본을 만들지 않습니다.

+ +
let words = ['one', 'two', 'three', 'four']
+words.forEach(function(word) {
+  console.log(word)
+  if (word === 'two') {
+    words.shift()
+  }
+})
+// one
+// two
+// four
+ +

배열 평탄화

+ +

다음 예제는 오직 시연 용으로만 추가한 것으로, 평탄화를 하려면 {{jsxref("Array.prototype.flat()")}}을 사용하세요.

+ +
function flatten(arr) {
+  const result = []
+
+  arr.forEach((i) => {
+    if (Array.isArray(i)) {
+      result.push(...flatten(i))
+    } else {
+      result.push(i)
+    }
+  })
+
+  return result
+}
+
+// Usage
+const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]
+
+flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.forEach")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/from/index.html b/files/ko/web/javascript/reference/global_objects/array/from/index.html new file mode 100644 index 0000000000..487cc36848 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,244 @@ +--- +title: Array.from() +slug: Web/JavaScript/Reference/Global_Objects/Array/from +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/from +--- +
{{JSRef}}
+ +

Array.from() 메서드는 유사 배열 객체(array-like object)나반복 가능한 객체(iterable object)를 얕게 복사해새로운Array 객체를 만듭니다.

+ +
{{EmbedInteractiveExample("pages/js/array-from.html")}}
+ + + +

구문

+ +
Array.from(arrayLike[, mapFn[, thisArg]])
+
+ +

매개변수

+ +
+
arrayLike
+
배열로 변환하고자 하는유사 배열 객체나 반복 가능한 객체.
+
mapFn{{Optional_inline}}
+
배열의 모든 요소에 대해 호출할 맵핑 함수.
+
thisArg{{Optional_inline}}
+
mapFn 실행 시에 this로 사용할 값.
+
+ +

반환 값

+ +

새로운 {{jsxref("Array")}} 인스턴스.

+ +

설명

+ +

다음과 같은 경우에 Array.from()으로새Array를 만들 수 있습니다.

+ + + +

Array.from()은 선택 매개변수인 mapFn를 가지는데,배열(혹은 배열 서브클래스)의 각 요소를{{jsxref("Array.prototype.map", "맵핑", "", 0)}}할 때 사용할 수 있습니다. 즉,Array.from(obj, mapFn, thisArg)는 중간에 다른 배열을 생성하지 않는다는 점을 제외하면Array.from(obj).map(mapFn, thisArg)와 같습니다. 이 특징은 typed arrays와 같은 특정 배열 서브클래스에서 중간 배열 값이 적절한 유형에 맞게 생략되기 때문에 특히 중요합니다.

+ +

from() 메서드의 length 속성은 1입니다.

+ +

ES2015 이후, 클래스 구문은 내장 및 새 클래스의 상속을 가능케 했습니다. 그 결과로 Array.from과 같은 정적 메서드는 Array의 서브클래스에 의해 상속되며, Array 대신 자신의 인스턴스를 만듭니다.

+ +

예제

+ +

String에서 배열 만들기

+ +
Array.from('foo');
+// ["f", "o", "o"]
+
+ +

Set에서 배열 만들기

+ +
const s = new Set(['foo', window]);
+Array.from(s);
+// ["foo", window]
+
+ +

Map에서 배열 만들기

+ +
const m = new Map([[1, 2], [2, 4], [4, 8]]);
+Array.from(m);
+// [[1, 2], [2, 4], [4, 8]]
+
+const mapper = new Map([['1', 'a'], ['2', 'b']]);
+Array.from(mapper.values());
+// ['a', 'b'];
+
+Array.from(mapper.keys());
+// ['1', '2'];
+
+ +

배열 형태를 가진 객체(arguments)에서 배열 만들기

+ +
function f() {
+  return Array.from(arguments);
+}
+
+f(1, 2, 3);
+
+// [1, 2, 3]
+
+ +

Array.from과 화살표 함수 사용하기

+ +
// Using an arrow function as the map function to
+// manipulate the elements
+Array.from([1, 2, 3], x => x + x);
+// [2, 4, 6]
+
+// Generate a sequence of numbers
+// Since the array is initialized with `undefined` on each position,
+// the value of `v` below will be `undefined`
+Array.from({length: 5}, (v, i) => i);
+// [0, 1, 2, 3, 4]
+
+ +

시퀀스 생성기(range)

+ +
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)
+const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
+
+// Generate numbers range 0..4
+range(0, 4, 1);
+// [0, 1, 2, 3, 4]
+
+// Generate numbers range 1..10 with step of 2
+range(1, 10, 2);
+// [1, 3, 5, 7, 9]
+
+// Generate the alphabet using Array.from making use of it being ordered as a sequence
+range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x));
+// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
+ +

폴리필

+ +

Array.from은 ECMA-262 표준 제6판에 추가됐습니다.따라서 어떤 표준 구현체에서는 사용할 수없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도Array.from을사용할 수 있습니다. 아래 알고리즘은ObjectTypeError가 변형되지 않고,callback.call의 계산 값이 원래의Function.prototype.call()과 같은 경우ECMA-262 제6판이 명시한 것과 동일합니다.또한 반복가능자(iterable)는 완벽하게 폴리필할 수없기에 본 구현은 ECMA-262 제6판의 제네릭 반복가능자를 지원하지 않습니다.

+ +
// Production steps of ECMA-262, Edition 6, 22.1.2.1
+if (!Array.from) {
+  Array.from = (function () {
+    var toStr = Object.prototype.toString;
+    var isCallable = function (fn) {
+      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
+    };
+    var toInteger = function (value) {
+      var number = Number(value);
+      if (isNaN(number)) { return 0; }
+      if (number === 0 || !isFinite(number)) { return number; }
+      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
+    };
+    var maxSafeInteger = Math.pow(2, 53) - 1;
+    var toLength = function (value) {
+      var len = toInteger(value);
+      return Math.min(Math.max(len, 0), maxSafeInteger);
+    };
+
+    // The length property of the from method is 1.
+    return function from(arrayLike/*, mapFn, thisArg */) {
+      // 1. Let C be the this value.
+      var C = this;
+
+      // 2. Let items be ToObject(arrayLike).
+      var items = Object(arrayLike);
+
+      // 3. ReturnIfAbrupt(items).
+      if (arrayLike == null) {
+        throw new TypeError('Array.from requires an array-like object - not null or undefined');
+      }
+
+      // 4. If mapfn is undefined, then let mapping be false.
+      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
+      var T;
+      if (typeof mapFn !== 'undefined') {
+        // 5. else
+        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
+        if (!isCallable(mapFn)) {
+          throw new TypeError('Array.from: when provided, the second argument must be a function');
+        }
+
+        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
+        if (arguments.length > 2) {
+          T = arguments[2];
+        }
+      }
+
+      // 10. Let lenValue be Get(items, "length").
+      // 11. Let len be ToLength(lenValue).
+      var len = toLength(items.length);
+
+      // 13. If IsConstructor(C) is true, then
+      // 13. a. Let A be the result of calling the [[Construct]] internal method
+      // of C with an argument list containing the single item len.
+      // 14. a. Else, Let A be ArrayCreate(len).
+      var A = isCallable(C) ? Object(new C(len)) : new Array(len);
+
+      // 16. Let k be 0.
+      var k = 0;
+      // 17. Repeat, while k < len… (also steps a - h)
+      var kValue;
+      while (k < len) {
+        kValue = items[k];
+        if (mapFn) {
+          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
+        } else {
+          A[k] = kValue;
+        }
+        k += 1;
+      }
+      // 18. Let putStatus be Put(A, "length", len, true).
+      A.length = len;
+      // 20. Return A.
+      return A;
+    };
+  }());
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.from', 'Array.from')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.from")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/includes/index.html b/files/ko/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..a646fd3bb4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,173 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +
{{JSRef}}
+ +

includes() 메서드는 배열이 특정 요소를 포함하고 있는지 판별합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-includes.html")}}
+ + + +

구문

+ +
arr.includes(valueToFind[, fromIndex])
+
+ +

매개변수

+ +
+
valueToFind
+
탐색할 요소. +
+

참고: 문자나 문자열을 비교할 때, includes()대소문자를 구분합니다.

+
+
+
fromIndex {{optional_inline}}
+
이 배열에서 searchElement 검색을 시작할 위치입니다. 음의 값은 array.length + fromIndex의 인덱스를 asc로 검색합니다. 기본값은 0입니다.
+
+ +

반환 값

+ +

{{jsxref("Boolean")}}.

+ +

예제

+ +
[1, 2, 3].includes(2);     // true
+[1, 2, 3].includes(4);     // false
+[1, 2, 3].includes(3, 3);  // false
+[1, 2, 3].includes(3, -1); // true
+[1, 2, NaN].includes(NaN); // true
+
+ +

fromIndex 가 배열의 길이보다 같거나 큰 경우

+ +

fromIndex 가 배열의 길이보다 같거나 크다면, false 를 반환합니다. 배열은 검색되지 않을 것입니다.

+ +
var arr = ['a', 'b', 'c'];
+
+arr.includes('c', 3);   // false
+arr.includes('c', 100); // false
+ +

0보다 작은 인덱스의 계산

+ +

fromIndex 가 음수라면, 이 계산된 인덱스는 valueToFind 를 찾기 시작할 배열의 위치로 사용되기 위해 연산됩니다. 만약 계산된 인덱스가 -1 * array.length 보다 작거나 같다면, 전체 배열이 검색될 것입니다.

+ +
// array length is 3
+// fromIndex is -100
+// computed index is 3 + (-100) = -97
+
+var arr = ['a', 'b', 'c'];
+
+arr.includes('a', -100); // true
+arr.includes('b', -100); // true
+arr.includes('c', -100); // true
+arr.includes('a', -2); // false
+ +

제네릭 메소드로 사용되는 includes()

+ +

includes() 메서드는 의도적으로 제네릭입니다. 배열 객체가 되기 위한 this 값을 요구하지 않아, 다른 종류의 객체에 적용될 수 있습니다 (e.g. 유사 배열 객체). 아래 예시는  이 함수의 arguments 객체로 호출되는 includes() 메소드를 보여줍니다.

+ +
(function() {
+  console.log([].includes.call(arguments, 'a')); // true
+  console.log([].includes.call(arguments, 'd')); // false
+})('a','b','c');
+ +

폴리필

+ +
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
+if (!Array.prototype.includes) {
+  Object.defineProperty(Array.prototype, 'includes', {
+    value: function(searchElement, fromIndex) {
+
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      // 1. Let O be ? ToObject(this value).
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // 3. If len is 0, return false.
+      if (len === 0) {
+        return false;
+      }
+
+      // 4. Let n be ? ToInteger(fromIndex).
+      //    (If fromIndex is undefined, this step produces the value 0.)
+      var n = fromIndex | 0;
+
+      // 5. If n ≥ 0, then
+      //  a. Let k be n.
+      // 6. Else n < 0,
+      //  a. Let k be len + n.
+      //  b. If k < 0, let k be 0.
+      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
+
+      function sameValueZero(x, y) {
+        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
+      }
+
+      // 7. Repeat, while k < len
+      while (k < len) {
+        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
+        // b. If SameValueZero(searchElement, elementK) is true, return true.
+        if (sameValueZero(o[k], searchElement)) {
+          return true;
+        }
+        // c. Increase k by 1.
+        k++;
+      }
+
+      // 8. Return false
+      return false;
+    }
+  });
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ES7')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.includes")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/index.html b/files/ko/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..4bb18af837 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,493 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - Example + - Global Objects + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +

JavaScript Array 전역 객체는 배열을 생성할 때 사용하는 리스트 형태의 고수준 객체입니다.

+ +

설명

+ +

배열은 프로토타입으로 탐색과 변형 작업을 수행하는 메서드를 갖는, 리스트와 비슷한 객체입니다. JavaScript에서 배열의 길이와 요소의 자료형은 고정되어 있지 않습니다. 배열의 길이가 언제든지 늘어나거나 줄어들 수 있기 때문에 JavaScript 배열들은 밀집도가 보장되지 않습니다. 보통 이 성질은 편리하지만, 목적에 맞지 않는다면 형식화 배열(typed array)을 사용하는 것을 고려해보세요.

+ +

배열은 요소 인덱스로 문자열(연관 배열)을 사용할 수 없으며 무조건 정수만 허용합니다. 속성 접근자를 사용해 정수 외 키에 접근할 경우 배열 리스트의 요소가 아니라 배열 객체의 속성 변수를 설정하거나 회수합니다. 배열 객체의 속성과 배열 요소의 리스트의 요소는 서로 다른 별개의 항목으로, 순회 및 변형 작업은 객체 속성에 적용되지 않습니다.

+ +

자주 사용하는 연산

+ +

배열 만들기

+ +
let fruits = ['사과', '바나나']
+
+console.log(fruits.length)
+// 2
+
+ +

인덱스로 배열의 항목에 접근하기

+ +
let first = fruits[0]
+// 사과
+
+let last = fruits[fruits.length - 1]
+// 바나나
+
+ +

배열의 항목들을 순환하며 처리하기

+ +
fruits.forEach(function (item, index, array) {
+  console.log(item, index)
+})
+// 사과 0
+// 바나나 1
+
+ +

배열 끝에 항목 추가하기

+ +
let newLength = fruits.push('오렌지')
+// ["사과", "바나나", "오렌지"]
+
+ +

배열 끝에서부터 항목 제거하기

+ +
let last = fruits.pop() // 끝에있던 '오렌지'를 제거
+// ["사과", "바나나"]
+
+ +

배열 앞에서부터 항목 제거하기

+ +
let first = fruits.shift() // 제일 앞의 '사과'를 제거
+// ["바나나"]
+
+ +

배열 앞에 항목 추가하기

+ +
let newLength = fruits.unshift('딸기') // 앞에 추가
+// ["딸기", "바나나"]
+
+ +

배열 안 항목의 인덱스 찾기

+ +
fruits.push('망고')
+// ["딸기", "바나나", "망고"]
+
+let pos = fruits.indexOf("바나나")
+// 1
+
+ +

인덱스 위치에 있는 항목 제거하기

+ +
let removedItem = fruits.splice(pos, 1) // 항목을 제거하는 방법
+
+// ["딸기", "망고"]
+
+ +

인덱스 위치에서부터 여러개의 항목 제거하기

+ +
let vegetables = ['양배추', '순무', '무', '당근']
+console.log(vegetables)
+// ["양배추", "순무", "무", "당근"]
+
+let pos = 1
+let n = 2
+
+let removedItems = vegetables.splice(pos, n)
+// 배열에서 항목을 제거하는 방법
+// pos 인덱스부터 n개의 항목을 제거함
+
+console.log(vegetables)
+// ["양배추", "당근"] (원 배열 vegetables의 값이 변함)
+
+console.log(removedItems)
+// ["순무", "무"]
+
+ +

배열 복사하기

+ +
let shallowCopy = fruits.slice() // 사본을 만드는 방법
+// ["딸기", "망고"]
+
+ +

배열 요소에 접근하기

+ +

JavaScript 배열의 인덱스는 0부터 시작합니다. 즉, 배열 첫 번째 요소의 인덱스는 0이고, 마지막 요소의 인덱스는 배열의 {{jsxref("Array.length", "length")}} 속성에서 1을 뺀 것과 같습니다.

+ +

잘못된 인덱스를 사용하면 undefined를 반환합니다.

+ +
let arr = ['첫 번재 요소입니다', '두 번째 요소입니다', '마지막 요소입니다']
+console.log(arr[0])              // '첫 번재 요소입니다'를 기록
+console.log(arr[1])              // '두 번재 요소입니다'를 기록
+console.log(arr[arr.length - 1]) // '마지막 요소입니다'를 기록
+
+ +

toString이 속성인 것과 마찬가지로(정확히 하자면, toString()은 메서드입니다) 배열의 요소도 속성입니다. 하지만 아래의 예시처럼 배열 요소에 접근하려 하면, 속성 이름이 유효하지 않기 때문에 구문 오류가 발생합니다.

+ +
console.log(arr.0) // 구문 오류
+
+ +

이 점에는 JavaScript 배열과 속성에 특별한 점이 없습니다. 숫자로 시작하는 JavaScript 속성은 마침표 구문으로 접근할 수 없으며, 반드시 괄호 표기법으로 접근해야 합니다.

+ +

예를 들어 '3d'라는 이름의 속성을 가진 객체에서 해당 속성에 접근할 땐 괄호 표기법을 사용해야만 합니다.

+ +
let years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
+console.log(years.0)   // 구문 오류
+console.log(years[0])  // 정상 작동
+
+ +
renderer.3d.setTexture(model, 'character.png')     // 구문 오류
+renderer['3d'].setTexture(model, 'character.png')  // 정상 작동
+
+ +

3d 예시에서 '3d'를 따옴표로 감싸야 함에 유의하세요. JavaScript 배열 인덱스도 따옴표로 둘러쌀 수는 있지만(years[2] 대신에 years['2']처럼), 굳이 필요하지는 않습니다.

+ +

years[2]의 2는 JavaScript 엔진이 암시적인 toString 변환을 사용해 문자열로 변환합니다. 그 결과로서 '2''02'years 객체에서 서로 다른 칸을 가리키며, 다음 코드는 true가 될 수 있습니다.

+ +
console.log(years['2'] != years['02']);
+
+ +

length 와 숫자형 속성의 관계

+ +

JavaScript 배열의 {{jsxref("Array.length", "length")}} 속성과 숫자형 속성은 연결되어 있습니다.

+ +

몇몇 배열 내장 메서드({{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}} 등)은 호출했을 때 배열의 {{jsxref("Array.length", "length")}} 속성의 값을 참조합니다.

+ +

다른 메서드({{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}} 등) 또한 배열의 {{jsxref("Array.length", "length")}} 속성의 업데이트를 유발합니다.

+ +
const fruits = []
+fruits.push('banana', 'apple', 'peach')
+
+console.log(fruits.length) // 3
+
+ +

JavaScript 배열의 속성을 설정할 때 그 속성이 유효한 배열 인덱스이고 그 인덱스가 현재 배열의 경계를 넘어간다면, JavaScript 엔진은 배열의 {{jsxref("Array.length", "length")}} 속성을 그에 맞춰 업데이트 합니다.

+ +
fruits[5] = 'mango'
+console.log(fruits[5])           // 'mango'
+console.log(Object.keys(fruits)) // ['0', '1', '2', '5']
+console.log(fruits.length)       // 6
+
+ +

{{jsxref("Array.length", "length")}}를 직접 늘릴 수 있습니다.

+ +
fruits.length = 10;
+console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
+console.log(fruits.length); // 10
+
+ +

하지만, {{jsxref("Array.length", "length")}} 속성을 감소시키면 요소를 지웁니다.

+ +
fruits.length = 2
+console.log(Object.keys(fruits)) // ['0', '1']
+console.log(fruits.length)       // 2
+
+ +

{{jsxref("Array.length")}} 문서에 더 자세한 설명이 있습니다.

+ +

매치 결과를 이용한 배열 생성

+ +

정규표현식과 문자열 사이의 매치 결과로 JavaScript 배열을 만들 수 있습니다. 이 배열은 매치에 대한 정보를 제공하는 속성들과 요소들을 가집니다. 이러한 배열은 {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, {{jsxref("String.replace")}}로부터 반환됩니다. 이 속성들과 요소들에 대한 설명을 돕기위해, 다음 예제를 보고 아래 테이블을 참조해주세요.

+ +
// 하나의 d와 하나 이상의 b에 하나의 d가 뒤따라 일치해야 합니다.
+// 일치한 b와 다음 d를 기억하십시오.
+// 대소문자 구분은 무시됩니다.
+
+var myRe = /d(b+)(d)/i;
+var myArray = myRe.exec('cdbBdbsbz');
+
+ +

매치로부터 반환되는 속성들과 요소들은 다음과 같습니다:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
속성/요소설명예시
input {{ReadOnlyInline}}정규 표현식과 일치시키는 원본 문자열을 나타내는 읽기 전용 속성입니다."cdbBdbsbz"
index {{ReadOnlyInline}}원본 문자열에서 정규 표현식이 처음 일치하는 문자열의 위치(원본 문자열의 첫 문자 위치를 0으로 하는)를 나타내는 읽기 전용 속성입니다.1
[0] {{ReadOnlyInline}}원본 문자열에서 정규 표현식이 처음 일치하는 문자열을 지정하는 읽기 전용 요소입니다."dbBd"
[1], ...[n] {{ReadOnlyInline}}만약 정규 표현식에 괄호가 포함돼 있다면 괄호에 일치하는 부분 문자열을 나타내는 읽기 전용 요소들입니다. 가능한 괄호 안의 부분 문자열의 수는 무제한입니다.[1]: bB
+ [2]: d
+ +

생성자

+ +
+
{{jsxref("Array.Array", "Array()")}}
+
Array 객체를 생성합니다.
+
+ +

정적 속성

+ +
+
Array.length
+
값이 1인 Array 생성자의 길이 속성입니다.
+
{{jsxref("Array.@@species", "get Array[@@species]")}}
+
파생 객체를 생성하는데 사용하는 생성자 함수입니다.
+
+ +

정적 메서드

+ +
+
{{jsxref("Array.from()")}}
+
유사 배열 또는 반복 가능한 객체로부터 새로운 Array 인스턴스를 생성합니다.
+
{{jsxref("Array.isArray()")}}
+
만약 변수가 배열이면 참을, 아니면 거짓을 반환합니다.
+
{{jsxref("Array.of()")}}
+
전달인자의 개수나 데이터 타입에 관계없이 새 Array 인스턴스를 생성합니다.
+
+ +

Array 인스턴스

+ +

모든 Array 인스턴스는 Array.prototype을 상속합니다. 다른 생성자와 마찬가지로, Array() 생성자의 프로토타입을 수정하면 모든 Array 인스턴스도 수정의 영향을 받습니다. 예를 들면, 새로운 메서드와 속성을 추가해 모든 Array를 확장할 수 있으므로, {{glossary("polyfill", "폴리필")}}에 쓰입니다.

+ +

그러나 배열 객체에 비표준 메서드를 추가하면 나중에 스스로, 혹은 JavaScript에 기능이 추가될 경우 문제가 될 수 있습니다.

+ +

잘 모를 법한 사실: Array.prototype은 그 스스로 Array입니다.

+ +
Array.isArray(Array.prototype) // true
+ +

인스턴스 속성

+ +
+
+
Array.prototype.constructor
+
객체의 프로토타입을 생성하는 함수를 지정합니다.
+
{{jsxref("Array.prototype.length")}}
+
배열의 원소 수를 나타냅니다.
+
{{jsxref("Array.@@unscopables", "Array.prototype[@@unscopables]")}}
+
{{jsxref("Statements/with", "with")}} 결속 범위로부터 제외하려는 속성 이름이 들어있는 기호입니다.
+
+
+ +

인스턴스 메서드

+ +

변경자 메서드

+ +
+

변경자 메서드는 배열을 수정합니다.

+ +
+
{{jsxref("Array.prototype.copyWithin()")}}
+
배열 내의 지정된 요소들을 동일한 배열 내에서 복사합니다.
+
{{jsxref("Array.prototype.fill()")}}
+
배열 안의 시작 인덱스부터 끝 인덱스까지의 요소값을 지정된 정적 값으로 채웁니다.
+
{{jsxref("Array.prototype.pop()")}}
+
배열에서 마지막 요소를 뽑아내고, 그 요소를 반환합니다.
+
{{jsxref("Array.prototype.push()")}}
+
배열의 끝에 하나 이상의 요소를 추가하고, 변경된 배열의 길이를 반환합니다.
+
{{jsxref("Array.prototype.reverse()")}}
+
배열의 요소 순서를 반전시킵니다. 첫 번째가 마지막이 되고 마지막이 첫 번째가 됩니다.
+
{{jsxref("Array.prototype.shift()")}}
+
배열에서 첫 번째 요소를 삭제하고 그 요소를 반환합니다.
+
{{jsxref("Array.prototype.sort()")}}
+
배열의 요소를 정렬하고 그 배열을 반환합니다.
+
{{jsxref("Array.prototype.splice()")}}
+
배열에서 요소를 추가/삭제합니다.
+
{{jsxref("Array.prototype.unshift()")}}
+
배열의 앞에 하나 이상의 요소를 추가하고 새로운 길이를 반환합니다.
+
+
+ +

접근자 메서드

+ +
+

접근자 메서드는 배열을 수정하지 않고, 기존 배열의 일부에 기반한 새로운 배열 또는 값을 반환합니다.

+ +
+
{{jsxref("Array.prototype.concat()")}}
+
배열을 매개변수로 주어진 배열/값과 이어붙인 새로운 배열을 반환합니다.
+
{{jsxref("Array.prototype.filter()")}}
+
지정한 콜백의 반환 결과가 true인 요소만 모은 새로운 배열을 반환합니다.
+
{{jsxref("Array.prototype.includes()")}}
+
배열이 주어진 값을 포함하는지 판별해 true 또는 false를 반환합니다.
+
{{jsxref("Array.prototype.indexOf()")}}
+
배열에서 주어진 값과 일치하는 제일 앞의 인덱스를 반환합니다. 없으면 -1을 반환합니다.
+
{{jsxref("Array.prototype.join()")}}
+
배열의 모든 요소를 문자열로 합칩니다.
+
{{jsxref("Array.prototype.lastIndexOf()")}}
+
배열에서 주어진 값과 일치하는 제일 뒤의 인덱스를 반환합니다. 없으면 -1을 반환합니다.
+
{{jsxref("Array.prototype.slice()")}}
+
배열의 일부를 추출한 새 배열을 반환합니다.
+
{{jsxref("Array.prototype.toSource()")}} {{non-standard_inline}}
+
지정한 배열을 나타내는 배열 리터럴을 반환합니다. 새로운 배열을 만들기 위해 이 값을 사용할 수 있습니다. {{jsxref("Object.prototype.toSource()")}} 메서드를 재정의합니다.
+
{{jsxref("Array.prototype.toString()")}}
+
배열과 그 요소를 나타내는 문자열을 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.
+
{{jsxref("Array.prototype.toLocaleString()")}}
+
배열과 그 요소를 나타내는 지역화된 문자열을 반환합니다. {{jsxref("Object.prototype.toLocaleString()")}} 메서드를 재정의합니다.
+
+
+ +

순회 메서드

+ +

배열을 처리하면서 호출할 콜백 함수를 받는 메서드 여럿이 존재합니다. 이런 메서드를 호출하면 배열의 length를 기억하므로, 아직 순회를 끝내지 않았을 때 요소를 더 추가하면 콜백이 방문하지 않습니다.

+ +

요소의 값을 바꾸거나, 요소를 제거하는 등 다른 변경점은 콜백 방문 시점에 따라 최종 값에 영향을 줄 수 있습니다. 비록 이런 동작 방식은 잘 정의되어 있으나, 여러분의 코드를 다른 사람이 읽을 때 헷갈리지 않도록 여기에 의존하면 안됩니다.

+ +

반드시 배열을 변형해야 한다면, 새로운 배열로 복사하세요.

+ +
+
+
{{jsxref("Array.prototype.entries()")}}
+
배열의 각 인덱스에 대한 키/값 쌍을 포함하는 새로운 배열 반복자 객체를 반환합니다.
+
{{jsxref("Array.prototype.every()")}}
+
배열의 모든 요소가 주어진 판별 콜백을 만족할 경우 true를 반환합니다.
+
{{jsxref("Array.prototype.find()")}}
+
주어진 판별 콜백을 만족하는 첫 번째 요소를 반환합니다. 만족하는 요소가 없으면 undefined를 반환합니다.
+
{{jsxref("Array.prototype.findIndex()")}}
+
주어진 판별 콜백을 만족하는 첫 번째 요소의 인덱스를 반환합니다. 만족하는 요소가 없으면 undefined를 반환합니다.
+
{{jsxref("Array.prototype.forEach()")}}
+
배열의 각각의 요소에 대해 콜백을 호출합니다.
+
{{jsxref("Array.prototype.keys()")}}
+
배열의 각 인덱스에 대한 키를 가지는 새로운 배열 반복자 객체를 반환합니다.
+
{{jsxref("Array.prototype.map()")}}
+
배열의 모든 요소 각각에 대하여 주어진 콜백 함수를 호출하고, 그 반환값을 모은 새로운 배열을 반환합니다.
+
{{jsxref("Array.prototype.reduce()")}}
+
주어진 콜백 함수를 가산기와 요소 각각에 대해 왼쪽에서 오른쪽으로 호출하여 하나의 값으로 줄인(reduce) 결과를 반환합니다.
+
{{jsxref("Array.prototype.reduceRight()")}}
+
주어진 콜백 함수를 가산기와 요소 각각에 대해 오른쪽에서 왼쪽으로 호출하여 하나의 값으로 줄인(reduce) 결과를 반환합니다.
+
{{jsxref("Array.prototype.some()")}}
+
배열의 어떤 요소가 주어진 판별 콜백을 만족할 경우 true를 반환합니다.
+
{{jsxref("Array.prototype.values()")}}
+
배열의 각 인덱스에 대한 값을 가지는 새로운 배열 반복자 객체를 반환합니다.
+
{{jsxref("Array.prototype.@@iterator()", "Array.prototype[@@iterator]()")}}
+
배열의 각 인덱스에 대한 값을 가지는 새로운 배열 반복자 객체를 반환합니다.
+
+
+ +

예제

+ +

배열 생성

+ +

아래 예제는 길이 0의 배열 msgArray 을 생성하고, msgArray[0]msgArray[99] 에 값을 할당하여, 배열의 길이를 100으로 변경합니다.

+ +
let msgArray = []
+msgArray[0] = 'Hello'
+msgArray[99] = 'world'
+
+if (msgArray.length === 100) {
+  console.log('The length is 100.')
+}
+ +

2차원 배열 생성

+ +

아래의 예제는 2차원 문자열 배열로 체스보드를 생성합니다. 첫번째 이동은 (6,4)의 'p'를 (4,4)로 복사하여 이루어집니다. 이전 위치 (6,4)는 빈공간으로 만듭니다.

+ +
let board = [
+  ['R','N','B','Q','K','B','N','R'],
+  ['P','P','P','P','P','P','P','P'],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  ['p','p','p','p','p','p','p','p'],
+  ['r','n','b','q','k','b','n','r'] ]
+
+console.log(board.join('\n') + '\n\n')
+
+// Move King's Pawn forward 2
+board[4][4] = board[6][4]
+board[6][4] = ' '
+console.log(board.join('\n'))
+ +

결과는 다음과 같습니다.

+ +
R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+p,p,p,p,p,p,p,p
+r,n,b,q,k,b,n,r
+
+R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , ,p, , ,
+ , , , , , , ,
+p,p,p,p, ,p,p,p
+r,n,b,q,k,b,n,r
+
+ +

배열을 사용하여 일련의 값을 테이블처럼 표시하기

+ +
const values = []
+for (let x = 0; x < 10; x++){
+ values.push([
+  2 ** x,
+  2 * x ** 2
+ ])
+}
+console.table(values)
+ +

결과는 다음과 같습니다.

+ +
0    1    0
+1    2    2
+2    4    8
+3    8    18
+4    16    32
+5    32    50
+6    64    72
+7    128    98
+8    256    128
+9    512    162
+
+ +

(첫번째 열은 (인덱스))

+ +

명세

+ + + + + + + + + + + + +
SpecificationInitial publication
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}ECMAScript 1
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/indexof/index.html b/files/ko/web/javascript/reference/global_objects/array/indexof/index.html new file mode 100644 index 0000000000..9748918d5a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/indexof/index.html @@ -0,0 +1,196 @@ +--- +title: Array.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf +--- +
{{JSRef}}
+ +

indexOf() 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다.

+ +
+

참고: 문자열은 {{jsxref("String.prototype.indexOf()")}}를 참고하세요.

+
+ +

{{EmbedInteractiveExample("pages/js/array-indexof.html")}}

+ +

구문

+ +
arr.indexOf(searchElement[, fromIndex])
+
+ +

매개변수

+ +
+
searchElement
+
배열에서 찾을 요소입니다.
+
fromIndex {{optional_inline}}
+
검색을 시작할 색인입니다. 인덱스가 배열의 길이보다 크거나 같은 경우 -1이 반환되므로 배열이 검색되지 않습니다. 제공된 색인 값이 음수이면 배열 끝에서부터의 오프셋 값으로 사용됩니다. 참고 : 제공된 색인이 음수이면 배열은 여전히 앞에서 뒤로 검색됩니다. 계산 된 인덱스가 0보다 작 으면 전체 배열이 검색됩니다. 기본값 : 0 (전체 배열 검색).
+
+ +

반환 값

+ +

배열 내의 요소의 최초의 인덱스. 발견되지 않으면 -1.

+ +

설명

+ +

indexOf()는 엄격한 동등성 (=== 또는 triple-equals 연산자에서 사용하는 것과 같은 메서드)을 사용하여 검색 요소를 Array의 요소와 비교합니다.

+ +

예제

+ +

indexOf() 사용하기

+ +

다음 예제에서는 indexOf ()를 사용하여 배열의 값을 찾습니다.

+ +
var array = [2, 9, 9];
+array.indexOf(2);     // 0
+array.indexOf(7);     // -1
+array.indexOf(9, 2);  // 2
+array.indexOf(2, -1); // -1
+array.indexOf(2, -3); // 0
+
+ +

요소의 모든 항목 찾기

+ +
var indices = [];
+var array = ['a', 'b', 'a', 'c', 'a', 'd'];
+var element = 'a';
+var idx = array.indexOf(element);
+while (idx != -1) {
+  indices.push(idx);
+  idx = array.indexOf(element, idx + 1);
+}
+console.log(indices);
+// [0, 2, 4]
+
+ +

요소가 배열에 존재하는지 확인하고 배열을 업데이트

+ +
function updateVegetablesCollection (veggies, veggie) {
+    if (veggies.indexOf(veggie) === -1) {
+        veggies.push(veggie);
+        console.log('새로운 veggies 컬렉션 : ' + veggies);
+    } else if (veggies.indexOf(veggie) > -1) {
+        console.log(veggie + ' 은 이미 veggies 컬렉션에 존재합니다.');
+    }
+}
+
+var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
+
+updateVegetablesCollection(veggies, 'spinach');
+// 새로운 veggies 컬렉션 : potato, tomato, chillies, green-pepper, spinach
+updateVegetablesCollection(veggies, 'spinach');
+// spinach 은 이미 veggies 컬렉션에 존재합니다.
+
+ +

폴리필

+ +
// ECMA-262, 제 5 판, 15.4.4.14의 생산 단계
+// 참조 : http://es5.github.io/#x15.4.4.14
+if (!Array.prototype.indexOf) {
+  Array.prototype.indexOf = function(searchElement, fromIndex) {
+
+    var k;
+
+    // 1. 이 값을 인수로 전달하는 ToObject를 호출 한 결과를
+    // o라고합니다.
+    if (this == null) {
+      throw new TypeError('"this" is null or not defined');
+    }
+
+    var o = Object(this);
+
+    // 2. lenValue를 Get 함수를 호출 한 결과로 둡니다.
+     // 인수가 "length"인 o의 내부 메소드.
+     // 3. len을 ToUint32 (lenValue)로 지정합니다.
+    var len = o.length >>> 0;
+
+    // 4. len이 0이면 -1을 반환합니다.
+    if (len === 0) {
+      return -1;
+    }
+
+    // 5.Index에서 인수가 전달 된 경우 n을
+    // ToInteger (fromIndex); 그렇지 않으면 n은 0이됩니다.
+    var n = fromIndex | 0;
+
+    // 6. If n >= len, return -1.
+    if (n >= len) {
+      return -1;
+    }
+
+   // 7. n> = 0 인 경우 k를 n이라고 합니다.
+   // 8. 그렇지 않으면 n <0, k는 len - abs (n)이됩니다.
+   // k가 0보다 작은 경우 k를 0으로 만듭니다.
+    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
+
+    // 9. k <len 인 동안 반복한다.
+    while (k < len) {
+       // a. Pk를 ToString (k)이라고합시다.
+       // 이것은 in 연산자의 LHS 피연산자에 대해 암시 적입니다.
+       // b. kPresent를 호출 한 결과라고합시다.
+       // Hasproperty 인수에 Pk가있는 o의 내부 메소드.
+       //이 단계는 c와 결합 될 수 있습니다.
+       // c. kPresent가 참이면
+       // i. elementK를 Get을 호출 한 결과로합시다.
+       // ToString (k) 인수를 가진 o의 내부 메쏘드.
+       // ii. 적용한 결과와 동일하게 봅시다.
+       // 엄격한 평등 비교 알고리즘
+       // searchElement 및 elementK.
+       // iii. 동일하면 k를 반환합니다.
+      if (k in o && o[k] === searchElement) {
+        return k;
+      }
+      k++;
+    }
+    return -1;
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
+

{{Compat("javascript.builtins.Array.indexOf")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/isarray/index.html b/files/ko/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..0a3a074a3d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,131 @@ +--- +title: Array.isArray() +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Reference + - polyfill + - 자바스크립트 + - 폴리필 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +
{{JSRef}}
+ +

Array.isArray() 메서드는 인자가 {{jsxref("Array")}}인지 판별합니다.

+ +
Array.isArray([1, 2, 3]);  // true
+Array.isArray({foo: 123}); // false
+Array.isArray('foobar');   // false
+Array.isArray(undefined);  // false
+
+ +

구문

+ +
Array.isArray(obj)
+ +

매개변수

+ +
+
obj
+
검사할 객체.
+
+ +

반환 값

+ +

객체가 {{jsxref("Array")}}라면 true, 아니라면 false.

+ +

설명

+ +

객체가 {{jsxref("Array")}}라면 true를 반환하고, 아니라면 false를 반환합니다.

+ +

자세한 정보는 “Determining with absolute accuracy whether or not a JavaScript object is an array”(자바스크립트 객체가 배열인지 정확히 판별하는 방법) 문서를 참조하세요.

+ +

예제

+ +
// 모두 true 반환
+Array.isArray([]);
+Array.isArray([1]);
+Array.isArray(new Array());
+Array.isArray(new Array('a', 'b', 'c', 'd'));
+Array.isArray(new Array(3));
+// Array.prototype은 스스로도 배열입니다
+Array.isArray(Array.prototype);
+
+// 모두 false 반환
+Array.isArray();
+Array.isArray({});
+Array.isArray(null);
+Array.isArray(undefined);
+Array.isArray(17);
+Array.isArray('Array');
+Array.isArray(true);
+Array.isArray(false);
+Array.isArray({ __proto__: Array.prototype });
+ +

instanceof vs isArray

+ +

Array 객체를 판별할 때, Array.isArrayiframe을 통해서도 작동하기 때문에 instanceof 보다 적합합니다.

+ +
var iframe = document.createElement('iframe');
+document.body.appendChild(iframe);
+xArray = window.frames[window.frames.length-1].Array;
+var arr = new xArray(1,2,3); // [1,2,3]
+
+// 올바른 Array 판별
+Array.isArray(arr);  // true
+// iframe을 통해서 작동하지 않기 때문에 올바르지 않은 방법
+arr instanceof Array; // false
+
+ +

폴리필

+ +

아래 코드를 실행하면 지원하지 않는 환경에서도 Array.isArray()를 사용할 수 있습니다.

+ +
if (!Array.isArray) {
+  Array.isArray = function(arg) {
+    return Object.prototype.toString.call(arg) === '[object Array]';
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태주석
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}초안. 자바스크립트 1.8.5 에 구현됨.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} +

 

+
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.isArray")}}
+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/join/index.html b/files/ko/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..7a78c568ab --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,91 @@ +--- +title: Array.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +
{{JSRef}}
+ +

join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.

+ +

{{EmbedInteractiveExample("pages/js/array-join.html")}}

+ +

구문

+ +
arr.join([separator])
+ +

매개변수

+ +
+
separator {{optional_inline}}
+
배열의 각 요소를 구분할 문자열을 지정합니다. 이 구분자는 필요한 경우 문자열로 변환됩니다. 생략하면 배열의 요소들이 쉼표로 구분됩니다. separator가 빈 문자열이면 모든 요소들이 사이에 아무 문자도 없이 연결됩니다.
+
+ +

반환 값

+ +

배열의 모든 요소들을 연결한 하나의 문자열을 반환합니다. 만약 arr.length 가 0이라면, 빈 문자열을 반환합니다.

+ +

설명

+ +

모든 배열 요소가 문자열로 변환된 다음 하나의 문자열로 연결됩니다.

+ +
+

요소가 undefined 또는 null이면 빈 문자열로 변환합니다.

+
+ +

예제

+ +

네 가지 다른 방법으로 배열 연결하기

+ +

다음 예제에서는 3개의 요소를 가진 배열 a를 만들고, 기본 구분자, 쉼표와 공백, 더하기 기호, 빈 문자열의 네 가지 구분자를 사용해 배열을 연결합니다.

+ +
var a = ['바람', '비', '불'];
+var myVar1 = a.join();      // myVar1에 '바람,비,불'을 대입
+var myVar2 = a.join(', ');  // myVar2에 '바람, 비, 불'을 대입
+var myVar3 = a.join(' + '); // myVar3에 '바람 + 비 + 불'을 대입
+var myVar4 = a.join('');    // myVar4에 '바람비불'을 대입
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}최초 정의.  JavaScript 1.1에 구현됨.
{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ES6')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.join")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/keys/index.html b/files/ko/web/javascript/reference/global_objects/array/keys/index.html new file mode 100644 index 0000000000..4afb826a3e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/keys/index.html @@ -0,0 +1,69 @@ +--- +title: Array.prototype.keys() +slug: Web/JavaScript/Reference/Global_Objects/Array/keys +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/keys +--- +
{{JSRef}}
+ +

keys() 메서드는 배열의 각 인덱스를 키 값으로 가지는 새로운 Array Iterator 객체를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-keys.html")}}

+ +

구문

+ +
arr.keys()
+ +

반환 값

+ +

새로운 {{jsxref("Array")}} 반복기 객체.

+ +

예제

+ +

키 반복기는 빈 인덱스를 무시하지 않음

+ +
var arr = ['a', , 'c'];
+var sparseKeys = Object.keys(arr);
+var denseKeys = [...arr.keys()];
+console.log(sparseKeys); // ['0', '2']
+console.log(denseKeys);  // [0, 1, 2]
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.keys")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html b/files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html new file mode 100644 index 0000000000..7e1519ae78 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/lastindexof/index.html @@ -0,0 +1,103 @@ +--- +title: Array.prototype.lastIndexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +--- +
{{JSRef}}
+ +

lastIndexOf() 메서드는 배열에서 주어진 값을 발견할 수 있는 마지막 인덱스를 반환하고, 요소가 존재하지 않으면 -1을 반환합니다. 배열 탐색은 fromIndex에서 시작하여 뒤로 진행합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-lastindexof.html")}}
+ + + +

구문

+ +
arr.lastIndexOf(searchElement[, fromIndex])
+ +

매개변수

+ +
+
searchElement
+
배열에서 찾을 요소.
+
fromIndex {{optional_inline}}
+
역순으로 검색을 시작할 인덱스. 배열의 길이에서 1을 뺀 값(arr.length - 1)이 기본값이므로 지정하지 않을 경우 전체 배열을 검색합니다. 주어진 값이 배열의 길이 이상이면 전체 배열을 검색합니다. 값이 음수인 경우, 배열의 마지막부터 시작하는 인덱스로 처리합니다. 다만, 음수를 제공하더라도 검색 순서는 뒤에서 앞입니다. 위의 모든 절차를 거친 최종 계산값이 0 미만인 경우, lastIndexOf()는 항상 -1을 반환합니다. 즉, 배열을 탐색하지 않습니다.
+
+ +

반환 값

+ +

주어진 값과 일치하는 마지막 요소의 인덱스, 없으면 -1.

+ +

설명

+ +

lastIndexOf는 일치 연산(=== 연산자와 동일)을 사용해 searchElement와 각 요소를 비교합니다.

+ +

예제

+ +

lastIndexOf 사용하기

+ +

다음 예제에서는 lastIndexOf를 사용하여 배열의 값을 찾습니다.

+ +
var array = [2, 5, 9, 2];
+array.lastIndexOf(2);     // 3
+array.lastIndexOf(7);     // -1
+array.lastIndexOf(2, 3);  // 3
+array.lastIndexOf(2, 2);  // 0
+array.lastIndexOf(2, -2); // 0
+array.lastIndexOf(2, -1); // 3
+
+ +

요소의 모든 항목 찾기

+ +

다음 예제에서는 lastIndexOf를 사용하여 {{jsxref("Array.prototype.push", "push")}}를 사용하여 지정된 배열의 요소 색인을 모두 찾아서 다른 배열에 추가합니다.

+ +
var indices = [];
+var array = ['a', 'b', 'a', 'c', 'a', 'd'];
+var element = 'a';
+var idx = array.lastIndexOf(element);
+while (idx != -1) {
+  indices.push(idx);
+  idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1);
+}
+
+console.log(indices);
+// [4, 2, 0]
+
+ +

배열의 첫 번째 요소 인 경우 요소가 fromIndex 매개 변수와 관계없이 항상 발견되므로 idx == 0 사례를 여기에서 개별적으로 처리해야합니다. 이는 {{jsxref ( "Array.prototype.indexOf", "indexOf")}} 메소드와 다릅니다.

+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.lastIndexOf")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/length/index.html b/files/ko/web/javascript/reference/global_objects/array/length/index.html new file mode 100644 index 0000000000..b241e88045 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/length/index.html @@ -0,0 +1,135 @@ +--- +title: Array.length +slug: Web/JavaScript/Reference/Global_Objects/Array/length +tags: + - Array + - JavaScript + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/length +--- +
{{JSRef}}
+ +

Array 인스턴스의 length 속성은 배열의 길이를 반환합니다. 반환값은 부호 없는 32비트 정수형이며, 배열의 최대 인덱스보다 항상 큽니다. length 속성에 값을 설정할 경우 배열의 길이를 변경합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-length.html")}}
+ + + +

설명

+ +

length 속성의 값은 양의 정수이며 232 미만의 값을 가집니다.

+ +
var namelistA = new Array(4294967296); // 2의 32제곱 = 4294967296
+var namelistC = new Array(-100) // 음수
+
+console.log(namelistA.length); // RangeError: Invalid array length
+console.log(namelistC.length); // RangeError: Invalid array length
+
+var namelistB = [];
+namelistB.length = Math.pow(2,32)-1; // 길이를 2의 32제곱 미만으로 설정
+console.log(namelistB.length);
+
+// 4294967295
+ +

아무 때나 length 속성에 값을 설정해 배열을 절단할 수 있습니다. length 속성으로 배열의 길이를 늘리면 실제 원소의 수가 증가합니다. 예를 들어 길이가 2인 배열의 length를 3으로 설정한다면 마지막에 undefined가 추가돼 총 3개의 요소를 갖게 됩니다.

+ +
var arr = [1, 2, 3];
+printEntries(arr);
+
+arr.length = 5; // set array length to 5 while currently 3.
+printEntries(arr);
+
+function printEntries(arr) {
+  var length = arr.length;
+  for (var i = 0; i < length; i++) {
+    console.log(arr[i]);
+  }
+  console.log('=== printed ===');
+}
+
+// 1
+// 2
+// 3
+// === printed ===
+// 1
+// 2
+// 3
+// undefined
+// undefined
+// === printed ===
+
+ +

그러나 length 속성의 값이 꼭 배열에 정의된 원소의 수를 나타내진 않습니다. length와 숫자형 속성의 관계를 참고하세요.

+ +

{{js_property_attributes(1, 0, 0)}}

+ +

예제

+ +

배열 순회

+ +

다음 예제는 numbers 배열을 length 속성의 크기만큼 순회합니다. 각 원소의 값은 두 배가 됩니다.

+ +
var numbers = [1, 2, 3, 4, 5];
+var length = numbers.length;
+for (var i = 0; i < length; i++) {
+  numbers[i] *= 2;
+}
+// numbers is now [2, 4, 6, 8, 10]
+
+ +

배열 단축

+ +

다음 예제는 numbers 배열의 현재 길이가 3보다 클 경우 3으로 줄입니다.

+ +
var numbers = [1, 2, 3, 4, 5];
+
+if (numbers.length > 3) {
+    numbers.length = 3;
+}
+
+console.log(numbers); // [1, 2, 3]
+console.log(numbers.length); // 3
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.length")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/map/index.html b/files/ko/web/javascript/reference/global_objects/array/map/index.html new file mode 100644 index 0000000000..b3f494a8e3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,293 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +
{{JSRef}}
+ +

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-map.html")}}

+ +

구문

+ +
arr.map(callback(currentValue[, index[, array]])[, thisArg])
+ +

매개변수

+ +
+
callback
+
새로운 배열 요소를 생성하는 함수. 다음 세 가지 인수를 가집니다.
+
+
+
currentValue
+
처리할 현재 요소.
+
index {{optional_inline}}
+
처리할 현재 요소의 인덱스.
+
array {{optional_inline}}
+
map()을 호출한 배열.
+
+
+
thisArg {{optional_inline}}
+
callback을 실행할 때 this로 사용되는 값.
+
+ +

반환 값

+ +

배열의 각 요소에 대해 실행한 callback의 결과를 모은 새로운 배열.

+ +

설명

+ +

mapcallback 함수를 각각의 요소에 대해 한번씩 순서대로 불러 그 함수의 반환값으로 새로운 배열을 만듭니다. callback 함수는 ({{jsxref("undefined")}}도 포함해서) 배열 값이 들어있는 인덱스에 대해서만 호출됩니다. 즉, 값이 삭제되거나 아직 값이 할당/정의되지 않은 인덱스에 대해서는 호출되지 않습니다.

+ +

callback 함수는 호출될 때 대상 요소의 값, 그 요소의 인덱스, 그리고 map을 호출한 원본 배열 3개의 인수를 전달받습니다.

+ +

thisArg 매개변수가 map에 전달된 경우 callback 함수의 this값으로 사용됩니다. 그 외의 경우 {{jsxref("undefined")}}값이 this 값으로 사용됩니다. callback 함수에서 최종적으로 볼 수 있는 this 값은  함수 내 this를 정하는 일반적인 규칙에 따라 결정됩니다.

+ +

map은 호출한 배열의 값을 변형하지 않습니다. 단, callback 함수에 의해서 변형될 수는 있습니다.

+ +

map이  처리할 요소의 범위는 첫 callback을 호출하기 전에 정해집니다. map이 시작한 이후 배열에 추가되는 요소들은 callback을 호출하지 않습니다. 배열에 존재하는 요소들의 값이 바뀐 경우 map이 방문하는 시점의 값이 callback에 전달됩니다. map이 시작되고, 방문하기 전에 삭제된 요소들은 방문하지 않습니다.

+ +

명세서에 정의된 알고리즘으로 인해 map을 호출한 배열의 중간이 비어있는 경우, 결과 배열 또한 동일한 인덱스를 빈 값으로 유지합니다.

+ +

예제

+ +

배열에 들어있는 숫자들의 제곱근을 구하여 새로운 배열을 만들기

+ +

다음 코드는 숫자의 배열을 받아 각 숫자들의 제곱근이 들어있는 새로운 배열을 만듭니다.

+ +
var numbers = [1, 4, 9];
+var roots = numbers.map(Math.sqrt);
+// roots는 [1, 2, 3]
+// numbers는 그대로 [1, 4, 9]
+
+ +

map을 활용해 배열 속 객체를 재구성하기

+ +

다음 코드는 오브젝트의 배열을 받아 각 오브젝트를 다른 형태으로 재구성해 새로운 배열을 만듭니다.

+ +
var kvArray = [{key:1, value:10},
+               {key:2, value:20},
+               {key:3, value: 30}];
+
+var reformattedArray = kvArray.map(function(obj){
+   var rObj = {};
+   rObj[obj.key] = obj.value;
+   return rObj;
+});
+// reformattedArray는 [{1:10}, {2:20}, {3:30}]
+
+// kvArray는 그대로
+// [{key:1, value:10},
+//  {key:2, value:20},
+//  {key:3, value: 30}]
+
+ +

인자를 받는 함수를 사용하여 숫자 배열 재구성하기

+ +

다음 코드는 인자가 한개인 함수를 이용하여 map이 어떻게 동작하는지 나타냅니다. 인자인 배열과 안의 요소들은 map을 통해 순회하면서 원본 배열로 부터 자동으로 할당됩니다.

+ +
var numbers = [1, 4, 9];
+var doubles = numbers.map(function(num) {
+  return num * 2;
+});
+// doubles는 이제 [2, 8, 18]
+// numbers는 그대로 [1, 4, 9]
+
+ +

map을 포괄적으로 사용하기

+ +

아래 예제는 {{jsxref("Global_Objects/String", "String")}}에 map을 사용해서 각 문자의 ASCII 인코딩 값을 요소로 갖는 배열을 얻는 방법을 보여줍니다.

+ +
var map = Array.prototype.map;
+var a = map.call('Hello World', function(x) { return x.charCodeAt(0); });
+// a는 이제 [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
+
+ +

map을 포괄적으로 사용하기 (querySelectorAll)

+ +

아래 예제는 querySelectorAll을 사용해서 수집된 객체들을 순회 처리하는 법을 보여줍니다. 이번 경우 체크한 옵션 박스를 콘솔에 프린트합니다.

+ +
var elems = document.querySelectorAll('select option:checked');
+var values = [].map.call(elems, function(obj) {
+  return obj.value;
+});
+
+ +

더 쉬운 방법은 {{jsxref("Array.from()")}}을 사용하는 것입니다.

+ +

까다로운 사례

+ +

(참고한 블로그 포스트)

+ +

map에 하나의 인자(순회하는 원소)만 받는 콜백을 사용하는 경우가 많습니다. 그러나 어떤 함수는 대개 하나의 인자로 호출하지만 두 개 이상의 인자를 사용하는 경우도 있습니다. 이로 인해 어떤 경우 혼란스러울 수도 있습니다.

+ +
// 아래 라인을 보시면...
+['1', '2', '3'].map(parseInt);
+// 결과를 [1, 2, 3] 으로 기대할 수 있습니다.
+// 그러나 실제 결과는 [1, NaN, NaN] 입니다.
+
+// parseInt 함수는 보통 하나의 인자만 사용하지만, 두 개를 받을 수 있습니다.
+// 첫 번째 인자는 변환하고자 하는 표현이고 두 번째는 숫자로 변환할 때 사용할 진법입니다.
+// Array.prototype.map은 콜백에 세 가지 인자를 전달합니다.
+// 배열의 값, 값의 인덱스, 그리고 배열
+// 세 번째 인자는 parseInt가 무시하지만 두 번째 인자는 아닙니다.
+// 따라서 혼란스러운 결과를 도출할 수 있습니다. 자세한 내용은 블로그 포스트를 참고하시길 바랍니다.
+
+function returnInt(element) {
+  return parseInt(element, 10);
+}
+
+['1', '2', '3'].map(returnInt); // [1, 2, 3]
+// 실제 결과가 예상한 대로 배열의 숫자와 같습니다.
+
+// 위와 같지만 더 간단한 화살표 표현식
+['1', '2', '3'].map(str => parseInt(str));
+
+// 더 간단하게 해결할 수 있는 방법
+['1', '2', '3'].map(Number); // [1, 2, 3]
+// 그러나 `parseInt`와 달리 float이나 지수표현도 반환합니다.
+['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]
+
+ +

폴리필

+ +

map은 ECMA-262 표준 제5판에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 map을 사용할 수 있습니다. 아래 알고리즘은 {{jsxref("Object")}}, {{jsxref("TypeError")}}, {{jsxref("Array")}}가 변형되지 않고, callback.call의 계산 값이 원래의 {{jsxref("Function.prototype.call()")}}과 같은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.

+ +
// Production steps of ECMA-262, Edition 5, 15.4.4.19
+// Reference: http://es5.github.io/#x15.4.4.19
+if (!Array.prototype.map) {
+
+  Array.prototype.map = function(callback, thisArg) {
+
+    var T, A, k;
+
+    if (this == null) {
+      throw new TypeError(' this is null or not defined');
+    }
+
+    // 1. Let O be the result of calling ToObject passing the |this|
+    //    value as the argument.
+    var O = Object(this);
+
+    // 2. Let lenValue be the result of calling the Get internal
+    //    method of O with the argument "length".
+    // 3. Let len be ToUint32(lenValue).
+    var len = O.length >>> 0;
+
+    // 4. If IsCallable(callback) is false, throw a TypeError exception.
+    // See: http://es5.github.com/#x9.11
+    if (typeof callback !== 'function') {
+      throw new TypeError(callback + ' is not a function');
+    }
+
+    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
+    if (arguments.length > 1) {
+      T = thisArg;
+    }
+
+    // 6. Let A be a new array created as if by the expression new Array(len)
+    //    where Array is the standard built-in constructor with that name and
+    //    len is the value of len.
+    A = new Array(len);
+
+    // 7. Let k be 0
+    k = 0;
+
+    // 8. Repeat, while k < len
+    while (k < len) {
+
+      var kValue, mappedValue;
+
+      // a. Let Pk be ToString(k).
+      //   This is implicit for LHS operands of the in operator
+      // b. Let kPresent be the result of calling the HasProperty internal
+      //    method of O with argument Pk.
+      //   This step can be combined with c
+      // c. If kPresent is true, then
+      if (k in O) {
+
+        // i. Let kValue be the result of calling the Get internal
+        //    method of O with argument Pk.
+        kValue = O[k];
+
+        // ii. Let mappedValue be the result of calling the Call internal
+        //     method of callback with T as the this value and argument
+        //     list containing kValue, k, and O.
+        mappedValue = callback.call(T, kValue, k, O);
+
+        // iii. Call the DefineOwnProperty internal method of A with arguments
+        // Pk, Property Descriptor
+        // { Value: mappedValue,
+        //   Writable: true,
+        //   Enumerable: true,
+        //   Configurable: true },
+        // and false.
+
+        // In browsers that support Object.defineProperty, use the following:
+        // Object.defineProperty(A, k, {
+        //   value: mappedValue,
+        //   writable: true,
+        //   enumerable: true,
+        //   configurable: true
+        // });
+
+        // For best browser support, use the following:
+        A[k] = mappedValue;
+      }
+      // d. Increase k by 1.
+      k++;
+    }
+
+    // 9. return A
+    return A;
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.map")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/observe/index.html b/files/ko/web/javascript/reference/global_objects/array/observe/index.html new file mode 100644 index 0000000000..015ae049c5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/observe/index.html @@ -0,0 +1,87 @@ +--- +title: Array.observe() +slug: Web/JavaScript/Reference/Global_Objects/Array/observe +tags: + - Array + - JavaScript + - Method + - Obsolete +translation_of: Archive/Web/JavaScript/Array.observe +--- +
{{JSRef}} {{obsolete_header}}
+ +

Array.observe() 메서드는 {{jsxref("Object.observe()")}}가 객체를 관찰하는 것과 비슷하게 , 배열의 변화를 비동기 적으로 관찰 하는데 사용 되었습니다. 그것은 발생 순서에 따른 변화의 흐름을 제공합니다. Object.observe()가 accept type list ["add", "update", "delete", "splice"]와 함께 호출되는 것과 같습니다. 하지만 이 API는 더이상 사용되지 않고 브라우저에서 제거 되었습니다. 대신, 더 일반적인 {{jsxref("Proxy")}} 객체를 사용하세요.

+ +

구문

+ +
Array.observe(arr, callback)
+ +

매개변수

+ +
+
arr
+
관찰 할 배열
+
callback
+
이 함수는 변화가 일어날때 마다 다음과 같은 인수와 함께 호출됩니다. +
+
changes
+
변경을 나타내는 각 객체들의 배열입니다. 이 변경 객체들의 프로퍼티 들은: +
    +
  • name: 변경된 프로퍼티의 이름
  • +
  • object: 변경 후 배열
  • +
  • type: 변경 타입을 나타내는 문자. "add", "update", "delete", 또는 "splice" 중 하나.
  • +
  • oldValue: "update" 나 "delete"유형에만 해당합니다. 변경 전 값.
  • +
  • index: "splice"유형에만 해당합니다. 변경이 발생한 인덱스.
  • +
  • removed: "splice"유형에만 해당합니다. 삭제 된 요소들의 배열.
  • +
  • addedCount: "splice"유형에만 해당합니다. 추가 된 요소들의 숫자.
  • +
+
+
+
+
+ +

설명

+ +

콜백 함수는 arr이 변경 될 때마다 호출되며 발생하는 순서대로 모든 변경 사항의 배열로 호출됩니다

+ +
+

Array.prototype.pop() "splice" 변경으로 보고되는 것처럼, 변경은 배열 메서드를 통해 일어납니다. 배열 길이를 변경하지 않는 인덱스 할당 변경은 "update" 변경으로 보고 될 수 있습니다.

+
+ +

예제

+ +

다른 변경 유형 로깅(Logging)

+ +
var arr = ['a', 'b', 'c'];
+
+Array.observe(arr, function(changes) {
+  console.log(changes);
+});
+
+arr[1] = 'B';
+// [{type: 'update', object: <arr>, name: '1', oldValue: 'b'}]
+
+arr[3] = 'd';
+// [{type: 'splice', object: <arr>, index: 3, removed: [], addedCount: 1}]
+
+arr.splice(1, 2, 'beta', 'gamma', 'delta');
+// [{type: 'splice', object: <arr>, index: 1, removed: ['B', 'c'], addedCount: 3}]
+
+ +

명세

+ +

Strawman proposal specification.

+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.observe")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/of/index.html b/files/ko/web/javascript/reference/global_objects/array/of/index.html new file mode 100644 index 0000000000..edcd9bddc5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,104 @@ +--- +title: Array.of() +slug: Web/JavaScript/Reference/Global_Objects/Array/of +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/of +--- +
{{JSRef}}
+ +

Array.of() 메서드는 인자의 수나 유형에 관계없이 가변 인자를 갖는 새 Array 인스턴스를 만듭니다.

+ +

Array.of()Array 생성자의 차이는 정수형 인자의 처리 방법에 있습니다. Array.of(7)은 하나의 요소 7을 가진 배열을 생성하지만 Array(7)length 속성이 7인 빈 배열을 생성합니다.

+ +
Array.of(7);       // [7]
+Array.of(1, 2, 3); // [1, 2, 3]
+
+Array(7);          // [ , , , , , , ]
+Array(1, 2, 3);    // [1, 2, 3]
+
+ +

구문

+ +
Array.of(element0[, element1[, ...[, elementN]]])
+ +

매개변수

+ +
+
elementN
+
배열을 생성할 때 사용할 요소.
+
+ +

반환 값

+ +

새로운 {{jsxref("Array")}} 객체.

+ +

설명

+ +

이 함수는 ECMAScript 2015 표준 일부입니다. 자세한 정보는 Array.of, Array.from 제안 사항Array.of 폴리필에서 확인하실 수 있습니다.

+ +

예제

+ +
Array.of(1);         // [1]
+Array.of(1, 2, 3);   // [1, 2, 3]
+Array.of(undefined); // [undefined]
+
+ +

폴리필

+ +

아래 코드를 다른 코드 이전에 포함하면 Array.of를 지원하지 않는 환경에서도 사용할 수 있습니다.

+ +
if (!Array.of) {
+  Array.of = function() {
+    return Array.prototype.slice.call(arguments);
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
+ +

 

+ +

 

+ +

 

+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.of")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/pop/index.html b/files/ko/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..d02df55262 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,91 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +
{{JSRef}}
+ +

pop() 메서드는 배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-pop.html")}}

+ +

구문

+ +
arr.pop()
+ +

반환 값

+ +

배열에서 제거한 요소. 빈 배열의 경우 {{jsxref("undefined")}} 를 반환합니다.

+ +

설명

+ +

pop 메서드는 배열에서 마지막 요소를 제거하여 그 값을 호출자(caller)에게 반환합니다.

+ +

pop은 일부러 일반(generic)입니다; 이 메서드는 배열을 닮은 객체에 {{jsxref("Function.call", "호출", "", 1)}} 또는 {{jsxref("Function.apply", "적용", "", 1)}}될 수 있습니다. 0부터 시작하는 일련의 연속되는 숫자 속성 내 마지막을 반영하는 length 속성을 포함하지 않는 객체는 어떤 의미 있는 방식으로도 행동하지 않을 수 있습니다.

+ +

빈 배열에 pop()을 호출하면, {{jsxref("undefined")}}를 반환합니다.

+ +

예제

+ +

배열의 마지막 요소 제거

+ +

다음 코드는 요소 넷을 포함하는 myFish 배열을 생성하고 그 마지막 요소를 제거합니다.

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+
+var popped = myFish.pop();
+
+console.log(myFish); // ['angel', 'clown', 'mandarin' ]
+
+console.log(popped); // 'sturgeon'
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의. JavaScript 1.2에서 구현됨.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.pop")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/push/index.html b/files/ko/web/javascript/reference/global_objects/array/push/index.html new file mode 100644 index 0000000000..73d9c9ad78 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/push/index.html @@ -0,0 +1,113 @@ +--- +title: Array.prototype.push() +slug: Web/JavaScript/Reference/Global_Objects/Array/push +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/push +--- +
{{JSRef}}
+ +

push() 메서드는 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-push.html")}}

+ +

구문

+ +
arr.push(element1[, ...[, elementN]])
+ +

매개변수

+ +
+
elementN
+
배열의 끝에 추가할 요소.
+
+ +

반환 값

+ +

호출한 배열의 새로운 {{jsxref("Array.length", "length")}} 속성.

+ +

설명

+ +

push 메서드는 배열 끝에 여러 값을 추가합니다.

+ +

push는 의도적으로 제네릭합니다. 배열을 닯은 객체에 {{jsxref("Function.call", "call()")}} 또는 {{jsxref("Function.apply", "apply()")}}로 사용될 수 있다. push 메서드는 주어진 값을 입력하는 것을 어디에 시작할 것인지를 결정하기 위해 length 속성에  의존한다. 만약 length 속성이 숫자로 변환 될 수 없다면 인덱스는 0을 사용한다. length 가 생성되게 될 경우에  길이 값이 존재하지 않을 가능성을 포함한다.  

+ +

String(문자열)이 변경할 수 없는 것처럼 비록 이 명령어의 어플리케이션들이 적합하지 않다고 할지라도 단지 원래 배열 같은 객체는 {{jsxref("Global_Objects/String", "strings", "", 1)}}이다.

+ +

예시

+ +

배열에 엘리먼트를 추가 하기

+ +

다음 코드는 두가지 엘리먼트를 포함하는 스포츠 배열을 생성하고 두개의 엘리먼트를 추가 한다. total 변수는 추가한 배열의 새 길이 값을 포함한다. 

+ +
var sports = ['축구', '야구'];
+var total = sports.push('미식축구', '수영');
+
+console.log(sports); // ['축구', '야구', '미식축구', '수영']
+console.log(total);  // 4
+
+ +

두개의 배열을 합치기

+ +

이 예제는 두번째 배열의 모든 엘리먼트를 push 하기 위해 {{jsxref("Function.apply", "apply()")}}를 사용한다.

+ +

만약 두번째 배열( 아래 예제에서는 moreVegs )이 매우 클 경우, 이 메소드를 사용하지 말아야 한다. 실제로 한 함수가 사용가능한 매개변수의 최대 개수에는 제한이 있기 때문이다. 더 자세한 사항은    {{jsxref("Function.apply", "apply()")}} 에서 찾아볼 수 있다.

+ +
var vegetables = ['설탕당근', '감자'];
+var moreVegs = ['셀러리', '홍당무'];
+
+// 첫번째 배열에 두번째 배열을 합친다.
+// vegetables.push('셀러리', '홍당무'); 하는 것과 동일하다.
+Array.prototype.push.apply(vegetables, moreVegs);
+
+console.log(vegetables); // ['설탕당근', '감자', '셀러리', '홍당무']
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세서상태비고
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의. JavaScript 1.2에서 구현되었음.
{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.push")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/reduce/index.html b/files/ko/web/javascript/reference/global_objects/array/reduce/index.html new file mode 100644 index 0000000000..bd3516865e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/reduce/index.html @@ -0,0 +1,573 @@ +--- +title: Array.prototype.reduce() +slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce +--- +
{{JSRef}}
+ +

reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-reduce.html")}}
+ + + +

리듀서 함수는 네 개의 인자를 가집니다.

+ +
    +
  1. 누산기accumulator (acc)
  2. +
  3. 현재 값 (cur)
  4. +
  5. 현재 인덱스 (idx)
  6. +
  7. 원본 배열 (src)
  8. +
+ +

리듀서 함수의 반환 값은 누산기에 할당되고, 누산기는 순회 중 유지되므로 결국 최종 결과는 하나의 값이 됩니다.

+ +

구문

+ +
arr.reduce(callback[, initialValue])
+ +

매개변수

+ +
+
callback
+
배열의 각 요소에 대해 실행할 함수. 다음 네 가지 인수를 받습니다.
+
+
+
accumulator
+
누산기accmulator는 콜백의 반환값을 누적합니다. 콜백의 이전 반환값 또는, 콜백의 첫 번째 호출이면서 initialValue를 제공한 경우에는 initialValue의 값입니다.
+
currentValue
+
처리할 현재 요소.
+
currentIndex {{optional_inline}}
+
처리할 현재 요소의 인덱스. initialValue를 제공한 경우 0, 아니면 1부터 시작합니다.
+
array {{optional_inline}}
+
reduce()를 호출한 배열.
+
+
+
initialValue {{optional_inline}}
+
callback의 최초 호출에서 첫 번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용합니다. 빈 배열에서 초기값 없이 reduce()를 호출하면 오류가 발생합니다.
+
+ +

반환 값

+ +

누적 계산의 결과 값.

+ +

설명

+ +

reduce()는 빈 요소를 제외하고 배열 내에 존재하는 각 요소에 대해 callback 함수를 한 번씩 실행하는데, 콜백 함수는 다음의 네 인수를 받습니다:

+ + + +

콜백의 최초 호출 때 accumulator와 currentValue는 다음 두 가지 값 중 하나를 가질 수 있습니다. 만약 reduce() 함수 호출에서 initialValue를 제공한 경우, accumulatorinitialValue와 같고 currentValue는 배열의 첫 번째 값과 같습니다. initialValue를 제공하지 않았다면, accumulator는 배열의 첫 번째 값과 같고 currentValue는 두 번째와 같습니다.

+ +
+

참고: initialValue를 제공하지 않으면, reduce()는 인덱스 1부터 시작해 콜백 함수를 실행하고 첫 번째 인덱스는 건너 뜁니다. initialValue를 제공하면 인덱스 0에서 시작합니다.

+
+ +

배열이 비어있는데 initialValue도 제공하지 않으면 {{jsxref("TypeError")}}가 발생합니다. 배열의 요소가 (위치와 관계없이) 하나 뿐이면서 initialValue를 제공되지 않은 경우, 또는 initialValue는 주어졌으나 배열이 빈 경우엔 그 단독 값을 callback 호출 없이 반환합니다.

+ +

다음의 예제처럼 initialValue을 제공하지 않으면 출력 가능한 형식이 세 가지이므로, 보통 초기값을 주는 것이 더 안전합니다.

+ +
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
+var maxCallback2 = ( max, cur ) => Math.max( max, cur );
+
+// initialValue 없이 reduce()
+[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
+[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }
+[                      ].reduce( maxCallback ); // TypeError
+
+// map/reduce로 개선 - 비었거나 더 큰 배열에서도 동작함
+[ { x: 22 }, { x: 42 } ].map( el => el.x )
+                        .reduce( maxCallback2, -Infinity );
+ +

reduce() 작동  방식

+ +

다음의 예제를 생각해 봅시다.

+ +
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
+  return accumulator + currentValue;
+});
+
+ +

콜백은 4번 호출됩니다. 각 호출의 인수와 반환값은 다음과 같습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
callbackaccumulatorcurrentValuecurrentIndexarray반환 값
1번째 호출011[0, 1, 2, 3, 4]1
2번째 호출122[0, 1, 2, 3, 4]3
3번째 호출333[0, 1, 2, 3, 4]6
4번째 호출644[0, 1, 2, 3, 4]10
+ +

reduce()가 반환하는 값으로는 마지막 콜백 호출의 반환값(10)을 사용합니다.

+ +

완전한 함수 대신에 {{jsxref("Functions/애로우_펑션", "화살표 함수","",1)}}를 제공할 수도 있습니다. 아래 코드는 위의 코드와 같은 결과를 반환합니다.

+ +
[0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr );
+
+ +

reduce()의 두 번째 인수로 초기값을 제공하는 경우, 결과는 다음과 같습니다:

+ +
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
+  return accumulator + currentValue;
+}, 10);
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 accumulatorcurrentValuecurrentIndexarray반환값
1번째 호출1000[0, 1, 2, 3, 4]10
2번째 호출1011[0, 1, 2, 3, 4]11
3번째 호출1122[0, 1, 2, 3, 4]13
4번째 호출1333[0, 1, 2, 3, 4]16
5번째 호출1644[0, 1, 2, 3, 4]20
+ +

이 때 reduce()가 결과로 반환하는 값은 20입니다.

+ +

예제

+ +

배열의 모든 값 합산

+ +
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
+  return accumulator + currentValue;
+}, 0);
+// sum is 6
+
+
+ +

화살표 함수로도 작성할 수 있습니다.

+ +
var total = [ 0, 1, 2, 3 ].reduce(
+  ( accumulator, currentValue ) => accumulator + currentValue,
+  0
+);
+ +

객체 배열에서의 값 합산

+ +

객체로 이루어진 배열에 들어 있는 값을 합산하기 위해서는 반드시 초기값을 주어 각 항목이 여러분의 함수를 거치도록 해야 합니다.

+ +
var initialValue = 0;
+var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
+    return accumulator + currentValue.x;
+},initialValue)
+
+console.log(sum) // logs 6
+
+ +

화살표 함수(arrow function)로도 작성할 수 있습니다: 

+ +
var initialValue = 0;
+var sum = [{x: 1}, {x:2}, {x:3}].reduce(
+    (accumulator, currentValue) => accumulator + currentValue.x
+    ,initialValue
+);
+
+console.log(sum) // logs 6
+ +

중첩 배열 펼치기flatten

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+  function(accumulator, currentValue) {
+    return accumulator.concat(currentValue);
+  },
+  []
+);
+// 펼친 결과: [0, 1, 2, 3, 4, 5]
+
+ +

화살표 함수로도 작성할 수 있습니다:

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+  ( accumulator, currentValue ) => accumulator.concat(currentValue),
+  []
+);
+
+ +

객체 내의 값 인스턴스 개수 세기

+ +
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
+
+var countedNames = names.reduce(function (allNames, name) {
+  if (name in allNames) {
+    allNames[name]++;
+  }
+  else {
+    allNames[name] = 1;
+  }
+  return allNames;
+}, {});
+// countedNames is:
+// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
+
+ +

속성으로 객체 분류하기

+ +
var people = [
+  { name: 'Alice', age: 21 },
+  { name: 'Max', age: 20 },
+  { name: 'Jane', age: 20 }
+];
+
+function groupBy(objectArray, property) {
+  return objectArray.reduce(function (acc, obj) {
+    var key = obj[property];
+    if (!acc[key]) {
+      acc[key] = [];
+    }
+    acc[key].push(obj);
+    return acc;
+  }, {});
+}
+
+var groupedPeople = groupBy(people, 'age');
+// groupedPeople is:
+// {
+//   20: [
+//     { name: 'Max', age: 20 },
+//     { name: 'Jane', age: 20 }
+//   ],
+//   21: [{ name: 'Alice', age: 21 }]
+// }
+
+ +

확장 연산자와 초기값을 이용하여 객체로 이루어진 배열에 담긴 배열 연결하기

+ +
// friends - an array of objects
+// where object field "books" - list of favorite books
+var friends = [{
+  name: 'Anna',
+  books: ['Bible', 'Harry Potter'],
+  age: 21
+}, {
+  name: 'Bob',
+  books: ['War and peace', 'Romeo and Juliet'],
+  age: 26
+}, {
+  name: 'Alice',
+  books: ['The Lord of the Rings', 'The Shining'],
+  age: 18
+}];
+
+// allbooks - list which will contain all friends' books +
+// additional list contained in initialValue
+var allbooks = friends.reduce(function(accumulator, currentValue) {
+  return [...accumulator, ...currentValue.books];
+}, ['Alphabet']);
+
+// allbooks = [
+//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
+//   'Romeo and Juliet', 'The Lord of the Rings',
+//   'The Shining'
+// ]
+
+ +

배열의 중복 항목 제거

+ +
+

참고: {{jsxref("Set")}}과 {{jsxref("Array.from()")}}을 사용할 수 있는 환경이라면, let orderedArray = Array.from(new Set(myArray));를 사용해 중복 요소를 제거할 수도 있습니다.

+
+ +
let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
+let result = arr.sort().reduce((accumulator, current) => {
+    const length = accumulator.length
+    if (length === 0 || accumulator[length - 1] !== current) {
+        accumulator.push(current);
+    }
+    return accumulator;
+}, []);
+console.log(result); //[1,2,3,4,5]
+
+ +

프로미스를 순차적으로 실행하기

+ +
/**
+ * Runs promises from array of functions that can return promises
+ * in chained manner
+ *
+ * @param {array} arr - promise arr
+ * @return {Object} promise object
+ */
+function runPromiseInSequence(arr, input) {
+  return arr.reduce(
+    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
+    Promise.resolve(input)
+  );
+}
+
+// promise function 1
+function p1(a) {
+  return new Promise((resolve, reject) => {
+    resolve(a * 5);
+  });
+}
+
+// promise function 2
+function p2(a) {
+  return new Promise((resolve, reject) => {
+    resolve(a * 2);
+  });
+}
+
+// function 3  - will be wrapped in a resolved promise by .then()
+function f3(a) {
+ return a * 3;
+}
+
+// promise function 4
+function p4(a) {
+  return new Promise((resolve, reject) => {
+    resolve(a * 4);
+  });
+}
+
+const promiseArr = [p1, p2, f3, p4];
+runPromiseInSequence(promiseArr, 10)
+  .then(console.log);   // 1200
+
+ +

함수 구성을 위한 파이프 함수

+ +
// Building-blocks to use for composition
+const double = x => x + x;
+const triple = x => 3 * x;
+const quadruple = x => 4 * x;
+
+// Function composition enabling pipe functionality
+const pipe = (...functions) => input => functions.reduce(
+    (acc, fn) => fn(acc),
+    input
+);
+
+// Composed functions for multiplication of specific values
+const multiply6 = pipe(double, triple);
+const multiply9 = pipe(triple, triple);
+const multiply16 = pipe(quadruple, quadruple);
+const multiply24 = pipe(double, triple, quadruple);
+
+// Usage
+multiply6(6); // 36
+multiply9(9); // 81
+multiply16(16); // 256
+multiply24(10); // 240
+
+ +

reduce()로 map() 작성

+ +
if (!Array.prototype.mapUsingReduce) {
+  Array.prototype.mapUsingReduce = function(callback, thisArg) {
+    return this.reduce(function(mappedArray, currentValue, index, array) {
+      mappedArray[index] = callback.call(thisArg, currentValue, index, array);
+      return mappedArray;
+    }, []);
+  };
+}
+
+[1, 2, , 3].mapUsingReduce(
+  (currentValue, index, array) => currentValue + index + array.length
+); // [5, 7, , 10]
+
+
+ +

폴리필

+ +
// ECMA-262의 진행 단계, 5판(Edition), 15.4.4.21
+// 참조: http://es5.github.io/#x15.4.4.21
+// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
+if (!Array.prototype.reduce) {
+  Object.defineProperty(Array.prototype, 'reduce', {
+    value: function(callback /*, initialValue*/) {
+      if (this === null) {
+        throw new TypeError( 'Array.prototype.reduce ' +
+          'called on null or undefined' );
+      }
+      if (typeof callback !== 'function') {
+        throw new TypeError( callback +
+          ' is not a function');
+      }
+
+      // 1. Let O be ? ToObject(this value).
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // Steps 3, 4, 5, 6, 7
+      var k = 0;
+      var value;
+
+      if (arguments.length >= 2) {
+        value = arguments[1];
+      } else {
+        while (k < len && !(k in o)) {
+          k++;
+        }
+
+        // 3. If len is 0 and initialValue is not present,
+        //    throw a TypeError exception.
+        if (k >= len) {
+          throw new TypeError( 'Reduce of empty array ' +
+            'with no initial value' );
+        }
+        value = o[k++];
+      }
+
+      // 8. Repeat, while k < len
+      while (k < len) {
+        // a. Let Pk be ! ToString(k).
+        // b. Let kPresent be ? HasProperty(O, Pk).
+        // c. If kPresent is true, then
+        //    i.  Let kValue be ? Get(O, Pk).
+        //    ii. Let accumulator be ? Call(
+        //          callbackfn, undefined,
+        //          « accumulator, kValue, k, O »).
+        if (k in o) {
+          value = callback(value, o[k], k, o);
+        }
+
+        // d. Increase k by 1.
+        k++;
+      }
+
+      // 9. Return accumulator.
+      return value;
+    }
+  });
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.
{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Array.reduce")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/reduceright/index.html b/files/ko/web/javascript/reference/global_objects/array/reduceright/index.html new file mode 100644 index 0000000000..07bbdb800e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/reduceright/index.html @@ -0,0 +1,283 @@ +--- +title: Array.prototype.reduceRight() +slug: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight +--- +
{{JSRef}}
+ +

reduceRight() 메서드는 누적기에 대해 함수를 적용하고 배열의 각 값 (오른쪽에서 왼쪽으로)은 값을 단일 값으로 줄여야합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-reduce-right.html")}}

+ +

왼쪽에서 오른쪽으로 {{jsxref("Array.prototype.reduce()")}}도 참조하십시오.

+ +

구문

+ +
arr.reduceRight(callback[, initialValue])
+ +

매개변수

+ +
+
callback
+
4 개의 인수를 취하여 배열의 각 값에 대해 실행할 함수입니다. +
+
previousValue
+
콜백의 마지막 호출에서 이전에 리턴 된 값 또는 제공된 경우 initialValue. (아래 참조).
+
currentValue
+
배열에서 처리중인 현재 요소입니다.
+
index
+
배열에서 처리중인 현재 요소의 인덱스입니다.
+
array
+
배열 reduce가 호출되었습니다.
+
+
+
initialValue
+
선택 과목. 콜백의 최초의 호출의 최초의 인수로서 사용하는 객체입니다.
+
+ +

반환 값

+ +

누적 계산의 결과를 반환합니다.

+ +

설명

+ +

reduceRight는 배열의 구멍을 제외하고 배열에있는 각 요소에 대해 콜백 함수를 한 번 실행합니다.이 인수는 초기 값 (또는 이전 콜백 호출의 값), 현재 요소의 값, 현재 인덱스 및 반복이 일어나는 배열.

+ +

reduceRight 콜백 호출은 다음과 같습니다.

+ +
array.reduceRight(function(previousValue, currentValue, index, array) {
+  // ...
+});
+
+ +

함수가 처음 호출 될 때 previousValue 및 currentValue는 두 값 중 하나가 될 수 있습니다. reduceValue에 대한 호출에 initialValue가 제공된 경우 previousValue는 initialValue와 같고 currentValue는 배열의 마지막 값과 같습니다. initialValue가 제공되지 않으면 previousValue는 배열의 마지막 값과 같고 currentValue는 두 번째 - 마지막 값과 같습니다.

+ +

배열이 비어 있고 initialValue가 제공되지 않으면 {{jsxref ( "TypeError")}}가 발생합니다. 배열에 요소가 1 개만 있어도 (위치에 관계없이) initialValue가 제공되지 않았던 경우, 또는 initialValue가 준비되어 있지만 배열이 비어있는 경우, 콜백을 호출하지 않고 솔로 값이 반환됩니다.

+ +

함수의 일부 실행 예제는 다음과 같습니다.

+ +
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
+  return previousValue + currentValue;
+});
+
+ +

콜백은 네 번 호출되며 각 호출의 인수와 반환 값은 다음과 같습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
previousValuecurrentValueindexarrayreturn value
first call433[0, 1, 2, 3, 4]7
second call722[0, 1, 2, 3, 4]9
third call911[0, 1, 2, 3, 4]10
fourth call1000[0, 1, 2, 3, 4]10
+ +

reduceRight에 의해 반환 된 값은 마지막 콜백 호출 (10)의 값이됩니다.

+ +

initialValue를 제공하면 결과는 다음과 같습니다.

+ +
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
+  return previousValue + currentValue;
+}, 10);
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
previousValuecurrentValueindexarrayreturn value
first call1044[0, 1, 2, 3, 4]14
second call1433[0, 1, 2, 3, 4]17
third call1722[0, 1, 2, 3, 4]19
fourth call1911[0, 1, 2, 3, 4]20
fifth call2000[0, 1, 2, 3, 4]20
+ +

reduceRight에 의해 이번에 반환 된 값은 물론 20입니다.

+ +

예제

+ +

배열 내 모든 값의 합계 구하기

+ +
var sum = [0, 1, 2, 3].reduceRight(function(a, b) {
+  return a + b;
+});
+// sum is 6
+
+ +

이중 배열 전개하기

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
+    return a.concat(b);
+}, []);
+// flattened is [4, 5, 2, 3, 0, 1]
+
+ +

reduce와 reduceRight의 차이점

+ +
var a = ["1", "2", "3", "4", "5"];
+var left  = a.reduce(function(prev, cur)      { return prev + cur; });
+var right = a.reduceRight(function(prev, cur) { return prev + cur; });
+
+console.log(left);  // "12345"
+console.log(right); // "54321"
+ +

폴리필

+ +

reduceRight는 5 판에서 ECMA-262 표준에 추가되었습니다. 표준의 모든 구현에 존재하지 않을 수도 있습니다. 이 문제를 해결하려면 스크립트 시작 부분에 다음 코드를 삽입하여 reduceRight를 기본적으로 지원하지 않는 구현에서 사용할 수있게하십시오.

+ +
// ECMA-262, 5 판, 15.4.4.22의 제작 단계
+// 참조 : http://es5.github.io/#x15.4.4.22
+if ('function' !== typeof Array.prototype.reduceRight) {
+  Array.prototype.reduceRight = function(callback /*, initialValue*/) {
+    'use strict';
+    if (null === this || 'undefined' === typeof this) {
+      throw new TypeError('Array.prototype.reduce called on null or undefined' );
+    }
+    if ('function' !== typeof callback) {
+      throw new TypeError(callback + ' is not a function');
+    }
+    var t = Object(this), len = t.length >>> 0, k = len - 1, value;
+    if (arguments.length >= 2) {
+      value = arguments[1];
+    } else {
+      while (k >= 0 && !(k in t)) {
+        k--;
+      }
+      if (k < 0) {
+        throw new TypeError('Reduce of empty array with no initial value');
+      }
+      value = t[k--];
+    }
+    for (; k >= 0; k--) {
+      if (k in t) {
+        value = callback(value, t[k], k, t);
+      }
+    }
+    return value;
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.22', 'Array.prototype.reduceRight')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.
{{SpecName('ES6', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.reduceRight")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/reverse/index.html b/files/ko/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..95b4c1a348 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,87 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +
{{JSRef}}
+ +

reverse() 메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다.

+ +

{{EmbedInteractiveExample("pages/js/array-reverse.html")}}

+ +

구문

+ +
a.reverse()
+ +

반환 값

+ +

순서가 반전된 배열.

+ +

설명

+ +

reverse 메서드는 호출한 배열을 반전하고 원본 배열을 변형하며 그 참조를 반환합니다.

+ +

예시

+ +

배열의 요소를 반전하기

+ +

다음 예시는 3개의 요소가 든 myArray 배열을 만든 후, 반전시킵니다.

+ +
const a = [1, 2, 3];
+console.log(a); // [1, 2, 3]
+
+a.reverse();
+console.log(a); // [3, 2, 1]
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.reverse")}}
+ +
 
+ +
 
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/shift/index.html b/files/ko/web/javascript/reference/global_objects/array/shift/index.html new file mode 100644 index 0000000000..bf610b95f9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/shift/index.html @@ -0,0 +1,102 @@ +--- +title: Array.prototype.shift() +slug: Web/JavaScript/Reference/Global_Objects/Array/shift +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift +--- +
{{JSRef}}
+ +

shift() 메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다. 이 메서드는 배열의 길이를 변하게 합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-shift.html")}}

+ +

구문

+ +
arr.shift()
+
+ +

반환 값

+ +

배열에서 제거한 요소. 빈 배열의 경우 {{jsxref("undefined")}} 를 반환합니다.

+ +

설명

+ +

shift 메서드는 0번째 위치의 요소를 제거 하고 연이은 나머지 값들의 위치를 한칸 씩 앞으로 당깁니다. 그리고 제거된 값을 반환 합니다. 만약 배열의 {{jsxref("Array.length", "length")}}가 0이라면 {{jsxref("undefined")}}를 리턴 합니다.

+ +

shift는 의도적인 일반형태로써; 이 메서드는 배열과 유사한 형태의 객체에서  {{jsxref("Function.call", "호출", "", 1)}} 하거나 {{jsxref("Function.apply", "적용", "", 1)}} 할 수 있습니다. 연속된 일련의 마지막 항목을 나타내는 길이 속성을 가지고 있지 않은 객체의 제로베이스 수치 속성에는 의미 있는 작동을 하지 않을 수 있습니다. (Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.)

+ +

예제

+ +

배열에서 한 요소 제거하기

+ +

아래 코드는 myFish 라는 배열에서 첫번째 요소를 제거 하기 전과 후를 보여 줍니다.  그리고 제거된 요소도 보여줍니다.

+ +
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
+
+console.log('myFish before: ' + myFish);
+// "제거전 myFish 배열: angel,clown,mandarin,surgeon"
+
+var shifted = myFish.shift();
+
+console.log('myFish after: ' + myFish);
+// "제거후 myFish 배열: clown,mandarin,surgeon"
+
+console.log('Removed this element: ' + shifted);
+// "제거된 배열 요소: angel"
+
+ +

while 반복문 안에서 shift() 사용하기

+ +

shift() 메서드는 while 문의 조건으로 사용되기도 합니다. 아래 코드에서는 while 문을 한번 돌 때 마다 배열의 다음 요소를 제거하고, 이는 빈 배열이 될 때까지 반복됩니다.

+ +
var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];
+
+while( (i = names.shift()) !== undefined ) {
+    console.log(i);
+}
+// Andrew, Edward, Paul, Chris, John
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ES6')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.shift")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/slice/index.html b/files/ko/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..a5264b1f86 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,155 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +
{{JSRef}}
+ +

slice() 메서드는 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.

+ +
{{EmbedInteractiveExample("pages/js/array-slice.html")}}
+ + + +

구문

+ +
arr.slice([begin[, end]])
+
+ +

매개변수

+ +
+
begin {{optional_inline}}
+
0을 시작으로 하는 추출 시작점에 대한 인덱스를 의미합니다.
+
음수 인덱스는 배열의 끝에서부터의 길이를 나타냅니다. slice(-2) 는 배열에서 마지막 두 개의 엘리먼트를 추출합니다.
+
beginundefined인 경우에는, 0번 인덱스부터 slice 합니다.
+
begin이 배열의 길이보다 큰 경우에는, 빈 배열을 반환합니다.
+
end {{optional_inline}}
+
추출을 종료 할 0 기준 인덱스입니다. sliceend 인덱스를 제외하고 추출합니다.
+
예를 들어, slice(1,4)는 두번째 요소부터 네번째 요소까지 (1, 2 및 3을 인덱스로 하는 요소) 추출합니다.
+
음수 인덱스는 배열의 끝에서부터의 길이를 나타냅니다. 예를들어 slice(2,-1) 는 세번째부터 끝에서 두번째 요소까지 추출합니다.
+
end가 생략되면 slice()는 배열의 끝까지(arr.length) 추출합니다.
+
+ +

     만약 end 값이 배열의 길이보다 크다면, silce()는 배열의 끝까지(arr.length) 추출합니다.

+ +
+
+

반환 값

+
+
+ +

추출한 요소를 포함한 새로운 배열.

+ +

설명

+ +

slice()는 원본을 대체하지 않습니다. 원본 배열에서 요소의 얕은 복사본을 반환합니다. 원본 배열의 요소는 다음과 같이 반환 된 배열에 복사됩니다:

+ + + +

새 요소를 두 배열 중 하나에 추가해도 다른 배열은 영향을 받지 않습니다.

+ +

예제

+ +

기존 배열의 일부 반환

+ +
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+let citrus = fruits.slice(1, 3)
+
+// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+// citrus contains ['Orange','Lemon']
+ +

slice 사용하기

+ +

다음 예제에서 slice()myCar에서 newCar라는 새 배열을 만듭니다. 두 가지 모두 myHonda 객체에 대한 참조를 포함합니다. myHonda의 색상이 자주색으로 변경되면 두 배열 모두 변경 사항을 반영합니다.

+ +
// Using slice, create newCar from myCar.
+let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }
+let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']
+let newCar = myCar.slice(0, 2)
+
+// Display the values of myCar, newCar, and the color of myHonda
+//  referenced from both arrays.
+console.log('myCar = ' + JSON.stringify(myCar))
+console.log('newCar = ' + JSON.stringify(newCar))
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+
+// Change the color of myHonda.
+myHonda.color = 'purple'
+console.log('The new color of my Honda is ' + myHonda.color)
+
+// Display the color of myHonda referenced from both arrays.
+console.log('myCar[0].color = ' + myCar[0].color)
+console.log('newCar[0].color = ' + newCar[0].color)
+ +

스크립트를 실행하면 다음과 같은 기록을 남깁니다.

+ +
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
+         'cherry condition', 'purchased 1997']
+newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
+myCar[0].color = red
+newCar[0].color = red
+The new color of my Honda is purple
+myCar[0].color = purple
+newCar[0].color = purple
+ +

배열형 객체

+ +

slice() 메서드를 호출하여 배열형 객체와 콜렉션을 새로운 Array로 변환할 수 있습니다. 단순히 {{jsxref("Function.prototype.bind()")}}를 사용해 객체에 slice()를 바인딩 하면 됩니다. 대표적인 "배열형 객체"의 예시는 함수 내의 {{jsxref("Functions/arguments", "arguments")}}입니다.

+ +
function list() {
+  return Array.prototype.slice.call(arguments);
+}
+
+let list1 = list(1, 2, 3); // [1, 2, 3]
+
+ +

{{jsxref("Function.prototype.call()")}} 메서드를 사용해서도 바인딩을 할 수 있으며, Array.prototype.slice.call 대신 더 짧게 [].slice.call로 작성할 수도 있습니다.

+ +

아무튼, 다음과 같이 {{jsxref("Function.prototype.bind", "bind()")}}를 사용해 줄일 수 있습니다.

+ +
let unboundSlice = Array.prototype.slice
+let slice = Function.prototype.call.bind(unboundSlice)
+
+function list() {
+  return slice(arguments)
+}
+
+let list1 = list(1, 2, 3) // [1, 2, 3]
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.slice")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/some/index.html b/files/ko/web/javascript/reference/global_objects/array/some/index.html new file mode 100644 index 0000000000..8fbe19bcda --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/some/index.html @@ -0,0 +1,202 @@ +--- +title: Array.prototype.some() +slug: Web/JavaScript/Reference/Global_Objects/Array/some +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/some +--- +
{{JSRef}}
+ +

some() 메서드는 배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트합니다.

+ +
+

참고: 빈 배열에서 호출하면 무조건 false를 반환합니다.

+
+ +

{{EmbedInteractiveExample("pages/js/array-some.html")}}

+ +

구문

+ +
arr.some(callback[, thisArg])
+ +

매개변수

+ +
+
callback
+
각 요소를 시험할 함수. 다음 세 가지 인수를 받습니다. +
+
currentValue
+
처리할 현재 요소.
+
index {{Optional_inline}}
+
처리할 현재 요소의 인덱스.
+
array {{Optional_inline}}
+
some을 호출한 배열.
+
+
+
thisArg {{Optional_inline}}
+
callback을 실행할 때 this로 사용하는 값.
+
+ +

반환 값

+ +

callback이 어떤 배열 요소라도 대해 참인({{Glossary("truthy")}}) 값을 반환하는 경우 true, 그 외엔 false.

+ +

설명

+ +

somecallback이 참(불린으로 변환했을 때 true가 되는 값)을 반환하는 요소를 찾을 때까지 배열에 있는 각 요소에 대해 한 번씩 callback 함수를 실행합니다. 해당하는 요소를 발견한 경우 some은 즉시 true를 반환합니다. 그렇지 않으면, 즉 모든 값에서 거짓을 반환하면 false를 반환합니다. 할당한 값이 있는 배열의 인덱스에서만 callback을 호출합니다. 삭제했거나 값을 할당한 적이 없는 인덱스에서는 호출하지 않습니다.

+ +

callback은 요소의 값, 해당 요소의 인덱스 및 순회하고 있는 배열 세 가지 인수와 함께 호출됩니다.

+ +

thisArg 매개변수를 some에 제공한 경우 callback의 this로 사용됩니다. 그 외엔 {{jsxref("undefined")}}값을 사용합니다. 최종적으로 callback이 볼 수 있는 this의 값은 함수가 볼 수 있는 this를 결정하는 평소 규칙을 따릅니다.

+ +

some은 호출한 배열을 변형하지 않습니다.

+ +

some이 처리하는 요소의 범위는 callback의 첫 호출 전에 설정됩니다. some 호출 이후로 배열에 추가하는 요소는 callback이 방문하지 않습니다. 배열에 원래 있었지만 아직 방문하지 않은 요소가 callback에 의해 변경된 경우, 그 인덱스를 방문하는 시점의 값을 사용합니다. 삭제한 요소는 방문하지 않습니다.

+ +

예제

+ +

배열의 요소 테스트

+ +

다음 예제는 배열 내 요소 중 하나라도 10보다 큰지 판별합니다.

+ +
function isBiggerThan10(element, index, array) {
+  return element > 10;
+}
+[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
+[12, 5, 8, 1, 4].some(isBiggerThan10); // true
+
+ +

화살표 함수를 사용한 배열의 요소 테스트

+ +

화살표 함수는 같은 테스트에 대해 더 짧은 구문을 제공합니다.

+ +
[2, 5, 8, 1, 4].some(elem => elem > 10);  // false
+[12, 5, 8, 1, 4].some(elem => elem > 10); // true
+
+ +

값이 배열 내 존재하는지 확인

+ +

다음 예제는 요소가 하나라도 배열 내 존재하는 경우 true를 반환합니다.

+ +
var fruits = ['apple', 'banana', 'mango', 'guava'];
+
+function checkAvailability(arr, val) {
+    return arr.some(function(arrVal) {
+        return val === arrVal;
+    });
+}
+
+checkAvailability(fruits, 'kela'); //false
+checkAvailability(fruits, 'banana'); //true
+ +

화살표 함수를 사용하여 값이 존재하는지 확인

+ +
var fruits = ['apple', 'banana', 'mango', 'guava'];
+
+function checkAvailability(arr, val) {
+    return arr.some(arrVal => val === arrVal);
+}
+
+checkAvailability(fruits, 'kela'); //false
+checkAvailability(fruits, 'banana'); //true
+ +

모든 값을 불린으로 변환

+ +
var TRUTHY_VALUES = [true, 'true', 1];
+
+function getBoolean(a) {
+    'use strict';
+
+    var value = a;
+
+    if (typeof value === 'string') {
+        value = value.toLowerCase().trim();
+    }
+
+    return TRUTHY_VALUES.some(function(t) {
+        return t === value;
+    });
+}
+
+getBoolean(false); // false
+getBoolean('false'); // false
+getBoolean(1); // true
+getBoolean('true'); // true
+ +

폴리필

+ +

some은 ECMA-262 표준 제5판에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 환경에서도 some을 사용할 수 있습니다. 아래 알고리즘은 {{jsxref("Object")}}와 {{jsxref("TypeError")}}가 변형되지 않고, fun.call의 계산 값이 원래의 {{jsxref("Function.prototype.call()")}}과 같은 경우 ECMA-262 제5판이 명시한 것과 동일합니다.

+ +
// ECMA-262 5판, 15.4.4.17항의 작성 과정
+// 출처: http://es5.github.io/#x15.4.4.17
+if (!Array.prototype.some) {
+  Array.prototype.some = function(fun/*, thisArg*/) {
+    'use strict';
+
+    if (this == null) {
+      throw new TypeError('Array.prototype.some called on null or undefined');
+    }
+
+    if (typeof fun !== 'function') {
+      throw new TypeError();
+    }
+
+    var t = Object(this);
+    var len = t.length >>> 0;
+
+    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
+    for (var i = 0; i < len; i++) {
+      if (i in t && fun.call(thisArg, t[i], i, t)) {
+        return true;
+      }
+    }
+
+    return false;
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES5.1', '#sec-15.4.4.17', 'Array.prototype.some')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.6에서 구현됨.
{{SpecName('ES6', '#sec-array.prototype.some', 'Array.prototype.some')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.some', 'Array.prototype.some')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.some")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/sort/index.html b/files/ko/web/javascript/reference/global_objects/array/sort/index.html new file mode 100644 index 0000000000..ddab9a428f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/sort/index.html @@ -0,0 +1,245 @@ +--- +title: Array.prototype.sort() +slug: Web/JavaScript/Reference/Global_Objects/Array/sort +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort +--- +
{{JSRef}}
+ +

sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다. 정렬은 stable sort가 아닐 수 있습니다. 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.

+ +

정렬 속도와 복잡도는 각 구현방식에 따라 다를 수 있습니다.

+ +

{{EmbedInteractiveExample("pages/js/array-sort.html")}}

+ +

구문

+ +
arr.sort([compareFunction])
+
+ +

매개변수

+ +
+
compareFunction {{optional_inline}}
+
정렬 순서를 정의하는 함수. 생략하면 배열은 각 요소의 문자열 변환에 따라 각 문자의 유니 코드 코드 포인트 값에 따라 정렬됩니다.
+
+ +

반환 값

+ +

정렬한 배열. 원 배열이 정렬되는 것에 유의하세요. 복사본이 만들어지는 것이 아닙니다.

+ +

설명

+ +

compareFunction이 제공되지 않으면 요소를 문자열로 변환하고 유니 코드 코드 포인트 순서로 문자열을 비교하여 정렬됩니다. 예를 들어 "바나나"는 "체리"앞에옵니다. 숫자 정렬에서는 9가 80보다 앞에 오지만 숫자는 문자열로 변환되기 때문에 "80"은 유니 코드 순서에서 "9"앞에옵니다.

+ +

compareFunction이 제공되면 배열 요소는 compare 함수의 반환 값에 따라 정렬됩니다. a와 b가 비교되는 두 요소라면,

+ + + +

따라서 compare 함수의 형식은 다음과 같습니다.

+ +
function compare(a, b) {
+  if (a is less than b by some ordering criterion) {
+    return -1;
+  }
+  if (a is greater than b by the ordering criterion) {
+    return 1;
+  }
+  // a must be equal to b
+  return 0;
+}
+
+ +

문자열 대신 숫자를 비교하기 위해 compare 함수는 a에서 b를 뺄 수 있습니다. 다음 함수는 배열을 오름차순으로 정렬합니다 (Infinity 및 NaN이 포함되어 있지 않은 경우).

+ +
function compareNumbers(a, b) {
+  return a - b;
+}
+
+ +

sort 메소드는 {{jsxref ( "연산자 / 함수", "함수식", "", 1)}} (및 클로저)와 함께 편리하게 사용할 수 있습니다.

+ +
var numbers = [4, 2, 5, 1, 3];
+numbers.sort(function(a, b) {
+  return a - b;
+});
+console.log(numbers);
+
+// [1, 2, 3, 4, 5]
+
+ +

개체는 해당 속성 중 하나의 값을 기준으로 정렬 할 수 있습니다.

+ +
var items = [
+  { name: 'Edward', value: 21 },
+  { name: 'Sharpe', value: 37 },
+  { name: 'And', value: 45 },
+  { name: 'The', value: -12 },
+  { name: 'Magnetic', value: 13 },
+  { name: 'Zeros', value: 37 }
+];
+
+// value 기준으로 정렬
+items.sort(function (a, b) {
+  if (a.value > b.value) {
+    return 1;
+  }
+  if (a.value < b.value) {
+    return -1;
+  }
+  // a must be equal to b
+  return 0;
+});
+
+// name 기준으로 정렬
+items.sort(function(a, b) {
+  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
+  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
+  if (nameA < nameB) {
+    return -1;
+  }
+  if (nameA > nameB) {
+    return 1;
+  }
+
+  // 이름이 같을 경우
+  return 0;
+});
+ +

예제

+ +

배열 만들기, 표시 및 정렬

+ +

다음 예제에서는 네 개의 배열을 만들고 원래 배열을 표시 한 다음 정렬 된 배열을 표시합니다. 숫자 배열은 비교 함수없이 정렬 된 다음 비교 함수로 정렬됩니다.

+ +
var stringArray = ['Blue', 'Humpback', 'Beluga'];
+var numericStringArray = ['80', '9', '700'];
+var numberArray = [40, 1, 5, 200];
+var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];
+
+function compareNumbers(a, b) {
+  return a - b;
+}
+
+console.log('stringArray:', stringArray.join());
+console.log('Sorted:', stringArray.sort());
+
+console.log('numberArray:', numberArray.join());
+console.log('Sorted without a compare function:', numberArray.sort());
+console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));
+
+console.log('numericStringArray:', numericStringArray.join());
+console.log('Sorted without a compare function:', numericStringArray.sort());
+console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers));
+
+console.log('mixedNumericArray:', mixedNumericArray.join());
+console.log('Sorted without a compare function:', mixedNumericArray.sort());
+console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers));
+
+ +

이 예제는 다음 출력을 생성합니다. 결과가 보여 주듯이 비교 함수가 사용되면 숫자는 숫자 또는 숫자 문자열인지 여부에 관계없이 올바르게 정렬됩니다.

+ +
stringArray: Blue,Humpback,Beluga
+Sorted: Beluga,Blue,Humpback
+
+numberArray: 40,1,5,200
+Sorted without a compare function: 1,200,40,5
+Sorted with compareNumbers: 1,5,40,200
+
+numericStringArray: 80,9,700
+Sorted without a compare function: 700,80,9
+Sorted with compareNumbers: 9,80,700
+
+mixedNumericArray: 80,9,700,40,1,5,200
+Sorted without a compare function: 1,200,40,5,700,80,9
+Sorted with compareNumbers: 1,5,9,40,80,200,700
+
+ +

비 ASCII 문자 정렬

+ +

ASCII 이외의 문자, 즉 악센트 부호가있는 문자 (e, é, è, a, ä 등)가있는 문자열을 정렬하려면 영어가 아닌 다른 언어의 문자열에 {{jsxref ( "String.localeCompare")}}를 사용하십시오. 이 함수는 해당 문자를 비교하여 올바른 순서로 나타낼 수 있습니다.

+ +
var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
+items.sort(function (a, b) {
+  return a.localeCompare(b);
+});
+
+// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
+
+ +

map을 사용한 정렬

+ +

compareFunction은 배열 내의 요소마다 여러 번 호출될 수 있습니다. 이러한 compareFunction의 성질에 따라,  높은 오버헤드가 발생할 수도 있습니다. compareFunction이 복잡해지고, 정렬할 요소가 많아질 경우, map을 사용한 정렬을 고려해보는 것이 좋습니다. 이 방법은 임시 배열을 하나 만들어서 여기에 실제 정렬에 사용할 값만을 뽑아서 넣어서 이를 정렬하고, 그 결과를 이용해서 실제 정렬을 하는 것입니다.

+ +
// 소트 할 배열
+var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
+
+// 임시 배열은 위치 및 정렬 값이있는 객체를 보유합니다.
+var mapped = list.map(function(el, i) {
+  return { index: i, value: el.toLowerCase() };
+})
+
+// 축소 치를 포함한 매핑 된 배열의 소트
+mapped.sort(function(a, b) {
+  return +(a.value > b.value) || +(a.value === b.value) - 1;
+});
+
+// 결과 순서를 위한 컨테이너
+var result = mapped.map(function(el){
+  return list[el.index];
+});
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4.4.11', 'Array.prototype.sort')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Array.sort")}}
+ +
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/splice/index.html b/files/ko/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..eb2a09af12 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,153 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +
{{JSRef}}
+ +

splice() 메서드는 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.

+ +
{{EmbedInteractiveExample("pages/js/array-splice.html")}}
+ + + +

구문

+ +
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
+
+ +

매개변수

+ +
+
start
+
배열의 변경을 시작할 인덱스입니다. 배열의 길이보다 큰 값이라면 실제 시작 인덱스는 배열의 길이로 설정됩니다. 음수인 경우 배열의 끝에서부터 요소를 세어나갑니다(원점 -1, 즉 -n이면 요소 끝의 n번째 요소를 가리키며 array.length - n번째 인덱스와 같음). 값의 절대값이 배열의 길이 보다 큰 경우 0으로 설정됩니다.
+
deleteCount {{optional_inline}}
+
배열에서 제거할 요소의 수입니다.
+
deleteCount를 생략하거나 값이 array.length - start보다 크면 start부터의 모든 요소를 제거합니다.
+
deleteCount가 0 이하라면 어떤 요소도 제거하지 않습니다. 이 때는 최소한 하나의 새로운 요소를 지정해야 합니다.
+
item1, item2, ... {{optional_inline}}
+
배열에 추가할 요소입니다. 아무 요소도 지정하지 않으면 splice()는 요소를 제거하기만 합니다.
+
+ +

반환 값

+ +

제거한 요소를 담은 배열. 하나의 요소만 제거한 경우 길이가 1인 배열을 반환합니다. 아무 값도 제거하지 않았으면 빈 배열을 반환합니다.

+ +

설명

+ +

만약 제거할 요소의 수와 추가할 요소의 수가 다른 경우 배열의 길이는 달라집니다.

+ +

예제

+ +

하나도 제거하지 않고, 2번 인덱스에 "drum" 추가

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2, 0, 'drum');
+
+// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
+// removed is [], no elements removed
+ +

하나도 제거하지 않고, 2번 인덱스에 "drum"과 "guitar" 추가

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2, 0, 'drum', 'guitar');
+
+// myFish is ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
+// removed is [], no elements removed
+
+ +

3번 인덱스에서 한 개 요소 제거

+ +
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(3, 1);
+
+// removed is ["mandarin"]
+// myFish is ["angel", "clown", "drum", "sturgeon"]
+
+ +

2번 인덱스에서 한 개 요소 제거하고 "trumpet" 추가

+ +
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
+var removed = myFish.splice(2, 1, 'trumpet');
+
+// myFish is ["angel", "clown", "trumpet", "sturgeon"]
+// removed is ["drum"]
+ +

0번 인덱스에서 두 개 요소 제거하고 "parrot", "anemone", "blue" 추가

+ +
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
+var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
+
+// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
+// removed is ["angel", "clown"]
+ +

2번 인덱스에서 두 개 요소 제거

+ +
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
+var removed = myFish.splice(myFish.length - 3, 2);
+
+// myFish is ["parrot", "anemone", "sturgeon"]
+// removed is ["blue", "trumpet"]
+ +

-2번 인덱스에서 한 개 요소 제거

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(-2, 1);
+
+// myFish is ["angel", "clown", "sturgeon"]
+// removed is ["mandarin"]
+ +

2번 인덱스를 포함해서 이후의 모든 요소 제거

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2);
+
+// myFish is ["angel", "clown"]
+// removed is ["mandarin", "sturgeon"]
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ES6')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Array.splice")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html b/files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html new file mode 100644 index 0000000000..4fc1bd7f1a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/tolocalestring/index.html @@ -0,0 +1,195 @@ +--- +title: Array.prototype.toLocaleString() +slug: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString +tags: + - Array + - Internationalization + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString +--- +
{{JSRef}}
+ +

toLocaleString() 메서드는 배열의 요소를 나타내는 문자열을 반환합니다. 요소는 toLocaleString 메서드를 사용하여 문자열로 변환되고 이 문자열은 locale 고유 문자열(가령 쉼표 “,”)에 의해 분리됩니다.

+ +

{{EmbedInteractiveExample("pages/js/array-tolocalestring.html")}}

+ +

구문

+ +
arr.toLocaleString([locales[, options]]);
+ +

매개변수

+ +
+
locales {{optional_inline}}
+
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the {{jsxref("Intl")}} page.
+
options {{optional_inline}}
+
An object with configuration properties, for numbers see {{jsxref("Number.prototype.toLocaleString()")}}, and for dates see {{jsxref("Date.prototype.toLocaleString()")}}.
+
+ +

반환 값

+ +

배열의 요소를 표현하는 문자열.

+ +

설명

+ +

배열의 요소는 toLocaleString 메서드를 사용하여 문자열로 변환됩니다:

+ + + +

예제

+ +

toLocaleString 사용

+ +
var number = 1337;
+var date = new Date();
+var myArr = [number, date, 'foo'];
+
+var str = myArr.toLocaleString();
+
+console.log(str);
+// '1337,6.12.2013 19:37:35,foo' 출력(log)
+// Europe/Berlin 시간대로 German (de-DE) locale에서 실행하는 경우
+
+ +

폴리필

+ +
// https://tc39.github.io/ecma402/#sup-array.prototype.tolocalestring
+if (!Array.prototype.toLocaleString) {
+  Object.defineProperty(Array.prototype, 'toLocaleString', {
+    value: function(locales, options) {
+      // 1. Let O be ? ToObject(this value).
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      var a = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(A, "length")).
+      var len = a.length >>> 0;
+
+      // 3. Let separator be the String value for the
+      //    list-separator String appropriate for the
+      //    host environment's current locale (this is
+      //    derived in an implementation-defined way).
+      // NOTE: In this case, we will use a comma
+      var separator = ',';
+
+      // 4. If len is zero, return the empty String.
+      if (len === 0) {
+        return '';
+      }
+
+      // 5. Let firstElement be ? Get(A, "0").
+      var firstElement = a[0];
+      // 6. If firstElement is undefined or null, then
+      //  a.Let R be the empty String.
+      // 7. Else,
+      //  a. Let R be ?
+      //     ToString(?
+      //       Invoke(
+      //        firstElement,
+      //        "toLocaleString",
+      //        « locales, options »
+      //       )
+      //     )
+      var r = firstElement == null ?
+        '' : firstElement.toLocaleString(locales, options);
+
+      // 8. Let k be 1.
+      var k = 1;
+
+      // 9. Repeat, while k < len
+      while (k < len) {
+        // a. Let S be a String value produced by
+        //   concatenating R and separator.
+        var s = r + separator;
+
+        // b. Let nextElement be ? Get(A, ToString(k)).
+        var nextElement = a[k];
+
+        // c. If nextElement is undefined or null, then
+        //   i. Let R be the empty String.
+        // d. Else,
+        //   i. Let R be ?
+        //     ToString(?
+        //       Invoke(
+        //        nextElement,
+        //        "toLocaleString",
+        //        « locales, options »
+        //       )
+        //     )
+        r = nextElement == null ?
+          '' : nextElement.toLocaleString(locales, options);
+
+        // e. Let R be a String value produced by
+        //   concatenating S and R.
+        r = s + r;
+
+        // f. Increase k by 1.
+        k++;
+      }
+
+      // 10. Return R.
+      return r;
+    }
+  });
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의.
{{SpecName('ES5.1', '#sec-15.2.4.3', 'Array.prototype.toLocaleString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}{{Spec2('ESDraft')}} 
{{SpecName('ES Int Draft', '#sup-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}{{Spec2('ES Int Draft')}}This definition supersedes the definition provided in ECMA-262.
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.toLocaleString")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/tosource/index.html b/files/ko/web/javascript/reference/global_objects/array/tosource/index.html new file mode 100644 index 0000000000..e503b9c617 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/tosource/index.html @@ -0,0 +1,71 @@ +--- +title: Array.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/Array/toSource +tags: + - Array + - JavaScript + - Method + - Non-standard + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toSource +--- +
{{JSRef}} {{non-standard_header}}
+ +

toSource() 메서드는 해당 배열의 소스 코드를 문자열로 반환합니다.

+ +

구문

+ +
arr.toSource()
+ +

반환 값

+ +

배열의 소스 코드를 나타내는 문자열을 반환합니다.

+ +

설명

+ +

toSource 메서드는 다음의 값을 반환합니다.

+ + + +

이 메서드는 보통 코드에 명시되지 않고 자바스크립트 내부적으로 호출됩니다. 디버깅을 위해 toSource를 호출하여 배열의 내용을 검사할 수 있습니다.

+ +

예제

+ +

배열의 소스 코드 검사하기

+ +

다음 코드는 배열의 소스 코드 문자열을 생성합니다.

+ +
var alpha = new Array('a', 'b', 'c');
+
+alpha.toSource();
+//returns ['a', 'b', 'c']
+
+ +

명세

+ +

Not part of any standard. Implemented in JavaScript 1.3.

+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Array.toSource")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/tostring/index.html b/files/ko/web/javascript/reference/global_objects/array/tostring/index.html new file mode 100644 index 0000000000..9a1179be14 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/tostring/index.html @@ -0,0 +1,80 @@ +--- +title: Array.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Array/toString +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toString +--- +
{{JSRef}}
+ +

toString() 메서드는 지정된 배열 및 그 요소를 나타내는 문자열을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-tostring.html")}}

+ +

구문

+ +
arr.toString()
+ +

반환 값

+ +

배열을 표현하는 문자열을 반환합니다.

+ +

설명

+ +

{{jsxref("Array")}} 객체는 {{jsxref("Object")}}의 toString 메서드를 재정의(override)합니다. Array 객체에 대해, toString 메서드는 배열을 합쳐(join) 쉼표로 구분된 각 배열 요소를 포함하는 문자열 하나를 반환합니다. 예를 들어, 다음 코드는 배열을 생성하며 그 배열을 문자열로 변환하기 위해 toString을 사용합니다.

+ +
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr'];
+var myVar = monthNames.toString(); // 'Jan,Feb,Mar,Apr'을 myVar에 할당.
+
+ +

JavaScript는 배열이 텍스트 값으로 표현되거나 배열이 문자열 연결(concatenation)에 참조될 때 자동으로 toString 메서드를 호출합니다.

+ +

ECMAScript 5 의미

+ +

JavaScript 1.8.5 (Firefox 4)부터, ECMAScript 제5판 의미(semantics)와 일치하는 toString() 메서드는 일반(generic) 메서드이므로 모든 객체에 사용될 수 있습니다. 객체가 join() 메서드가 있는 경우, 호출되어 그 값이 반환됩니다. 그렇지 않으면 {{jsxref("Object.prototype.toString()")}}가 호출되어 그 결과값이 반환됩니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.1에서 구현됨.
{{SpecName('ES5.1', '#sec-15.4.4.2', 'Array.prototype.toString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.toString")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/unshift/index.html b/files/ko/web/javascript/reference/global_objects/array/unshift/index.html new file mode 100644 index 0000000000..c4a03fd091 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,91 @@ +--- +title: Array.prototype.unshift() +slug: Web/JavaScript/Reference/Global_Objects/Array/unshift +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift +--- +
{{JSRef}}
+ +

unshift() 메서드는 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-unshift.html")}}

+ +

구문

+ +
arr.unshift([...elementN])
+ +

매개변수

+ +
+
elementN
+
배열 맨 앞에 추가할 요소.
+
+ +

반환 값

+ +

메서드를 호출한 배열의 새로운 {{jsxref("Array.length", "length")}} 속성.

+ +

설명

+ +

unshift 메서드는 배열 형태의 객체 시작점에 주어진 값을 삽입합니다.

+ +

unshift는 제네릭하도록 설계되었으며, 배열 형태를 가진 객체가 {{jsxref("Function.call", "호출", "", 1)}}하거나 객체에 {{jsxref("Function.apply", "적용", "", 1)}}할 수 있습니다. length 속성을 가지지 않고, 대신 마지막 요소를 0부터 시작하는 순차적 인덱스로만 나타내는 객체에서는 의도한 것과 다르게 행동할 수 있습니다.

+ +

예제

+ +
var arr = [1, 2];
+
+arr.unshift(0); // result of call is 3, the new array length
+// arr is [0, 1, 2]
+
+arr.unshift(-2, -1); // = 5
+// arr is [-2, -1, 0, 1, 2]
+
+arr.unshift([-3]);
+// arr is [[-3], -2, -1, 0, 1, 2]
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ES6')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.unshift")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/array/values/index.html b/files/ko/web/javascript/reference/global_objects/array/values/index.html new file mode 100644 index 0000000000..eb66adb964 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/array/values/index.html @@ -0,0 +1,87 @@ +--- +title: Array.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Array/values +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/values +--- +
{{JSRef}}
+ +

values() 메서드는 배열의 각 인덱스에 대한 값을 가지는 새로운 Array Iterator 객체를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/array-values.html")}}

+ +

구문

+ +
arr.values()
+
+ +

반환 값

+ +

새로운 {{jsxref("Array")}} 반복기 객체.

+ +

예제

+ +

for...of 루프를 통한 반복

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr.values();
+// your browser must support for..of loop
+// and let-scoped variables in for loops
+for (let letter of eArr) {
+  console.log(letter);
+}
+
+ +

다른 반복법

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr.values();
+console.log(eArr.next().value); // w
+console.log(eArr.next().value); // y
+console.log(eArr.next().value); // k
+console.log(eArr.next().value); // o
+console.log(eArr.next().value); // p
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES2015', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Array.values")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/arraybuffer/arraybuffer/index.html b/files/ko/web/javascript/reference/global_objects/arraybuffer/arraybuffer/index.html new file mode 100644 index 0000000000..4012646fa4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/arraybuffer/arraybuffer/index.html @@ -0,0 +1,70 @@ +--- +title: ArrayBuffer() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/ArrayBuffer +tags: + - ArrayBuffer + - Constructor + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/ArrayBuffer +--- +
{{JSRef}}
+ +

ArrayBuffer() 생성자는 {{jsxref("ArrayBuffer")}} 객체를 생성합니다.

+ +
{{EmbedInteractiveExample("pages/js/arraybuffer-constructor.html")}}
+ + + +

구문

+ +
new ArrayBuffer(length)
+
+ +

매개변수

+ +
+
length
+
생성할 ArrayBuffer의 바이트 크기.
+
+ +

반환 값

+ +

지정한 크기를 가진 새로운 ArrayBuffer 객체. 내용은 모두 0으로 초기화됩니다.

+ +

예외

+ +

length가 {{jsxref("Number.MAX_SAFE_INTEGER")}}보다 크거나, 음수면 {{jsxref("RangeError")}}.

+ +

예제

+ +

아래 예제 코드는 8바이트 버퍼를 생성한 후 {{jsxref("Int32Array")}} 뷰로 그 버퍼를 참조합니다.

+ +
var buffer = new ArrayBuffer(8);
+var view   = new Int32Array(buffer);
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.ArrayBuffer.ArrayBuffer")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/arraybuffer/bytelength/index.html b/files/ko/web/javascript/reference/global_objects/arraybuffer/bytelength/index.html new file mode 100644 index 0000000000..b17502631a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/arraybuffer/bytelength/index.html @@ -0,0 +1,57 @@ +--- +title: ArrayBuffer.prototype.byteLength +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength +tags: + - ArrayBuffer + - JavaScript + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength +--- +
{{JSRef}}
+ +

byteLength 접근자 속성은 {{jsxref("ArrayBuffer")}}의 길이를 바이트 단위로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/arraybuffer-bytelength.html")}}
+ + + +

구문

+ +
arraybuffer.byteLength
+ +

설명

+ +

byteLength 속성은 설정자 속성이 undefined인 접근자 속성으로, 오직 읽기만 가능합니다. byteLength는 배열 버퍼를 처음 생성할 때 정해지며 바꿀 수 없습니다. ArrayBuffer가 분리된 경우 0을 반환합니다.

+ +

예제

+ +
var buffer = new ArrayBuffer(8);
+buffer.byteLength; // 8
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-get-arraybuffer.prototype.bytelength', 'ArrayBuffer.prototype.byteLength')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.ArrayBuffer.byteLength")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/arraybuffer/index.html b/files/ko/web/javascript/reference/global_objects/arraybuffer/index.html new file mode 100644 index 0000000000..8b5b0cd361 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,97 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +tags: + - ArrayBuffer + - JavaScript + - Reference + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +
{{JSRef}}
+ +

ArrayBuffer 객체는 일반적인 고정 길이 원시 이진 데이터 버퍼를 나타냅니다.

+ +

ArrayBuffer는 바이트로 구성된 배열로, 다른 언어에서는 종종 "바이트 배열"이라고 부릅니다. ArrayBuffer에 담긴 정보를 직접 수정하는 것은 불가능하지만, 대신 형식화 배열이나 {{jsxref("DataView")}} 객체를 통해 버퍼를 특정 형식으로 나타내고, 이를 통해 버퍼의 내용을 읽거나 쓸 수 있습니다.

+ +

{{jsxref("ArrayBuffer.ArrayBuffer", "ArrayBuffer()")}} 생성자는 주어진 길이를 가진 새로운 ArrayBuffer를 생성합니다. 또한 Base64 문자열이나 로컬 파일처럼 기존 데이터에서 배열 버퍼를 생성할 수도 있습니다.

+ +

생성자

+ +
+
{{jsxref("ArrayBuffer.ArrayBuffer", "ArrayBuffer()")}}
+
새로운 ArrayBuffer 객체를 생성합니다.
+
+ +

속성

+ +
+
ArrayBuffer.length
+
ArrayBuffer 생성자의 길이 속성으로, 값은 1입니다.
+
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
+
파생 객체를 생성할 때 사용할 생성자 함수입니다.
+
ArrayBuffer.prototype
+
모든 ArrayBuffer 객체에 속성을 추가할 수 있습니다.
+
+ +

메서드

+ +
+
{{jsxref("ArrayBuffer.isView()")}}
+
주어진 매개변수가 형식화 배열 객체 또는 {{jsxref("DataView")}}와 같은 ArrayBuffer의 뷰면 true를, 아니면 false를 반환합니다.
+
{{jsxref("ArrayBuffer.transfer()")}} {{experimental_inline}}
+
주어진 버퍼의 내용으로 새로운 버퍼를 만들고, 그 길이를 지정한 길이만큼 자르거나 확장(0 초기화)한 후 반환합니다.
+
+ +

인스턴스

+ +

모든 ArrayBuffer 인스턴스는 ArrayBuffer.prototype을 상속합니다.

+ +

속성

+ +
+
ArrayBuffer.prototype.constructor
+
객체의 프로토타입을 생성하는 함수를 지정합니다. 초깃값은 내장 ArrayBuffer 생성자입니다.
+
{{jsxref("ArrayBuffer.prototype.byteLength")}} {{readonlyInline}}
+
ArrayBuffer의 바이트 길이입니다. 처음 생성 시 정해지며 변경할 수 없습니다.
+
+ +

메서드

+ +
+
{{jsxref("ArrayBuffer.prototype.slice()")}}
+
ArrayBuffer를 지정한 위치에서 잘라낸 새로운 ArrayBuffer를 반환합니다.
+
+ +

예제

+ +

다음 코드는 8바이트 버퍼를 생성하고, {{jsxref("Global_Objects/Int32Array", "Int32Array")}} 뷰로 그 버퍼를 참조합니다.

+ +
const buffer = new ArrayBuffer(8);
+const view = new Int32Array(buffer);
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-arraybuffer-objects', 'ArrayBuffer')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.ArrayBuffer")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/arraybuffer/isview/index.html b/files/ko/web/javascript/reference/global_objects/arraybuffer/isview/index.html new file mode 100644 index 0000000000..c68d5e0ef3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/arraybuffer/isview/index.html @@ -0,0 +1,76 @@ +--- +title: ArrayBuffer.isView() +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView +tags: + - ArrayBuffer + - JavaScript + - Method + - Reference + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView +--- +
{{JSRef}}
+ +

ArrayBuffer.isView() 메서드는 주어진 값이 ArrayBuffer 뷰, 즉 형식화 배열 객체 또는 {{jsxref("DataView")}}인지 판별합니다..

+ +
{{EmbedInteractiveExample("pages/js/arraybuffer-isview.html")}}
+ + + +

구문

+ +
ArrayBuffer.isView(value)
+ +

매개변수

+ +
+
value
+
판별할 값.
+
+ +

반환 값

+ +

주어진 값이 {{jsxref("ArrayBuffer")}} 뷰라면 true, 아니면 false.

+ +

예제

+ +
ArrayBuffer.isView();                    // false
+ArrayBuffer.isView([]);                  // false
+ArrayBuffer.isView({});                  // false
+ArrayBuffer.isView(null);                // false
+ArrayBuffer.isView(undefined);           // false
+ArrayBuffer.isView(new ArrayBuffer(10)); // false
+
+ArrayBuffer.isView(new Uint8Array());    // true
+ArrayBuffer.isView(new Float32Array());  // true
+ArrayBuffer.isView(new Int8Array(10).subarray(0, 3)); // true
+
+const buffer = new ArrayBuffer(2);
+const dv = new DataView(buffer);
+ArrayBuffer.isView(dv); // true
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-arraybuffer.isview', 'ArrayBuffer.isView')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.ArrayBuffer.isView")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/arraybuffer/slice/index.html b/files/ko/web/javascript/reference/global_objects/arraybuffer/slice/index.html new file mode 100644 index 0000000000..6c286be9aa --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/arraybuffer/slice/index.html @@ -0,0 +1,77 @@ +--- +title: ArrayBuffer.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/slice +tags: + - ArrayBuffer + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/slice +--- +
{{JSRef}}
+ +

slice() 메서드는 현재 ArrayBuffer를 주어진 시작과 끝점에 맞춰 자른 새로운 ArrayBuffer를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/arraybuffer-slice.html")}}
+ + + +

구문

+ +
arraybuffer.slice(begin[, end])
+ +

매개변수

+ +
+
begin
+
자르기 시작할 지점을 나타내는 0 기반 인덱스.
+
+ +
+
end {{optional_inline}}
+
자르기 끝낼 지점을 나타내는 바이트 인덱스. 지정하지 않은 경우 새로운 ArrayBuffer는 지정한 시작점부터 현재 ArrayBuffer의 끝까지 가지게 됩니다.
+
+ +

반환 값

+ +

새로운 {{jsxref("ArrayBuffer")}} 객체.

+ +

설명

+ +

slice() 메서드는 end 매개변수로 지정한 바이트 위치 바로 앞까지 현재 배열 버퍼를 복사합니다. beginend는 음의 값인 경우 배열의 시작부터 위치를 세지 않고 끝에서부터 셉니다.

+ +

end 값이 유효한 범위를 벗어날 경우 버퍼 길이에 맞춰 잘라냅니다. 또한 새로운 ArrayBuffer의 길이가 음의 값이 나올 경우 0으로 처리합니다.

+ +

예제

+ +

ArrayBuffer 복사하기

+ +
const buf1 = new ArrayBuffer(8);
+const buf2 = buf1.slice(0);
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-arraybuffer.prototype.slice', 'ArrayBuffer.prototype.slice')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.ArrayBuffer.slice")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/asyncfunction/index.html b/files/ko/web/javascript/reference/global_objects/asyncfunction/index.html new file mode 100644 index 0000000000..9578d2e534 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/asyncfunction/index.html @@ -0,0 +1,125 @@ +--- +title: AsyncFunction +slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction +--- +
{{JSRef}}
+ +

AsyncFunction 생성자는 새로운 {{jsxref("Statements/async_function", "async function")}} 객체를 만든다. 자바스크립트에서 모든 비동기 함수는 사실상 AsyncFunction 객체이다.

+ +

AsyncFunction이 전역변수가 아님에 주의한다. 다음코드를 보면 알 수 있다. 

+ +
Object.getPrototypeOf(async function(){}).constructor
+
+ +

문법

+ +
new AsyncFunction([arg1[, arg2[, ...argN]],] functionBody)
+ +

파라미터

+ +
+
arg1, arg2, ... argN
+
인수의 이름들은 함수내에서 사용되는 이름이다. 이름은 자바스크립트 식별자 로 유용한 문자열이거나 컴마로 구분된 문자열 목록이어야 한다. 예를들면 "x","theValue",or"a,b"와 같다.
+
functionBody
+
함수 정의를 구성하는 자바스크립트 명령문들로 구성된 문자열.
+
+ +

상세설명

+ +

AsyncFunction 생성자를 통해 만들어진 {{jsxref("Statements/async_function", "async function")}} 객체는 함수가 만들어질때 분석된다. 이방법에서는 코드가 실행되지 않을 때도 작동하기 때문에 {{jsxref("Statements/async_function", "async function expression")}} 으로 비동기함수를 정의하고 해당 코드에서 호출할 때보다 비효율적이다.

+ +

함수에 전달된 모든 인수들은 전달된 순서대로 함수내에서 인수이름으로 식별자가 생성된 것처럼 다루어진다.

+ +
+

주의: AsyncFunction 생성자로 만들어진 {{jsxref("Statements/async_function", "async functions")}} 객체는 클로저를 생성 컨텍스트에 만들지 않는다; 이 객체들은 항상  전역 범위에서 생성됩니다. 

+ +

이객체들을 실행할 때,  AsyncFunction생성자가 호출 된 범위의 변수가 아니라 자신의 지역 변수와 전역 변수에만 액세스 할 수 있습니다 .

+ +

이것은 비동기 함수 표현식을위한 코드와 함께 {{jsxref ( "Global_Objects / eval", "eval")}}을 사용하는 것과 다릅니다.

+
+ +

AsyncFunction 생성자를 (new 연산자를 사용하지 않고) 함수로 호출하는 것과 생성자로 동작시키는 것은 동일하다.

+ +

속성

+ +
+
AsyncFunction.length
+
AsyncFunction 생성자의 length 속성(이 값은 1임).
+
AsyncFunction.prototype
+
모든 비동기 함수 객체에 속성을 추가할 수 있도록 함.
+
AsyncFunction.constructor
+
초기값은 {{jsxref("AsyncFunction")}}임.
+
AsyncFunction.prototype[@@toStringTag]
+
"AsyncFunction"을 반환.
+
+ +

AsyncFunction 인스턴스

+ +

AsyncFunction 인스턴스는 AsyncFunction.prototype 에서ㅜ메소드와 속성을 상속받는다.

+ +

여느 생성자에서와 같이 모든 AsyncFunction 인스턴스들을 수정할 수 있도록 생성자의 prototype 객체를 수정할 수 있다.

+ +

예제

+ +

AsyncFunction 생성자를 통한 비동기 함수 만들기

+ +
function resolveAfter2Seconds(x) {
+  return new Promise(resolve => {
+    setTimeout(() => {
+      resolve(x);
+    }, 2000);
+  });
+}
+
+let AsyncFunction = Object.getPrototypeOf(async function(){}).constructor
+
+let a = new AsyncFunction('a',
+                          'b',
+                          'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);');
+
+a(10, 20).then(v => {
+  console.log(v); // 4초 후에 30을 출력
+});
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-objects', 'AsyncFunction object')}}{{Spec2('ESDraft')}}Initial definition in ES2017.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.AsyncFunction")}}

+ + + +

참고 문서

+ + diff --git a/files/ko/web/javascript/reference/global_objects/atomics/index.html b/files/ko/web/javascript/reference/global_objects/atomics/index.html new file mode 100644 index 0000000000..6f155e8272 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/atomics/index.html @@ -0,0 +1,162 @@ +--- +title: Atomics +slug: Web/JavaScript/Reference/Global_Objects/Atomics +translation_of: Web/JavaScript/Reference/Global_Objects/Atomics +--- +
{{JSRef}} {{SeeCompatTable}}
+ +
Atomics 오브젝트는 atomic operations  정적메소드로서 제공됩니다. 다음과 같은 오브젝트와 함께 {{jsxref("SharedArrayBuffer")}} 사용합니다.
+ +

Atomic operations Atomic Module을 인스톨해야합니다. 다른 global objects들과 다르게 Atomic은 constructor가 아닙니다. new operator를 사용하면 안되고 invoke Atomics object 함수로 사용하면됩니다. Atomics의 속성과 함수들은 static입니다.  (as is the case with the {{jsxref("Math")}} object, for example).

+ +

Methods

+ +

Atomic operations

+ +

메모리가 공유되었을때, 멀티쓰레드는 메모리안에 같은 데이터들을 읽거나 쓸 수 있습니다.
+ Atomic operations은 예측 가능한 값을 쓰고 읽으며 다음 작업이 시작되기 전에 작업이 완료되고,작업이 중단되지 않도록합니다.

+ +
+
{{jsxref("Atomics.add()")}}
+
Adds a given value at a given position in the array. Returns the old value at that position.
+
{{jsxref("Atomics.and()")}}
+
Computes a bitwise AND at a given position in the array. Returns the old value at that position.
+
{{jsxref("Atomics.compareExchange()")}}
+
Stores a given value at a given position in the array, if it equals a given value. Returns the old value.
+
{{jsxref("Atomics.exchange()")}}
+
Stores a given value at a given position in the array. Returns the old value.
+
+ +
+
{{jsxref("Atomics.load()")}}
+
Returns the value at the given position in the array.
+
{{jsxref("Atomics.or()")}}
+
Computes a bitwise OR at a given position in the array. Returns the old value at that position.
+
{{jsxref("Atomics.store()")}}
+
Stores a given value at the given position in the array. Returns the value.
+
{{jsxref("Atomics.sub()")}}
+
Subtracts a given value at a given position in the array. Returns the old value at that position.
+
{{jsxref("Atomics.xor()")}}
+
Computes a bitwise XOR at a given position in the array. Returns the old value at that position.
+
+ +

Wait and wake

+ +

The wait() and wake() methods are modeled on Linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs.

+ +
+
{{jsxref("Atomics.wait()")}}
+
+

Verifies that a given position in the array still contains a given value and sleeps awaiting or times out. Returns either "ok", "not-equal", or "timed-out". If waiting is not allowed in the calling agent then it throws an Error exception (most browsers will not allow wait() on the browser's main thread).

+
+
{{jsxref("Atomics.wake()")}}
+
Wakes up some agents that are sleeping in the wait queue on the given array position. Returns the number of agents that were woken up.
+
{{jsxref("Atomics.isLockFree()", "Atomics.isLockFree(size)")}}
+
+

An optimization primitive that can be used to determine whether to use locks or atomic operations. Returns true, if an atomic operation on arrays of the given element size will be implemented using a hardware atomic operation (as opposed to a lock). Experts only.

+
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Shared Memory', '#AtomicsObject', 'Atomics')}}{{Spec2('Shared Memory')}}Initial definition.
{{SpecName('ESDraft')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}} [2]{{CompatNo}}{{CompatGeckoDesktop("46")}} [1] [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("46")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] This feature is disabled by a preference setting. In about:config, set javascript.options.shared_memory to true

+ +

[2] The implementation is under development and needs these runtime flags: --js-flags=--harmony-sharedarraybuffer --enable-blink-feature=SharedArrayBuffer

+ +

Compatibility notes

+ +

[3] The Shared memory specification is still stabilizing. Prior to SpiderMonkey 48 {{geckoRelease(48)}}, the latest API names and semantics weren't implemented yet. The changes between Firefox version 46 and version 48 are:

+ + + +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/bigint/bigint/index.html b/files/ko/web/javascript/reference/global_objects/bigint/bigint/index.html new file mode 100644 index 0000000000..9a7405fac8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/bigint/bigint/index.html @@ -0,0 +1,62 @@ +--- +title: BigInt() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/BigInt/BigInt +tags: + - BigInt + - Constructor + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/BigInt/BigInt +--- +
{{JSRef}}
+ +

BigInt() 생성자는 {{jsxref("BigInt")}} 객체를 생성합니다.

+ +

구분

+ +
BigInt(value);
+
+ +

매개변수

+ +
+
value
+
생성하는 객체에 할당할 숫자 값. 문자열 또는 정수를 사용할 수 있습니다.
+
+ +
+

참고: BigInt()는 {{jsxref("Operators/new", "new")}} 연산자와 함께 사용하지 않습니다.

+
+ +

예제

+ +
BigInt(123);
+// 123n
+
+ +

명세

+ + + + + + + + + + + + +
SpecificationStatus
{{SpecName('ESDraft', '#sec-bigint-constructor', 'BigInt constructor')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.BigInt.BigInt")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/bigint/index.html b/files/ko/web/javascript/reference/global_objects/bigint/index.html new file mode 100644 index 0000000000..dcfc19e799 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/bigint/index.html @@ -0,0 +1,280 @@ +--- +title: BigInt +slug: Web/JavaScript/Reference/Global_Objects/BigInt +tags: + - BigInt + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/BigInt +--- +
{{JSRef}}
+ +

BigInt는 {{jsxref("Number")}} 원시 값이 안정적으로 나타낼 수 있는 최대치인 253 - 1보다 큰 정수를 표현할 수 있는 내장 객체입니다.

+ +

설명

+ +

BigInt는 정수 리터럴의 뒤에 n을 붙이거나(10n) 함수 BigInt()를 호출해 생성할 수 있습니다.

+ +
const theBiggestInt = 9007199254740991n;
+
+const alsoHuge = BigInt(9007199254740991);
+// ↪ 9007199254740991n
+
+const hugeString = BigInt("9007199254740991");
+// ↪ 9007199254740991n
+
+const hugeHex = BigInt("0x1fffffffffffff");
+// ↪ 9007199254740991n
+
+const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
+// ↪ 9007199254740991n
+ +

BigInt와 {{jsxref("Number")}}는 어떤 면에서 비슷하지만 중요한 차이점이 있습니다. 예컨대 BigInt는 내장 {{jsxref("Math")}} 객체의 메서드와 함께 사용할 수 없고, 연산에서 Number와 혼합해 사용할 수 없습니다. 따라서 먼저 같은 자료형으로 변환해야 합니다. 그러나, BigIntNumber로 바뀌면 정확성을 잃을 수 있으니 주의해야 합니다.

+ +

자료형 정보

+ +

BigInttypeof 판별 결과는 "bigint"입니다.

+ +
typeof 1n === 'bigint'; // true
+typeof BigInt('1') === 'bigint'; // true
+
+ +

{{jsxref("Object")}}로 감싼 BigInt는 일반적인 object 자료형으로 취급합니다.

+ +
typeof Object(1n) === 'object'; // true
+
+ +

연산자

+ +

+, *, -, **, % 연산자를 BigInt나 객체로 감싼 BigInt에서 사용할 수 있습니다. 비트 연산자도 사용할 수 있으나, 모든 BigInt는 부호를 가져야 하므로 >>> (부호 버림 오른쪽 시프트)는 사용할 수 없습니다. asm.js에서 문제를 일으키지 않도록, 단항 + 연산자도 지원하지 않습니다.

+ +
const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER);
+// ↪ 9007199254740991
+
+const maxPlusOne = previousMaxSafe + 1n;
+// ↪ 9007199254740992n
+
+const theFuture = previousMaxSafe + 2n;
+// ↪ 9007199254740993n, this works now!
+
+const multi = previousMaxSafe * 2n;
+// ↪ 18014398509481982n
+
+const subtr = multi – 10n;
+// ↪ 18014398509481972n
+
+const mod = multi % 10n;
+// ↪ 2n
+
+const bigN = 2n ** 54n;
+// ↪ 18014398509481984n
+
+bigN * -1n
+// ↪ –18014398509481984n
+
+ +

/ 연산자도 정수 연산에서 예상할 수 있는 결과를 동일하게 도출합니다. 그러나 BigIntBigDecimal이 아니므로, 연산의 결과는 언제나 소수점 이하를 버립니다. 즉, 정수가 아닌 결과는 나오지 않습니다.

+ +
+

소수점 결과를 포함하는 연산을 BigInt와 사용하면 소수점 이하는 사라집니다.

+
+ +
const expected = 4n / 2n;
+// ↪ 2n
+
+const rounded = 5n / 2n;
+// ↪ 2.5n이 아니라 2n
+
+ +

비교

+ +

BigInt는 {{jsxref("Number")}}와 일치하지 않지만 동등합니다.

+ +
0n === 0
+// ↪ false
+
+0n == 0
+// ↪ true
+ +

NumberBigInt는 일반적인 방법으로 비교할 수 있습니다.

+ +
1n < 2
+// ↪ true
+
+2n > 1
+// ↪ true
+
+2 > 2
+// ↪ false
+
+2n > 2
+// ↪ false
+
+2n >= 2
+// ↪ true
+ +

배열의 요소로 함께 사용했을 땐 정렬도 가능합니다.

+ +
const mixed = [4n, 6, -12n, 10, 4, 0, 0n];
+// ↪  [4n, 6, -12n, 10, 4, 0, 0n]
+
+mixed.sort();
+// ↪ [-12n, 0, 0n, 10, 4n, 4, 6]
+
+ +

{{jsxref("Object")}}로 감싼 BigInt의 경우 다른 객체와 마찬가지로 자기 자신과 비교했을 때만 일치합니다.

+ +
0n === Object(0n); // false
+Object(0n) === Object(0n); // false
+
+const o = Object(0n);
+o === o // true
+
+ +

조건

+ +

BigInt는 다음의 상황에서는 {{jsxref("Number")}}처럼 행동합니다.

+ + + +
if (0n) {
+  console.log('if에서 안녕!');
+} else {
+  console.log('else에서 안녕!');
+}
+
+// ↪ "else에서 안녕!"
+
+0n || 12n
+// ↪ 12n
+
+0n && 12n
+// ↪ 0n
+
+Boolean(0n)
+// ↪ false
+
+Boolean(12n)
+// ↪ true
+
+!12n
+// ↪ false
+
+!0n
+// ↪ true
+
+ +

생성자

+ +
+
{{jsxref("BigInt.BigInt", "BigInt()")}}
+
BigInt 객체를 생성합니다.
+
+ +

정적 메서드

+ +
+
{{jsxref("BigInt.asIntN()")}}
+
주어진 BigInt-2width-12width-1 - 1의 범위로 자릅니다.
+
{{jsxref("BigInt.asUintN()")}}
+
주어진 BigInt02width - 1의 범위로 자릅니다.
+
+ +

인스턴스 메서드

+ +
+
{{jsxref("BigInt.prototype.toLocaleString()")}}
+
BigInt를 주어진 언어에 적합한 형태를 가진 문자열로 변환해 반환합니다. {{jsxref("Object.prototype.toLocaleString()")}} 메서드를 재정의합니다.
+
{{jsxref("BigInt.prototype.toString()")}}
+
BigInt의 값을 주어진 진수로 표현한 문자열을 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.
+
{{jsxref("BigInt.prototype.valueOf()")}}
+
BigInt 객체의 원시 값 표현을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 재정의합니다.
+
+ +

권장사항

+ +

변환

+ +

BigInt를 {{jsxref("Number")}}로 변환하는 과정에서 정확도를 유실할 수 있으므로, 253보다 큰 값을 예상할 수 있는 경우 BigInt만 사용하는 것이 좋습니다.

+ +

암호화

+ +

BigInt가 지원하는 연산의 소요시간은 상수 시간이 아니기 때문에 암호화에 적합하지 않습니다.

+ +

JSON과 함께 사용하기

+ +

BigInt는 직렬화할 수 없기 때문에, {{jsxref("JSON.stringify()")}}에 BigInt를 포함한 값을 전달한다면 TypeError가 발생합니다. 대신, 필요한 경우 자신만의 toJSON 메서드를 만들 수 있습니다.

+ +
BigInt.prototype.toJSON = function() { return this.toString(); }
+ +

이제 아래 코드가 오류를 던지지 않고 문자열을 반환합니다.

+ +
JSON.stringify(BigInt(1));
+// '"1"'
+
+ +

예제

+ +

소수 구하기

+ +
// 주어진 BigInt가 소수이면 true 반환
+function isPrime(p) {
+  for (let i = 2n; i * i <= p; i++) {
+    if (p % i === 0n) return false;
+  }
+  return true;
+}
+
+// BigInt를 받아, n번째 소수를 BigInt로 반환
+function nthPrime(nth) {
+  let maybePrime = 2n;
+  let prime = 0n;
+
+  while (nth >= 0n) {
+    if (isPrime(maybePrime)) {
+      nth -= 1n;
+      prime = maybePrime;
+    }
+    maybePrime += 1n;
+  }
+
+  return prime;
+}
+
+nthPrime(20n)
+// ↪ 73n
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName("ESDraft", "#sec-bigint-objects", "BigInt objects")}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.BigInt")}}

+ +

구현 진척도

+ +

본 기능은 아직 안정적인 크로스 브라우징에 도달하지 못했으므로, 매일 업데이트되는 아래 표에서 브라우저별 구현 상황을 확인할 수 있습니다. 이 데이터는 각 브라우저 JavaScript 엔진의 나이틀리 빌드 또는 최신 릴리즈판에서, JavaScript 표준 테스트인 Test262의 관련 항목을 시험해 생성합니다.

+ +

{{EmbedTest262ReportResultsTable("BigInt")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html b/files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html new file mode 100644 index 0000000000..6ba56eb37e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/bigint/prototype/index.html @@ -0,0 +1,59 @@ +--- +title: BigInt.prototype +slug: Web/JavaScript/Reference/Global_Objects/BigInt/prototype +tags: + - BigInt + - JavaScript + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/BigInt/prototype +--- +
{{JSRef}}
+ +

BigInt.prototype 속성은 {{jsxref("BigInt")}} 생성자의 프로토타입을 나타냅니다.

+ +

{{js_property_attributes(0, 0, 0)}}

+ +

설명

+ +

모든 {{jsxref("BigInt")}} 인스턴스는 BigInt.prototype을 상속합니다. BigInt 생성자의 프로토타입 객체를 변형해 모든 BigInt 인스턴스에 영향을 줄 수 있습니다.

+ +

속성

+ +
+
BigInt.prototype.constructor
+
이 객체의 인스턴스를 만들 때 사용한 함수를 반환합니다. 기본값은 {{jsxref("BigInt")}} 객체입니다.
+
+ +

메서드

+ +
+
BigInt.prototype.toLocaleString()
+
BigInt를 주어진 언어에 적합한 형태를 가진 문자열로 변환해 반환합니다. {{jsxref("Object.prototype.toLocaleString()")}} 메서드를 재정의합니다.
+
BigInt.prototype.toString()
+
BigInt의 값을 주어진 진수로 표현한 문자열을 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.
+
BigInt.prototype.valueOf()
+
BigInt 객체의 원시 값 표현을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 재정의합니다.
+
+ +

명세

+ + + + + + + + + + + + +
SpecificationStatus
BigInt.prototypeStage 3
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.BigInt.prototype")}}

diff --git a/files/ko/web/javascript/reference/global_objects/boolean/boolean/index.html b/files/ko/web/javascript/reference/global_objects/boolean/boolean/index.html new file mode 100644 index 0000000000..bbe86a5134 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/boolean/boolean/index.html @@ -0,0 +1,55 @@ +--- +title: Boolean() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/Boolean/Boolean +tags: + - Boolean + - Constructor + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean/Boolean +--- +
{{JSRef}}
+ +

Boolean() 생성자는 {{jsxref("Boolean")}} 객체를 생성할 때 사용합니다.

+ +
{{EmbedInteractiveExample("pages/js/boolean-constructor.html")}}
+ + + +

구문

+ +
new Boolean([value])
+ +

매개변수

+ +
+
value {{optional_inline}}
+
Boolean 객체의 초깃값.
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-boolean-constructor', 'Boolean constructor')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Boolean.Boolean")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/boolean/index.html b/files/ko/web/javascript/reference/global_objects/boolean/index.html new file mode 100644 index 0000000000..06618f3ffe --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/boolean/index.html @@ -0,0 +1,108 @@ +--- +title: Boolean +slug: Web/JavaScript/Reference/Global_Objects/Boolean +tags: + - Boolean + - Constructor + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean +--- +
{{JSRef}}
+ +

Boolean 객체는 불리언 값을 감싸고 있는 객체입니다.

+ +

설명

+ +

첫 번재 매개변수로서 전달한 값은 필요한 경우 불리언 값으로 변환됩니다. 값이 없거나 0, -0, {{jsxref("null")}}, false, {{jsxref("NaN")}}, {{jsxref("undefined")}}, 빈 문자열 ("")이라면 객체의 초기값은 false가 됩니다. 문자열 "false"를 포함한 그 외 모든 다른 값은 초기값을 true로 설정합니다.

+ +

Boolean 객체의 truefalse 값을 원시 Booleantrue, false와 혼동해선 안됩니다.

+ +

값이 {{jsxref("undefined")}}, {{jsxref("null")}}이 아닌 모든 객체는 조건문에서 true로 계산됩니다. 이는 값이 falseBoolean 객체도 포함합니다. 즉 아래 {{jsxref("Statements/if...else", "if")}} 문의 조건은 참입니다.

+ +
var x = new Boolean(false);
+if (x) {
+  // 이 코드는 실행됨
+}
+
+ +

그러나 원시 Boolean 값에는 적용되지 않습니다. 따라서 아래 {{jsxref("Statements/if...else", "if")}} 문의 조건은 거짓입니다.

+ +
var x = false;
+if (x) {
+  // 이 코드는 실행되지 않음
+}
+
+ +

불리언이 아닌 값을 변환할 때 Boolean 객체를 사용해선 안됩니다. 대신 Boolean 함수를 사용하세요.

+ +
var x = Boolean(expression);     // 추천
+var x = new Boolean(expression); // 사용하지 말것
+ +

값이 falseBoolean 객체를 포함한 어떠한 객체를 Boolean 객체의 초기값으로 넘겨주더라도 새로운 Boolean 객체는 true를 가집니다.

+ +
var myFalse = new Boolean(false);   // 초기값 거짓
+var g = Boolean(myFalse);           // 초기값 참
+var myString = new String('Hello'); // 문자열 객체
+var s = Boolean(myString);          // 초기값 참
+ +

Boolean 원시 값의 자리에서 Boolean 객체를 이용해선 안됩니다.

+ +

생성자

+ +
+
{{jsxref("Boolean.Boolean", "Boolean()")}}
+
Boolean 객체를 생성합니다.
+
+ +

인스턴스 메서드

+ +
+
{{jsxref("Boolean.prototype.toString()")}}
+
객체의 값에 따라 문자열 "true" 또는 "false"를 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.
+
{{jsxref("Boolean.prototype.valueOf()")}}
+
{{jsxref("Boolean")}} 객체의 원시값을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 재정의합니다.
+
+ +

예제

+ +

false 값으로 초기화한 Boolean 객체 만들기

+ +
var bNoParam = new Boolean();
+var bZero = new Boolean(0);
+var bNull = new Boolean(null);
+var bEmptyString = new Boolean('');
+var bfalse = new Boolean(false);
+ +

true 값으로 초기화한 Boolean 객체 만들기

+ +
var btrue = new Boolean(true);
+var btrueString = new Boolean('true');
+var bfalseString = new Boolean('false');
+var bSuLin = new Boolean('Su Lin');
+var bArrayProto = new Boolean([]);
+var bObjProto = new Boolean({});
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-boolean-objects', 'Boolean')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Boolean")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html b/files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html new file mode 100644 index 0000000000..7d1ce4f379 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/boolean/prototype/index.html @@ -0,0 +1,81 @@ +--- +title: Boolean.prototype +slug: Web/JavaScript/Reference/Global_Objects/Boolean/prototype +tags: + - Boolean + - JavaScript + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean +--- +
{{JSRef}}
+ +

Boolean.prototype 속성은 {{jsxref("Boolean")}} 생성자의 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +
{{EmbedInteractiveExample("pages/js/boolean-constructor.html")}}
+ + + +

설명

+ +

{{jsxref("Boolean")}} 인스턴스는 Boolean.prototype을 상속받습니다. 생성자의 프로토타입 객체를 사용해 모든 Boolean 인스턴스에 속성이나 메서드를 추가할 수 있습니다.

+ +

속성

+ +
+
Boolean.prototype.constructor
+
인스턴스의 프로토타입을 생성한 함수를 반환합니다. 기본값은 {{jsxref("Boolean")}} 함수입니다.
+
+ +

메서드

+ +
+
{{jsxref("Boolean.prototype.toSource()")}} {{non-standard_inline}}
+
{{jsxref("Boolean")}} 객체의 소스를 포함한 문자열을 반환합니다. 반환 문자열을 사용해 동일한 객체를 생성할 수 있습니다. {{jsxref("Object.prototype.toSource()")}} 메서드를 재정의합니다.
+
{{jsxref("Boolean.prototype.toString()")}}
+
객체의 값에 따라 문자열 "true" 또는 "false"를 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 재정의합니다.
+
{{jsxref("Boolean.prototype.valueOf()")}}
+
{{jsxref("Boolean")}} 객체의 원시 값을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 재정의합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.6.3.1', 'Boolean.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-boolean.prototype', 'Boolean.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-boolean.prototype', 'Boolean.prototype')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Boolean.prototype")}}

diff --git a/files/ko/web/javascript/reference/global_objects/boolean/tostring/index.html b/files/ko/web/javascript/reference/global_objects/boolean/tostring/index.html new file mode 100644 index 0000000000..5cdb2c1f47 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/boolean/tostring/index.html @@ -0,0 +1,69 @@ +--- +title: Boolean.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Boolean/toString +tags: + - Boolean + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean/toString +--- +
{{JSRef}}
+ +

toString() 메서드는 {{jsxref("Boolean")}} 객체를 나타내는 문자열을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/boolean-tostring.html")}}
+ + + +

구문

+ +
bool.toString()
+ +

반환 값

+ +

{{jsxref("Boolean")}} 객체를 나타내는 문자열.

+ +

설명

+ +

{{jsxref("Boolean")}} 객체는 {{jsxref("Object.prototype.toString()")}} 메서드를 상속받지 않고 재정의합니다. Boolean 객체에서 toString() 메서드는 객체의 문자열 표현을 반환합니다.

+ +

JavaScript는 {{jsxref("Boolean")}}을 문자열로 표현해야 할 때나 문자열 결합에 사용할 때 toString()을 자동으로 호출합니다.

+ +

toString()은 불리언 객체의 값에 따라 문자열 "true" 또는 "false"를 반환합니다.

+ +

예제

+ +

toString() 사용하기

+ +
var flag = new Boolean(true);
+flag.toString(); // false
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-boolean.prototype.tostring', 'Boolean.prototype.toString')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Boolean.toString")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/boolean/valueof/index.html b/files/ko/web/javascript/reference/global_objects/boolean/valueof/index.html new file mode 100644 index 0000000000..50df1d98d2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/boolean/valueof/index.html @@ -0,0 +1,67 @@ +--- +title: Boolean.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/Boolean/valueOf +tags: + - Boolean + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean/valueOf +--- +
{{JSRef}}
+ +

valueOf() 메서드는 {{jsxref("Boolean")}} 객체의 원시 값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/boolean-valueof.html")}}
+ + + +

구문

+ +
bool.valueOf()
+ +

반환 값

+ +

{{jsxref("Boolean")}} 객체의 원시 값.

+ +

설명

+ +

valueOf() 메서드는 {{jsxref("Boolean")}} 객체나 불리언 리터럴의 원시 값을 Boolean 자료형의 값으로 반환합니다.

+ +

valueOf() 메서드는 보통 JavaScript 내부에서 호출하며 코드에서 명시적으로 사용하지는 않습니다.

+ +

예제

+ +

valueOf 사용하기

+ +
var x = new Boolean();
+x.valueOf(); // false
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-boolean.prototype.valueof', 'Boolean.prototype.valueOf')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Boolean.valueOf")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/dataview/dataview/index.html b/files/ko/web/javascript/reference/global_objects/dataview/dataview/index.html new file mode 100644 index 0000000000..7c8b3634a1 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/dataview/dataview/index.html @@ -0,0 +1,75 @@ +--- +title: DataView() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/DataView/DataView +tags: + - Constructor + - DataView + - JavaScript + - Reference + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/DataView/DataView +--- +
{{JSRef}}
+ +

DataView() 생성자는 새로운 {{jsxref("DataView")}} 객체를 생성합니다.

+ +
{{EmbedInteractiveExample("pages/js/dataview-constructor.html")}}
+ + + +

구문

+ +
new DataView(buffer [, byteOffset [, byteLength]])
+ +

매개변수

+ +
+
buffer
+
새로운 DataView 객체의 저장소로 사용할 {{jsxref("ArrayBuffer")}} 또는 {{jsxref("SharedArrayBuffer")}} {{experimental_inline}}.
+
byteOffset {{optional_inline}}
+
새로운 뷰가 참조할 첫 번째 바이트로의 바이트 단위 오프셋. 지정하지 않을 경우 버퍼 뷰는 첫 번째 바이트부터 시작합니다.
+
byteLength {{optional_inline}}
+
바이트 배열의 요소 수. 지정하지 않을 경우 뷰의 길이는 버퍼의 길이와 같아집니다.
+
+ +

반환 값

+ +

지정한 데이터 버퍼를 나타내는 새로운 DataView 객체.

+ +

DataView 객체는 배열 버퍼의 "인터프리터"라고 생각하면 좀 더 쉽습니다. DataView는 읽기와 쓰기 모두에서 버퍼에 잘 맞도록 숫자를 올바르게 변환하는 법, 즉 정수/부동소수점 실수 변환, 엔디언 등 이진 형식으로 나타낸 숫자의 처리법을 알고 있습니다.

+ +

예외

+ +
+
{{jsxref("RangeError")}}
+
+

byteOffset 또는 byteLength 매개변수가 버퍼의 끝을 벗어남.

+ +

예를 들어, 버퍼가 16바이트 길이인데 byteOffset을 8로, byteLength를 10으로 설정할 경우 총 길이 18로서 2바이트를 초과하므로 오류가 발생합니다.

+
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-dataview-constructor', 'DataView constructor')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.DataView.DataView")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/dataview/index.html b/files/ko/web/javascript/reference/global_objects/dataview/index.html new file mode 100644 index 0000000000..3bde0a032c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/dataview/index.html @@ -0,0 +1,168 @@ +--- +title: DataView +slug: Web/JavaScript/Reference/Global_Objects/DataView +tags: + - DataView + - JavaScript + - Reference + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/DataView +--- +
{{JSRef}}
+ +

DataView 뷰는 플랫폼의 자체 {{glossary("endianness", "엔디언")}}(바이트 정렬 방법)에 신경 쓰지 않으면서 {{jsxref("ArrayBuffer")}}에서 다양한 숫자 자료형의 데이터를 읽고 쓰기 위한 저수준 인터페이스를 제공합니다.

+ +

설명

+ +

엔디언

+ +

다중 바이트 숫자 자료형은 장치의 아키텍처에 따라 메모리에 다르게 표현됩니다. {{glossary("endianness", "엔디언")}} 용어 사전을 참고하세요. DataView 접근자는 코드를 실행하는 컴퓨터의 엔디언에 관계 없이 데이터의 접근법을 명시적으로 통제할 수 있습니다.

+ +
var littleEndian = (function() {
+  var buffer = new ArrayBuffer(2);
+  new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
+  // Int16Array uses the platform's endianness.
+  return new Int16Array(buffer)[0] === 256;
+})();
+console.log(littleEndian); // true or false
+ +

64비트 정수 자료형

+ +

JavaScript는 64비트 정수형 값에 대한 표준 지원을 아직 제공하지 않으므로 DataView도 64비트 연산을 지원하지 않습니다. 필요한 경우 최대 정확도 {{jsxref("Number.MAX_SAFE_INTEGER")}}의 값을 가져올 수 있는 getUint64() 함수를 만들 수는 있으며, 어느 정도까지는 충분할 것입니다.

+ +
function getUint64(dataview, byteOffset, littleEndian) {
+  // split 64-bit number into two 32-bit (4-byte) parts
+  const left =  dataview.getUint32(byteOffset, littleEndian);
+  const right = dataview.getUint32(byteOffset+4, littleEndian);
+
+  // combine the two 32-bit values
+  const combined = littleEndian? left + 2**32*right : 2**32*left + right;
+
+  if (!Number.isSafeInteger(combined))
+    console.warn(combined, 'exceeds MAX_SAFE_INTEGER. Precision may be lost');
+
+  return combined;
+}
+ +

완전한 범위의 64비트를 지원해야 할 경우 {{jsxref("BigInt")}}를 사용하세요. 단, BigInt는 사용자 계층 라이브러리 구현체보다는 훨씬 빠르지만, 가변 크기라는 성질로 인해 JavaScript 32비트 정수보다는 항상 느릴 수밖에 없습니다.

+ +
const BigInt = window.BigInt, bigThirtyTwo = BigInt(32), bigZero = BigInt(0);
+function getUint64BigInt(dataview, byteOffset, littleEndian) {
+  // split 64-bit number into two 32-bit (4-byte) parts
+  const left = BigInt(dataview.getUint32(byteOffset|0, !!littleEndian)>>>0);
+  const right = BigInt(dataview.getUint32((byteOffset|0) + 4|0, !!littleEndian)>>>0);
+
+  // combine the two 32-bit values and return
+  return littleEndian ? (right<<bigThirtyTwo)|left : (left<<bigThirtyTwo)|right;
+}
+ +

생성자

+ +
+
{{jsxref("DataView.DataView", "DataView()")}}
+
새로운 DataView 객체를 생성합니다.
+
+ +

속성

+ +
+
DataView.prototype.constructor
+
객체의 프로토타입을 생성한 함수를 나타냅니다. 초깃값은 내장 DataView 생성자입니다.
+
{{jsxref("DataView.prototype.buffer")}} {{readonlyInline}}
+
뷰가 참조하는 {{jsxref("ArrayBuffer")}}입니다.
+
{{jsxref("DataView.prototype.byteLength")}} {{readonlyInline}}
+
뷰의 시작점부터 측정한 {{jsxref("ArrayBuffer")}}의 길이(바이트 단위)입니다.
+
{{jsxref("DataView.prototype.byteOffset")}} {{readonlyInline}}
+
뷰의 시작점 오프셋(바이트 단위)입니다.
+
+ +

메서드

+ +

읽기

+ +
+
{{jsxref("DataView.prototype.getInt8()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 8비트 정수(byte)를 가져옵니다.
+
{{jsxref("DataView.prototype.getUint8()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 8비트 부호 없는 정수(unsigned byte)를 가져옵니다.
+
{{jsxref("DataView.prototype.getInt16()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 16비트 정수(short)를 가져옵니다.
+
{{jsxref("DataView.prototype.getUint16()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 16비트 부호 없는 정수(unsigned short)를 가져옵니다.
+
{{jsxref("DataView.prototype.getInt32()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 32비트 정수(long)를 가져옵니다.
+
{{jsxref("DataView.prototype.getUint32()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 32비트 부호 없는 정수(unsigned short)를 가져옵니다.
+
{{jsxref("DataView.prototype.getFloat32()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 32비트 실수(float)를 가져옵니다.
+
{{jsxref("DataView.prototype.getFloat64()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 64비트 실수(double)를 가져옵니다.
+
{{jsxref("DataView.prototype.getBigInt64()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 64비트 정수(long long)를 가져옵니다.
+
{{jsxref("DataView.prototype.getBigUint64()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치의 64비트 부호 없는 정수(unsigned long long)를 가져옵니다.
+
+ +

쓰기

+ +
+
{{jsxref("DataView.prototype.setInt8()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 8비트 정수(byte)를 저장합니다.
+
{{jsxref("DataView.prototype.setUint8()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 8비트 부호 없는 정수(unsigned byte)를 저장합니다.
+
{{jsxref("DataView.prototype.setInt16()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 16비트 정수(short)를 저장합니다.
+
{{jsxref("DataView.prototype.setUint16()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 16비트 부호 없는 정수(unsigned short)를 저장합니다.
+
{{jsxref("DataView.prototype.setInt32()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 32비트 정수(long)를 저장합니다.
+
{{jsxref("DataView.prototype.setUint32()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 32비트 부호 없는 정수(unsigned long)를 저장합니다.
+
{{jsxref("DataView.prototype.setFloat32()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 32비트 실수(float)를 저장합니다.
+
{{jsxref("DataView.prototype.setFloat64()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 64비트 실수(double)를 저장합니다.
+
{{jsxref("DataView.prototype.setBigInt64()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 64비트 정수(long long)를 저장합니다.
+
{{jsxref("DataView.prototype.setBigUint64()")}}
+
뷰의 시작점에서부터 주어진 오프셋을 적용한 위치에 64비트 부호 없는 정수(unsigned long long)를 저장합니다.
+
+ +

예제

+ +
var buffer = new ArrayBuffer(16);
+var view = new DataView(buffer, 0);
+
+view.setInt16(1, 42);
+view.getInt16(1); //42
+
+ +

명세

+ + + + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-dataview-objects', 'DataView')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.DataView")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getdate/index.html b/files/ko/web/javascript/reference/global_objects/date/getdate/index.html new file mode 100644 index 0000000000..1a5d6f2d5a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getdate/index.html @@ -0,0 +1,84 @@ +--- +title: Date.prototype.getDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDate +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDate +--- +
{{JSRef}}
+ +

getDate() 메서드는 주어진 날짜의 현지 시간 기준 일을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/date-getdate.html")}}
+ + + +

구문

+ +
dateObj.getDate()
+ +

반환 값

+ +

현지 시간에 따라, 주어진 날짜의 일에 해당하는 1 이상 31 이하의 정수.

+ +

예제

+ +

getDate() 사용하기

+ +

아래 코드의 두 번째 명령문은 Xmas95의 값에 기반하여 day에 2를 할당합니다.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var day = Xmas95.getDate();
+
+console.log(day); // 25
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.5.14', 'Date.prototype.getDate')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.getDate")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getday/index.html b/files/ko/web/javascript/reference/global_objects/date/getday/index.html new file mode 100644 index 0000000000..1c936def69 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getday/index.html @@ -0,0 +1,95 @@ +--- +title: Date.prototype.getDay() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDay +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDay +--- +
{{JSRef}}
+ +

getDay() 메서드는 주어진 날짜의 현지 시간 기준 요일을 반환합니다. 0은 일요일을 나타냅니다. 현재의 일을 반환하려면 {{jsxref("Date.prototype.getDate()")}}를 사용하세요.

+ +
{{EmbedInteractiveExample("pages/js/date-getday.html")}}
+ + + +

구문

+ +
dateObj.getDay()
+ +

반환 값

+ +

현지 시간에 따라, 주어진 날짜의 요일에 해당하는 0 이상 6 이하의 정수. (일요일은 0, 월요일은 1, 화요일은 2, ...)

+ +

예제

+ +

getDay() 사용하기

+ +

1995년 12월 25일은 월요일입니다. 따라서 아래 코드의 두 번째 명령문은 Xmas95의 값에 기반하여 weekday에 1을 할당합니다.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var weekday = Xmas95.getDay();
+
+console.log(weekday); // 1
+
+ +
+

참고: 필요하다면, 요일의 이름("월요일" 등)을 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}과 options 매개변수를 사용해 얻을 수 있습니다. 이 방법을 사용하면 국제화도 더 쉬워집니다.

+ +
var options = { weekday: 'long'};
+console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95));
+// Monday
+console.log(new Intl.DateTimeFormat('ko-KR', options).format(Xmas95));
+// 월요일
+
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.5.16', 'Date.prototype.getDay')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.getDay")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getfullyear/index.html b/files/ko/web/javascript/reference/global_objects/date/getfullyear/index.html new file mode 100644 index 0000000000..c1a90e5340 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getfullyear/index.html @@ -0,0 +1,88 @@ +--- +title: Date.prototype.getFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +--- +
{{JSRef}}
+ +

getFullYear() 메서드는 주어진 날짜의 현지 시간 기준 연도를 반환합니다.

+ +

{{jsxref("Date.prototype.getYear()", "getYear()")}} 메서드 대신 이 메서드를 사용하세요.

+ +
{{EmbedInteractiveExample("pages/js/date-getfullyear.html")}}
+ + + +

구문

+ +
dateObj.getFullYear()
+ +

반환 값

+ +

현지 시간에 따라, 주어진 날짜의 연도에 해당하는 숫자.

+ +

설명

+ +

getFullYear()가 반환하는 값은 절댓값입니다. getFullYear()는 1000년과 9999년 사이의, 1995년과 같은 날짜에 대해서는 네 자리 숫자를 반환합니다. 이 메서드를 사용해야 2000년 이후의 날짜에 대해서도 호환을 유지할 수 있습니다.

+ +

예제

+ +

getFullYear() 사용하기

+ +

다음 예제에서는 현재 연도의 네 자릿값을 변수 year에 할당합니다.

+ +
var today = new Date();
+var year = today.getFullYear();
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.10', 'Date.prototype.getFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.getFullYear")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/gethours/index.html b/files/ko/web/javascript/reference/global_objects/date/gethours/index.html new file mode 100644 index 0000000000..8095548633 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/gethours/index.html @@ -0,0 +1,83 @@ +--- +title: Date.prototype.getHours() +slug: Web/JavaScript/Reference/Global_Objects/Date/getHours +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getHours +--- +
{{JSRef}}
+ +

getHours() 메서드는 주어진 날짜의 현지 시간 기준 시를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/date-gethours.html")}}
+ + + +

구문

+ +
dateObj.getHours()
+ +

반환 값

+ +

주어진 날짜의 현지 시간 기준 시를 나타내는 0에서 23 사이의 정수.

+ +

예제

+ +

getHours() 사용하기

+ +

아래의 두 번째 명령문은 {{jsxref("Date")}} 객체 Xmas95 날짜의 시를 hours 변수에 할당합니다.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var hours = Xmas95.getHours();
+
+console.log(hours); // 23
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.18', 'Date.prototype.getHours')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.getHours")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getmilliseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/getmilliseconds/index.html new file mode 100644 index 0000000000..49be5d7ff7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getmilliseconds/index.html @@ -0,0 +1,81 @@ +--- +title: Date.prototype.getMilliseconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds +--- +
{{JSRef}}
+ +

getMilliseconds() 메서드는 Date 인스턴스의 밀리초를 현지 시간 기준으로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/date-getmilliseconds.html")}}
+ + + +

구문

+ +
dateObj.getMilliseconds()
+ +

반환 값

+ +

주어진 날짜의 현지 시간 기준 밀리초를 나타내는 0에서 999 사이의 정수.

+ +

예제

+ +

getMilliseconds() 사용하기

+ +

다음 예제에서는 현재 시간의 밀리초를 변수 milliseconds에 할당합니다.

+ +
var today = new Date();
+var milliseconds = today.getMilliseconds();
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.24', 'Date.prototype.getMilliseconds')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.getMilliseconds")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getminutes/index.html b/files/ko/web/javascript/reference/global_objects/date/getminutes/index.html new file mode 100644 index 0000000000..5cd9c3c99a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getminutes/index.html @@ -0,0 +1,83 @@ +--- +title: Date.prototype.getMinutes() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMinutes +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMinutes +--- +
{{JSRef}}
+ +

getMinutes() 메서드는 Date 인스턴스의 분을 현지 시간 기준으로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/date-getminutes.html")}}
+ + + +

구문

+ +
dateObj.getMinutes()
+ +

반환 값

+ +

주어진 날짜의 현지 시간 기준 분을 나타내는 0에서 59 사이의 정수.

+ +

예제

+ +

getMinutes() 사용하기

+ +

다음 예제는 {{jsxref("Date")}} 객체 Xmas95의 분을 사용해 변수 minutes에 15를 할당합니다.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var minutes = Xmas95.getMinutes();
+
+console.log(minutes); // 15
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.20', 'Date.prototype.getMinutes')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-date.prototype.getminutes', 'Date.prototype.getMinutes')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-date.prototype.getminutes', 'Date.prototype.getMinutes')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.getMinutes")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getmonth/index.html b/files/ko/web/javascript/reference/global_objects/date/getmonth/index.html new file mode 100644 index 0000000000..48fe002a99 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getmonth/index.html @@ -0,0 +1,94 @@ +--- +title: Date.prototype.getMonth() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMonth +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMonth +--- +
{{JSRef}}
+ +

getMonth() 메서드는 Date 객체의 월 값을 현지 시간에 맞춰 반환합니다. 월은 0부터 시작합니다.

+ +
{{EmbedInteractiveExample("pages/js/date-getmonth.html")}}
+ + + +

구문

+ +
dateObj.getMonth()
+ +

반환 값

+ +

현지 시간 기준 월을 나타내는 0에서 11 사이의 정수. 0은 1월, 1은 2월... 을 나타냅니다.

+ +

예제

+ +

getMonth() 사용하기

+ +

다음 예제는 {{jsxref("Date")}} 객체 Xmas95의 값을 사용해 변수 month에 11을 할당합니다.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var month = Xmas95.getMonth();
+
+console.log(month); // 11
+
+ +
+

참고: 필요한 경우 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat()")}}과 options 매개변수를 사용해 해당하는 달의 이름("January" 등)을 가져올 수 있습니다. 이 방법을 사용하면 국제화도 보다 편리합니다.

+ +
var options = { month: 'long'};
+console.log(new Intl.DateTimeFormat('ko-KR', options).format(Xmas95));
+// 12월
+console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95));
+// December
+
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.12', 'Date.prototype.getMonth')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-date.prototype.getmonth', 'Date.prototype.getMonth')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-date.prototype.getmonth', 'Date.prototype.getMonth')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.getMonth")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/getseconds/index.html new file mode 100644 index 0000000000..c5155d4d4a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getseconds/index.html @@ -0,0 +1,83 @@ +--- +title: Date.prototype.getSeconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getSeconds +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getSeconds +--- +
{{JSRef}}
+ +

getSeconds() 메서드는 Date 객체의 초 값을 현지 시간에 맞춰 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/date-getseconds.html")}}
+ + + +

구문

+ +
dateObj.getSeconds()
+ +

반환 값

+ +

현지 시간 기준 초를 나타내는 0에서 59 사이의 정수.

+ +

예제

+ +

getSeconds() 사용하기

+ +

다음 예제는 {{jsxref("Date")}} 객체 Xmas95의 값을 사용해 변수 seconds에 30을 할당합니다.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var seconds = Xmas95.getSeconds();
+
+console.log(seconds); // 30
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.22', 'Date.prototype.getSeconds')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.getSeconds")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/gettime/index.html b/files/ko/web/javascript/reference/global_objects/date/gettime/index.html new file mode 100644 index 0000000000..20b554b41f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/gettime/index.html @@ -0,0 +1,139 @@ +--- +title: Date.prototype.getTime() +slug: Web/JavaScript/Reference/Global_Objects/Date/getTime +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getTime +--- +
{{JSRef}}
+ +

getTime() 메서드는 표준시에 따라 지정된 날짜의 시간에 해당하는 숫자 값을 반환합니다.

+ +

이 메서드를 사용하면 다른 {{jsxref ( "Date")}} 객체에 날짜와 시간을 지정할 수 있습니다. 이 메소드는 기능적으로 {{jsxref("Date.valueof", "valueOf()")}} 메소드와 동일합니다.

+ +

Syntax

+ +
dateObj.getTime()
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 주어진 날짜 사이의 경과 시간 (밀리 초)을 나타내는 숫자입니다.

+ +

Examples

+ +

날짜 복사에 getTime () 사용

+ +

동일한 시간 값으로 날짜 객체를 생성합니다.

+ +
// 월은 0부터 시작하여 생일은 1995 년 1 월 10 일이됩니다.
+var birthday = new Date(1994, 12, 10);
+var copy = new Date();
+copy.setTime(birthday.getTime());
+
+ +

 

+ +

측정 실행 시간

+ +

새로 생성 된 {{jsxref ( "Date")}} 객체에서 두 개의 연속 getTime () 호출을 뺀 후에이 두 호출 사이의 시간 범위를 지정하십시오. 일부 작업의 실행 시간을 계산하는 데 사용할 수 있습니다. 불필요한 {{jsxref ( "Date")}} 객체를 인스턴스화하지 않으려면 {{jsxref("Date.now()")}}를 참조하십시오.

+ +
var end, start;
+
+start = new Date();
+for (var i = 0; i < 1000; i++) {
+  Math.sqrt(i);
+}
+end = new Date();
+
+console.log('Operation took ' + (end.getTime() - start.getTime()) + ' msec');
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.9', 'Date.prototype.getTime')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.gettime', 'Date.prototype.getTime')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.gettime', 'Date.prototype.getTime')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html b/files/ko/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html new file mode 100644 index 0000000000..5f1681767f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html @@ -0,0 +1,119 @@ +--- +title: Date.prototype.getTimezoneOffset() +slug: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset +--- +
{{JSRef}}
+ +

getTimezoneOffset() 메소드는 현재 로케일 (즉, 호스트 시스템 설정)에 대한 시간대 오프셋 (UTC)을 분 단위로 반환합니다.

+ +

Syntax

+ +
dateObj.getTimezoneOffset()
+ +

Return value

+ +

현재 호스트 설정을 기반으로하는 날짜에 대한 시간대 오프셋 (UTC) (분)을 나타내는 숫자입니다.

+ +

Description

+ +

시간대 오프셋은 UTC와 현지 시간의 차이 (분)입니다. 이것은 로컬 시간대가 UTC보다 뒤떨어져 있으면 오프셋이 양수이고 앞에있을 경우 음수임을 의미합니다. 예를 들어, 시간대 UTC + 10 : 00 (오스트레일리아 동부 표준시, 블라디보스토크 시간, 차모로 표준시)의 경우 -600이 반환됩니다.

+ +

반환 된 표준 시간대 오프셋은 호출 된 날짜에 적용되는 오프셋입니다. 호스트 시스템이 일광 절약 시간으로 구성된 경우 오프셋은 Date가 나타내는 날짜와 시간에 따라 변경되고 일광 절약 시간이 적용됩니다.

+ +

Examples

+ +

Using getTimezoneOffset()

+ +
// 호스트 장치의 현재 시간대 오프셋 가져 오기
+var x = new Date();
+var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
+
+// 2016 년 국제 노동절 (5 월 1 일)에 대한 시간대 오프셋 가져 오기
+var labourDay = new Date(2016,4,1)
+var labourDayOffset = labourDay.getTimezoneOffset() / 60;
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.26', 'Date.prototype.getTimezoneOffset')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.gettimezoneoffset', 'Date.prototype.getTimezoneOffset')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.gettimezoneoffset', 'Date.prototype.getTimezoneOffset')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatIE("5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcdate/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcdate/index.html new file mode 100644 index 0000000000..f74fb120db --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcdate/index.html @@ -0,0 +1,118 @@ +--- +title: Date.prototype.getUTCDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCDate +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCDate +--- +
{{JSRef}}
+ +

getUTCDate() 메서드는 표준시에 따라 지정된 날짜에 해당 월의 요일 (날짜)을 반환합니다.

+ +

Syntax

+ +
dateObj.getUTCDate()
+ +

Return value

+ +

보편적 인 시간에 따라 지정된 날짜의 달의 날짜를 나타내는 1에서 31 사이의 정수입니다.

+ +

Examples

+ +

Using getUTCDate()

+ +

다음 예제에서는 현재 날짜의 일 부분을 day 변수에 할당합니다.

+ +
var today = new Date();
+var day = today.getUTCDate();
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.15', 'Date.prototype.getUTCDate')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getutcdate', 'Date.prototype.getUTCDate')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getutcdate', 'Date.prototype.getUTCDate')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcday/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcday/index.html new file mode 100644 index 0000000000..c451fba612 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcday/index.html @@ -0,0 +1,118 @@ +--- +title: Date.prototype.getUTCDay() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCDay +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCDay +--- +
{{JSRef}}
+ +

getUTCDay() 메서드는 지정된 날짜의 요일을 표준시에 따라 반환합니다. 여기서 0은 일요일을 나타냅니다.

+ +

Syntax

+ +
dateObj.getUTCDay()
+ +

Return value

+ +

지정된 날짜의 요일에 해당하는 표준시에 따른 정수입니다 (일요일은 0, 월요일은 1, 화요일은 2 등).

+ +

Examples

+ +

Using getUTCDay()

+ +

다음 예제에서는 현재 날짜의 평일 부분을 weekday 변수에 할당합니다.

+ +
var today = new Date();
+var weekday = today.getUTCDay();
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.17', 'Date.prototype.getUTCDay')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getutcday', 'Date.prototype.getUTCDay')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getutcday', 'Date.prototype.getUTCDay')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcfullyear/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcfullyear/index.html new file mode 100644 index 0000000000..f7097db08a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcfullyear/index.html @@ -0,0 +1,121 @@ +--- +title: Date.prototype.getUTCFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCFullYear +--- +
{{JSRef}}
+ +

getUTCFullYear() 메서드는 표준시에 따라 지정된 날짜의 연도를 반환합니다.

+ +

Syntax

+ +
dateObj.getUTCFullYear()
+ +

Return value

+ +

주어진 날짜의 연도를 표준시에 따라 나타내는 숫자입니다.

+ +

Description

+ +

getUTCFullYear()에 의해 반환 된 값은 1995 년과 같이 2000 년과 호환되는 절대 숫자입니다.

+ +

Examples

+ +

Using getUTCFullYear()

+ +

다음 예제에서는 현재 연도의 4 자리 값을 변수 year에 할당합니다.

+ +
var today = new Date();
+var year = today.getUTCFullYear();
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.11', 'Date.prototype.getUTCFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getutcfullyear', 'Date.prototype.getUTCFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getutcfullyear', 'Date.prototype.getUTCFullYear')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getutchours/index.html b/files/ko/web/javascript/reference/global_objects/date/getutchours/index.html new file mode 100644 index 0000000000..11171e568c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutchours/index.html @@ -0,0 +1,117 @@ +--- +title: Date.prototype.getUTCHours() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCHours +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCHours +--- +
{{JSRef}}
+ +

getUTCHours () 메서드는 표준시에 따라 지정된 날짜의 시간을 반환합니다.

+ +

Syntax

+ +
dateObj.getUTCHours()
+ +

Return value

+ +

0부터 23까지의 정수로, 표준시에 따라 지정된 날짜의 시간을 나타냅니다.

+ +

Examples

+ +

Using getUTCHours()

+ +

다음 예제에서는 현재 시간의 시간 부분을 시간 변수로 지정합니다.

+ +
var today = new Date();
+var hours = today.getUTCHours();
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.19', 'Date.prototype.getUTCHours')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getutchours', 'Date.prototype.getUTCHours')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getutchours', 'Date.prototype.getUTCHours')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcmilliseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcmilliseconds/index.html new file mode 100644 index 0000000000..8121d3c7c4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcmilliseconds/index.html @@ -0,0 +1,117 @@ +--- +title: Date.prototype.getUTCMilliseconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCMilliseconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCMilliseconds +--- +
{{JSRef}}
+ +

getUTCMilliseconds() 메서드는 표준시에 따라 지정된 날짜의 밀리 초를 반환합니다.

+ +

Syntax

+ +
dateObj.getUTCMilliseconds()
+ +

Return value

+ +

0부터 999까지의 정수로, 표준시에 따라 지정된 날짜의 밀리 초를 나타냅니다.

+ +

Examples

+ +

Using getUTCMilliseconds()

+ +

다음 예제에서는 현재 시간의 밀리 초 부분을 밀리 초 변수에 할당합니다.

+ +
var today = new Date();
+var milliseconds = today.getUTCMilliseconds();
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.25', 'Date.prototype.getUTCMilliseconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getutcmilliseconds', 'Date.prototype.getUTCMilliseconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getutcmilliseconds', 'Date.prototype.getUTCMilliseconds')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcminutes/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcminutes/index.html new file mode 100644 index 0000000000..45c453dced --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcminutes/index.html @@ -0,0 +1,117 @@ +--- +title: Date.prototype.getUTCMinutes() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCMinutes +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCMinutes +--- +
{{JSRef}}
+ +

getUTCMinutes() 메서드는 표준시에 따라 지정된 날짜의 분을 반환합니다.

+ +

Syntax

+ +
dateObj.getUTCMinutes()
+ +

Return value

+ +

0부터 59까지의 정수로, 표준시에 따라 지정된 날짜의 분을 나타냅니다.

+ +

Examples

+ +

Using getUTCMinutes()

+ +

다음 예제에서는 현재 시간의 분 부분을 minutes 변수에 할당합니다.

+ +
var today = new Date();
+var minutes = today.getUTCMinutes();
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.21', 'Date.prototype.getUTCMinutes')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getutcminutes', 'Date.prototype.getUTCMinutes')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getutcminutes', 'Date.prototype.getUTCMinutes')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcmonth/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcmonth/index.html new file mode 100644 index 0000000000..b4031536d6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcmonth/index.html @@ -0,0 +1,117 @@ +--- +title: Date.prototype.getUTCMonth() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth +--- +
{{JSRef}}
+ +

getUTCMonth()는 지정된 날짜의 월을 0부터 시작하는 값 (0은 첫 해를 나타냄)으로 표준시에 따라 반환합니다.

+ +

Syntax

+ +
dateObj.getUTCMonth()
+ +

Return value

+ +

0부터 11까지의 정수로, 표준시에 따라 주어진 날짜의 달에 해당합니다. 1 월은 0, 2 월은 1, 3 월은 2 등입니다.

+ +

Examples

+ +

Using getUTCMonth()

+ +

다음 예제에서는 현재 날짜의 월 부분을 month 변수에 할당합니다.

+ +
var today = new Date();
+var month = today.getUTCMonth();
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.13', 'Date.prototype.getUTCMonth')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getutcmonth', 'Date.prototype.getUTCMonth')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getutcmonth', 'Date.prototype.getUTCMonth')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/getutcseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/getutcseconds/index.html new file mode 100644 index 0000000000..d643903df7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/getutcseconds/index.html @@ -0,0 +1,117 @@ +--- +title: Date.prototype.getUTCSeconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCSeconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getUTCSeconds +--- +
{{JSRef}}
+ +

getUTCSeconds() 메서드는 표준시에 따라 지정된 날짜의 초를 반환합니다.

+ +

Syntax

+ +
dateObj.getUTCSeconds()
+ +

Return value

+ +

0부터 59까지의 정수로, 표준시에 따라 지정된 날짜의 초를 나타냅니다.

+ +

Examples

+ +

Using getUTCSeconds()

+ +

다음 예제에서는 현재 시간의 초 부분을 초 변수에 지정합니다.

+ +
var today = new Date();
+var seconds = today.getUTCSeconds();
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.23', 'Date.prototype.getUTCSeconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getutcseconds', 'Date.prototype.getUTCSeconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getutcseconds', 'Date.prototype.getUTCSeconds')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/index.html b/files/ko/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..d9cf05bbdb --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,239 @@ +--- +title: Date +slug: Web/JavaScript/Reference/Global_Objects/Date +tags: + - Constructor + - Date + - JavaScript + - Reference + - 날짜 + - 시간 +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +
{{JSRef}}
+ +

Date 생성자는 시간의 특정 지점을 나타내는 Date 객체를 생성합니다. Date 객체는 1970년 1월 1일 UTC(국제표준시) 00:00으로부터 지난 시간을 밀리초로 나타내는 유닉스 타임스탬프를 사용합니다.

+ +
{{EmbedInteractiveExample("pages/js/date-constructor.html")}}
+ + + +

Date 객체 초기화

+ +

JavaScript Date 객체를 생성하는 법은 {{jsxref("new")}} 연산자를 사용하는 것이 유일합니다.

+ +
let now = new Date();
+ +

단순히 {{jsxref("Date", "Date")}} 객체를 직접 호출했을 때, 반환 값은 Date 객체가 아니라 날짜를 나타낸 문자열입니다. JavaScript는 Date 리터럴 구문이 없습니다.

+ +

구문

+ +
new Date();
+new Date(value);
+new Date(dateString);
+new Date(year, monthIndex[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
+
+ +

매개변수

+ +

Date() 생성자는 네 가지 형태로 사용할 수 있습니다.

+ +

매개변수 없음

+ +

매개변수를 제공하지 않으면, 현지 시간으로 생성 순간의 날짜와 시간을 나타내는 Date 객체를 생성합니다.

+ +

유닉스 타임스탬프

+ +
+
value
+
유닉스 타임스탬프, 즉 1970년 1월 1일 00:00:00 UTC(유닉스 시간)부터의 시간을 밀리초 단위로 표현하되 윤초는 무시한 정숫값. 대부분의 유닉스 타임스탬프 함수는 초 단위까지만 정확함을 유의하세요.
+
+

타임스탬프 문자열

+
+
dateString
+
날짜를 표현하는 문자열값. {{jsxref("Date.parse()")}} 메서드가 인식할 수 있는 형식(IETF 호환 RFC 2822 타임스탬프ISO8601의 한 버전)이어야 합니다 +
참고: Date 생성자(와 Date.parse)를 사용해 날짜 문자열에서 시간을 알아내는건 하지 않는 것이 좋습니다. 브라우저 간 차이와 여러 비일관성이 존재하며 RFC 2822 규격 문자열의 지원은 관례일 뿐입니다. ISO 8601 규격 문자열은 시간 정보가 없을 때("1970-01-01" 등) 현지 시간이 아닌 UTC 기준으로 처리합니다.
+
+
+ +

개별 날짜 및 시간 구성 요소

+ +

적어도 연도와 월이 주어지면, 자신의 구성 요소(연, 월, 일, 시, 분, 초, 밀리초)를 모두 매개변수의 값에서 가져오는 Date 객체를 생성합니다. 누락한 요소에는 가장 낮은 값(day는 1, 나머지는 0)을 사용합니다.

+ +
+
year
+
연도를 나타내는 정숫값. 0부터 99는 1900부터 1999로 처리합니다. {{anch("두 자리 연도는 1900년대로", "아래 예제")}}를 참고하세요.
+
monthIndex
+
월을 나타내는 정숫값. 0은 1월을 나타내고 11은 12월을 나타냅니다.
+
day {{optional_inline}}
+
일을 나타내는 정숫값. 기본값은 1입니다.
+
hours {{optional_inline}}
+
시를 나타내는 정숫값. 기본값은 0(자정)입니다.
+
+ +
+
minutes {{optional_inline}}
+
분을 나타내는 정숫값. 기본값은 0분입니다.
+
seconds {{optional_inline}}
+
초를 나타내는 정숫값. 기본값은 0초입니다.
+
milliseconds {{optional_inline}}
+
밀리초를 나타내는 정숫값. 기본값은 0밀리초입니다.
+
+ +

설명

+ +

유닉스 시간과 타임스탬프

+ +

JavaScript 날짜는 1970년 1월 1일 자정 (UTC)로부터 지난 시간을 밀리초 단위로 나타낸 것입니다. 이 날짜와 시간을 합쳐 유닉스 시간이라고 부릅니다. 유닉스 시간은 컴퓨터로 날짜와 시간을 기록할 때 널리 사용하는 기준점입니다.

+ +
+

참고: 시간과 날짜는 현시 시간으로 저장된다는 점을 기억하는게 중요합니다. 시간, 날짜, 아니면 각각의 구성 요소를 회수하는 기본 메서드도 현지 시간에서 동작합니다.

+
+ +

하루는 86,400,000 밀리초입니다. 타임스탬프 기록에 사용하는 수의 크기를 고려했을 때, Date 객체는 유닉스 시간으로부터 약 ±100,000,000일 (1억일)을 기록할 수 있습니다. 따라서 293,742년이 오면 문제가 발생할 여지가 있습니다.

+ +

날짜 형식과 시간대 변환

+ +

날짜를 얻는 방법과 시간대를 바꾸는 메서드는 여럿 있습니다. 그 중 특히 유용한 함수는 날짜 및 시간을 국제 표준 시간인 협정 표준시(UTC)로 반환하는 함수입니다. UTC는 그리니치 시간대라고도 불리는데, 기준 시간대가 영국의 런던과 인근의 그리니치를 지나는 경선이기 때문입니다. 사용자의 장치는 현지 시간을 제공합니다.

+ +

{{jsxref("Date.getDay", "getDay()")}}와 {{jsxref("Date.setHours", "setHours()")}}처럼 현지 시간을 기준으로 한 구성요소 읽기 및 쓰기 메서드처럼, {{jsxref("Date.getDayUTC", "getUTCDay()")}} 와 {{jsxref("Date.setHoursUTC", "setUTCHours()")}}처럼 UTC를 기준으로 하는 읽기 및 쓰기 메서드도 존재합니다.

+ +

속성

+ +
+
{{jsxref("Date.prototype")}}
+
Date 객체에 추가 속성을 부여할 수 있습니다.
+
Date.length
+
Date.length의 값은 7로, 생성자가 받을 수 있는 매개변수의 수입니다. 보통 유용하게 쓸 수 있는 값은 아닙니다.
+
+ +

메서드

+ +
+
{{jsxref("Date.now()")}}
+
1970년 1월 1일 00:00:00 UTC(유닉스 시간)부터 지난 시간을 밀리초 단위의 숫자 값으로 반환합니다. 윤초는 무시합니다.
+
{{jsxref("Date.parse()")}}
+
Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC. +
Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.
+
+
{{jsxref("Date.UTC()")}}
+
Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored.
+
+ +

JavaScript Date 인스턴스

+ +

All Date instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the Date constructor can be modified to affect all Date instances.

+ +

Date.prototype 메서드

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}
+ +

예제

+ +

날짜를 지정하는 여러가지 방법

+ +

아래 예제는 날짜를 지정하는 몇가지 방법을 보여줍니다:

+ +
+

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

+
+ +
var today = new Date();
+var birthday = new Date("December 17, 1995 03:24:00");
+var birthday = new Date(95,11,17);
+var birthday = new Date(95,11,17,3,24,0);
+
+ +

두 자리 연도는 1900년대로

+ +

In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.

+ +
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+// Deprecated method, 98 maps to 1998 here as well
+date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
+
+ +

경과시간 계산

+ +

The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds.

+ +

Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.

+ +
// Date 객체 사용
+var start = Date.now();
+
+// 시간이 오래 걸리는 작업을 여기 배치합니다
+doSomethingForALongTime();
+var end = Date.now();
+var elapsed = end - start; // 경과 시간, 밀리초.
+
+ +
// 내장 메서드 사용
+var start = new Date();
+
+// 시간이 오래 걸리는 작업을 여기 배치합니다.
+doSomethingForALongTime();
+var end = new Date();
+var elapsed = end.getTime() - start.getTime(); // 경과 시간, 밀리초.
+
+ +
// to test a function and get back its return
+function printElapsedTime(fTest) {
+  var nStartTime = Date.now(),
+      vReturn = fTest(),
+      nEndTime = Date.now();
+
+  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
+  return vReturn;
+}
+
+var yourFunctionReturn = printElapsedTime(yourFunction);
+ +
Note: In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.
+ +

Get the number of seconds since Unix Epoch

+ +
var seconds = Math.floor(Date.now() / 1000);
+ +

In this case it's important to return only an integer (so a simple division won't do), and also to only return actually elapsed seconds (that's why this code uses {{jsxref("Math.floor()")}} and not {{jsxref("Math.round()")}}).

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date", 3)}}

diff --git a/files/ko/web/javascript/reference/global_objects/date/now/index.html b/files/ko/web/javascript/reference/global_objects/date/now/index.html new file mode 100644 index 0000000000..323df8ad45 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,119 @@ +--- +title: Date.now() +slug: Web/JavaScript/Reference/Global_Objects/Date/now +translation_of: Web/JavaScript/Reference/Global_Objects/Date/now +--- +
{{JSRef}}
+ +

Date.now() 메소드는 UTC 기준으로 1970년 1월 1일 0시 0분 0초부터 현재까지 경과된 밀리 초를 반환합니다.

+ +

문법

+ +
var timeInMs = Date.now();
+ +

인자

+ +

없음

+ +

설명

+ +

now() 메소드는 1970년 1월 1일 0시 0분 0초부터 현재까지 경과된 밀리 초를 {{jsxref("Number")}} 형으로 반환합니다.

+ +

now()는 {{jsxref("Date")}}의 정적 메소드이기 때문에, 항상 Date.now() 처럼 사용하셔야 합니다.

+ +

Polyfill

+ +

이 메소든는 ECMA-262 5판에서 표준화되었습니다. 아직 이 메소드를 지원하도록 갱신되지 않은 엔진들은 이 메소드의 미지원에 대한 차선책으로 다음 코드를 활용하실 수 있습니다.

+ +
if (!Date.now) {
+  Date.now = function now() {
+    return new Date().getTime();
+  };
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES6', '#sec-date.now', 'Date.now')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9")}}{{CompatIE("9")}}{{CompatOpera("10.50")}}{{CompatSafari("4")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/parse/index.html b/files/ko/web/javascript/reference/global_objects/date/parse/index.html new file mode 100644 index 0000000000..57e8effa54 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/parse/index.html @@ -0,0 +1,231 @@ +--- +title: Date.parse() +slug: Web/JavaScript/Reference/Global_Objects/Date/parse +translation_of: Web/JavaScript/Reference/Global_Objects/Date/parse +--- +
{{JSRef}}
+ +

Date.parse () 메서드는 날짜의 문자열 표현을 구문 분석하고 1970 년 1 월 1 일 00:00:00 UTC 이후의 밀리 초 수를 반환하거나 문자열이 인식되지 않거나 경우에 따라 잘못된 날짜 값을 포함하는 경우 NaN을 반환합니다. (예 : 2015-02-31).

+ +

ES5까지는 Date.parse를 사용하지 않는 것이 좋습니다. 문자열 구문 분석은 전적으로 구현에 따라 다릅니다. 다른 호스트가 날짜 문자열을 구문 분석하는 방법에는 여전히 많은 차이점이 있으므로 날짜 문자열을 수동으로 구문 분석해야합니다 (다양한 형식을 수용하면 라이브러리가 도움이 될 수 있습니다).

+ +

Syntax

+ +

Direct call:

+ +
Date.parse(dateString)
+ +

Implicit call:

+ +
new Date(dateString)
+ +

Parameters

+ +
+
dateString
+
RFC2822 또는 ISO 8601 날짜를 나타내는 문자열 (다른 형식도 사용할 수 있지만 예기치 않은 결과 일 수 있음)
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC 이후 경과 된 밀리 초를 나타내는 숫자 및 주어진 문자열 표현을 파싱하여 얻은 날짜입니다. 인수가 유효한 날짜를 나타내지 않으면 {{jsxref ( "NaN")}}이 반환됩니다.

+ +

Description

+ +

parse () 메서드는 날짜 문자열 (예 : "Dec 25, 1995")을 사용하고 1970 년 1 월 1 일 00:00:00 UTC 이후의 밀리 초 수를 반환합니다. 이 함수는 예를 들어 {{jsxref("Date.prototype.setTime()", "setTime()")}} 메서드 및 {{jsxref ( "Global_Objects / Date ","Date ")}} 객체를 반환합니다.

+ +

주어진 시간을 나타내는 문자열이 주어지면 parse ()는 시간 값을 반환합니다. RFC2822 / IETF 날짜 구문 (RFC2822 섹션 3.3)을 받아들입니다. "Mon, 25 Dec 1995 13:30:00 GMT". 미국 대륙의 표준 시간대 약어를 이해하지만, 일반적으로 "Mon, 25 Dec 1995 13:30:00 +0430"(그리니치 자오선의 동쪽으로 4 시간 30 분)과 같이 시간대 오프셋을 사용하십시오.

+ +

GMT와 UTC는 동등한 것으로 간주됩니다. 현지 시간대는 시간대 정보가없는 RFC2822 섹션 3.3 형식의 인수를 해석하는 데 사용됩니다.

+ +

날짜 문자열 구문 분석의 차이로 인해 결과가 일관되지 않아 문자열을 수동으로 구문 분석하는 것이 좋습니다. 특히 "2015-10-12 12:00:00"과 같은 문자열을 NaN으로 구문 분석 할 수있는 다른 ECMAScript 구현, UTC 또는 현지 시간대.

+ +

ECMAScript 5 ISO-8601 format support

+ +

날짜 시간 문자열은 ISO 8601 형식 일 수 있습니다. 예를 들어, "2011-10-10"(날짜 만) 또는 "2011-10-10T14 : 48 : 00"(날짜 및 시간)을 전달하고 구문 분석 할 수 있습니다. 문자열이 ISO 8601 날짜 인 경우 UTC 시간대는 인수를 해석하는 데 사용됩니다. 문자열이 ISO 8601 형식의 날짜 및 시간이면 로컬로 처리됩니다.

+ +

날짜 문자열 구문 분석 중에 시간대 지정자를 사용하여 인수를 해석하지만 반환되는 값은 1970 년 1 월 1 일 00:00:00 UTC와 인수 또는 NaN이 나타내는 시점 사이의 밀리 초입니다.

+ +

parse ()는 {{jsxref ( "Date")}}의 정적 메서드이기 때문에 {{jsxref ( "Date")}} 인스턴스의 메서드가 아닌 Date.parse ()로 호출됩니다.

+ +

가정 된 시간대의 차이점

+ +

"March 7, 2014"이라는 날짜 문자열이 주어지면 parse ()는 현지 시간대를 사용하지만 "2014-03-07"과 같은 ISO 형식이 주어지면 UTC (ES5 및 ECMAScript 2015)의 시간대로 가정합니다. 따라서 {{jsxref ( "Date")}} 이러한 문자열을 사용하여 생성 된 객체는 시스템이 현지 표준 시간대 (UTC)로 설정되어 있지 않으면 지원되는 ECMAScript 버전에 따라 다른 순간을 나타낼 수 있습니다. 즉, 변환되는 문자열의 형식에 따라 동등하게 나타나는 두 개의 날짜 문자열이 서로 다른 두 개의 값을 가질 수 있습니다.

+ +

구현 특정 날짜 형식으로 폴백

+ +

ECMAScript 사양은 다음과 같이 설명합니다. String이 표준 형식을 준수하지 않으면 함수는 구현 특정 휴리스틱 또는 구현 특정 파싱 알고리즘으로 폴백 할 수 있습니다. 인식 할 수없는 문자열 또는 ISO 형식의 문자열에 잘못된 요소 값이 포함 된 날짜로 인해 Date.parse ()가 {{jsxref ( "NaN")}}을 반환합니다.

+ +

그러나 ECMA-262에 정의 된 ISO 형식으로 인식되지 않는 날짜 문자열의 잘못된 값은 제공된 브라우저 및 값에 따라 {{jsxref ( "NaN")}}이 될 수도 있고 그렇지 않을 수도 있습니다 (예 :

+ +
// Non-ISO string with invalid date values
+new Date('23/25/2014');
+
+ +

Firefox 30에서는 2015 년 11 월 25 일, Safari 7에서는 유효하지 않은 날짜로 처리됩니다. 그러나 문자열이 ISO 형식 문자열로 인식되고 유효하지 않은 값을 포함하면 {{jsxref ( "NaN ")}} ES5 이상을 준수하는 모든 브라우저에서 :

+ +
// ISO string with invalid values
+new Date('2014-25-23').toISOString();
+// returns "RangeError: invalid date" in all es5 compliant browsers
+
+ +

SpiderMonkey의 구현 관련 추론은 jsdate.cpp에서 찾을 수 있습니다. 문자열 "10 06 2014"는 부적합한 ISO 형식의 예이므로 맞춤 루틴으로 되돌아갑니다. 파싱이 어떻게 작동하는지에 대한 대략적인 개요를 참조하십시오.

+ +
new Date('10 06 2014');
+
+ +

2014 년 10 월 6 일과 2014 년 6 월 10 일이 아닌 현지 날짜로 취급됩니다. 다른 예 :

+ +
new Date('foo-bar 2014').toString();
+// returns: "Invalid Date"
+
+Date.parse('foo-bar 2014');
+// returns: NaN
+
+ +

Examples

+ +

Using Date.parse()

+ +

IPOdate가 기존의 {{jsxref ( "Date")}} 객체 인 경우 다음과 같이 1995 년 8 월 9 일 (현지 시간)으로 설정할 수 있습니다.

+ +
IPOdate.setTime(Date.parse('Aug 9, 1995'));
+ +

표준이 아닌 날짜 문자열을 파싱하는 몇 가지 다른 예는 다음과 같습니다.

+ +
Date.parse('Aug 9, 1995');
+ +

문자열이 표준 시간대를 지정하지 않고 ISO 형식이 아니므로 표준 시간대 GMT-0300의 807937200000과 다른 표준 시간대의 다른 값을 반환하므로 표준 시간대는 기본적으로 local입니다.

+ +
Date.parse('Wed, 09 Aug 1995 00:00:00 GMT');
+ +

GMT (UTC)가 제공되는 현지 시간대와 상관없이 807926400000을 반환합니다.

+ +
Date.parse('Wed, 09 Aug 1995 00:00:00');
+ +

인수에 표준 시간대 지정자가 없으므로 ISO 형식이 아니기 때문에 표준 시간대 GMT-0300에서 807937200000과 다른 표준 시간대의 다른 값을 반환하므로 로컬로 처리됩니다.

+ +
Date.parse('Thu, 01 Jan 1970 00:00:00 GMT');
+ +

현지 시간대와 상관없이 0을 반환합니다. GMT (UTC)가 제공됩니다.

+ +
Date.parse('Thu, 01 Jan 1970 00:00:00');
+ +

표준 시간대가 제공되지 않고 문자열이 ISO 형식이 아니기 때문에 표준 시간대 GMT-0400의 14400000과 다른 표준 시간대의 다른 값을 반환하므로 현지 표준 시간대가 사용됩니다.

+ +
Date.parse('Thu, 01 Jan 1970 00:00:00 GMT-0400');
+ +

현지 시간대와 관계없이 14400000을 반환합니다. GMT (UTC)가 제공됩니다.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.4.2', 'Date.parse')}}{{Spec2('ES5.1')}}ISO 8601 format added.
{{SpecName('ES6', '#sec-date.parse', 'Date.parse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.parse', 'Date.parse')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ISO 8601 format{{CompatVersionUnknown}}{{CompatGeckodesktop("2.0")}}{{CompatIE("9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ISO 8601 format{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Compatibility notes

+ + + +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/prototype/index.html b/files/ko/web/javascript/reference/global_objects/date/prototype/index.html new file mode 100644 index 0000000000..7fe5dc9617 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/prototype/index.html @@ -0,0 +1,182 @@ +--- +title: Date.prototype +slug: Web/JavaScript/Reference/Global_Objects/Date/prototype +tags: + - Date + - JavaScript + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +
{{JSRef}}
+ +

Date.prototype 속성은 {{jsxref("Date")}} 생성자의 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0, 0, 1)}}
+ +

설명

+ +

JavaScript {{jsxref("Date")}} 인스턴스는 Date.prototype을 상속합니다. 생성자의 프로토타입을 변경해 모든 Date 인스턴스의 속성과 메서드를 수정할 수 있습니다.

+ +

2000년대 달력과의 호환성을 위해 연도는 언제나 완전하게 네 자리 숫자로 작성해야 합니다. 즉 98 대신 1998이 올바른 작성법입니다. Date는 완전한 연도 설정에 도움이 될 {{jsxref("Date.prototype.getFullYear()", "getFullYear()")}}, {{jsxref("Date.prototype.setFullYear()", "setFullYear()")}}, {{jsxref("Date.prototype.getUTCFullYear()", "getUTCFullYear()")}}, {{jsxref("Date.prototype.setUTCFullYear()", "setUTCFullYear()")}} 메서드를 가지고 있습니다.

+ +

ECMAScript 6부터 Date.prototype은 {{jsxref("Date")}} 인스턴스가 아닌 평범한 객체입니다.

+ +

속성

+ +
+
Date.prototype.constructor
+
인스턴스 생성에 사용한 생성자를 반환합니다. 기본값은 {{jsxref("Date")}}입니다.
+
+ +

메서드

+ +

접근자

+ +
+
{{jsxref("Date.prototype.getDate()")}}
+
주어진 날짜의 일(1-31)을 현지 시간에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getDay()")}}
+
주어진 날짜의 요일(0-6)을 현지 시간에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getFullYear()")}}
+
주어진 날짜의 연도(4자리 수)를 현지 시간에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getHours()")}}
+
주어진 날짜의 시(0-23)를 현지 시간에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getMilliseconds()")}}
+
주어진 날짜의 밀리초(0-999)를 현지 시간에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getMinutes()")}}
+
주어진 날짜의 분(0-59)을 현지 시간에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getMonth()")}}
+
주어진 날짜의 월(0-11)을 현지 시간에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getSeconds()")}}
+
주어진 날짜의 초(0-59)를 현지 시간에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getTime()")}}
+
주어진 날짜와 1970년 1월 1일 0시 0분(UTC)의 차이를 밀리초로 반환합니다.
+
{{jsxref("Date.prototype.getTimezoneOffset()")}}
+
현재 로케일의 시간대 차이를 분으로 환산해 반환합니다.
+
{{jsxref("Date.prototype.getUTCDate()")}}
+
주어진 날짜의 일(1-31)을 UTC에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getUTCDay()")}}
+
주어진 날짜의 요일(0-6)을 UTC에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getUTCFullYear()")}}
+
주어진 날짜의 연도(4자리 수)를 UTC에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getUTCHours()")}}
+
주어진 날짜의 시(0-23)를 UTC에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getUTCMilliseconds()")}}
+
주어진 날짜의 밀리초(0-999)를 UTC에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getUTCMinutes()")}}
+
주어진 날짜의 분(0-59)을 UTC에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getUTCMonth()")}}
+
주어진 날짜의 월(0-11)을 UTC에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getUTCSeconds()")}}
+
주어진 날짜의 초(0-59)를 UTC에 맞춰 반환합니다.
+
{{jsxref("Date.prototype.getYear()")}} {{deprecated_inline}}
+
주어진 날짜의 연도(주로 두세자리 숫자)를 현지 시간에 맞춰 반환합니다. {{jsxref("Date.prototype.getFullYear()", "getFullYear()")}}를 사용하세요.
+
+ +

설정자

+ +
+
{{jsxref("Date.prototype.setDate()")}}
+
Sets the day of the month for a specified date according to local time.
+
{{jsxref("Date.prototype.setFullYear()")}}
+
Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to local time.
+
{{jsxref("Date.prototype.setHours()")}}
+
Sets the hours for a specified date according to local time.
+
{{jsxref("Date.prototype.setMilliseconds()")}}
+
Sets the milliseconds for a specified date according to local time.
+
{{jsxref("Date.prototype.setMinutes()")}}
+
Sets the minutes for a specified date according to local time.
+
{{jsxref("Date.prototype.setMonth()")}}
+
Sets the month for a specified date according to local time.
+
{{jsxref("Date.prototype.setSeconds()")}}
+
Sets the seconds for a specified date according to local time.
+
{{jsxref("Date.prototype.setTime()")}}
+
Sets the {{jsxref("Date")}} object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC, allowing for negative numbers for times prior.
+
{{jsxref("Date.prototype.setUTCDate()")}}
+
Sets the day of the month for a specified date according to universal time.
+
{{jsxref("Date.prototype.setUTCFullYear()")}}
+
Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to universal time.
+
{{jsxref("Date.prototype.setUTCHours()")}}
+
Sets the hour for a specified date according to universal time.
+
{{jsxref("Date.prototype.setUTCMilliseconds()")}}
+
Sets the milliseconds for a specified date according to universal time.
+
{{jsxref("Date.prototype.setUTCMinutes()")}}
+
Sets the minutes for a specified date according to universal time.
+
{{jsxref("Date.prototype.setUTCMonth()")}}
+
Sets the month for a specified date according to universal time.
+
{{jsxref("Date.prototype.setUTCSeconds()")}}
+
Sets the seconds for a specified date according to universal time.
+
{{jsxref("Date.prototype.setYear()")}} {{deprecated_inline}}
+
Sets the year (usually 2-3 digits) for a specified date according to local time. Use {{jsxref("Date.prototype.setFullYear()", "setFullYear()")}} instead.
+
+ +

변환 접근자

+ +
+
{{jsxref("Date.prototype.toDateString()")}}
+
Returns the "date" portion of the {{jsxref("Date")}} as a human-readable string like 'Thu Apr 12 2018'
+
{{jsxref("Date.prototype.toISOString()")}}
+
Converts a date to a string following the ISO 8601 Extended Format.
+
{{jsxref("Date.prototype.toJSON()")}}
+
Returns a string representing the {{jsxref("Date")}} using {{jsxref("Date.prototype.toISOString()", "toISOString()")}}. Intended for use by {{jsxref("JSON.stringify()")}}.
+
{{jsxref("Date.prototype.toGMTString()")}} {{deprecated_inline}}
+
Returns a string representing the {{jsxref("Date")}} based on the GMT (UT) time zone. Use {{jsxref("Date.prototype.toUTCString()", "toUTCString()")}} instead.
+
{{jsxref("Date.prototype.toLocaleDateString()")}}
+
Returns a string with a locality sensitive representation of the date portion of this date based on system settings.
+
{{jsxref("Date.prototype.toLocaleFormat()")}} {{non-standard_inline}}
+
Converts a date to a string, using a format string.
+
{{jsxref("Date.prototype.toLocaleString()")}}
+
Returns a string with a locality sensitive representation of this date. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.
+
{{jsxref("Date.prototype.toLocaleTimeString()")}}
+
Returns a string with a locality sensitive representation of the time portion of this date based on system settings.
+
{{jsxref("Date.prototype.toSource()")}} {{non-standard_inline}}
+
Returns a string representing the source for an equivalent {{jsxref("Date")}} object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.
+
{{jsxref("Date.prototype.toString()")}}
+
Returns a string representing the specified {{jsxref("Date")}} object. Overrides the {{jsxref("Object.prototype.toString()")}} method.
+
{{jsxref("Date.prototype.toTimeString()")}}
+
Returns the "time" portion of the {{jsxref("Date")}} as a human-readable string.
+
{{jsxref("Date.prototype.toUTCString()")}}
+
Converts a date to a string using the UTC timezone.
+
{{jsxref("Date.prototype.valueOf()")}}
+
Returns the primitive value of a {{jsxref("Date")}} object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.9.5', 'Date.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-date-prototype-object', 'Date.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-the-date-prototype-object', 'Date.prototype')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.prototype")}}

diff --git a/files/ko/web/javascript/reference/global_objects/date/setdate/index.html b/files/ko/web/javascript/reference/global_objects/date/setdate/index.html new file mode 100644 index 0000000000..17f2b8aa02 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setdate/index.html @@ -0,0 +1,127 @@ +--- +title: Date.prototype.setDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/setDate +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setDate +--- +
{{JSRef}}
+ +

setDate() 메서드는 현재 설정된 월의 시작 부분을 기준으로 {{jsxref ( "Date")}} 객체의 날짜를 설정합니다.

+ +

Syntax

+ +
dateObj.setDate(dayValue)
+ +

Parameters

+ +
+
dayValue
+
월의 일을 나타내는 정수입니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 주어진 날짜 사이의 밀리 초 ({{jsxref ( "Date")}} 개체도 변경됩니다).

+ +

Description

+ +

dayValue가 해당 월의 날짜 값 범위를 벗어나면 setDate ()는 그에 따라 {{jsxref ( "Date")}} 객체를 업데이트합니다. 예를 들어, dayValue에 0이 제공되면 날짜는 이전 달의 마지막 날로 설정됩니다.

+ +

Examples

+ +

Using setDate()

+ +
var theBigDay = new Date(1962, 6, 7); // 1962-07-07
+theBigDay.setDate(24);  // 1962-07-24
+theBigDay.setDate(32);  // 1962-08-01
+theBigDay.setDate(22);  // 1962-08-22
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.36', 'Date.prototype.setDate')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setdate', 'Date.prototype.setDate')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setdate', 'Date.prototype.setDate')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setfullyear/index.html b/files/ko/web/javascript/reference/global_objects/date/setfullyear/index.html new file mode 100644 index 0000000000..f9faaca856 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setfullyear/index.html @@ -0,0 +1,133 @@ +--- +title: Date.prototype.setFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/setFullYear +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setFullYear +--- +
{{JSRef}}
+ +

setFullYear() 메서드는 현지 시간에 따라 지정된 날짜의 전체 연도를 설정합니다. 새로운 타임 스탬프를 반환합니다.

+ +

Syntax

+ +
dateObj.setFullYear(yearValue[, monthValue[, dayValue]])
+ +

Parameters

+ +
+
yearValue
+
연도의 숫자 값을 지정하는 정수입니다 (예 : 1995).
+
monthValue
+
선택 과목. 1 월에서 12 월까지의 월을 나타내는 0에서 11 사이의 정수입니다.
+
dayValue
+
선택 과목. 한 달의 날짜를 나타내는 1 - 31 사이의 정수입니다. dayValue 매개 변수를 지정하는 경우 monthValue도 지정해야합니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

monthValue 및 dayValue 매개 변수를 지정하지 않으면 {{jsxref ("Date.prototype.getMonth()", "getMonth()")}} 및 {{jsxref("Date.prototype.getDate)","getDate()")}} 메소드가 사용됩니다.

+ +

지정한 매개 변수가 예상 범위를 벗어나면 setFullYear ()가 다른 매개 변수와 {{jsxref ( "Date")}} 객체의 날짜 정보를 그에 따라 업데이트하려고 시도합니다. 예를 들어, monthValue에 15를 지정하면 연도가 1 (yearValue + 1)만큼 증가하고 3은 해당 월에 사용됩니다.

+ +

Examples

+ +

Using setFullYear()

+ +
var theBigDay = new Date();
+theBigDay.setFullYear(1997);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.40', 'Date.prototype.setFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setfullyear', 'Date.prototype.setFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setfullyear', 'Date.prototype.setFullYear')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/sethours/index.html b/files/ko/web/javascript/reference/global_objects/date/sethours/index.html new file mode 100644 index 0000000000..cbc1d4ff32 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/sethours/index.html @@ -0,0 +1,138 @@ +--- +title: Date.prototype.setHours() +slug: Web/JavaScript/Reference/Global_Objects/Date/setHours +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setHours +--- +
{{JSRef}}
+ +

setHours () 메서드는 현지 시간에 따라 지정된 날짜의 시간을 설정하고 1970 년 1 월 1 일 00:00:00 UTC 이후 업데이트 된 {{jsxref ( "Date")}}에 의해 표시되는 시간 (밀리 초)을 반환합니다. 예.

+ +

Syntax

+ +
dateObj.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])
+ +

Versions prior to JavaScript 1.3

+ +
dateObj.setHours(hoursValue)
+ +

Parameters

+ +
+
hoursValue
+
시를 나타내는 0에서 23 사이의 정수입니다.
+
minutesValue
+
선택 과목. 분을 나타내는 0에서 59 사이의 정수입니다.
+
secondsValue
+
선택 과목. 초를 나타내는 0에서 59 사이의 정수입니다. secondsValue 매개 변수를 지정하면 minutesValue도 지정해야합니다.
+
msValue
+
선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다. msValue 매개 변수를 지정하는 경우 minutesValue 및 secondsValue도 지정해야합니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

minutesValue, secondsValue 및 msValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getMinutes()", "getMinutes()")}}에서 반환 된 값, {{jsxref("Date.prototype.getSeconds()","getSeconds()")}} 및 {{jsxref("Date.prototype.getMilliseconds()","getMilliseconds()")}} 메서드가 사용됩니다.

+ +

지정한 매개 변수가 예상 범위를 벗어나면 setHours ()는 그에 따라 {{jsxref ("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 secondsValue에 100을 사용하면 분은 1 (minutesValue + 1)만큼 증가하고 40은 초 단위로 사용됩니다.

+ +

Examples

+ +

Using setHours()

+ +
var theBigDay = new Date();
+theBigDay.setHours(7);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.34', 'Date.prototype.setHours')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.sethours', 'Date.prototype.setHours')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.sethours', 'Date.prototype.setHours')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setmilliseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/setmilliseconds/index.html new file mode 100644 index 0000000000..d0904ae69e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setmilliseconds/index.html @@ -0,0 +1,126 @@ +--- +title: Date.prototype.setMilliseconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setMilliseconds +--- +
{{JSRef}}
+ +

setMilliseconds () 메서드는 현지 시간에 따라 지정된 날짜의 밀리 초를 설정합니다.

+ +

Syntax

+ +
dateObj.setMilliseconds(millisecondsValue)
+ +

Parameters

+ +
+
millisecondsValue
+
밀리 초를 나타내는 0에서 999 사이의 숫자입니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

예상되는 범위를 벗어난 숫자를 지정하면 {{jsxref ( "Date")}} 객체의 날짜 정보가 그에 따라 업데이트됩니다. 예를 들어, 1005를 지정하면 초 수가 1 씩 증가하고 5는 밀리 초 단위로 사용됩니다.

+ +

Examples

+ +

Using setMilliseconds()

+ +
var theBigDay = new Date();
+theBigDay.setMilliseconds(100);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.28', 'Date.prototype.setMilliseconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setmilliseconds', 'Date.prototype.setMilliseconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setmilliseconds', 'Date.prototype.setMilliseconds')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setminutes/index.html b/files/ko/web/javascript/reference/global_objects/date/setminutes/index.html new file mode 100644 index 0000000000..296923aa47 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setminutes/index.html @@ -0,0 +1,136 @@ +--- +title: Date.prototype.setMinutes() +slug: Web/JavaScript/Reference/Global_Objects/Date/setMinutes +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setMinutes +--- +
{{JSRef}}
+ +

setMinutes () 메서드는 현지 시간에 따라 지정된 날짜의 분을 설정합니다.

+ +

Syntax

+ +
dateObj.setMinutes(minutesValue[, secondsValue[, msValue]])
+ +

Versions prior to JavaScript 1.3

+ +
dateObj.setMinutes(minutesValue)
+ +

Parameters

+ +
+
minutesValue
+
분을 나타내는 0에서 59 사이의 정수입니다.
+
secondsValue
+
선택 과목. 초를 나타내는 0에서 59 사이의 정수입니다. secondsValue 매개 변수를 지정하면 minutesValue도 지정해야합니다.
+
msValue
+
선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다. msValue 매개 변수를 지정하는 경우 minutesValue 및 secondsValue도 지정해야합니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

secondsValue 및 msValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getSeconds()", "getSeconds()")}} 및 {{jsxref ("Date.prototype.getMilliseconds ","getMilliseconds() ")}} 메소드가 사용됩니다.

+ +

지정한 매개 변수가 예상 범위를 벗어나면 setMinutes ()는 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 secondsValue에 100을 사용하면 분은 1 (minutesValue + 1)만큼 증가하고 40은 초 단위로 사용됩니다.

+ +

Examples

+ +

Using setMinutes()

+ +
var theBigDay = new Date();
+theBigDay.setMinutes(45);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.32', 'Date.prototype.setMinutes')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setminutes', 'Date.prototype.setMinutes')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setminutes', 'Date.prototype.setMinutes')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setmonth/index.html b/files/ko/web/javascript/reference/global_objects/date/setmonth/index.html new file mode 100644 index 0000000000..bd954f83e9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setmonth/index.html @@ -0,0 +1,147 @@ +--- +title: Date.prototype.setMonth() +slug: Web/JavaScript/Reference/Global_Objects/Date/setMonth +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setMonth +--- +
{{JSRef}}
+ +

setMonth () 메서드는 현재 설정된 연도에 따라 지정된 날짜의 월을 설정합니다.

+ +

Syntax

+ +
dateObj.setMonth(monthValue[, dayValue])
+ +

Versions prior to JavaScript 1.3

+ +
dateObj.setMonth(monthValue)
+ +

Parameters

+ +
+
monthValue
+
1 월에서 12 월까지의 월을 나타내는 0에서 11 사이의 정수입니다.
+
dayValue
+
선택 과목. 한 달의 날짜를 나타내는 1에서 31 사이의 정수입니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

dayValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getDate()", "getDate()")}} 메서드에서 반환 된 값이 사용됩니다.

+ +

지정한 매개 변수가 예상 범위를 벗어나면 setMonth ()는 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 monthValue에 15를 사용하면 연도가 1 씩 증가하고 3은 월에 사용됩니다.

+ +

현재 날짜가이 메서드의 동작에 영향을 미칩니다. 개념적으로 새로운 날짜를 반환하기 위해 매개 변수로 지정된 새 달의 첫 번째 날에 해당 월의 현재 날짜로 지정된 일 수를 추가합니다. 예를 들어 현재 값이 2016 년 8 월 31 일인 경우 setMonth를 1로 설정하면 2016 년 3 월 2 일에 반환됩니다. 이는 2016 년 2 월에 29 일이 있었기 때문입니다.

+ +

Examples

+ +

Using setMonth()

+ +
var theBigDay = new Date();
+theBigDay.setMonth(6);
+
+//Watch out for end of month transitions
+var endOfMonth = new Date(2016, 7, 31);
+endOfMonth.setMonth(1);
+console.log(endOfMonth); //Wed Mar 02 2016 00:00:00
+
+
+
+ +

 

+ +

 

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.38', 'Date.prototype.setMonth')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setmonth', 'Date.prototype.setMonth')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setmonth', 'Date.prototype.setMonth')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/setseconds/index.html new file mode 100644 index 0000000000..3b3ea09ead --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setseconds/index.html @@ -0,0 +1,134 @@ +--- +title: Date.prototype.setSeconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/setSeconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setSeconds +--- +
{{JSRef}}
+ +

setSeconds () 메서드는 현지 시간에 따라 지정된 날짜의 초를 설정합니다.

+ +

Syntax

+ +
dateObj.setSeconds(secondsValue[, msValue])
+ +

Versions prior to JavaScript 1.3

+ +
dateObj.setSeconds(secondsValue)
+ +

Parameters

+ +
+
secondsValue
+
초를 나타내는 0에서 59 사이의 정수입니다.
+
msValue
+
선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

msValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getMilliseconds()", "getMilliseconds()")}} 메서드에서 반환 된 값이 사용됩니다.

+ +

지정한 매개 변수가 예상 범위를 벗어나면 setSeconds ()는 {{jsxref("Date")}} 객체의 날짜 정보를 그에 따라 업데이트하려고 시도합니다. 예를 들어, secondsValue에 100을 사용하면 {{jsxref("Date")}} 객체에 저장된 분이 1 씩 증가하고 40 초 동안 사용됩니다.

+ +

Examples

+ +

Using setSeconds()

+ +
var theBigDay = new Date();
+theBigDay.setSeconds(30);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.30', 'Date.prototype.setSeconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setseconds', 'Date.prototype.setSeconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setseconds', 'Date.prototype.setSeconds')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/settime/index.html b/files/ko/web/javascript/reference/global_objects/date/settime/index.html new file mode 100644 index 0000000000..e47d43720a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/settime/index.html @@ -0,0 +1,127 @@ +--- +title: Date.prototype.setTime() +slug: Web/JavaScript/Reference/Global_Objects/Date/setTime +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setTime +--- +
{{JSRef}}
+ +

setTime () 메서드는 {{jsxref ( "Date")}} 객체를 1970 년 1 월 1 일 00:00:00 UTC부터 밀리 초 단위로 나타내는 시간으로 설정합니다.

+ +

Syntax

+ +
dateObj.setTime(timeValue)
+ +

Parameters

+ +
+
timeValue
+
1970 년 1 월 1 일 00:00:00 UTC 이후의 밀리 초 수를 나타내는 정수입니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 (사실상 인수의 값) 사이의 밀리 초 수입니다.

+ +

Description

+ +

setTime () 메서드를 사용하면 다른 {{jsxref ( "Date")}} 객체에 날짜와 시간을 지정할 수 있습니다.

+ +

Examples

+ +

Using setTime()

+ +
var theBigDay = new Date('July 1, 1999');
+var sameAsBigDay = new Date();
+sameAsBigDay.setTime(theBigDay.getTime());
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.27', 'Date.prototype.setTime')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.settime', 'Date.prototype.setTime')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.settime', 'Date.prototype.setTime')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcdate/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcdate/index.html new file mode 100644 index 0000000000..28c1ef3835 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcdate/index.html @@ -0,0 +1,126 @@ +--- +title: Date.prototype.setUTCDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCDate +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCDate +--- +
{{JSRef}}
+ +

setUTCDate() 메서드는 표준시에 따라 지정된 날짜의 날짜를 설정합니다.

+ +

Syntax

+ +
dateObj.setUTCDate(dayValue)
+ +

Parameters

+ +
+
dayValue
+
한 달의 날짜를 나타내는 1에서 31 사이의 정수입니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

지정한 매개 변수가 예상 범위를 벗어난 경우 setUTCDate ()는 그에 따라 {{jsxref ( "Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어, dayValue에 40을 사용하고 {{jsxref ( "Date")}} 객체에 저장된 달이 6 월이면 일이 10으로 변경되고 월이 7 월로 증가합니다.

+ +

Examples

+ +

Using setUTCDate()

+ +
var theBigDay = new Date();
+theBigDay.setUTCDate(20);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.37', 'Date.prototype.setUTCDate')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setutcdate', 'Date.prototype.setUTCDate')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setutcdate', 'Date.prototype.setUTCDate')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcfullyear/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcfullyear/index.html new file mode 100644 index 0000000000..8410c68faa --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcfullyear/index.html @@ -0,0 +1,132 @@ +--- +title: Date.prototype.setUTCFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCFullYear +--- +
{{JSRef}}
+ +

setUTCFullYear() 메서드는 지정된 날짜의 전체 연도를 표준시에 따라 설정합니다.

+ +

Syntax

+ +
dateObj.setUTCFullYear(yearValue[, monthValue[, dayValue]])
+ +

Parameters

+ +
+
yearValue
+
연도의 숫자 값을 지정하는 정수입니다 (예 : 1995).
+
monthValue
+
선택 과목. 1 월에서 12 월까지의 월을 나타내는 0에서 11 사이의 정수입니다.
+
dayValue
+
선택 과목. 한 달의 날짜를 나타내는 1 - 31 사이의 정수입니다. dayValue 매개 변수를 지정하는 경우 monthValue도 지정해야합니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

monthValue 및 dayValue 매개 변수를 지정하지 않으면 {{jsxref ( "Date.prototype.getUTCMonth ()", "getUTCMonth()")}} 및 {{jsxref("Date.prototype.getUTCDate)","getUTCDate()")}} 메소드가 사용됩니다.

+ +

지정한 매개 변수가 예상 범위를 벗어난 경우 setUTCFullYear ()는 다른 매개 변수와 {{jsxref("Date")}} 객체의 날짜 정보를 그에 따라 업데이트하려고 시도합니다. 예를 들어, monthValue에 15를 지정하면 연도가 1 (yearValue + 1)만큼 증가하고 3은 해당 월에 사용됩니다.

+ +

Examples

+ +

Using setUTCFullYear()

+ +
var theBigDay = new Date();
+theBigDay.setUTCFullYear(1997);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.41', 'Date.prototype.setUTCFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setutcfullyear', 'Date.prototype.setUTCFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setutcfullyear', 'Date.prototype.setUTCFullYear')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setutchours/index.html b/files/ko/web/javascript/reference/global_objects/date/setutchours/index.html new file mode 100644 index 0000000000..dae2e10373 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutchours/index.html @@ -0,0 +1,134 @@ +--- +title: Date.prototype.setUTCHours() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCHours +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCHours +--- +
{{JSRef}}
+ +

setUTCHours () 메서드는 표준시에 따라 지정된 날짜의 시간을 설정하고 1970 년 1 월 1 일 00:00:00 UTC 이후 업데이트 된 {{jsxref ( "Date")}}에 의해 표시되는 시간 (밀리 초)을 반환합니다. 예.

+ +

Syntax

+ +
dateObj.setUTCHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])
+ +

Parameters

+ +
+
hoursValue
+
시를 나타내는 0에서 23 사이의 정수입니다.
+
minutesValue
+
선택 과목. 분을 나타내는 0에서 59 사이의 정수입니다.
+
secondsValue
+
선택 과목. 초를 나타내는 0에서 59 사이의 정수입니다. secondsValue 매개 변수를 지정하면 minutesValue도 지정해야합니다.
+
msValue
+
선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다. msValue 매개 변수를 지정하는 경우 minutesValue 및 secondsValue도 지정해야합니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

minutesValue, secondsValue 및 msValue 매개 변수를 지정하지 않으면 {{jsxref ( "Date.prototype.getUTCMinutes()", "getUTCMinutes()")}}, {{jsxref("Date.prototype .getUTCSeconds() ","getUTCSeconds()")}} 및 {{jsxref("Date.prototype.getUTCMilliseconds() ","getUTCMilliseconds()")}} 메소드가 사용됩니다.

+ +

지정한 매개 변수가 예상 범위를 벗어나면 setUTCHours ()는 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 secondsValue에 100을 사용하면 분은 1 (minutesValue + 1)만큼 증가하고 40은 초 단위로 사용됩니다.

+ +

Examples

+ +

Using setUTCHours()

+ +
var theBigDay = new Date();
+theBigDay.setUTCHours(8);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.35', 'Date.prototype.setUTCHours')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setutchours', 'Date.prototype.setUTCHours')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setutchours', 'Date.prototype.setUTCHours')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcmilliseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcmilliseconds/index.html new file mode 100644 index 0000000000..8f93cc7875 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcmilliseconds/index.html @@ -0,0 +1,126 @@ +--- +title: Date.prototype.setUTCMilliseconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCMilliseconds +--- +
{{JSRef}}
+ +

setUTCMilliseconds() 메서드는 표준시에 따라 지정된 날짜의 밀리 초를 설정합니다.

+ +

Syntax

+ +
dateObj.setUTCMilliseconds(millisecondsValue)
+ +

Parameters

+ +
+
millisecondsValue
+
밀리 초를 나타내는 0에서 999 사이의 숫자입니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

지정한 매개 변수가 예상 범위를 벗어난 경우 setUTCMilliseconds ()는 그에 따라 {{jsxref ( "Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 millisecondsValue에 1100을 사용하면 {{jsxref ( "Date")}} 객체에 저장된 초가 1 씩 증가하고 100은 밀리 초 단위로 사용됩니다.

+ +

Examples

+ +

Using setUTCMilliseconds()

+ +
var theBigDay = new Date();
+theBigDay.setUTCMilliseconds(500);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.29', 'Date.prototype.setUTCMilliseconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setutcmilliseconds', 'Date.prototype.setUTCMilliseconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setutcmilliseconds', 'Date.prototype.setUTCMilliseconds')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcminutes/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcminutes/index.html new file mode 100644 index 0000000000..c39b343935 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcminutes/index.html @@ -0,0 +1,132 @@ +--- +title: Date.prototype.setUTCMinutes() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCMinutes +--- +
{{JSRef}}
+ +

setUTCMinutes() 메서드는 표준시에 따라 지정된 날짜의 분을 설정합니다.

+ +

Syntax

+ +
dateObj.setUTCMinutes(minutesValue[, secondsValue[, msValue]])
+ +

Parameters

+ +
+
minutesValue
+
분을 나타내는 0에서 59 사이의 정수입니다.
+
secondsValue
+
선택 과목. 초를 나타내는 0에서 59 사이의 정수입니다. secondsValue 매개 변수를 지정하면 minutesValue도 지정해야합니다.
+
msValue
+
선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다. msValue 매개 변수를 지정하는 경우 minutesValue 및 secondsValue도 지정해야합니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

secondsValue 및 msValue 매개 변수를 지정하지 않으면 {{jsxref ( "Date.prototype.getUTCSeconds()", "getUTCSeconds()")}} 및 {{jsxref ("Date.prototype.getUTCMilliseconds","getUTCMilliseconds()")}} 메소드가 사용됩니다.

+ +

지정한 매개 변수가 예상 범위를 벗어나면 setUTCMinutes ()는 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 secondsValue에 100을 사용하면 분은 1 (minutesValue + 1)만큼 증가하고 40은 초 단위로 사용됩니다.

+ +

Examples

+ +

Using setUTCMinutes()

+ +
var theBigDay = new Date();
+theBigDay.setUTCMinutes(43);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.33', 'Date.prototype.setUTCMinutes')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setutcminutes', 'Date.prototype.setUTCMinutes')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setutcminutes', 'Date.prototype.setUTCMinutes')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcmonth/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcmonth/index.html new file mode 100644 index 0000000000..266112be92 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcmonth/index.html @@ -0,0 +1,130 @@ +--- +title: Date.prototype.setUTCMonth() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth +--- +
{{JSRef}}
+ +

setUTCMonth () 메서드는 표준시에 따라 지정된 날짜의 월을 설정합니다.

+ +

Syntax

+ +
dateObj.setUTCMonth(monthValue[, dayValue])
+ +

Parameters

+ +
+
monthValue
+
1 월에서 12 월까지의 월을 나타내는 0에서 11 사이의 정수입니다.
+
dayValue
+
선택 과목. 한 달의 날짜를 나타내는 1에서 31 사이의 정수입니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

dayValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getUTCDate()", "getUTCDate()")}} 메서드에서 반환 된 값이 사용됩니다.

+ +

지정한 매개 변수가 예상 범위를 벗어난 경우 setUTCMonth()는 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어 monthValue에 15를 사용하면 연도가 1 씩 증가하고 3은 월에 사용됩니다.

+ +

Examples

+ +

Using setUTCMonth()

+ +
var theBigDay = new Date();
+theBigDay.setUTCMonth(11);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.39', 'Date.prototype.setUTCMonth')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setutcmonth', 'Date.prototype.setUTCMonth')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setutcmonth', 'Date.prototype.setUTCMonth')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/setutcseconds/index.html b/files/ko/web/javascript/reference/global_objects/date/setutcseconds/index.html new file mode 100644 index 0000000000..f4d5609444 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/setutcseconds/index.html @@ -0,0 +1,130 @@ +--- +title: Date.prototype.setUTCSeconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds +--- +
{{JSRef}}
+ +

setUTCSeconds() 메서드는 표준시에 따라 지정된 날짜의 초를 설정합니다.

+ +

Syntax

+ +
dateObj.setUTCSeconds(secondsValue[, msValue])
+ +

Parameters

+ +
+
secondsValue
+
초를 나타내는 0에서 59 사이의 정수입니다.
+
msValue
+
선택 과목. 밀리 초를 나타내는 0에서 999 사이의 숫자입니다.
+
+ +

Return value

+ +

1970 년 1 월 1 일 00:00:00 UTC와 업데이트 된 날짜 사이의 밀리 초 숫자입니다.

+ +

Description

+ +

msValue 매개 변수를 지정하지 않으면 {{jsxref("Date.prototype.getUTCMilliseconds()", "getUTCMilliseconds()")}} 메서드에서 반환 된 값이 사용됩니다.

+ +

지정한 매개 변수가 예상 범위를 벗어나면 setUTCSeconds()가 그에 따라 {{jsxref("Date")}} 객체의 날짜 정보를 업데이트하려고 시도합니다. 예를 들어, secondsValue에 100을 사용하면 {{jsxref("Date")}} 객체에 저장된 분이 1 씩 증가하고 40 초 동안 사용됩니다.

+ +

Examples

+ +

Using setUTCSeconds()

+ +
var theBigDay = new Date();
+theBigDay.setUTCSeconds(20);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.31', 'Date.prototype.setUTCSeconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.setutcseconds', 'Date.prototype.setUTCSeconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.setutcseconds', 'Date.prototype.setUTCSeconds')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/todatestring/index.html b/files/ko/web/javascript/reference/global_objects/date/todatestring/index.html new file mode 100644 index 0000000000..1ded363e99 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/todatestring/index.html @@ -0,0 +1,82 @@ +--- +title: Date.prototype.toDateString() +slug: Web/JavaScript/Reference/Global_Objects/Date/toDateString +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toDateString +--- +
{{JSRef}}
+ +

toDateString() 메서드는 미국 영어로 사람이 읽을 수있는 형태로 {{jsxref("Date")}} 객체의 날짜 부분을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/date-todatestring.html")}}

+ +

구문

+ +
dateObj.toDateString()
+ +

반환 값

+ +

주어진 {{jsxref ( "Date")}} 객체의 날짜 부분을 사람이 읽을 수있는 형태로 미국 영어로 나타내는 문자열입니다.

+ +

설명

+ +

{{jsxref ( "Date")}} 인스턴스는 특정 시점을 참조합니다. {{jsxref ( "Date.prototype.toString ()", "toString ()")}}을 호출하면 사람이 읽을 수있는 형식의 미국식 영어로 된 날짜가 반환됩니다. SpiderMonkey에서는 날짜 부분 (일, 월, 연도)과 시간 부분 (시, 분, 초 및 시간대)으로 구성됩니다. 때로는 날짜 부분의 문자열을 얻는 것이 바람직합니다. 이러한 일은 toDateString () 메서드를 사용하여 수행 할 수 있습니다.

+ +

toDateString () 메서드는 ECMA-262를 구현하는 호환 엔진이 {{jsxref ( "Date.prototype.toString ()", "toString ()")}} 날짜 ")}} 객체를 사용할 수 있습니다. 형식은 구현에 따라 다르며 간단한 문자열 분할 방법은 여러 엔진에서 일관된 결과를 생성하지 않을 수 있습니다.

+ +

예제

+ +

A basic usage of toDateString()

+ +
var d = new Date(1993, 6, 28, 14, 39, 7);
+
+console.log(d.toString());     // logs Wed Jul 28 1993 14:39:07 GMT-0600 (PDT)
+console.log(d.toDateString()); // logs Wed Jul 28 1993
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.9.5.3', 'Date.prototype.toDateString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.todatestring', 'Date.prototype.toDateString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.todatestring', 'Date.prototype.toDateString')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Date.toDateString")}}

+ +
 
+ +
 
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/toisostring/index.html b/files/ko/web/javascript/reference/global_objects/date/toisostring/index.html new file mode 100644 index 0000000000..a9743f04d6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/toisostring/index.html @@ -0,0 +1,107 @@ +--- +title: Date.prototype.toISOString() +slug: Web/JavaScript/Reference/Global_Objects/Date/toISOString +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toISOString +--- +
{{JSRef}}
+ +

toISOString() 메서드는 단순화한 확장 ISO 형식(ISO 8601)의 문자열을 반환합니다. 반환값은 언제나 24글자 또는 27글자(각각 YYYY-MM-DDTHH:mm:ss.sssZ 또는 ±YYYYYY-MM-DDTHH:mm:ss.sssZ)입니다. 시간대는 언제나 UTC이며 접미어 "Z"로 표현합니다.

+ +
{{EmbedInteractiveExample("pages/js/date-toisostring.html")}}
+ + + +

구문

+ +
dateObj.toISOString()
+ +

반환 값

+ +

주어진 날짜를 국제표준시 기준 ISO 8601 형식으로 표현한 문자열.

+ +

예제

+ +

toISOString() 사용하기

+ +

아래 예제는 비표준 문자열의 분석을 포함하고 있어 비 Mozilla 브라우저에서는 올바르게 작동하지 않을 수 있습니다.

+ +
const today = new Date('05 October 2011 14:48 UTC');
+
+console.log(today.toISOString()); // Returns 2011-10-05T14:48:00.000Z
+ +

폴리필

+ +

toISOString은 ECMA-262 제5판에 표준으로 자리잡았습니다. 아직 지원하지 않는 환경에서는 다음 코드를 추가해 대체할 수 있습니다.

+ +
if (!Date.prototype.toISOString) {
+  (function() {
+
+    function pad(number) {
+      if (number < 10) {
+        return '0' + number;
+      }
+      return number;
+    }
+
+    Date.prototype.toISOString = function() {
+      return this.getUTCFullYear() +
+        '-' + pad(this.getUTCMonth() + 1) +
+        '-' + pad(this.getUTCDate()) +
+        'T' + pad(this.getUTCHours()) +
+        ':' + pad(this.getUTCMinutes()) +
+        ':' + pad(this.getUTCSeconds()) +
+        '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
+        'Z';
+    };
+
+  }());
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.9.5.43', 'Date.prototype.toISOString')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.
{{SpecName('ES6', '#sec-date.prototype.toisostring', 'Date.prototype.toISOString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.toisostring', 'Date.prototype.toISOString')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.toISOString")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/tojson/index.html b/files/ko/web/javascript/reference/global_objects/date/tojson/index.html new file mode 100644 index 0000000000..5f069e3417 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/tojson/index.html @@ -0,0 +1,81 @@ +--- +title: Date.prototype.toJSON() +slug: Web/JavaScript/Reference/Global_Objects/Date/toJSON +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toJSON +--- +
{{JSRef}}
+ +

toJSON() 메서드는 {{jsxref("Date")}} 객체의 문자열 표현을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/date-tojson.html")}}
+ + + +

구문

+ +
dateObj.toJSON()
+ +

반환 값

+ +

주어진 날짜의 문자열 표현.

+ +

설명

+ +

{{jsxref("Date")}} 인스턴스는 시간의 특정 지점을 가리킵니다. toJSON()을 호출하면 {{jsxref("Date.prototype.toISOString()", "toISOString()")}} 사용해 그 인스턴스가 가리키는 시간의 문자열 표현을 반환합니다. toJSON()은  Date 값을 {{Glossary("JSON")}}으로 직렬화할 때 유용하게 사용할 수 있도록 만들어졌습니다.

+ +

예제

+ +

toJSON() 사용하기

+ +
const jsonDate = (new Date()).toJSON();
+const backToDate = new Date(jsonDate);
+
+console.log(jsonDate); //2015-10-26T07:46:36.611Z
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.9.5.44', 'Date.prototype.toJSON')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.toJSON")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/tostring/index.html b/files/ko/web/javascript/reference/global_objects/date/tostring/index.html new file mode 100644 index 0000000000..5adaaf4f84 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/tostring/index.html @@ -0,0 +1,125 @@ +--- +title: Date.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Date/toString +tags: + - Date + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/toString +--- +
{{JSRef}}
+ +

 toString() 메서드는 {{jsxref("Date")}} 객체의 시간을 문자열로 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/date-tostring.html")}}

+ +

구문

+ +
dateObj.toString()
+ +

반환 값

+ +

주어진 날짜를 나타내는 문자열.

+ +

설명

+ +

{{jsxref("Date")}} 객체는 toString() 메서드를 {{jsxref("Object.prototype")}}이 아닌 {{jsxref("Date.prototype")}}에서 상속받습니다. Date.prototype.toString()의 반환값은 ECMA-262에 명시되어있으며 다음과 같이 요약할 수 있습니다.

+ + + +

예: "Sat Sep 01 2018 14:53:26 GMT+0900 (KST)"

+ +

ECMAScript 2018(제9판) 전까지 toString()의 반환 형식은 구현에 따라 다를 수 있었습니다. 따라서 특정 형식에 의존하지 않아야 합니다.

+ +

toString() 메서드는 날짜를 문자열로 표현해야 할 때 자동으로 쓰입니다. console.log(new Date())const today = 'Today is ' + new Date() 등의 경우를 예로 들 수 있습니다.

+ +

toString()은 제네릭 메서드로 this의 값이 {{jsxref("Date")}}일 필요는 없습니다. 그러나 내부적으로 [[TimeValue]] 속성이 필요한데, 이는 JavaScript로는 설정할 수 없어 결국 사용이 Date 인스턴스로 제한됩니다. Date 외의 다른 객체에서 호출하면 {{jsxref("TypeError")}}가 발생합니다.

+ +

예제

+ +

toString() 사용

+ +
var x = new Date();
+var myVar = x.toString(); // assigns a string value to myVar in the same format as:
+                          // Mon Sep 08 1998 14:36:22 GMT+0900 (KST)
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.2', 'Date.prototype.toLocaleTimeString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.tostring', 'Date.prototype.toString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.tostring', 'Date.prototype.toString')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.toString")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/utc/index.html b/files/ko/web/javascript/reference/global_objects/date/utc/index.html new file mode 100644 index 0000000000..f340c4d44a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/utc/index.html @@ -0,0 +1,139 @@ +--- +title: Date.UTC() +slug: Web/JavaScript/Reference/Global_Objects/Date/UTC +tags: + - Date + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Date/UTC +--- +
{{JSRef}}
+ +

Date.UTC() 메서드는 {{jsxref("Date")}} 생성자와 비슷한 매개변수를 받지만, 모두 UTC로 취급합니다. 반환 값은 1970년 1월 1일 00:00:00 UTC부터 매개변수가 나타내는 시간의 차이를 밀리초로 나타낸 수입니다.

+ +
{{EmbedInteractiveExample("pages/js/date-utc.html")}}
+ + + +

구문

+ +

ECMAScript 2017 이상:

+ +
Date.UTC(year[, month[, day[, hour[, minute[, second[, millisecond]]]]])
+ +

ECMAScript 2016 이하: (month 필수)

+ +
Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])
+ +

매개변수

+ +
+
year
+
네 자리 연도.
+
month
+
월을 나타내는 0(1월)에서 11(12월) 사이의 정수. ECMAScript 2016까지는 필수 매개변수였으나, ECMA2017부터는 선택사항입니다.
+
day {{optional_inline}}
+
일을 나타내는 1에서 31 사이의 정수. 기본값은 1입니다.
+
hour {{optional_inline}}
+
시를 나타내는 0에서 23 사이의 정수. 기본값은 0입니다.
+
minute {{optional_inline}}
+
분을 나타내는 0에서 59 사이의 정수. 기본값은 0입니다.
+
second {{optional_inline}}
+
초를 나타내는 0에서 59 사이의 정수. 기본값은 0입니다.
+
millisecond {{optional_inline}}
+
밀리초를 나타내는 0에서 999 사이의 정수. 기본값은 0입니다.
+
+ +

반환 값

+ +

주어진 날짜와 1970년 1월 1일 00:00:00 UTC의 차이를 밀리초로 나타낸 숫자.

+ +

설명

+ +

Date.UTC()는 날짜 및 시간을 받고, 1970년 1월 1일 00:00:00 UTC와의 차이를 밀리초 수로 나타내 반환합니다.

+ +

0에서 99 사이의 연도는 20세기(1900 + year)로 취급합니다. 즉 95를 입력할 경우 1995로 취급합니다.

+ +

Date.UTC() 메서드는 {{jsxref("Date")}} 생성자와 다른 점이 두 가지 있습니다.

+ + + +

주어진 매개변수가 통상적인 범위를 벗어나면 Date.UTC() 메서드는 다른 매개변수 값을 조절해 계산합니다. 예를 들어, 월 값으로 15를 사용하면 연도가 1 증가(year + 1)하고, 월 계산에는 3을 대신 사용합니다.

+ +

Date.UTC()는 {{jsxref("Date")}}의 정적 메서드이므로, 사용자가 생성한 {{jsxref("Date")}} 인스턴스에서 호출하지 않고 Date.UTC() 형태로 사용합니다.

+ +

예제

+ +

Date.UTC() 사용하기

+ +

다음 예제는 현지 시간 대신 UTC를 사용하여 {{jsxref("Date")}} 객체를 생성합니다.

+ +
var utcDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0));
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-15.9.4.3', 'Date.UTC')}}{{Spec2('ES5.1')}}
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Date.UTC")}}

+ +

호환성 참고사항

+ +

매개변수를 두 개 미만 제공하는 경우

+ +

Date.UTC()가 두 개 미만의 매개변수를 받은 경우, ECMAScript 2017은 {{jsxref("NaN")}}을 반환할 것을 요구합니다. 이를 지원하지 않던 엔진은 업데이트됐습니다. ({{bug(1050755)}}, ecma-262 #642를 참고하세요)

+ +
Date.UTC();
+Date.UTC(1);
+
+// Safari: NaN
+// Chrome/Opera/V8: NaN
+
+// Firefox <54: non-NaN
+// Firefox 54+: NaN
+
+// IE: non-NaN
+// Edge: NaN
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/date/valueof/index.html b/files/ko/web/javascript/reference/global_objects/date/valueof/index.html new file mode 100644 index 0000000000..778321f74e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/date/valueof/index.html @@ -0,0 +1,79 @@ +--- +title: Date.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/Date/valueOf +translation_of: Web/JavaScript/Reference/Global_Objects/Date/valueOf +--- +
{{JSRef}}
+ +

valueOf() 함수는 {{jsxref("Date")}} 객체의 원시값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/date-valueof.html")}}
+ +

Syntax

+ +
dateObj.valueOf()
+ +

Return value

+ +

반환되는 milliseconds 값은 1 January 1970 00:00:00 UTC 와 주어진 일시 사이의 값입니다.

+ +

Description

+ +

valueOf() 함수는 01 January, 1970 UTC 이후의 milliseconds 단위의 자연수 타입인 {{jsxref("Date")}} 객체의 원시값을 반환합니다.

+ +

이 함수는 {{jsxref("Date.prototype.getTime()")}} 함수와 동일한 결과값을 반환합니다.

+ +

이 함수는 사용자 코드에 명시된 것이 아닌, JavaScript 자체에 포함되어 있습니다.

+ +

Examples

+ +

Using valueOf()

+ +
var x = new Date(56, 6, 17);
+var myVar = x.valueOf();      // myVar에 -424713600000를 할당합니다.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}최초 정의. JavaScript 1.1에서 구현
{{SpecName('ES5.1', '#sec-15.9.5.8', 'Date.prototype.valueOf')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-date.prototype.valueof', 'Date.prototype.valueOf')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-date.prototype.valueof', 'Date.prototype.valueOf')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.valueOf")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/decodeuri/index.html b/files/ko/web/javascript/reference/global_objects/decodeuri/index.html new file mode 100644 index 0000000000..bb29400506 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/decodeuri/index.html @@ -0,0 +1,101 @@ +--- +title: decodeURI() +slug: Web/JavaScript/Reference/Global_Objects/decodeURI +tags: + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Global_Objects/decodeURI +--- +
{{jsSidebar("Objects")}}
+ +

decodeURI() 함수는 {{jsxref("encodeURI")}}이나 비슷한 루틴으로 사전에 만들어진 URI(Uniform Resource Identifier, 인터넷식별자) 를 해독합니다.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-decodeuri.html")}}
+ + + +

구문

+ +
decodeURI(encodedURI)
+ +

파라미터

+ +
+
encodedURI
+
완전하고 암호화된 인터넷식별자(URI)
+
+ +

리턴 값

+ +

주어진 암호화된 URI의 암호화되지 않은 버전을 나타내는 새 문자열을 반환합니다.

+ +

예외

+ +

encodedURI에 유효하지 않은 문자열이 포함된 경우 {{jsxref("URIError")}} ("malformed URI sequence") 예외를 던집니다.

+ +

설명

+ +

암호화된 URI의 각 이스케이프 시퀀스(확장문자열)를 자신을 나타내는 문자로 바꾸지만 {{jsxref ( "encodeURI")}}에서 도입할 수 없었던 이스케이프 시퀀스는 해독하지 않습니다. "#"문자는 이스케이프 시퀀스에서 해독되지 않습니다.

+ +

예제

+ +

Decoding a Cyrillic URL

+ +
decodeURI('https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B');
+// "https://developer.mozilla.org/ru/docs/JavaScript_шеллы"
+
+ +

Catching errors

+ +
try {
+  var a = decodeURI('%E0%A4%A');
+} catch(e) {
+  console.error(e);
+}
+
+// URIError: malformed URI sequence
+ +

사양

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.3.1', 'decodeURI')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-decodeuri-encodeduri', 'decodeURI')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-decodeuri-encodeduri', 'decodeURI')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.decodeURI")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/decodeuricomponent/index.html b/files/ko/web/javascript/reference/global_objects/decodeuricomponent/index.html new file mode 100644 index 0000000000..d263252cbf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/decodeuricomponent/index.html @@ -0,0 +1,92 @@ +--- +title: decodeURIComponent() +slug: Web/JavaScript/Reference/Global_Objects/decodeURIComponent +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/decodeURIComponent +--- +
{{jsSidebar("Objects")}}
+ +

decodeURIComponent() 함수는 {{jsxref("encodeURIComponent")}} 나 비슷한 방법으로 생성된 Uniform Resource Identifier(URI) 컴포넌트를 해독합니다.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-decodeuricomponent.html")}}
+ + + +

구문

+ +
decodeURIComponent(encodedURI)
+ +

매개변수

+ +
+
encodedURI
+
암호화된 Uniform Resource Identifier(URI) 컴포넌트.
+
+ +

반환 값

+ +

이스케이프되지 않은 특정 글자들 중 새로운 문자열.

+ +

예외

+ +

잘못 사용되었을 경우 {{jsxref ( "URIError")}} ( " malformed URI sequence ") 예외를 발생시킵니다.

+ +

설명

+ +

암호화된 URI 컴포넌트에서 각각의 이스케이프 시퀀스(확장 문자열)를 자신을 나타내는 문자로 바꿉니다.

+ +

예제

+ +

키릴문자 URL 컴포넌트의 복호화

+ +
decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
+// "JavaScript_шеллы"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의.
{{SpecName('ES5.1', '#sec-15.1.3.2', 'decodeURIComponent')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-decodeuricomponent-encodeduricomponent', 'decodeURIComponent')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-decodeuricomponent-encodeduricomponent', 'decodeURIComponent')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.decodeURIComponent")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/encodeuri/index.html b/files/ko/web/javascript/reference/global_objects/encodeuri/index.html new file mode 100644 index 0000000000..c5dff2ed37 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/encodeuri/index.html @@ -0,0 +1,111 @@ +--- +title: encodeURI() +slug: Web/JavaScript/Reference/Global_Objects/encodeURI +tags: + - JavaScript + - Reference + - URI + - URL +translation_of: Web/JavaScript/Reference/Global_Objects/encodeURI +--- +
{{jsSidebar("Objects")}}
+ +

encodeURI() 함수는 {{glossary("URI")}}의 특정한 문자를 UTF-8로 인코딩해 하나, 둘, 셋, 혹은 네 개의 연속된 이스케이프 문자로 나타냅니다. (두 개의 대리 문자로 이루어진 문자만 이스케이프 문자 네 개로 변환됩니다.)

+ +
{{EmbedInteractiveExample("pages/js/globalprops-encodeuri.html")}}
+ + + +

구문

+ +
encodeURI(URI)
+ +

매개변수

+ +
+
URI
+
완전한 URI.
+
+ +

반환 값

+ +

주어진 문자열을 URI로서 인코딩한 새로운 문자열.

+ +

설명

+ +

encodeURI() 함수는 URI에서 특별한 뜻을 가진 문자(예약 문자)는 인코딩 하지 않습니다. 아래 예제는 "URI 도식"이 포함할 수 있는 모든 부분을 담고 있습니다. 일부 문자가 어떤 방식으로 특별한 의미를 주입하고 있는지 잘 살펴보세요.

+ +
http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor
+ +

따라서 encodeURI()는 완전한 URI를 형성하는데 필요한 문자는 인코딩 하지 않습니다. 또한, 예약된 목적을 가지지는 않지만 URI가 그대로 포함할 수 있는 몇 가지 문자("비예약 표식")도 인코딩 하지 않습니다. (RFC 2396을 참고하세요)

+ +

encodeURI() 는 다음 문자를 제외한 문자를 이스케이프 합니다.

+ +
이스케이프 하지 않는 문자:
+
+    A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
+
+
+ +

encodeURI()와 {{jsxref("encodeURIComponent", "encodeURIComponent()")}}의 차이는 다음과 같습니다.

+ +
var set1 = ";,/?:@&=+$#"; // 예약 문자
+var set2 = "-_.!~*'()";   // 비예약 표식
+var set3 = "ABC abc 123"; // 알파벳 및 숫자, 공백
+
+console.log(encodeURI(set1)); // ;,/?:@&=+$#
+console.log(encodeURI(set2)); // -_.!~*'()
+console.log(encodeURI(set3)); // ABC%20abc%20123 (공백은 %20으로 인코딩)
+
+console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23
+console.log(encodeURIComponent(set2)); // -_.!~*'()
+console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (공백은 %20으로 인코딩)
+
+
+ +

encodeURI() 혼자서는 {{domxref("XMLHttpRequest")}} 등이 사용할, 적합한 HTTP {{httpmethod("GET")}}과 {{httpmethod("POST")}} 요청을 구성할 수 없습니다. GETPOST에서 특별한 문자로 취급하는 "&", "+", "="를 인코딩 하지 않기 때문입니다. 그러나 encodeURIComponent()는 저 세 문자도 인코딩 대상에 포함합니다.

+ +

상위-하위 쌍을 이루지 않은 단일 대리 문자를 인코딩 시도하면 {{jsxref("URIError")}}가 발생합니다.

+ +
// high-low pair ok
+console.log(encodeURIComponent('\uD800\uDFFF'));
+
+// lone high surrogate throws "URIError: malformed URI sequence"
+console.log(encodeURIComponent('\uD800'));
+
+// lone low surrogate throws "URIError: malformed URI sequence"
+console.log(encodeURIComponent('\uDFFF'));
+
+ +

또한, URL의 보다 최신 RFC인 RFC3986을 따르고자 한다면, 대괄호가 {{glossary("IPv6")}} 지원을 위해 추가로 예약됨에 따라 encodeURI()가 인코딩하지 않으므로 URL을 생성할 때 주의해야 합니다. 다음 예시 코드가 도움이 될 수도 있습니다.

+ +
function fixedEncodeURI(str) {
+    return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
+}
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-encodeuri-uri', 'encodeURI')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.encodeURI")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/encodeuricomponent/index.html b/files/ko/web/javascript/reference/global_objects/encodeuricomponent/index.html new file mode 100644 index 0000000000..191f66b198 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/encodeuricomponent/index.html @@ -0,0 +1,148 @@ +--- +title: encodeURIComponent() +slug: Web/JavaScript/Reference/Global_Objects/encodeURIComponent +tags: + - JavaScript + - Reference + - URI +translation_of: Web/JavaScript/Reference/Global_Objects/encodeURIComponent +--- +
{{jsSidebar("Objects")}}
+ +

encodeURIComponent() 함수는 {{glossary("URI")}}의 특정한 문자를 UTF-8로 인코딩해 하나, 둘, 셋, 혹은 네 개의 연속된 이스케이프 문자로 나타냅니다. (두 개의 대리 문자로 이루어진 문자만 이스케이프 문자 네 개로 변환됩니다.)

+ +
{{EmbedInteractiveExample("pages/js/globalprops-encodeuricomponent.html")}}
+ + + +

구문

+ +
encodeURIComponent(str);
+ +

매개변수

+ +
+
str
+
URI 구성요소.
+
+ +

반환 값

+ +

주어진 문자열을 URI 구성요소로서 인코딩한 새로운 문자열.

+ +

설명

+ +

encodeURIComponent()는 다음 문자를 제외한 문자를 이스케이프 합니다.

+ +
Not Escaped:
+
+    A-Z a-z 0-9 - _ . ! ~ * ' ( )
+
+
+ +

encodeURIComponent()와 {{jsxref("encodeURI", "encodeURI()")}}의 차이는 다음과 같습니다.

+ +
var set1 = ";,/?:@&=+$";  // Reserved Characters
+var set2 = "-_.!~*'()";   // Unescaped Characters
+var set3 = "#";           // Number Sign
+var set4 = "ABC abc 123"; // Alphanumeric Characters + Space
+
+console.log(encodeURI(set1)); // ;,/?:@&=+$
+console.log(encodeURI(set2)); // -_.!~*'()
+console.log(encodeURI(set3)); // #
+console.log(encodeURI(set4)); // ABC%20abc%20123 (the space gets encoded as %20)
+
+console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
+console.log(encodeURIComponent(set2)); // -_.!~*'()
+console.log(encodeURIComponent(set3)); // %23
+console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20)
+
+ +

상위-하위 쌍을 이루지 않은 단일 대리 문자를 인코딩 시도하면 {{jsxref("URIError")}}가 발생합니다.

+ +
// high-low pair ok
+console.log(encodeURIComponent('\uD800\uDFFF'));
+
+// lone high surrogate throws "URIError: malformed URI sequence"
+console.log(encodeURIComponent('\uD800'));
+
+// lone low surrogate throws "URIError: malformed URI sequence"
+console.log(encodeURIComponent('\uDFFF'));
+
+ +

encodeURIComponent()를 사용해, 서버에 {{HTTPMethod("POST")}}로 요청할 양식 필드를 인코딩 하세요. 입력 중 의도치 않게 생성될 수 있는 HTML 특수 개체 등의 "&" 문자를 처리할 수 있습니다.

+ +

예를 들어 사용자가 입력한 "Jack & Jill""Jack &amp; Jill"로 인코딩 됩니다. encodeURIComponent()를 사용하지 않았다면 서버가 앰퍼샌드를 새로운 필드의 시작으로 인식할 수 있으므로 데이터의 무결성을 해칠 수 있습니다.

+ +

application/x-www-form-urlencoded의 스페이스는 "+"로 치환되어야 하므로, encodeURIComponent()의 결과에 추가로 "%20""+"로 바꾸세요.

+ +

비록 URI의 구분자로서 형식화된 사용처는 없지만, 그럼에도 !, ', (, ), *을 추가로 예약하는 RFC 3986을 엄격하게 따르려면 아래의 코드를 사용해보세요.

+ +
function fixedEncodeURIComponent(str) {
+  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
+    return '%' + c.charCodeAt(0).toString(16);
+  });
+}
+
+ +

예제

+ +

다음 예제는 UTF-8 {{HTTPHeader("Content-Disposition")}} 과{{HTTPHeader("Link")}} 서버 응답 헤더에서 (UTF-8 파일 이름 등의 이유로) 필요한 문자 인코딩 방법을 보입니다.

+ +
var fileName = 'my file(2).txt';
+var header = "Content-Disposition: attachment; filename*=UTF-8''"
+             + encodeRFC5987ValueChars(fileName);
+
+console.log(header);
+// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
+
+
+function encodeRFC5987ValueChars(str) {
+    return encodeURIComponent(str).
+        // Note that although RFC3986 reserves "!", RFC5987 does not,
+        // so we do not need to escape it
+        replace(/['()]/g, escape). // i.e., %27 %28 %29
+        replace(/\*/g, '%2A').
+            // The following are not required for percent-encoding per RFC5987,
+            // so we can allow for a little better readability over the wire: |`^
+            replace(/%(?:7C|60|5E)/g, unescape);
+}
+
+// here is an alternative to the above function
+function encodeRFC5987ValueChars2(str) {
+  return encodeURIComponent(str).
+    // Note that although RFC3986 reserves "!", RFC5987 does not,
+    // so we do not need to escape it
+    replace(/['()*]/g, c => "%" + c.charCodeAt(0).toString(16)). // i.e., %27 %28 %29 %2a (Note that valid encoding of "*" is %2A
+                                                                 // which necessitates calling toUpperCase() to properly encode)
+    // The following are not required for percent-encoding per RFC5987,
+    // so we can allow for a little better readability over the wire: |`^
+    replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(parseInt(hex, 16)));
+}
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-encodeuricomponent-uricomponent', 'encodeURIComponent')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.encodeURIComponent")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/error/index.html b/files/ko/web/javascript/reference/global_objects/error/index.html new file mode 100644 index 0000000000..986cb5afa0 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/error/index.html @@ -0,0 +1,240 @@ +--- +title: Error +slug: Web/JavaScript/Reference/Global_Objects/Error +tags: + - Error + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Error +--- +
{{JSRef}}
+ +

Error 생성자는 오류 객체를 생성합니다. Error 객체의 인스턴스는 런타임 오류가 발생했을 때 던져집니다. Error 객체를 사용자 지정 예외의 기반 객체로 사용할 수도 있습니다.

+ +

구문

+ +
new Error([message[, fileName[, lineNumber]]])
+ +

매개변수

+ +
+
message {{optional_inline}}
+
사람이 읽을 수 있는, 오류에 대한 설명.
+
fileName {{optional_inline}} {{non-standard_inline}}
+
생성할 Error 객체의 fileName 속성 값. 기본값은 Error 생성자를 호출한 코드를 포함하고 있는 파일의 이름입니다.
+
lineNumber {{optional_inline}} {{non-standard_inline}}
+
생성할 Error 객체의 lineNumber 속성 값. 기본값은 Error 생성자 호출을 포함한 줄 번호입니다.
+
+ +

설명

+ +

런타임 오류는 새로운 Error 객체를 생성하고 던집니다.

+ +

이 페이지는 Error 오브젝트 자체와, 생성자 함수로서의 사용처를 다룹니다. Error 인스턴스가 상속하는 속성과 메서드는 {{jsxref("Error.prototype")}}을 참고하세요.

+ +

함수로 사용

+ +

Error를 {{jsxref("Operators/new", "new")}} 없이 함수로 사용하면 Error 객체를 반환합니다. 즉 Error를 직접 호출해도 인스턴스를 만드는 것과 동일한 결과를 얻을 수 있습니다.

+ +
// 이렇게 호출하는 것과
+const x = Error('I was created using a function call!');
+​​​​// 이렇게 사용하는게 동일
+const y = new Error('I was constructed via the "new" keyword!');
+
+ +

오류 유형

+ +

JavaScript에는 일반적인 Error 생성자 외에도 7개의 중요 오류 생성자가 존재합니다. 클라이언트측 예외에 대해서는 제어 흐름과 에러 처리를 참고하세요.

+ +
+
{{jsxref("EvalError")}}
+
전역 함수 {{jsxref("eval", "eval()")}}에서 발생하는 오류의 인스턴스를 생성합니다.
+
{{jsxref("InternalError")}} {{non-standard_inline}}
+
JavaScript 엔진의 내부에서 오류가 발생했음을 나타내는 오류 인스턴스를 생성합니다.
+
{{jsxref("RangeError")}}
+
숫자 변수나 매개변수가 유효한 범위를 벗어났음을 나타내는 오류 인스턴스를 생성합니다.
+
{{jsxref("ReferenceError")}}
+
잘못된 참조를 했음을 나타내는 오류 인스턴스를 생성합니다.
+
{{jsxref("SyntaxError")}}
+
{{jsxref("eval", "eval()")}}이 코드를 분석하는 중 잘못된 구문을 만났음을 나타내는 오류 인스턴스를 생성합니다.
+
{{jsxref("TypeError")}}
+
변수나 매개변수가 유효한 자료형이 아님을 나타내는 오류 인스턴스를 생성합니다.
+
{{jsxref("URIError")}}
+
{{jsxref("encodeURI", "encodeURI()")}}나 {{jsxref("decodeURI", "decodeURl()")}} 함수에 부적절한 매개변수를 제공했을 때 발생하는 오류의 인스턴스를 생성합니다.
+
+ +

속성

+ +
+
{{jsxref("Error.prototype")}}
+
Error 인스턴스에 속성을 추가할 수 있습니다.
+
+ +

메서드

+ +

전역 Error 객체는 자신의 메서드를 가지지 않습니다. 그러나 프로토타입 체인을 통해 일부 메서드를 상속받습니다.

+ +

Error 인스턴스

+ +
{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Error/prototype', '설명')}}
+ +

속성

+ +
{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Error/prototype', '속성')}}
+ +

메서드

+ +
{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Error/prototype', '메서드')}}
+ +

예제

+ +

일반적인 오류 던지기

+ +

Error 객체를 생성한 후엔 대개 {{jsxref("Statements/throw", "throw")}} 키워드를 이용해 던집니다. {{jsxref("Statements/try...catch", "try...catch")}} 구문을 이용하여 오류를 처리할 수 있습니다.

+ +
try {
+  throw new Error("이런!");
+} catch (e) {
+  alert(e.name + ": " + e.message);
+}
+
+ +

특정 오류 처리하기

+ +

this should probably be removed오류의 {{jsxref("Object.prototype.constructor", "constructor")}} 속성을 판별해 특정 오류에 대해서만 처리를 할 수 있습니다. 현대적인 JavaScript 엔진의 코드를 작성한다면 {{jsxref("Operators/instanceof", "instanceof")}} 키워드를 이용할 수도 있습니다.

+ +
try {
+  foo.bar();
+} catch (e) {
+  if (e instanceof EvalError) {
+    alert(e.name + ": " + e.message);
+  } else if (e instanceof RangeError) {
+    alert(e.name + ": " + e.message);
+  }
+  // ... etc
+}
+
+ +

사용자 정의 에러 타입

+ +

throw new MyError() 이후 instanceof MyError로 직접 만든 오류를 판별할 수 있도록 Error의 파생 오류 정의를 고려해보세요. 더 깔끔하고 일관적인 오류 처리 코드를 작성할 수 있습니다. StackOverflow의 "What's a good way to extend Error in JavaScript?"를 방문해 심도 있는 논의를 읽어보세요.

+ +

ES6 사용자 정의 오류 클래스

+ +
+

Babel 버전 7 미만으로 사용자 정의 오류 클래스를 처리하려면 {{jsxref("Object.defineProperty()")}} 메서드를 사용해 정의해야만 합니다. 그렇지 않으면 오래된 Babel 및 다른 트랜스파일러가 추가 설정 없이 코드를 처리할 수 없습니다.

+
+ +
+

ES2015 클래스를 사용할 때, 일부 브라우저는 CustomError 생성자를 스택 트레이스에 포함합니다.

+
+ +
class CustomError extends Error {
+  constructor(foo = 'bar', ...params) {
+    // Pass remaining arguments (including vendor specific ones) to parent constructor
+    super(...params);
+
+    // Maintains proper stack trace for where our error was thrown (only available on V8)
+    if (Error.captureStackTrace) {
+      Error.captureStackTrace(this, CustomError);
+    }
+
+    // Custom debugging information
+    this.foo = foo;
+    this.date = new Date();
+  }
+}
+
+try {
+  throw new CustomError('baz', 'bazMessage');
+} catch(e){
+  console.log(e.foo); //baz
+  console.log(e.message); //bazMessage
+  console.log(e.stack); //stacktrace
+}
+ +

ES5 사용자 정의 오류 객체

+ +
+

프로토타입 선언을 사용하면 모든 브라우저가 CustomError 생성자를 스택 트레이스에 포함합니다.

+
+ +
function CustomError(foo, message, fileName, lineNumber) {
+  var instance = new Error(message, fileName, lineNumber);
+  instance.foo = foo;
+  Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
+  if (Error.captureStackTrace) {
+    Error.captureStackTrace(instance, CustomError);
+  }
+  return instance;
+}
+
+CustomError.prototype = Object.create(Error.prototype, {
+  constructor: {
+    value: Error,
+    enumerable: false,
+    writable: true,
+    configurable: true
+  }
+});
+
+if (Object.setPrototypeOf){
+  Object.setPrototypeOf(CustomError, Error);
+} else {
+  CustomError.__proto__ = Error;
+}
+
+
+try {
+  throw new CustomError('baz', 'bazMessage');
+} catch(e){
+  console.log(e.foo); //baz
+  console.log(e.message) ;//bazMessage
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.11', 'Error')}}{{Spec2('ES5.1')}} 
{{SpecName('ES2015', '#sec-error-objects', 'Error')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Error")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/error/name/index.html b/files/ko/web/javascript/reference/global_objects/error/name/index.html new file mode 100644 index 0000000000..bca8a4937f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/error/name/index.html @@ -0,0 +1,72 @@ +--- +title: Error.prototype.name +slug: Web/JavaScript/Reference/Global_Objects/Error/name +translation_of: Web/JavaScript/Reference/Global_Objects/Error/name +--- +
{{JSRef}}
+ +
name 프로퍼티는 에러 타입을 설명하기 위한 이름을 나타냅니다. 초기값은 "Error"입니다.
+ +

설명

+ +

{{jsxref("Error")}} 인스턴스는 주어진 이름인 "Error"를 기본 값으로 갖습니다. name 프로퍼티는 {{jsxref("Error.prototype.message", "message")}}와 함께 {{jsxref("Error.prototype.toString()")}}에서 사용되며 해당 에러를 문자열로 표현합니다.

+ +

예제

+ +

사용자 정의 에러 발생시키기

+ +
var e = new Error('Malformed input'); // e.name은 'Error'
+
+e.name = 'ParseError';
+throw e;
+// e.toString()은 'ParseError: Malformed input'을 반환합니다
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.11.4.2', 'Error.prototype.name')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error.prototype.name', 'Error.prototype.name')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error.prototype.name', 'Error.prototype.name')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
+
+ + +

{{Compat("javascript.builtins.Error.name")}}

+
+
+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/global_objects/eval/index.html b/files/ko/web/javascript/reference/global_objects/eval/index.html new file mode 100644 index 0000000000..000c8b2228 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/eval/index.html @@ -0,0 +1,285 @@ +--- +title: eval() +slug: Web/JavaScript/Reference/Global_Objects/eval +tags: + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/eval +--- +
{{jsSidebar("Objects")}}
+ +
+

주의: 문자열로부터 eval()을 실행하는 것은 엄청나게 위험합니다. eval()을 사용하면 해커가 위험한 코드를 사용할 수 있습니다. 아래에 eval을 절대 사용하지 말 것!을 확인하세요.

+
+ +

eval()은 문자로 표현된 JavaScript 코드를 실행하는 함수입니다.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-eval.html")}}
+ +

구문

+ +
eval(string)
+ +

매개변수

+ +
+
string
+
자바스크립트 표현식, 명령문, 또는 연속되는 다수의 명령문을 나타내는 문자열. 표현식은 이미 존재하는 객체의 변수나 속성을 포함할 수 있습니다.
+
+ +

반환값

+ +

주어진 코드를 평가하여 얻은 값. 값이 없다면 {{jsxref("undefined")}}를 반환합니다.

+ +

설명

+ +

eval()은 전역 객체의 함수 속성입니다.

+ +

eval()의 인자는 문자열입니다. 인자가 표현식을 나타낸다면 eval()은 표현식을 평가합니다. 인자가 하나 이상의 JavaScript 명령문을 나타낸다면 모두 실행합니다. 연산식을 계산하기 위해 eval()을 호출하지 마세요. 자바스크립트는 연산식을 알아서 계산합니다.

+ +

문자열로 연산식을 구성하면 나중에 eval()로 계산할 수 있습니다. x 라는 변수가 있다고 가정하면 x가 포함된 연산식을 문자열로, 예를 들어 "3 * x + 2"로 나타내고 나중에 eval()을 호출해서 계산을 연기할 수 있습니다.

+ +

eval()의 인자가 문자열이 아니면 eval()은 인자를 그대로 반환합니다. 다음 예시에서, String 생성자가 명시된 경우 문자열을 계산하는 대신 String 객체를 반환합니다.

+ +
eval(new String("2 + 2")); // "2 + 2"를 포함한 String 객체를 반환
+eval("2 + 2");             // 4를 반환
+
+ +

toString()을 사용하는 일반적인 방식으로 제약을 피할 수 있습니다.

+ +
var expression = new String("2 + 2");
+eval(expression.toString());            // 4를 반환
+
+ +

eval을 직접 호출하지 않고 참조를 통해 간접적으로 사용한다면 ECMAScript 5부터는 지역 범위가 아니라 전역 범위에서 동작합니다. 예를 들어 eval()로 함수를 선언하면 전역 함수가 되고, 실행되는 코드는 실행되는 위치의 지역 범위에 접근할 수 없습니다.

+ +
function test() {
+  var x = 2, y = 4;
+  console.log(eval('x + y'));  // 직접 호출, 지역 범위 사용, 결과값은 6
+  var geval = eval; // eval을 전역 범위로 호출하는 것과 같음
+  console.log(geval('x + y')); // 간접 호출, 전역 범위 사용, `x`가 정의되지 않았으므로 ReferenceError 발생
+  (0, eval)('x + y'); // 다른 방식으로 간접 호출
+}
+ +

eval을 절대 사용하지 말 것!

+ +

eval()은 인자로 받은 코드를 caller의 권한으로 수행하는 위험한 함수입니다. 악의적인 영향을 받았을 수 있는 문자열을 eval()로 실행한다면, 당신의 웹페이지나 확장 프로그램의 권한으로 사용자의 기기에서 악의적인 코드를 수행하는 결과를 초래할 수 있습니다. 또한, 제3자 코드가 eval()이 호출된 위치의 스코프를 볼 수 있으며, 이를 이용해 비슷한 함수인 {{jsxref("Global_Objects/Function", "Function")}}으로는 실현할 수 없는 공격이 가능합니다.

+ +

또한 최신 JS 엔진에서 여러 코드 구조를 최적화하는 것과 달리 eval()은 JS 인터프리터를 사용해야 하기 때문에 다른 대안들보다 느립니다.

+ +

추가로, 최신 JavaScript 인터프리터는 자바스크립트를 기계 코드로 변환합니다. 즉, 변수명의 개념이 완전히 없어집니다. 그러나 eval을 사용하면 브라우저는 기계 코드에 해당 변수가 있는지 확인하고 값을 대입하기 위해 길고 무거운 변수명 검색을 수행해야 합니다. 또한 eval()을 통해 자료형 변경 등 변수에 변화가 일어날 수 있으며, 브라우저는 이에 대응하기 위해 기계 코드를 재작성해야 합니다. 그러나, (다행히) window.Function이라는 eval보다 훨씬 나은 대안이 있습니다. eval()을 사용하는 코드를 Function()으로 바꾸는 방법에 대해서는 아래를 참조하세요.

+ +

eval을 사용하는 나쁜 코드:

+ +
function looseJsonParse(obj){
+    return eval(obj);
+}
+console.log(looseJsonParse(
+   "{a:(4-1), b:function(){}, c:new Date()}"
+))
+
+ +

eval이 없는 코드:

+ +
function looseJsonParse(obj){
+    return Function('"use strict";return (' + obj + ')')();
+}
+console.log(looseJsonParse(
+   "{a:(4-1), b:function(){}, c:new Date()}"
+))
+
+ +

위의 두 코드는 얼핏 보면 같은 방식으로 실행되는 것처럼 보이지만, eval이 있는 코드가 훨씬 느립니다. 평가되는 객체의 c: new Date()를 주목하세요. eval이 없는 함수의 경우 이 객체는 전역 범위에서 평가되기 때문에 브라우저에서는 Date를 같은 이름의 지역 변수가 아니라 window.Date로 취급할 수 있습니다. 그러나 eval()을 사용하는 코드에서는 아래와 같은 경우도 존재할 수 있기 때문에 Date를 이렇게 취급할 수 없습니다.

+ +
function Date(n){
+    return ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][n%7 || 0];
+}
+function looseJsonParse(obj){
+    return eval(obj);
+}
+console.log(looseJsonParse(
+   "{a:(4-1), b:function(){}, c:new Date()}"
+))
+
+ +

그러므로 eval()이 있는 코드의 경우 브라우저는 Date()라는 지역 변수의 존재를 확인하기 위해 무거운 변수명 탐색을 수행해야 하며, 이는 Function()과 비교하면 매우 느립니다.

+ +

만약 위의 상황에서 실제로 새로 선언한 Date 함수를 Function()에서 실행해야 하는 상황을 생각해 봅시다. 이렇게 되면 eval()로 돌아가야 할까요? 물론 아닙니다. 아래의 접근을 시도해 보세요.

+ +
function Date(n){
+    return ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][n%7 || 0];
+}
+function runCodeWithDateFunction(obj){
+    return Function('"use strict";return (' + obj + ')')()(
+        Date
+    );
+}
+console.log(runCodeWithDateFunction(
+   "function(Date){ return Date(5) }"
+))
+
+ +

위 코드는 삼중 중첩 함수를 사용하기 때문에 매우 비효율적으로 보일 수 있지만, 이 방법의 이점을 우선 살펴봅시다.

+ +

1. runCodeWithDateFunction에 문자열로 전달된 코드를 최소화minify할 수 있다.

+ +

2. Function call overhead is minimal, making the far smaller code size well worth the benefit

+ +

3. Function()"use strict";를 사용함으로써 코드의 성능을 최적화할 수 있다.

+ +

4. eval()을 사용하지 않으므로 실행 속도가 훨씬 빠르다.

+ +

마지막으로 코드 최소화의 측면에서 살펴보면, 위와 같이 Function()을 사용했을 때는 아래의 최소화된 코드와 같이 함수의 인자 이름 역시 짧게 줄일 수 있으므로 runCodeWithDateFunction에 전달하는 코드 문자열을 더욱 효율적으로 줄일 수 있습니다.

+ +
console.log(Function('"use strict";return(function(a){return a(5)})')()(function(a){
+return"Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" ")[a%7||0]}));
+ +

자주 쓰이는 용례에 대해서는 eval()이나 Function()보다 안전하고 빠른 대안도 존재합니다.

+ +

객체의 속성에 접근하기

+ +

속성명으로 속성을 찾는 데 eval()을 사용해서는 안 됩니다. 다음 예제와 같이 코드를 실행하기 전까지는 접근할 속성을 알 수 없는 상황을 생각해 봅시다. 이 상황은 eval로 처리할 수 있습니다.

+ +
var obj = { a: 20, b: 30 };
+var propname = getPropName();  // "a" 또는 "b"를 반환
+
+eval( "var result = obj." + propname );
+
+ +

그러나 여기에서 eval()을 쓸 필요가 없고, 지양되어야 합니다. 그 대신 훨씬 빠르고 안전한 속성 접근자를 사용하여야 합니다.

+ +
var obj = { a: 20, b: 30 };
+var propname = getPropName();  // "a" 또는 "b"를 반환
+var result = obj[ propname ];  //  obj[ "a" ]는 obj.a와 동일함
+
+ +

이 방법으로 더 깊은 속성에도 접근할 수 있습니다. eval()을 사용한다면 다음과 같을 것입니다.

+ +
var obj = {a: {b: {c: 0}}};
+var propPath = getPropPath();  // "a.b.c"를 반환한다고 가정
+
+eval( 'var result = obj.' + propPath );
+ +

여기서 eval()의 사용을 피하려면 속성 경로를 split한 다음 순서대로 접근할 수도 있습니다.

+ +
function getDescendantProp(obj, desc) {
+  var arr = desc.split('.');
+  while (arr.length) {
+    obj = obj[arr.shift()];
+  }
+  return obj;
+}
+
+var obj = {a: {b: {c: 0}}};
+var propPath = getPropPath();  // "a.b.c"를 반환한다고 가정
+var result = getDescendantProp(obj, propPath);
+ +

속성에 값을 대입하는 것도 비슷하게 할 수 있습니다.

+ +
function setDescendantProp(obj, desc, value) {
+  var arr = desc.split('.');
+  while (arr.length > 1) {
+    obj = obj[arr.shift()];
+  }
+  return obj[arr[0]] = value;
+}
+
+var obj = {a: {b: {c: 0}}};
+var propPath = getPropPath();  // "a.b.c"를 반환한다고 가정
+var result = setDescendantProp(obj, propPath, 1);  // test.a.b.c의 값은 1로 지정됨
+
+ +

단편적인 코드 수행 대신 함수 사용하기

+ +

JavaScript의 함수는 1급 객체이므로 다른 API에 함수를 인자로 전달할 수도 있고, 변수나 객체의 속성으로 대입할 수도 있습니다. 다수의 DOM API는 이 점을 염두에 두고 설계되므로, 다음과 같이 코드를 짜야 합니다.

+ +
// setTimeout(" ... ", 1000) 대신에
+setTimeout(function() { ... }, 1000);
+
+// elt.setAttribute("onclick", "...") 대신에
+elt.addEventListener("click", function() { ... } , false); 
+ +

또한 클로저를 이용해 문자열을 합치는 등의 연산 없이 매개변수화된 함수를 생성할 수 있습니다.

+ +

JSON 파싱 (문자열을 JavaScript 객체로 변환)

+ +

eval()을 호출하려는 문자열에 코드가 아니라 데이터가 포함되어 있다면(예를 들어 "[1, 2, 3]"과 같은 배열), 대신 JavaScript의 문법 일부를 이용해 문자열로 데이터를 표현할 수 있는 JSON을 사용하는 것을 고려해 보세요. Downloading JSON and JavaScript in extensions도 참고해 보세요.

+ +

JSON 문법은 JavaScript 문법에 비해 제약이 있기 때문에, 유효한 JavaScript 리터럴이 JSON으로 변환되지 않는 경우도 있습니다. 예를 들어, JSON에서는 배열이나 객체를 콤마로 끝낼 수 없고, 객체 리터럴에서 속성명(키)은 반드시  따옴표로 감싸야 합니다. 나중에 JSON으로 파싱할 문자열을 생성할 때는 JSON 직렬 변환기JSON serializer를 사용하여야 합니다.

+ +

코드 대신 데이터 전달하기

+ +

예를 들어, 웹 페이지의 내용을 추출하는 확장 프로그램은 JavaScript 코드 대신 XPath에 스크랩 규칙을 정의할 수 있습니다.

+ +

제한된 권한으로 코드 실행하기

+ +

제3자 코드를 실행해야 할 때는 제한된 권한으로 실행하는 것을 고려해야 합니다. 이는 주로 확장 프로그램이나 XUL 어플리케이션에 적용되며, 이때 Components.utils.evalInSandbox를 사용할 수 있습니다.

+ +

예제

+ +

eval 사용하기

+ +

아래 코드에서 eval()를 포함하는 문장은 모두 42를 반환합니다. 전자는 문자열 "x + y + 1"을, 후자는 문자열 "42"를 평가합니다.

+ +
var x = 2;
+var y = 39;
+var z = "42";
+eval("x + y + 1"); // 42를 반환
+eval(z);           // 42를 반환
+
+ +

eval을 사용해서 JavaScript 코드 문자열 평가하기

+ +

다음 예제에서는 eval()을 사용하여 str 문자열을 평가합니다. 이 문자열은 x가 5이면 로그를 출력한 다음 z에 42를 할당하고, 그렇지 않으면 z에 0 을 할당하는 JavaScript 코드입니다. 두 번째 문장이 실행되면, eval()은 이 문장의 집합을 수행하고, z에 할당된 값을 반환합니다.

+ +
var x = 5;
+var str = "if (x == 5) {console.log('z is 42'); z = 42;} else z = 0; ";
+
+console.log("z is ", eval(str));
+ +

여러 값을 정의할 경우 마지막 값을 반환합니다.

+ +
var x = 5;
+var str = "if (x == 5) {console.log('z is 42'); z = 42; x = 420; } else z = 0;";
+
+console.log('x is ', eval(str)); // z는 42, x는 420
+ +

마지막 표현식이 수행된다

+ +

eval() 은 마지막 표현식의 평가값을 반환합니다.

+ +
var str = "if ( a ) { 1+1; } else { 1+2; }";
+var a = true;
+var b = eval(str);  // 2를 반환
+
+console.log("b is : " + b);
+
+a = false;
+b = eval(str);  // 3을 반환
+
+console.log("b is : " + b);
+ +

함수 정의 문자열로서의 eval 은 앞뒤를 "("와 ")"로 감싸야 한다

+ +
var fctStr1 = "function a() {}"
+var fctStr2 = "(function a() {})"
+var fct1 = eval(fctStr1)  // undefined를 반환
+var fct2 = eval(fctStr2)  // 함수를 반환
+
+ +

+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.eval")}}

+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/global_objects/evalerror/index.html b/files/ko/web/javascript/reference/global_objects/evalerror/index.html new file mode 100644 index 0000000000..4c8fcf38dd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/evalerror/index.html @@ -0,0 +1,112 @@ +--- +title: EvalError +slug: Web/JavaScript/Reference/Global_Objects/EvalError +tags: + - Error + - EvalError + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/EvalError +--- +
{{JSRef}}
+ +

EvalError 객체는 전역 {{jsxref("Global_Objects/eval", "eval()")}} 함수에 관한 오류를 나타냅니다. 이 예외는 JavaScript에 의해 더 이상 발생하지 않지만 EvalError 객체는 하위 호환성을 위해 남아있습니다.

+ +

구문

+ +
new EvalError([message[, fileName[, lineNumber]]])
+ +

매개변수

+ +
+
message {{optional_inline}}
+
인간이 읽을 수 있는 오류 설명.
+
fileName {{optional_inline}} {{non-standard_inline}}
+
예외의 원인이 된 코드를 포함하는 파일의 이름.
+
lineNumber {{optional_inline}} {{non-standard_inline}}
+
예외를 발생시킨 코드의 행 번호.
+
+ +

속성

+ +
+
{{jsxref("EvalError.prototype")}}
+
EvalError 객체에 속성을 추가할 수 있습니다.
+
+ +

메서드

+ +

전역 EvalError에는 자체 메서드가 없지만 프로토 타입 체인을 통해 일부 메서드를 상속받습니다.

+ +

EvalError 인스턴스

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError/prototype', 'Properties')}}
+ +

Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError/prototype', 'Methods')}}
+ +

예제

+ +

EvalError는 현재 ECMAScript 사양에서 사용되지 않으므로 런타임에 의해 throw되지 않습니다. 그러나 개체 자체는 이전 버전의 사양과의 하위 호환성을 유지합니다.

+ +

Creating an EvalError

+ +
try {
+  throw new EvalError('Hello', 'someFile.js', 10);
+} catch (e) {
+  console.log(e instanceof EvalError); // true
+  console.log(e.message);              // "Hello"
+  console.log(e.name);                 // "EvalError"
+  console.log(e.fileName);             // "someFile.js"
+  console.log(e.lineNumber);           // 10
+  console.log(e.columnNumber);         // 0
+  console.log(e.stack);                // "@Scratchpad/2:2:9\n"
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.11.6.1', 'EvalError')}}{{Spec2('ES5.1')}}Not used in this specification. Present for backward compatibility.
{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-evalerror', 'EvalError')}}{{Spec2('ES6')}}Not used in this specification. Present for backward compatibility.
{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-evalerror', 'EvalError')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.EvalError")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/function/apply/index.html b/files/ko/web/javascript/reference/global_objects/function/apply/index.html new file mode 100644 index 0000000000..1e59ed07f7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/apply/index.html @@ -0,0 +1,236 @@ +--- +title: Function.prototype.apply() +slug: Web/JavaScript/Reference/Global_Objects/Function/apply +tags: + - Function + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply +--- +
{{JSRef}}
+ +

apply() 메서드는 주어진 this 값과 배열 (또는 유사 배열 객체) 로 제공되는 arguments 로 함수를 호출합니다.

+ +
+

참고: 이 함수의 구문은 거의 {{jsxref("Function.call", "call()")}} 구문과 유사합니다. 근본적인 차이점은  call() 은 함수에 전달될 인수 리스트를 받는데 비해, apply()인수들의 단일 배열을 받는다는 점입니다.

+
+ +

{{EmbedInteractiveExample("pages/js/function-apply.html")}}

+ + + +

구문

+ +
func.apply(thisArg, [argsArray])
+ +

매개변수

+ +
+
thisArg
+
옵션. func 를 호출하는데 제공될 this 의 값. this 는 메소드에 의해 실제로 보여지는 값이 아닐 수 있음을 유의합니다. 메소드가 {{jsxref("Strict_mode", "non-strict mode", "", 1)}} 코드의 함수일 경우, {{jsxref("null")}} 과 {{jsxref("undefined")}} 가 전역 객체로 대체되며, 기본 값은 제한됩니다.
+
argsArray
+
옵션. func 이 호출되어야 하는 인수를 지정하는 유사 배열 객체, 함수에 제공된 인수가 없을 경우 {{jsxref("null")}} 또는 {{jsxref("undefined")}}. ECMAScript 5 의 시작으로 이러한 인수들은 배열 대신 제네릭 유사 배열 객체로 사용될 수 있습니다. 아래의 {{anch("Browser_compatibility", "브라우저 호환성")}} 정보를 보세요.
+
+ +

반환값

+ +

지정한 this 값과 인수들로 호출한 함수의 결과.

+ +

설명

+ +

이미 존재하는 함수를 호출할 때 다른 this 객체를 할당할 수 있습니다. this 는 현재 객체, 호출하는 객체를 참조합니다. apply 를 사용해, 새로운 객체마다 메소드를 재작성할 필요없이 한 번만 작성해 다른 객체에 상속시킬 수 있습니다.

+ +

apply 는 지원되는 인수의 타입만 제외하면 {{jsxref("Function.call", "call()")}} 과 매우 유사합니다. 인수(파라미터)의 리스트 대신 인수들의 배열을 사용할 수 있습니다. 또한 apply 를 사용해, 배열 리터럴이나 (예, func.apply(this, ['eat', 'bananas']), {{jsxref("Array")}} 객체 (예, func.apply(this, new Array('eat', 'bananas'))) 를 사용할 수 있습니다.

+ + + +

argsArray 파라미터를 위한 {{jsxref("Functions/arguments", "arguments")}} 를 사용할 수도 있습니다. arguments 는 함수의 지역 변수입니다. 이는 호출된 객체의 지정되지 않은 모든 인수에 대해 사용할 수 있습니다. 따라서, apply 메소드를 사용할 때 호출된 객체의 인수를 알 필요가 없습니다. arguments 를 사용해 모든 인수들을 호출된 객체로 전달할 수 있습니다. 그럼 호출된 객체는 그 인수들을 처리할 수 있게 됩니다.

+ + + +

ECMAScript 5번 째 판의 시작으로, 모든 유사 배열 객체 타입을 사용할 수 있으며, 실제로 이는 프로퍼티 length 와 범위 (0..length-1) 내의 정수 프로퍼티를 갖는 다는 것을 의미합니다. 예를 들면, 이제 {{domxref("NodeList")}} 또는 { 'length': 2, '0': 'eat', '1': 'bananas' } 와 같은 커스텀 객체를 사용할 수 있습니다.

+ +
Chrome 14와 Internet Explorer 9를 포함한 대부분의 브라우저는 아직 유사배열객체를 apply에 사용할 수 없으며 오류가 출력됩니다.
+ +

예제

+ +

배열에 배열을 붙이기 위해 apply 사용하기

+ +

push 를 사용하여 요소를 배열에 추가 할 수 있습니다. push 는 가변 인수를 허용하기 때문에 여러 요소를 동시에 추가 할 수 있습니다. 그러나 push 에 배열을 전달하면 요소를 개별적으로 추가하는 대신 실제로 해당 배열을 단일 요소로 추가하므로 결국 배열 내부에 배열로 끝납니다. 그것이 우리가 원하는 것이 아니라면? 이 경우 concat 은 우리가 원하는 동작을 하지만 실제로는 기존 배열에 추가되지 않고 새 배열을 만들어 반환 합니다. 그러나 우리는 기존 배열에 추가하고 싶었습니다 ... 그럼 이제 어쩌죠? 루프를 작성 할까요? 분명히 아니죠?

+ +

방법은 apply !

+ +
var array = ['a', 'b'];
+var elements = [0, 1, 2];
+array.push.apply(array, elements);
+console.info(array); // ["a", "b", 0, 1, 2]
+
+ +

apply 와 내장함수 사용

+ +

apply 를 보다 효과적으로 이용하면 일부 내장 함수는 어떤 작업에 대해서는 배열과 루프없이 쉽게 처리됩니다. 다음 예제에서는 배열에서 최대값과 최소값을 구하기 위해 Math.max/Math.min 함수를 이용하고 있습니다.

+ +
// min/max number in an array
+var numbers = [5, 6, 2, 3, 7];
+
+// using Math.min/Math.max apply
+var max = Math.max.apply(null, numbers);
+// 이는 Math.max(numbers[0], ...) 또는 Math.max(5, 6, ...)
+// 와 거의 같음
+
+var min = Math.min.apply(null, numbers);
+
+// vs. simple loop based algorithm
+max = -Infinity, min = +Infinity;
+
+for (var i = 0; i < numbers.length; i++) {
+  if (numbers[i] > max) {
+    max = numbers[i];
+  }
+  if (numbers[i] < min) {
+    min = numbers[i];
+  }
+}
+
+ +

하지만 이러한 방식으로 apply 를 사용하는 경우 주의해야 합니다. JavaScript 엔진의 인수 길이 제한을 초과하는 위험성에 대해 이해할 필요가 있습니다. 함수에 너무 많은(대략 몇 만개 이상) 인수를 줄 때의 상황은 엔진마다 다른데(예를 들어 JavaScriptCore의 경우 인수의 개수 제한은 65536), 상한이 특별히 정해져 있지 않기 때문입니다. 어떤 엔진은 예외를 던집니다. 더 심한 경우는 실제 함수에 인수를 전달했음에도 불구하고 참조할 수 있는 인수의 수를 제한하고 있는 경우도 있습니다(이러한 엔진에 대해 더 자세히 설명하면, 그 엔진이 arguments의 상한을 4개로 했다고 하면[실제 상한은 물론 더 위일 것입니다], 위 예제 코드의 전체 배열이 아니라 5, 6, 2, 3 만 apply 에 전달되어 온 것처럼 작동합니다).

+ +

만약 사용하는 배열 변수의 수가 수만을 초과하는 경우에는 복합적인 전략을 강구해야할 것입니다:한 번에 전달할 배열을 분할하여 사용하기:

+ +
function minOfArray(arr) {
+  var min = Infinity;
+  var QUANTUM = 32768;
+
+  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
+    var submin = Math.min.apply(null,
+                                arr.slice(i, Math.min(i + QUANTUM, len)));
+    min = Math.min(submin, min);
+  }
+
+  return min;
+}
+
+var min = minOfArray([5, 6, 2, 3, 7]);
+
+
+ + + +

생성자 체이닝을 위한 apply 사용

+ +

Java 와 유사하게, 객체를 위한 {{jsxref("Operators/new", "constructors", "", 1)}} 체이닝을 위해 apply 를 사용할 수 있습니다. 다음 예제에서 인수 리스트 대신 생성자로 유사 배열 객체를 사용할 수 있게 해주는 construct 라는 전역 {{jsxref("Function")}} 메소드를 생성할 것입니다. 

+ +
Function.prototype.construct = function(aArgs) {
+  var oNew = Object.create(this.prototype);
+  this.apply(oNew, aArgs);
+  return oNew;
+};
+ +
+

알림: 위에서 사용된 Object.create() 메소드는 상대적으로 새로운 것입니다. 대안으로, 다음 접근법 중 하나를 고려하세요.

+ +

{{jsxref("Object/__proto__", "Object.__proto__")}} 사용

+ +
Function.prototype.construct = function (aArgs) {
+  var oNew = {};
+  oNew.__proto__ = this.prototype;
+  this.apply(oNew, aArgs);
+  return oNew;
+};
+ +

클로져 사용:

+ +
Function.prototype.construct = function(aArgs) {
+  var fConstructor = this, fNewConstr = function() {
+    fConstructor.apply(this, aArgs);
+  };
+  fNewConstr.prototype = fConstructor.prototype;
+  return new fNewConstr();
+};
+ +

{{jsxref("Function")}} 생성자 사용

+ +
Function.prototype.construct = function (aArgs) {
+  var fNewConstr = new Function("");
+  fNewConstr.prototype = this.prototype;
+  var oNew = new fNewConstr();
+  this.apply(oNew, aArgs);
+  return oNew;
+};
+
+ +

사용 예제

+ +
function MyConstructor() {
+  for (var nProp = 0; nProp < arguments.length; nProp++) {
+    this['property' + nProp] = arguments[nProp];
+  }
+}
+
+var myArray = [4, 'Hello world!', false];
+var myInstance = MyConstructor.construct(myArray);
+
+console.log(myInstance.property1);                // logs 'Hello world!'
+console.log(myInstance instanceof MyConstructor); // logs 'true'
+console.log(myInstance.constructor);              // logs 'MyConstructor'
+ +

알림: 네이티브가 아닌 Function.construct 메소드는 {{jsxref("Date")}} 와 같은 일부 네이티브 생성자와 동작하지 않을 것입니다. 그런 경우, {{jsxref("Function.prototype.bind")}} 메소드를 사용해야 합니다. 예를 들어, 다음과 같은 배열이 있다고 할 때, {{jsxref("Global_Objects/Date", "Date")}} 생성자: [2012, 11, 4] 와 함께 사용되려면 다음과 같이 작성해야 합니다: new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))(). 이는 가장 좋은 방법이 아니며, 어떤 상용 환경에서도 사용되지 않을 수 있습니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의. JavaScript 1.3 에 구현됨.
{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + + + +

{{Compat("javascript.builtins.Function.apply")}}

+ + + +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/function/arguments/index.html b/files/ko/web/javascript/reference/global_objects/function/arguments/index.html new file mode 100644 index 0000000000..9a498f2468 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/arguments/index.html @@ -0,0 +1,60 @@ +--- +title: Function.arguments +slug: Web/JavaScript/Reference/Global_Objects/Function/arguments +translation_of: Web/JavaScript/Reference/Global_Objects/Function/arguments +--- +
{{JSRef}} {{deprecated_header}}
+ +

function.arguments 속성은 함수로 부터 넘겨 받은 arguments에 해당하는 배열과 같은 객체이다. 간단하게 {{jsxref("Functions/arguments", "arguments")}}를 대신 사용하자. 이 속성은 strict mode에서 꼬리 호출 최적화 때문에 금지 된다.

+ +

설명

+ +

function.arguments 문법은 deprecated 되었다. 함수 내 에서 사용 가능한 객체{{jsxref("Functions/arguments", "arguments")}}에 접근하는 추천되는 방법은 단순히 {{jsxref("Functions/arguments", "arguments")}}변수로 참조하는 것이다.

+ +

반복문의 경우, 함수 f 가 여러번 호출 스택에 나타나면, f.arguments의 값은 함수의 가장 최근 호출 arguments를 나타낸다.

+ +

arguments의 값은 함수 실행 과정에서 특별한 호출이 없다면 일반적으로 null 이다 (즉, 함수가 호출은 되었으나 반환되지 않음).

+ +

예제

+ +

arguments object를 사용한 예시

+ +
function f(n) { g(n - 1); }
+
+function g(n) {
+  console.log('before: ' + g.arguments[0]);
+  if (n > 0) { f(n); }
+  console.log('after: ' + g.arguments[0]);
+}
+
+f(2);
+
+console.log('returned: ' + g.arguments);
+
+// Output
+
+// before: 1
+// before: 0
+// after: 0
+// after: 1
+// returned: null
+
+ +

Specifications

+ +

function.arguments는 표준이 아니다. ECMAScript 3에서 {{jsxref("Functions/arguments", "arguments")}}를 참조하기 때문에 deprecated 되었다.

+ +

Browser 호환성

+ +
+ + +

{{Compat("javascript.builtins.Function.arguments")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/function/bind/index.html b/files/ko/web/javascript/reference/global_objects/function/bind/index.html new file mode 100644 index 0000000000..6a39852239 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/bind/index.html @@ -0,0 +1,296 @@ +--- +title: Function.prototype.bind() +slug: Web/JavaScript/Reference/Global_Objects/Function/bind +tags: + - ECMAScript 2015 + - Function + - JavaScript + - Method + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind +--- +
{{JSRef}}
+ +

bind() 메소드가 호출되면 새로운 함수를 생성합니다. 받게되는 첫 인자의 value로는 this 키워드를 설정하고, 이어지는 인자들은 바인드된 함수의 인수에 제공됩니다.

+ +
{{EmbedInteractiveExample("pages/js/function-bind.html", "taller")}}
+ + + +

구문

+ +
func.bind(thisArg[, arg1[, arg2[, ...]]])
+ +

매개변수

+ +
+
thisArg
+
바인딩 함수가 대상 함수(target function)의 this에 전달하는 값입니다. 바인딩 함수를 {{jsxref("Operators/new", "new")}} 연산자로 생성한 경우 무시됩니다. bind를 사용하여 setTimeout 내에 콜백 함수를 만들 때, thisArg로 전달된 원시 값은 객체로 변환됩니다. bind할 인수(argument)가 제공되지 않으면  실행 스코프 내의 this는 새로운 함수의 thisArg로 처리됩니다.
+
arg1, arg2, ...
+
대상 함수의 인수 앞에 사용될 인수.
+
+ +

반환 값

+ +

지정한 this 값 및 초기 인수를 사용하여 변경한 원본 함수의 복제본.

+ +

설명

+ +

bind() 함수는 새로운 바인딩한 함수를 만듭니다. 바인딩한 함수는 원본 함수 객체를 감싸는 함수로, ECMAScript 2015에서 말하는 특이 함수 객체exotic function object입니다. 바인딩한 함수를 호출하면 일반적으로 래핑된 함수가 호출 됩니다.

+ +

바인딩한 함수는 다음과 같은 내부 속성을 가지고 있습니다.

+ + + +

바인딩된 함수가 호출될 때 [[BoundTargetFunction]]의 내부 메소드 [[Call]]을 호출합니다. [[Call]] 은 Call(boundThis, args)와 같은 인자를 가집니다. 이 때, boundThis[[BoundThis]]이고, args는 함수가 호출될 때 전달되어 따라오는 [[BoundArguments]] 입니다.

+ +

바인딩된 함수는 {{jsxref("Operators/new", "new")}} 연산자를 사용하여 생성될 수도 있습니다: 그렇게 하면 대상 함수가 마치 대신 생성된 것처럼 행동합니다. 제공된 this 값은 무시됩니다, 앞에 붙인(prepend) 인수는 에뮬레이트된 함수에 제공되지만.

+ +

예제

+ +

바인딩된 함수 생성

+ +

bind()의 가장 간단한 사용법은 호출 방법과 관계없이 특정 this 값으로 호출되는 함수를 만드는 겁니다. 초보 JavaScript 프로그래머로서 흔한 실수는 객체로부터 메소드를 추출한 뒤 그 함수를 호출할때, 원본 객체가 그 함수의 this로 사용될 것이라 기대하는 겁니다(예시 : 콜백 기반 코드에서 해당 메소드 사용). 그러나 특별한 조치가 없으면, 대부분의 경우 원본 객체는 손실됩니다. 원본 객체가 바인딩 되는 함수를 생성하면, 이러한 문제를 깔끔하게 해결할 수 있습니다.

+ +
this.x = 9;
+var module = {
+  x: 81,
+  getX: function() { return this.x; }
+};
+
+module.getX(); // 81
+
+var retrieveX = module.getX;
+retrieveX();
+// 9 반환 - 함수가 전역 스코프에서 호출됐음
+
+// module과 바인딩된 'this'가 있는 새로운 함수 생성
+// 신입 프로그래머는 전역 변수 x와
+// module의 속성 x를 혼동할 수 있음
+var boundGetX = retrieveX.bind(module);
+boundGetX(); // 81
+
+ +

부분 적용 함수

+ +

bind()의 다음으로 간단한 사용법은 미리 지정된 초기 인수가 있는 함수를 만드는 겁니다. 지정될 초기 인수가 있다면 제공된 this 값을 따르고, 바인딩 된 함수에 전달되어 바인딩 된 함수가 호출될 때마다 대상 함수의 인수 앞에 삽입됩니다.

+ +
function list() {
+  return Array.prototype.slice.call(arguments);
+}
+
+var list1 = list(1, 2, 3); // [1, 2, 3]
+
+// 선행될 인수를 설정하여 함수를 생성합니다.
+var leadingThirtysevenList = list.bind(null, 37);
+
+var list2 = leadingThirtysevenList();  // [37]
+
+var list3 = leadingThirtysevenList(1, 2, 3);  // [37, 1, 2, 3]
+
+
+function addArguments(arg1, arg2) {
+    return arg1 + arg2
+}
+
+var result1 = addArguments(1, 2); // 3
+
+// 첫 번째 인수를 지정하여 함수를 생성합니다.
+var addThirtySeven = addArguments.bind(null, 37);
+
+var result2 = addThirtySeven(5); // 37 + 5 = 42
+
+// 두 번째 인수는 무시됩니다.
+var result3 = addThirtySeven(5, 10); // 37 + 5 = 42
+
+ +

setTimeout과 함께 사용

+ +

{{domxref("window.setTimeout()")}} 내에서 기본으로, this 키워드는 {{ domxref("window") }} (또는 global) 객체로 설정됩니다. 클래스 인스턴스를 참조하는 this를 필요로 하는 클래스 메소드로 작업하는 경우, 명시해서 this를 콜백 함수에 바인딩할 수 있습니다, 인스턴스를 유지하기 위해.

+ +
function LateBloomer() {
+  this.petalCount = Math.ceil(Math.random() * 12) + 1;
+}
+
+// 1초 지체 후 bloom 선언
+LateBloomer.prototype.bloom = function() {
+  window.setTimeout(this.declare.bind(this), 1000);
+};
+
+LateBloomer.prototype.declare = function() {
+  console.log('I am a beautiful flower with ' +
+    this.petalCount + ' petals!');
+};
+
+var flower = new LateBloomer();
+flower.bloom();
+// 1초 뒤, 'declare' 메소드 유발
+ +

생성자로 쓰이는 바인딩된 함수

+ +
+

경고: 이 부분은 JavaScript 능력을 보이고 bind() 메소드의 일부 극단 상황(edge case)을 기록합니다. 아래 보이는 메소드는 일을 하는 가장 좋은 방법은 아니며 아마도 상용 환경에서 전혀 사용되지 않을 겁니다.

+
+ +

바인딩된 함수는 자동으로 대상 함수에 의해 생성되는 새로운 인스턴스를 생성하는 {{jsxref("Operators/new", "new")}} 연산자와 함께 쓰기에 적합합니다. 바인딩된 함수가 값을 생성하는 데 쓰이는 경우, 제공된 this는 무시됩니다. 그러나, 제공된 인수는 여전히 생성자 호출에 (인수부) 앞에 붙습니다:

+ +
function Point(x, y) {
+  this.x = x;
+  this.y = y;
+}
+
+Point.prototype.toString = function() {
+  return this.x + ',' + this.y;
+};
+
+var p = new Point(1, 2);
+p.toString(); // '1,2'
+
+// 아래 폴리필에서는 지원되지 않음,
+
+// 원 bind와는 잘 작동:
+
+var YAxisPoint = Point.bind(null, 0/*x*/);
+
+
+var emptyObj = {};
+var YAxisPoint = Point.bind(emptyObj, 0/*x*/);
+
+var axisPoint = new YAxisPoint(5);
+axisPoint.toString(); // '0,5'
+
+axisPoint instanceof Point; // true
+axisPoint instanceof YAxisPoint; // true
+new Point(17, 42) instanceof YAxisPoint; // true
+
+ +

{{jsxref("Operators/new", "new")}}와 함께 쓰기 위한 바인딩된 함수를 만들기 위해 특별한 일을 할 필요가 없음을 주의하세요. 그 결과 분명히 호출되는 바인딩된 함수를 만들기 위해 특별히 아무것도 할 필요가 없습니다, 오히려 {{jsxref("Operators/new", "new")}}를 사용해서만 호출되는 바인딩된 함수를 요구하는 경우에도.

+ +
// 예는 JavaScript 콘솔에서 직접 실행될 수 있음
+// ...위에서부터 이어짐
+
+// 여전히 일반 함수로서 호출될 수 있음
+// (보통 이를 원하지 않더라도)
+YAxisPoint(13);
+
+emptyObj.x + ',' + emptyObj.y;
+// >  '0,13'
+
+ +

오로지 {{jsxref("Operators/new", "new")}}를 사용하거나 호출해서만 바인딩된 함수의 사용을 지원하고 싶은 경우, 대상 함수는 그 제한을 강제해야 합니다.

+ +

바로 가기 생성

+ +

bind()는 특정 this 값을 필요로 하는 함수의 바로 가기(shortcut)를 만들고 싶은 경우에도 도움이 됩니다.

+ +

가령, 배열 같은 객체를 실제 배열로 변환하는 데 사용하고 싶은 {{jsxref("Array.prototype.slice")}}를 취하세요. 이와 같은 바로 가기를 만들 수 있습니다:

+ +
var slice = Array.prototype.slice;
+
+// ...
+
+slice.apply(arguments);
+
+ +

bind()로, 이는 단순화될 수 있습니다. 다음 조각 코드에서, slice는 {{jsxref("Function.prototype")}}의 {{jsxref("Function.prototype.apply()", "apply()")}} 함수에 바인딩된 함수입니다, this 값을 {{jsxref("Array.prototype")}}의 {{jsxref("Array.prototype.slice()", "slice()")}} 함수로 설정한 채. 이는 추가 apply() 호출은 삭제될 수 있음을 뜻합니다:

+ +
// 이전 예에서 "slice"와 같음
+var unboundSlice = Array.prototype.slice;
+var slice = Function.prototype.apply.bind(unboundSlice);
+
+// ...
+
+slice(arguments);
+
+ +

폴리필

+ +

bind 함수는 ECMA-262 제5판에 추가되었습니다; 그러하기에 모든 브라우저에 없을 수 있습니다. 스크립트 시작 부분에 다음 코드를 삽입함으로써 이 문제를 부분적으로 해결할수 있으며,  bind() 지원하지 않는 구현에서도  대부분의 기능을 사용할 수 있습니다.

+ +
if (!Function.prototype.bind) {
+  Function.prototype.bind = function(oThis) {
+    if (typeof this !== 'function') {
+      // ECMAScript 5 내부 IsCallable 함수와
+      // 가능한 가장 가까운 것
+      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
+    }
+
+    var aArgs   = Array.prototype.slice.call(arguments, 1),
+        fToBind = this,
+        fNOP    = function() {},
+        fBound  = function() {
+          return fToBind.apply(this instanceof fNOP
+                 ? this
+                 : oThis,
+                 aArgs.concat(Array.prototype.slice.call(arguments)));
+        };
+
+    if (this.prototype) {
+      // Function.prototype은 prototype 속성이 없음
+      fNOP.prototype = this.prototype;
+    }
+    fBound.prototype = new fNOP();
+
+    return fBound;
+  };
+}
+
+ +

이 알고리즘과 스펙화된 알고리즘 간 많은 차이(충분히 다른 차이가 있을 수 있습니다, 이 목록은 정말 철저히 하지 않았기에) 중 일부는 다음입니다:

+ + + +

이 부분 구현을 쓰기로 고른 경우, 동작이 ECMA-262 제5판을 벗어난 경우에 의존하지 않아야 합니다! 그러나 주의 약간(과 아마도 특정 요구에 맞추기 위한 추가 수정)으로, 이 부분 구현은 bind()가 스펙에 따라 널리 구현될 때까지 적당한 다리가 될 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.8.5에서 구현됨.
{{SpecName('ES6', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Function.bind")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/function/call/index.html b/files/ko/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..a92a7ab931 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,197 @@ +--- +title: Function.prototype.call() +slug: Web/JavaScript/Reference/Global_Objects/Function/call +tags: + - Function + - JavaScript + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +
{{JSRef}}
+ +

call() 메소드는 주어진 this 값 및 각각 전달된 인수와 함께 함수를 호출합니다.

+ +
+

주의: 이 함수 구문은 {{jsxref("Function.prototype.apply", "apply()")}}와 거의 동일하지만, call()인수 목록을, 반면에 apply()인수 배열 하나를 받는다는 점이 중요한 차이점입니다.

+
+ +

{{EmbedInteractiveExample("pages/js/function-call.html")}}

+ +

구문

+ +
func.call(thisArg[, arg1[, arg2[, ...]]])
+ +

매개변수

+ +
+
thisArg
+
func 호출에 제공되는 this의 값.
+
+ +
+
+
+
+

this는 메소드에 의해 보이는 실제값이 아닐 수 있음을 주의하세요: 메소드가 {{jsxref("Functions_and_function_scope/Strict_mode", "비엄격 모드", "", 1)}} 코드 내 함수인 경우, {{jsxref("Global_Objects/null", "null")}} 및 {{jsxref("Global_Objects/undefined", "undefined")}}는 전역 객체로 대체되고 원시값은 객체로 변환됩니다.

+
+
+
+ +

arg1, arg2, ...

+ +
+
객체를 위한 인수.
+
+ +

반환값(Return Value)

+ +

this 와 arguments 를 매개로 호출된 함수의 반환값

+ +

설명

+ +

call()은 이미 할당되어있는 다른 객체의 함수/메소드를 호출하는 해당 객체에 재할당할때 사용됩니다. this는 현재 객체(호출하는 객체)를 참조합니다. 메소드를 한번 작성하면 새 객체를 위한 메소드를 재작성할 필요 없이 call()을 이용해 다른 객체에 상속할 수 있습니다.

+ +

+ +

객체의 생성자 연결에 call 사용

+ +

Java와 비슷하게, 객체의 생성자 연결(chain)에 call을 사용할 수 있습니다. 다음 예에서, Product 객체의 생성자는 nameprice 를 매개변수로 정의됩니다. 다른 두 함수 FoodToythisnameprice를 전달하는 Product를 호출합니다. Productnameprice 속성을 초기화하고, 특수한 두 함수(Food 및 Toy)는 category를 정의합니다.

+ +
function Product(name, price) {
+  this.name = name;
+  this.price = price;
+
+  if (price < 0) {
+    throw RangeError('Cannot create product ' +
+                      this.name + ' with a negative price');
+  }
+}
+
+function Food(name, price) {
+  Product.call(this, name, price);
+  this.category = 'food';
+}
+
+function Toy(name, price) {
+  Product.call(this, name, price);
+  this.category = 'toy';
+}
+
+var cheese = new Food('feta', 5);
+var fun = new Toy('robot', 40);
+
+ +

익명 함수 호출에 call 사용

+ +

이 예제에서는 익명 함수를 만들고 배열 내 모든 객체에서 이를 호출하기 위해 call을 사용합니다. 여기서 익명 함수의 주목적은 배열 내 객체의 정확한 인덱스를 출력할 수 있는 모든 객체에 print 함수를 추가하는 것 입니다.

+ +
+

this 값으로 객체 전달이 반드시 필요하지는 않지만, 해당 예제에서는 설명의 목적으로 사용했습니다. 

+
+ +
var animals = [
+  { species: 'Lion', name: 'King' },
+  { species: 'Whale', name: 'Fail' }
+];
+
+for (var i = 0; i < animals.length; i++) {
+  (function(i) {
+    this.print = function() {
+      console.log('#' + i + ' ' + this.species
+                  + ': ' + this.name);
+    }
+    this.print();
+  }).call(animals[i], i);
+}
+
+ +

함수 호출 및 'this'를 위한 문맥 지정에 call 사용

+ +

아래 예제에서, greet을 호출하면 this 값은 객체 obj에 바인딩됩니다.

+ +
function greet() {
+  var reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
+  console.log(reply);
+}
+
+var obj = {
+  animal: 'cats', sleepDuration: '12 and 16 hours'
+};
+
+greet.call(obj);  // cats typically sleep between 12 and 16 hours
+
+ +

첫번째 인수 지정 없이 함수 호출에 call 사용

+ +

아래 예제에서, display 함수에 첫번째 인수를 전달하지 않고 호출합니다. 첫번째 인수를 전달하지 않으면, this의 값은 전역 객체에 바인딩됩니다.

+ +
var sData = 'Wisen';
+function display(){
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call();  // sData value is Wisen
+
+ +
+

 주의: 엄격 모드(strict mode)에서, this 는 undefined값을 가집니다. See below.

+
+ +
'use strict';
+
+var sData = 'Wisen';
+
+function display() {
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call(); // Cannot read the property of 'sData' of undefined
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.3에서 구현됨.
{{SpecName('ES5.1', '#sec-15.3.4.4', 'Function.prototype.call')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function.prototype.call', 'Function.prototype.call')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Function.call")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/function/index.html b/files/ko/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..5d7dde941a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,167 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - Constructor + - Function + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

Function 생성자는 새 Function 객체를 만듭니다. 이 생성자를 직접 호출하여 동적으로 함수를 생성할 수도 있으나, 보안 문제 및 {{jsxref("eval")}}과 유사한(그러나 훨씬 덜 심각한) 성능 문제가 발생할 수 있습니다. 하지만 eval과 달리, Function 생성자는 전역 범위로 한정된 함수만 생성합니다.

+ +
{{EmbedInteractiveExample("pages/js/function-constructor.html")}}
+ + + +

모든 JavaScript 함수는 사실 Function 객체입니다. 이는 (function(){}).constructor === Function이 참을 반환하는 것에서 알 수 있습니다.

+ +

구문

+ +
new Function ([arg1[, arg2[, ...argN]],] functionBody)
+ +

매개변수

+ +
+
arg1, arg2, ... argN
+
형식 인수 이름으로 사용할 이름. 각 이름은 유효한 JavaScript {{glossary("identifier", "식별자")}}거나, 쉼표로 구분한 유효한 식별자 목록이어야 합니다. 즉, "x", "theValue", "x,theValue"등의 값을 사용할 수 있습니다.
+
functionBody
+
함수 정의를 구성하는 JavaScript 문을 담은 문자열.
+
+ +

설명

+ +

Function 생성자로 생성한 Function 객체는 함수를 생성할 때 구문 분석을 수행합니다. 반면, {{jsxref("Operators/function", "함수 표현식", "", 1)}}이나 {{jsxref("Statements/function", "함수 선언문", "", 1)}}으로 함수를 정의하고 코드 내에서 호출한 경우 나머지 코드와 함께 구문 분석되므로, Function 생성자가 더 비효율적입니다.

+ +

함수로 전달되는 모든 인수는 생성될 함수의 매개 변수 식별자 이름으로 전달되는 순서대로 처리됩니다.

+ +

(new 연산자를 사용하지 않고) 함수로써 Function 생성자를 호출하는 것은 생성자로 호출하는 것과 같습니다. 하지만, new 연산자가 제거됨으로써 코드의 크기를 약간(4 바이트 더 작게) 줄일 수 있으므로 Function에 대해서는 new 연산자를 사용하지 않는 것이 좋습니다.

+ +

Function의 속성과 메서드

+ +

전역 Function 객체는 자신만의 메서드 또는 속성이 없습니다. 그러나, 그 자체로 함수이기에 {{jsxref("Function.prototype")}}에서 프로토타입 체인을 통해 일부 메서드 및 속성을 상속받습니다.

+ +

Function 프로토타입 객체

+ +

속성

+ +
+
+
{{jsxref("Function.arguments")}} {{deprecated_inline}}
+
함수에 전달되는 인수(argument)에 해당하는 배열. 이는 {{jsxref("Function")}}의 속성으로 사라지므로(deprecated), 대신 함수 내에서 이용 가능한 {{jsxref("Functions/arguments", "arguments")}} 객체를 사용하세요.
+
{{jsxref("Function.arity")}} {{obsolete_inline}}
+
함수에 의해 기대되는 인수의 수를 지정하기 위해 사용됐으나 제거되었습니다. 대신 {{jsxref("Function.length", "length")}} 속성을 사용하세요.
+
{{jsxref("Function.caller")}} {{non-standard_inline}}
+
현재 실행 중인 함수를 호출한 함수를 지정합니다.
+
{{jsxref("Function.length")}}
+
함수에 의해 기대되는 인수의 수를 지정합니다.
+
{{jsxref("Function.name")}}
+
함수명.
+
{{jsxref("Function.displayName")}} {{non-standard_inline}}
+
함수의 표시명.
+
Function.prototype.constructor
+
객체의 프로토타입을 만드는 함수를 지정합니다. 자세한 사항은 {{jsxref("Object.prototype.constructor")}} 참조.
+
+
+ +

메서드

+ +
+
+
{{jsxref("Function.prototype.apply()")}}
+
함수를 호출하고 this를 제공된 값으로 설정합니다, 인수는 {{jsxref("Array")}} 객체로 전달될 수 있습니다.
+
{{jsxref("Function.prototype.bind()")}}
+
호출될 때 this를 제공된 값으로 설정하는 새로운 함수를 만듭니다, 새로운 함수가 호출됐을 때 주어진 순서로 모두 제공되는 선행 인수와 함께.
+
{{jsxref("Function.prototype.call()")}}
+
함수를 호출(실행)하고 this를 제공된 값으로 설정합니다, 인수는 그대로 전달될 수 있습니다.
+
{{jsxref("Function.prototype.isGenerator()")}} {{non-standard_inline}}
+
함수가 생성기인 경우 true를 반환합니다; 그렇지 않으면 false를 반환합니다.
+
{{jsxref("Function.prototype.toSource()")}} {{non-standard_inline}}
+
함수의 소스 코드를 나타내는 문자열을 반환합니다. {{jsxref("Object.prototype.toSource")}} 메서드를 재정의(override)합니다.
+
{{jsxref("Function.prototype.toString()")}}
+
함수의 소스 코드를 나타내는 문자열을 반환합니다. {{jsxref("Object.prototype.toString")}} 메서드를 재정의합니다.
+
+
+ +

Function 인스턴스

+ +

Function 인스턴스는 {{jsxref("Function.prototype")}}에서 메서드 및 속성을 상속받습니다. 모든 생성자와 마찬가지로, 생성자의 프로토타입 객체를 바꿈으로써 모든 Function 인스턴스에 변화를 줄 수 있습니다.

+ +

예제

+ +

Function 생성자에 인수 지정하기

+ +

다음 코드는 인수 두 개를 갖는 Function 객체를 생성합니다.

+ +
// 예제는 JavaScript 콘솔에서 직접 실행하실 수 있습니다
+
+// 두 개의 인수를 가지고 그 둘의 합을 반환하는 함수 생성
+var adder = new Function('a', 'b', 'return a + b');
+
+// 함수 호출
+adder(2, 6);
+// > 8
+
+ +

인수 "a" 및 "b"는 함수 몸통(body)의 "return a + b"에 사용되는 형식 인수명입니다.

+ +

Function 생성자와 함수 선언의 차이

+ +

Function 생성자로 만들어지는 함수는 생성 컨텍스트에 대한 클로저(closure)를 생성하지 않습니다; 이들 함수는 항상 전역 범위에서 생성됩니다. 함수가 실행될 때, 자신의 지역 변수와 전역 변수에만 접근할 수 있으며 Function 생성자가 호출된 그 범위의 변수에는 접근할 수 없습니다. 이 점이 함수 표현식 코드에서 {{jsxref("eval")}}을 사용하는 것과 다른 점입니다.

+ +
var x = 10;
+
+function createFunction1() {
+    var x = 20;
+    return new Function('return x;'); // 여기서 |x|는 전역 범위에 있는 |x|를 참조함.
+}
+
+function createFunction2() {
+    var x = 20;
+    function f() {
+        return x; // 여기서 |x|는 위의 지역에 있는 |x|를 참조함.
+    }
+    return f;
+}
+
+var f1 = createFunction1();
+console.log(f1());          // 10
+var f2 = createFunction2();
+console.log(f2());          // 20
+
+ +

위 코드는 브라우저에서는 정상 동작하지만, {{glossary("Node.js")}}에서는 x를 찾을 수 없어, f1()ReferenceError를 생성합니다. 이는 Node.js의 최상위 스크립트 범위가 전역이 아닌 모듈이므로, x도 모듈 범위에 종속되기 때문입니다.

+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Function")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/function/length/index.html b/files/ko/web/javascript/reference/global_objects/function/length/index.html new file mode 100644 index 0000000000..f9e6b30adf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/length/index.html @@ -0,0 +1,80 @@ +--- +title: Function.length +slug: Web/JavaScript/Reference/Global_Objects/Function/length +tags: + - Function + - JavaScript + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Function/length +--- +
{{JSRef}}
+ +

length 속성은 함수가 기대하는 인수의 수를 나타냅니다.

+ +

{{EmbedInteractiveExample("pages/js/function-length.html")}}

+ +
{{js_property_attributes(0,0,1)}}
+ +

설명

+ +

length는 함수 객체의 속성으로, 함수가 얼마나 많은 인수를 기대하는지 나타냅니다, 즉 형식 매개변수의 수. 이 수는 {{jsxref("rest_parameters", "나머지 매개변수", "", 1)}}를 포함하지 않습니다. 그에 반해, {{jsxref("Functions/arguments/length", "arguments.length")}}는 함수에 지역(local)이고 실제로 함수에 전달된 인수의 수를 제공합니다.

+ +

Function 생성자의 데이터 속성

+ +

{{jsxref("Function")}} 생성자는 그 자체로 {{jsxref("Function")}} 객체입니다. 그 length 데이터 속성은 값이 1입니다. 속성의 attribute: 쓰기가능(Writable): false, 열거가능(Enumerable): false, 설정가능(Configurable): true.

+ +

Function 프로토타입 객체의 속성

+ +

{{jsxref("Function")}} 프로토타입 객체의 length 속성은 값이 0입니다.

+ +

예제

+ +
console.log(Function.length); /* 1 */
+
+console.log((function()        {}).length); /* 0 */
+console.log((function(a)       {}).length); /* 1 */
+console.log((function(a, b)    {}).length); /* 2 등. */
+console.log((function(...args) {}).length); /* 0, 나머지 매개변수는 계산되지 않음 */
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.1에서 구현됨.
{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ES6')}}이 속성의 설정가능(configurable) attribute은 이제 true임.
{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Function.length")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/function/name/index.html b/files/ko/web/javascript/reference/global_objects/function/name/index.html new file mode 100644 index 0000000000..ce2d665b73 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/name/index.html @@ -0,0 +1,191 @@ +--- +title: Function.name +slug: Web/JavaScript/Reference/Global_Objects/Function/name +tags: + - ECMAScript6 + - Function + - JavaScript + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Function/name +--- +
{{JSRef}}
+ +

function.name 속성(property)은 함수 이름을 반환합니다.

+ +
{{js_property_attributes(0,0,1)}}
+ +

비표준, ES6 이전 구현에서는 설정가능(configurable) attribute도 false였음을 주의하세요.

+ +

설명

+ +

name 속성은 함수 이름 또는 (ES6 구현 이전) 익명(anonymous) 함수에 대해서는 빈 문자열을 반환합니다:

+ +
function doSomething() {}
+
+console.log(doSomething.name); // logs "doSomething"
+
+ +

new Function(...) 또는 그냥 Function(...) 구문으로 생성된 함수는 name 속성을 빈 문자열로 설정합니다. 다음 예에서는 익명 함수가 생성되므로 name은 빈 문자열을 반환합니다:

+ +
var f = function() {};
+var object = {
+  someMethod: function() {}
+};
+
+console.log(f.name == ''); // true
+console.log(object.someMethod.name == ''); // 역시 true
+
+ +

ES6 함수를 구현한 브라우저는 익명 함수 이름을 그 구문상 위치로부터 추측할 수 있습니다. 예를 들어:

+ +
var f = function() {};
+console.log(f.name); // "f"
+ +

{{jsxref("Operators/Function", "function 식", "", 1)}}에서 이름으로 함수를 정의할 수 있습니다:

+ +
var object = {
+  someMethod: function object_someMethod() {}
+};
+console.log(object.someMethod.name); // logs "object_someMethod"
+
+try { object_someMethod } catch(e) { console.log(e); }
+// ReferenceError: object_someMethod가 정의되지 않음
+
+ +

함수 이름은 바꿀 수 없습니다, 이 속성은 읽기 전용입니다:

+ +
var object = {
+  // 익명
+  someMethod: function() {}
+};
+
+object.someMethod.name = 'someMethod';
+console.log(object.someMethod.name); // 빈 문자열, someMethod는 익명
+
+ +

그러나 바꾸려면, {{jsxref("Object.defineProperty()")}}를 사용할 수 있습니다.

+ +

+ +

객체의 'class'를 확인하기 위해 obj.constructor.name을 사용할 수 있습니다:

+ +
function a() {}
+
+var b = new a();
+
+console.log(b.constructor.name); // logs "a"
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-name', 'name')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-name', 'name')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(33.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatChrome(43.0)}}{{CompatGeckoDesktop(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Inferred names on anonymous functions{{CompatChrome(51.0)}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Inferred names on anonymous functions{{CompatNo}}{{CompatChrome(51.0)}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(51.0)}}
+
+ +

[1] {{bug(883377)}} 참조.

diff --git a/files/ko/web/javascript/reference/global_objects/function/tosource/index.html b/files/ko/web/javascript/reference/global_objects/function/tosource/index.html new file mode 100644 index 0000000000..dcfbdf49e6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/function/tosource/index.html @@ -0,0 +1,71 @@ +--- +title: Function.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/Function/toSource +tags: + - JavaScript + - 메소드 + - 함수 +translation_of: Web/JavaScript/Reference/Global_Objects/Function/toSource +--- +
{{JSRef}} {{non-standard_header}}
+ +

toSource() 메소드는 객체의 소스 코드를 나타내는 스트링을 반환합니다.

+ +

구문

+ +
function.toSource();
+
+ +

반환 값

+ +

객체의 소스 코드를 나타내는 스트링.

+ +

설명

+ +

toSource 메소드는 다음 값들을 반환합니다.

+ + + +

이 메소드는 보통 JavaScript 에 의해 내부적으로 호출되며 코드에서 명시적으로 사용되지 않습니다. 디버깅할 때 객체의 컨텐츠를 검사하기 위해 toSource 를 호출해보실 수 있습니다.

+ +

명세

+ +

어떠한 표준의 일부도 아닙니다. JavaScript 1.3 에서 구현되었습니다.

+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Function.toSource")}}

+
+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/generator/index.html b/files/ko/web/javascript/reference/global_objects/generator/index.html new file mode 100644 index 0000000000..d29b282355 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/generator/index.html @@ -0,0 +1,186 @@ +--- +title: Generator +slug: Web/JavaScript/Reference/Global_Objects/Generator +tags: + - ECMAScript 2015 + - Generator + - JavaScript + - Legacy Generator + - Legacy Iterator + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Generator +--- +
{{JSRef}}
+ +

Generator 객체는 {{jsxref("Statements/function*", "generator function", "", 1)}} 으로부터 반환된 값이며 반복자와 반복자 프로토콜을 준수합니다.

+ +

문법

+ +
function* gen() {
+  yield 1;
+  yield 2;
+  yield 3;
+}
+
+var g = gen(); // "Generator { }"
+ +

메서드

+ +
+
{{jsxref("Generator.prototype.next()")}}
+
{{jsxref("Operators/yield", "yield")}} 표현을 통해 yield된 값을 반환합니다.
+
{{jsxref("Generator.prototype.return()")}}
+
주어진 값을 반환하고 생성기를 종료합니다.
+
{{jsxref("Generator.prototype.throw()")}}
+
생성기로 에러를 throw합니다.
+
+ +

예시

+ +

무한 반복자

+ +
function* idMaker(){
+    var index = 0;
+    while(true)
+        yield index++;
+}
+
+var gen = idMaker(); // "Generator { }"
+
+console.log(gen.next().value); // 0
+console.log(gen.next().value); // 1
+console.log(gen.next().value); // 2
+// ...
+ +

오래된 Generator 객체

+ +

Firefox (SpiderMonkey)는 JavaScript 1.7에서 이전 버전의 생성기도 구현 했습니다.이 버전에서는 함수 선언에서 별표 (*)가 필요하지 않습니다 (함수 본문에서 yield 키워드 만 사용). 그러나 오래된 생성기는 더 이상 사용되지 않습니다. 사용하지 마십시오. 곧 제거 될 것입니다 ({{bug(1083482)}}).

+ +

오래된 Generator 메서드들

+ +
+
Generator.prototype.next() {{non-standard_inline}}
+
{{jsxref("Operators/yield", "yield")}} 표현을 통해 yield된 값을 반환합니다. ES2015 Generator 객체의 next() 에 해당합니다.
+
Generator.prototype.close() {{non-standard_inline}}
+
Generator를 닫고, next()가 호출되면 {{jsxref("StopIteration")}} 에러를 던집니다. ES2015 Generator 객체의 return() 에 해당합니다.
+
Generator.prototype.send() {{non-standard_inline}}
+
Generator에 값을 전달하기 위해 사용 합니다. 이 값은 {{jsxref("Operators/yield", "yield")}} 표현식에서 반환되고, 다음 {{jsxref("Operators/yield", "yield")}} 표현식으로 부터 yield된 값을 반환합니다. send(x)는 ES2015 Generator 객체의 next(x)에 해당합니다.
+
Generator.prototype.throw() {{non-standard_inline}}
+
Generator 로 에러를 throw합니다. ES2015 Generator 객체의 throw() 에 해당합니다.
+
+ +

오래된 Generator 예제

+ +
function* fibonacci() {
+  var a = yield 1;
+  yield a * 2;
+}
+
+var it = fibonacci();
+console.log(it);          // "Generator {  }"
+console.log(it.next());   // 1
+console.log(it.send(10)); // 20
+console.log(it.close());  // undefined
+console.log(it.next());   // throws StopIteration (as the generator is now closed)
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator-objects', 'Generator objects')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(39.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(39.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(39.0)}}
+
+ +

 

+ +

같이 보기

+ +

오래된 Generator

+ + + +

ES2015 Generator

+ + diff --git a/files/ko/web/javascript/reference/global_objects/generator/next/index.html b/files/ko/web/javascript/reference/global_objects/generator/next/index.html new file mode 100644 index 0000000000..7f041f9d9b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/generator/next/index.html @@ -0,0 +1,153 @@ +--- +title: Generator.prototype.next() +slug: Web/JavaScript/Reference/Global_Objects/Generator/next +translation_of: Web/JavaScript/Reference/Global_Objects/Generator/next +--- +
{{JSRef}}
+ +

 next() 메소드는 done과 value 프로퍼티를 가진 객체를 반환한다. 또한 next() 메소드를 호출할 때 매개변수를 제공하여 그 값을 generator에 전달할 수 있다.

+ +

문법

+ +
gen.next(value)
+ +

매개 변수

+ +
+
value
+
Generator에 전달할 값
+
+ +

반환값

+ +

두 개의 프로퍼티를 가진 객체:

+ + + +

예제

+ +

next() 사용하기

+ +

아래의 예시는 간단한 generator와 next 메소드를 통해서 반환되는 객체이다:

+ +
function* gen() {
+  yield 1;
+  yield 2;
+  yield 3;
+}
+
+var g = gen(); // "Generator { }"
+g.next();      // "Object { value: 1, done: false }"
+g.next();      // "Object { value: 2, done: false }"
+g.next();      // "Object { value: 3, done: false }"
+g.next();      // "Object { value: undefined, done: true }"
+
+ +

Generator에 값 전달하기

+ +

이 예시에서는 next가 값과 함께 호출되었다. 첫 번째 호출이 아무것도 출력하지 않은 것은 Generator가 아직 아무런 값도 yield 하지않았기 때문이다. (두 번째 호출과 함께 전달된 정수 2는 Generator 내부의 yield 키워드에 전달되어 value로 할당되었고 console.log로 출력되었다)

+ +
function* gen() {
+  while(true) {
+    var value = yield null;
+    console.log(value);
+  }
+}
+
+var g = gen();
+g.next(1);
+// "{ value: null, done: false }"
+g.next(2);
+// "{ value: null, done: false }"
+// 2
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-generator.prototype.next', 'Generator.prototype.next')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator.prototype.next', 'Generator.prototype.next')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(26)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(26)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/generator/return/index.html b/files/ko/web/javascript/reference/global_objects/generator/return/index.html new file mode 100644 index 0000000000..0c2f9b929d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/generator/return/index.html @@ -0,0 +1,132 @@ +--- +title: Generator.prototype.return() +slug: Web/JavaScript/Reference/Global_Objects/Generator/return +translation_of: Web/JavaScript/Reference/Global_Objects/Generator/return +--- +
{{JSRef}}
+ +

return() 메소드는 제공된 값을 반환하고 Generator를 종료시킨다.

+ +

문법

+ +
gen.return(value)
+ +

매개 변수

+ +
+
value
+
반환될 값.
+
+ +

반환 값

+ +

이 함수의 호출과 함께 주어진 인수 값을 반환한다.

+ +

예시

+ +

return() 사용

+ +

아래의 예시는 간단한 Generator와 return 메소드를 보여준다.

+ +
function* gen() {
+  yield 1;
+  yield 2;
+  yield 3;
+}
+
+var g = gen();
+
+g.next();        // { value: 1, done: false }
+g.return("foo"); // { value: "foo", done: true }
+g.next();        // { value: undefined, done: true }
+
+ +

참고사항:

+ +

만약 donetrue이면 반환되는 객체의 value 프로퍼티의 값은 undefined이다. (return(값)은 next()와 동일)

+ +
function* gen() {yield 1;}
+var g = gen();
+console.log(g.next());//{ value: 1, done: false }
+console.log(g.next());//{ value: undefined, done: true }
+console.log(g.return(1)); //{ value: undefined, done: true }
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-generator.prototype.return', 'Generator.prototype.return')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator.prototype.return', 'Generator.prototype.return')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/generator/throw/index.html b/files/ko/web/javascript/reference/global_objects/generator/throw/index.html new file mode 100644 index 0000000000..534eefe0f6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/generator/throw/index.html @@ -0,0 +1,99 @@ +--- +title: Generator.prototype.throw() +slug: Web/JavaScript/Reference/Global_Objects/Generator/throw +tags: + - ECMAScript 2015 + - Generator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Generator/throw +--- +
{{JSRef}}
+ +

throw() 메서드는 Generator의 실행을 재개시키고 Generator 함수의 실행 문맥 속으로 error를 주입한다. donevalue 프로퍼티를 가진 객체를 반환한다.

+ +

구문

+ +
gen.throw(exception)
+ +

매개변수

+ +
+
exception
+
Generator 함수의 실행 문맥 속으로 주입할 예외. 디버깅의 목적이라면 instanceof {{jsxref("Error")}} 인 것이 유용하다.
+
+ +

반환 값

+ +

두 개의 프로퍼티를 가진 객체

+ + + +

예제

+ +

throw() 사용하기

+ +

다음의 예시는 간단한 Generator 함수와 throw 메소드를 통해서 주입된 에러를 보여준다. 에러는 try...catch블록을 통해서 핸들링 할 수 있다.

+ +
function* gen() {
+  while(true) {
+    try {
+       yield 42;
+    } catch(e) {
+      console.log("Error caught!");
+    }
+  }
+}
+
+var g = gen();
+g.next();
+// { value: 42, done: false }
+g.throw(new Error("Something went wrong"));
+// "Error caught!"
+// { value: 42, done: false }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Generator.throw")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/generatorfunction/index.html b/files/ko/web/javascript/reference/global_objects/generatorfunction/index.html new file mode 100644 index 0000000000..73ee12769d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/generatorfunction/index.html @@ -0,0 +1,112 @@ +--- +title: GeneratorFunction +slug: Web/JavaScript/Reference/Global_Objects/GeneratorFunction +tags: + - Constructor + - ECMAScript 2015 + - Iterator + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/GeneratorFunction +--- +
{{JSRef}}
+ +

GeneratorFunction 생성자는 새로운 {{jsxref("Statements/function*", "generator function")}} 객체를 생성한다. JavaScript 에서 모든 generator function 은 실제로 GeneratorFunction object 이다.

+ +

주의할 점은, GeneratorFunction 이 전역 객체(global object)가 아니란 점이다. GeneratorFunction은 다음의 코드를 실행해서 얻을 수 있다.

+ +
Object.getPrototypeOf(function*(){}).constructor
+
+ +

Syntax

+ +
new GeneratorFunction ([arg1[, arg2[, ...argN]],] functionBody)
+ +

Parameters

+ +
+
arg1, arg2, ... argN
+
이 함수에서 공식적인 argument 이름들로 사용되는 이름들이다. 각각은 유효한 Javascript 식별자이거나 쉼표로 구분된 문자열 리스트에 해당되는 문자열이어야 한다; for example "x", "theValue", or "a,b".
+
functionBody
+
함수 정의를 구성하는 JavaScript 문이 포함된 문자열.
+
+ +

Description

+ +

GeneratorFunction 생성자로 생성된 {{jsxref("Statements/function*", "generator function")}} 객체는 그 함수가 생성될 때 분석한다. 이러한 함수들이 나머지 코드들과 함께 분석되기 때문에, {{jsxref("Statements/function*", "function* expression")}}으로 generator function을 선언하고 코드 내에서 호출하는 것보다 덜 효율적입니다.

+ +

그 함수로 전달된 모든 arguments는 생성될 함수 안에서 파라미터의 식별자 이름으로 그것들이 전달된 순서대로 처리된다.

+ +
+

Note: {{jsxref("Statements/function*", "generator function")}} created with the GeneratorFunction constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the GeneratorFunction constructor was called. This is different from using {{jsxref("Global_Objects/eval", "eval")}} with code for a generator function expression.

+
+ +

new 없이 GeneratorFunction 생성자를 함수처럼 사용하는 것은 생성자처럼 사용하는 것과 동일한 효과를 갖는다.

+ +

Properties

+ +
+
GeneratorFunction.length
+
GeneratorFunction 생성자의 length 속성으로 1 값을 갖는다.
+
{{jsxref("GeneratorFunction.prototype")}}
+
모든 generator function objects 에 속성의 추가를 허용한다.
+
+ +

GeneratorFunction prototype object

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction/prototype', 'Properties')}}
+ +

GeneratorFunction instances

+ +

GeneratorFunction 인스턴스는 {{jsxref("GeneratorFunction.prototype")}} 으로부터 속성과 메서드를 상속한다. 다른 모든 생성자들처럼, 생성자의 prototype object 를 변경함으로써 모든 GeneratorFunction instance 에 변화를 줄 수 있다.

+ +

Examples

+ +

GeneratorFunction 생성자로 generator function 생성하기

+ +
var GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor
+var g = new GeneratorFunction("a", "yield a * 2");
+var iterator = g(10);
+console.log(iterator.next().value); // 20
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-generatorfunction-objects', 'GeneratorFunction')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-generatorfunction-objects', 'GeneratorFunction')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.GeneratorFunction")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/globalthis/index.html b/files/ko/web/javascript/reference/global_objects/globalthis/index.html new file mode 100644 index 0000000000..df3323a00b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/globalthis/index.html @@ -0,0 +1,89 @@ +--- +title: globalThis +slug: Web/JavaScript/Reference/Global_Objects/globalThis +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/globalThis +--- +
{{jsSidebar("Objects")}}
+ +

전역 globalThis 속성은 전역 this 값을 가진 전역 객체를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-globalthis.html")}}
+ + + +

{{JS_Property_Attributes(1, 0, 1)}}

+ +

설명

+ +

역사적으로, 서로 다른 JavaScript 환경의 전역 범위에 접근하는건 서로 다른 구문을 필요로 했습니다. 웹에서는 {{domxref("Window.window", "window")}}, {{domxref("Window.self", "self")}}, {{domxref("Window.frames", "frames")}}를 사용할 수 있지만, Web Workers에서는 self만 동작합니다. Node.js에서는 아무것도 쓸 수 없고, 대신 global을 사용해야 합니다.
+ 비엄격 모드에서의 함수 내부에서 this를 사용할 수도 있겠지만, 모듈이나 엄격 모드의 함수에서는 {{jsxref("undefined")}}를 가리키는 문제가 있습니다. Function('return this')()를 사용하는 방법도 존재하지만, 브라우저의 {{glossary("CSP")}} 등으로 {{jsxref("eval", "eval()")}}을 사용할 수 없는 환경에선 {{jsxref("Function")}}도 이렇게 사용할 수 없습니다.

+ +

globalThis 속성은 환경에 무관하게 전역 this 값, 즉 전역 객체에 접근하는 표준 방법을 제공합니다. window, self 등 비슷한 속성과는 다르게 브라우저/비 브라우저 맥락 모두에서의 동작을 보장합니다. 따라서 코드를 구동하는 환경을 모르더라도 전역 객체에 일관적으로 접근할 수 있습니다.

+ +

HTML과 WindowProxy

+ +

많은 JavaScript 엔진에서 globalThis는 실제 전역 객체를 가리킬 것이나, 웹 브라우저는 {{htmlelement("iframe")}}과 교차 창 보안 문제로 인하여 전역 객체를 감싼 {{jsxref("Proxy")}}를 대신 가리키고, 실제 객체에는 직접 접근할 수 없습니다. 일반적인 사용에는 차이가 없다고 봐도 무방하지만, 알아두는 것이 중요합니다.

+ +

이름

+ +

selfglobal처럼, 다른 인기있던 제안은 기존 코드와의 호환성 문제를 우려해 제외됐습니다. 언어 제안서의 "NAMING" 문서를 방문해 더 자세한 정보를 읽어보세요.

+ +

예제

+ +

환경별 전역 접근

+ +

globalThis 없이 현재 환경의 전역 객체를 가져오는 방법 중 유일하게 믿을만한 방법은 Function('return this')() 입니다. 그러나 일부 환경에서는 CSP 위반에 걸리는 코드이므로, es6-shim은 대신 다음 검사를 수행합니다.

+ +
var getGlobal = function () {
+  if (typeof self !== 'undefined') { return self; }
+  if (typeof window !== 'undefined') { return window; }
+  if (typeof global !== 'undefined') { return global; }
+  throw new Error('unable to locate global object');
+};
+
+var globals = getGlobal();
+
+if (typeof globals.setTimeout !== 'function') {
+  // no setTimeout in this environment!
+}
+
+ +

globalThis를 사용할 수 있으면 환경별 전역 객체 검사는 더 이상 필요하지 않습니다.

+ +
if (typeof globalThis.setTimeout !== 'function') {
+  // no setTimeout in this environment!
+}
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName("ESDraft", "#sec-globalthis", "globalThis")}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.globalThis")}}

+ +

구현 진척도

+ +

본 기능은 아직 안정적인 크로스 브라우징에 도달하지 못했으므로, 매일 업데이트되는 아래 표에서 브라우저별 구현 상황을 확인할 수 있습니다. 이 데이터는 각 브라우저 JavaScript 엔진의 나이틀리 빌드 또는 최신 릴리즈판에서, JavaScript 표준 테스트인 Test262의 관련 항목을 시험해 생성합니다.

+ +

{{EmbedTest262ReportResultsTable("globalThis")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/index.html b/files/ko/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..b0741e8fe2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/index.html @@ -0,0 +1,204 @@ +--- +title: 표준 내장 객체 +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - Overview + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects +--- +
{{jsSidebar("Objects")}}
+ +

이 장은 JavaScript의 모든 표준 내장 객체와 그 메서드 및 속성을 나열합니다.

+ +

표준 내장 객체와 전역 객체를 헷갈리지 않도록 주의하세요. 표준 내장 객체는 전역 범위의 여러 객체를 일컫습니다. 전역 객체는 엄격 모드를 사용하지 않을 땐 전역 범위에서 {{jsxref("Operators/this", "this")}}, 지원하는 환경에선 {{jsxref("globalThis")}}를 사용해 접근할 수 있는 객체입니다. 사실 전역 범위는 전역 객체와 전역 객체가 상속한 속성으로 이루어집니다.

+ +

전역 범위의 나머지 객체는 사용자 스크립트가 생성하거나, 호스트 응용 프로그램이 제공합니다. 브라우저 맥락에서 사용 가능한 호스트 객체는 API 참고서에서 읽을 수 있습니다. DOM 및 코어 JavaScript의 차이에 관한 자세한 정보는 JavaScript 기술 개요를 참고하세요.

+ +

항목별 표준 객체

+ +

값 속성

+ +

아래 전역 속성은 간단한 값을 반환하며 속성이나 메서드를 가지고 있지 않습니다.

+ + + +

함수 속성

+ +

객체에 붙지 않고 전역으로 호출하는 함수로, 반환 값을 호출자에게 바로 반환합니다.

+ +
+ +
+ +

기초 객체

+ +

다른 모든 객체의 기반이 되는 기초이자 기본 객체입니다. 일반 객체, 함수, 오류를 나타내는 객체를 포함합니다.

+ + + +

오류 객체

+ +

오류 객체는 기초 객체의 특별한 유형으로, 기본적인 {{jsxref("Error")}} 객체와 함께 특정 용도에 최적화된 오류 형태도 포함합니다.

+ +
+ +
+ +

숫자 및 날짜

+ +

숫자, 날짜, 수학 계산을 나타내는 기본 객체입니다.

+ + + +

텍스트 처리

+ +

문자열을 나타내는 객체로 문자열을 조작할 방법도 제공합니다.

+ + + +

인덱스 콜렉션

+ +

인덱스 값으로 정렬된 데이터의 콜렉션을 나타냅니다. 배열(형식배열 포함)과 배열형 객체를 포함합니다.

+ +
+ +
+ +

키 콜렉션

+ +

키를 사용하는 콜렉션을 나타냅니다. {{jsxref("Map")}}, {{jsxref("Set")}} 등 순회 가능한 콜렉션은 요소를 삽입 순서대로 순회할 수 있습니다.

+ + + +

구조화된 데이터

+ +

구조화된 데이터 버퍼 및 JavaScript Object Notation(JSON)을 사용하여 작성한 데이터를 나타내고 상호작용합니다.

+ + + +

제어 추상화 객체

+ +

제어 추상화는 코드 구조화에 도움을 줍니다. 특히, 비동기 코드를 (예를 들어) 깊게 중첩된 콜백 함수 없이 작성할 수 있습니다.

+ + + +

리플렉션

+ + + +

국제화

+ +

ECMAScript 코어에 추가된 언어 구분 기능입니다.

+ +
+ +
+ +

WebAssembly

+ +
+ +
+ +

기타

+ + diff --git a/files/ko/web/javascript/reference/global_objects/infinity/index.html b/files/ko/web/javascript/reference/global_objects/infinity/index.html new file mode 100644 index 0000000000..6305621f65 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/infinity/index.html @@ -0,0 +1,65 @@ +--- +title: Infinity +slug: Web/JavaScript/Reference/Global_Objects/Infinity +tags: + - JavaScript + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Infinity +--- +
{{jsSidebar("Objects")}}
+ +

Infinity 전역 속성은 무한대를 나타내는 숫자값입니다.

+ +

{{js_property_attributes(0,0,0)}}

+ +
{{EmbedInteractiveExample("pages/js/globalprops-infinity.html")}}
+ + + +

설명

+ +

Infinity는 전역 객체의 속성입니다. 즉, 전역 스코프의 변수입니다.

+ +

Infinity의 초기값은 {{jsxref("Number.POSITIVE_INFINITY")}}입니다. Infinity(양의 무한대)는 다른 어떤 수보다 더 큽니다.

+ +

수학적인 무한대와는 일부 차이점이 있습니다. {{jsxref("Number.POSITIVE_INFINITY")}} 문서에서 더 알아보세요.

+ +

Infinity는 ECMAScript 5 명세에 따라 읽기 전용입니다.

+ +

예제

+ +
console.log(Infinity);          /* Infinity */
+console.log(Infinity + 1);      /* Infinity */
+console.log(Math.pow(10,1000)); /* Infinity */
+console.log(Math.log(0));       /* -Infinity */
+console.log(1 / Infinity);      /* 0 */
+console.log(1 / 0);             /* Infinity */
+
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Infinity")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/internalerror/index.html b/files/ko/web/javascript/reference/global_objects/internalerror/index.html new file mode 100644 index 0000000000..e6e5769902 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/internalerror/index.html @@ -0,0 +1,120 @@ +--- +title: InternalError +slug: Web/JavaScript/Reference/Global_Objects/InternalError +translation_of: Web/JavaScript/Reference/Global_Objects/InternalError +--- +
{{JSRef}} {{non-standard_header}}
+ +

InternalError 객체는 JavaScript 엔진 내부에서 발생한 에러를 나타냅니다. 예를 들면, "InternalError: too much recursion"라는 에러가 있으며, 이것은 "내부 에러: 너무 많은 재귀 호출" 상황이 발생했을 때 나타납니다. 

+ +

구문

+ +
new InternalError([message[, fileName[, lineNumber]]])
+ +

파라메터

+ +
+
message
+
선택적 파라메터. 에러에 대한 설명.
+
fileName {{non-standard_inline}}
+
선택적 파라메터. 예외(Exception)가 발생한 코드를 포함하고 있는 파일 명.
+
lineNumber {{non-standard_inline}}
+
선택적 파라메터. 예외(Exception)이 발생한 코드의 라인 넘버.
+
+ +

설명

+ +

InternalError 는 JavaScript 엔진에서 내부 에러가 발생할 때마다 던져집니다.

+ +

다음의 에러 예시 들의 경우는 일반적으로 어떤 값이 너무 큰 경우 입니다.

+ + + +

속성

+ +
+
{{jsxref("InternalError.prototype")}}
+
InternalError 객체에 속성을 추가하도록 해줍니다.
+
+ +

메소드

+ +

전역(global)의 InternalError 는 고유의 함수를 가지고 있지 않지만, 몇 가지의 메소드를 프로토타입 체인으로부터 상속받습니다.

+ +

InternalError 인스턴스

+ +

속성

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/InternalError/prototype', 'Properties')}}
+ +

메소드

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/InternalError/prototype', 'Methods')}}
+ +

스펙

+ +

Not part of any specifications.

+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html b/files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html new file mode 100644 index 0000000000..e854c2073a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/internalerror/prototype/index.html @@ -0,0 +1,100 @@ +--- +title: InternalError.prototype +slug: Web/JavaScript/Reference/Global_Objects/InternalError/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/InternalError +--- +
{{JSRef}} {{non-standard_header}}
+ +

InternalError.prototype 속성은 {{jsxref("InternalError")}} 생성자의 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

모든 {{jsxref("InternalError")}} 인스턴스는 InternalError.prototype 으로부터 상속받습니다. 프로토타입은 모든 인스턴스에 속성이나 메소드를 추가하거나 하는 데에 사용할 수 있습니다.

+ +

속성

+ +
+
InternalError.prototype.constructor
+
인스턴스의 프로토타입을 생성하는 함수를 명시합니다. 
+
{{jsxref("Error.prototype.message", "InternalError.prototype.message")}}
+
에러 메시지. {{jsxref("Error")}} 로부터 상속받습니다. 
+
{{jsxref("Error.prototype.name", "InternalError.prototype.name")}}
+
에러명. {{jsxref("Error")}} 로부터 상속받습니다.
+
{{jsxref("Error.prototype.fileName", "InternalError.prototype.fileName")}}
+
에러를 발생시킨 파일의 경로. {{jsxref("Error")}} 로부터 상속받습니다.
+
{{jsxref("Error.prototype.lineNumber", "InternalError.prototype.lineNumber")}}
+
에러를 발생시킨 파일의 라인 넘버. {{jsxref("Error")}} 로부터 상속받습니다.
+
{{jsxref("Error.prototype.columnNumber", "InternalError.prototype.columnNumber")}}
+
에러를 발생 시킨 라인의 컬럼 넘버. {{jsxref("Error")}} 로부터 상속받습니다.
+
{{jsxref("Error.prototype.stack", "InternalError.prototype.stack")}}
+
스택 트레이스. {{jsxref("Error")}} 로부터 상속받습니다. 
+
+ +

메소드

+ +

비록 {{jsxref("InternalError")}}의 프로토타입 객체는 고유의 메소드를 가지고 있지는 않습니다. 하지만, {{jsxref("InternalError")}} 인스턴스는 프로토타입 체인을 통해 몇 가지의 메소드를 상속 받습니다.

+ +

스펙

+ +

Not part of any specifications.

+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/index.html b/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/index.html new file mode 100644 index 0000000000..0758e1332b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/index.html @@ -0,0 +1,303 @@ +--- +title: Intl.DateTimeFormat +slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat +tags: + - DateTimeFormat + - Internationalization + - Intl + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat +--- +
{{JSRef}}
+ +

Intl.DateTimeFormat은 언어에 맞는 날짜 및 시간 서식을 지원하는 객체의 생성자입니다. dateStyletimeStyle 옵션을 통해 날짜와 시간 형식을 빠르게 맞출 수 있고, 더 자세한 조정을 위한 다른 옵션도 존재합니다.

+ +
{{EmbedInteractiveExample("pages/js/intl-datetimeformat.html")}}
+ + + +

구문

+ +
new Intl.DateTimeFormat([locales[, options]])
+Intl.DateTimeFormat.call(this[, locales[, options]])
+ +

매개변수

+ +
+
locales {{optional_inline}}
+
+

BCP 47 언어 태그를 포함하는 문자열이나 문자열의 배열. 로케일 매개변수의 일반적인 형식 및 해석은 {{jsxref("Intl", "Intl 문서", "#Locale_identification_and_negotiation", 1)}}를 참고하세요. 다음의 유니코드 확장 키를 사용할 수 있습니다.

+ +
+
nu
+
사용할 기수법. "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt" 등을 사용할 수 있습니다.
+
ca
+
역법. "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc" 등을 사용할 수 있습니다.
+
hc
+
시간 사이클. "h11", "h12", "h23", "h24" 등을 사용할 수 있습니다.
+
+
+
options {{optional_inline}}
+
+

다음 속성을 포함하는 객체.

+ +
+
dateStyle
+
format()을 호출했을 때 사용할 날짜 서식. 가능한 값은 다음을 포함합니다. +
    +
  • "full"
  • +
  • "long"
  • +
  • "medium"
  • +
  • "short"
  • +
+
+
timeStyle
+
format()을 호출했을 때 사용할 시간 서식. 가능한 값은 다음을 포함합니다. +
    +
  • "full"
  • +
  • "long"
  • +
  • "medium"
  • +
  • "short"
  • +
+
+
localeMatcher
+
사용할 로케일 매칭 알고리즘. 가능한 값은 "lookup""best fit"이고, 기본값은 "best fit"입니다. 자세한 정보는 {{jsxref("Intl", "Intl 문서", "#로케일_조정", 1)}}를 참고하세요.
+
timeZone
+
사용할 시간대. 구현체가 반드시 인식해야 하는 유일한 값은 "UTC"입니다. 기본값은 런타임의 기본 시간대입니다. 구현체에 따라 "Asia/Shanghai", "Asia/Kolkata", "America/New_York" 등 IANA 시간대 데이터베이스의 시간대 이름을 인식할 수도 있습니다.
+
hour12
+
24시간제 대신 12시간제를 사용할지 여부. 가능한 값은 truefalse이고, 기본값은 로케일에 따라 다릅니다. 이 옵션을 지정하면 hc 언어 태그와 hourCycle 옵션을 모두 무시합니다.
+
hourCycle
+
사용할 시간제. 가능한 값은 "h11", "h12", "h23", "h24"입니다. 이 옵션을 지정하면 hc 언어 태그를 무시합니다. hour12 옵션을 지정한 경우 그 값이 우선순위를 가집니다.
+
formatMatcher
+
사용할 서식 매칭 알고리즘. 가능한 값은 "basic""best fit"이고, 기본값은 "best fit"입니다. 아래의 단락에서 이 속성의 자세한 정보를 확인하세요.
+
+ +

이후의 속성은 서식을 적용한 출력 결과가 사용할 날짜 및 시간 구성요소를 나타냅니다. 구현체는 적어도 아래의 부분집합을 지원해야 합니다.

+ +
    +
  • weekday, year, month, day, hour, minute, second
  • +
  • weekday, year, month, day
  • +
  • year, month, day
  • +
  • year, month
  • +
  • month, day
  • +
  • hour, minute, second
  • +
  • hour, minute
  • +
+ +

구현체에 따라 다른 집합을 지원할 수도 있습니다. 서식 요청은 가능한 모든 부분집합 조합 중 최적으로 일치하는 집합으로 조정됩니다. 조정 알고리즘에는 명세에 완벽히 정의된 basic 알고리즘과, 구현체에 따라 다른 best-fit 알고리즘 두 종류가 있으며 formatMatcher 속성의 값이 어느 쪽을 사용할지 결정합니다.

+ +
+
weekday
+
요일. 가능한 값은 다음과 같습니다. +
    +
  • "long" (금요일, Thursday 등)
  • +
  • "short" ((금), Thu 등)
  • +
  • "narrow" ((금), T 등). 일부 로케일에서는 두 개의 요일이 같은 값을 스타일을 가질 수 있습니다. (예: ThursdayTuesday 둘 다 T)
  • +
+
+
era
+
시대. 가능한 값은 다음과 같습니다. +
    +
  • "long" (서기, Anno Domini 등)
  • +
  • "short" (AD 등)
  • +
  • "narrow" (A, AD 등)
  • +
+
+
year
+
연도. 가능한 값은 다음과 같습니다. +
    +
  • "numeric" (2019년, 2019 등)
  • +
  • "2-digit" (19년, 19 등)
  • +
+
+
month
+
월. 가능한 값은 다음과 같습니다. +
    +
  • "numeric" (3 등)
  • +
  • "2-digit" (03 등)
  • +
  • "long" (3월, March 등)
  • +
  • "short" (Mar 등)
  • +
  • "narrow" (M 등). 일부 로케일에서는 두 개의 요일이 같은 값을 스타일을 가질 수 있습니다. (예: MarchMay 둘 다 M)
  • +
+
+
day
+
일. 가능한 값은 다음과 같습니다. +
    +
  • "numeric" (1 등)
  • +
  • "2-digit" (01 등)
  • +
+
+
hour
+
시. 가능한 값은 "numeric", "2-digit"입니다.
+
minute
+
분. 가능한 값은 "numeric", "2-digit"입니다.
+
second
+
초. 가능한 값은 "numeric", "2-digit"입니다.
+
timeZoneName
+
시간대 이름. 가능한 값은 다음과 같습니다. +
    +
  • "long" (한국 표준시, British Summer Time등)
  • +
  • "short" (GMT+9 등)
  • +
+
+
+ +

각 구성요소 속성의 기본값은 {{jsxref("undefined")}}입니다. 그러나 모든 속성이 {{jsxref("undefined")}}일 경우, year, month, day"numeric"으로 취급합니다.

+
+
+ +

설명

+ +

속성

+ +
+
{{jsxref("DateTimeFormat.prototype", "Intl.DateTimeFormat.prototype")}}
+
모든 인스턴스에 속성을 추가할 수 있습니다.
+
+ +

메서드

+ +
+
{{jsxref("DateTimeFormat.supportedLocalesOf", "Intl.DateTimeFormat.supportedLocalesOf()")}}
+
주어진 로케일 목록 중, 런타임이 지원하는 항목을 배열로 반환합니다.
+
+ +

DateTimeFormat 인스턴스

+ +

속성

+ +

DateTimeFormat 인스턴스는 프로토타입의 다음 속성을 상속합니다.

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/prototype', '속성')}}
+ +

메서드

+ +

DateTimeFormat 인스턴스는 프로토타입의 다음 메서드를 상속합니다.

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/prototype', '메서드')}}
+ +

예제

+ +

DateTimeFormat 사용하기

+ +

로케일을 지정하지 않고 사용하면 기본 로케일 및 기본 옵션 서식을 적용한 문자열을 반환합니다.

+ +
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
+
+// 매개변수 없이 toLocaleString() 호출한 결과는
+// 구현체, 기본 로케일, 기본 시간대에 다라 달라짐
+console.log(new Intl.DateTimeFormat().format(date));
+// → ko-KR 로케일(언어)와 Asia/Seoul 시간대(UTC+0900)에서 "2012. 12. 20."
+
+ +

locales 사용하기

+ +

다음 예제는 지역화된 숫자 서식의 예시를 보입니다. 어플리케이션의 사용자 인터페이스 언어에 맞는 서식을 적용하려면 locales 매개변수로 적절한 언어(와, 필요한 경우 대체 언어)를 제공하는걸 잊지 마세요.

+ +
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
+
+// 아래 결과는 모두 Asia/Seoul 시간대를 사용한 결과 (UTC+0900, 한국 표준시)
+
+// 한국어에서 날짜 표기는 연월일 순서
+console.log(new Intl.DateTimeFormat('ko-KR').format(date));
+// → "2012. 12. 20."
+
+// 미국 영어에서 날짜 표기는 월일년 순서
+console.log(new Intl.DateTimeFormat('en-US').format(date));
+// → "12/20/2012"
+
+// 영국 영어에서 날짜 표기는 일월년 순서
+console.log(new Intl.DateTimeFormat('en-GB').format(date));
+// → "20/12/2012"
+
+// 대부분의 아랍어 국가에서는 진짜 아라비아 숫자 사용
+console.log(new Intl.DateTimeFormat('ar-EG').format(date));
+// → "٢٠‏/١٢‏/٢٠١٢"
+
+// 일본어의 경우 어플리케이션에 연호를 사용해야 할 수도 있음
+// 2012년은 헤이세이 24년
+console.log(new Intl.DateTimeFormat('ja-JP-u-ca-japanese').format(date));
+// → "24/12/20"
+
+// 발리어와 같이 지원되지 않을 수도 있는 언어를 지정할 때는
+// 다음과 같이 대체 언어를 지정할 수 있음. 아래의 경우 대체 언어는 인도어
+console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date));
+// → "20/12/2012"
+
+ +

options 사용하기

+ +

options 매개변수를 지정해 날짜와 시간 서식 결과를 원하는 형태로 바꿀 수 있습니다.

+ +
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
+
+// 긴 날짜 서식에 더해 요일 요청
+var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
+console.log(new Intl.DateTimeFormat('de-DE', options).format(date));
+// → "Donnerstag, 20. Dezember 2012"
+
+// 어플리케이션이 GMT를 사용해야 하고, 그 점을 명시해야 할 때
+options.timeZone = 'UTC';
+options.timeZoneName = 'short';
+console.log(new Intl.DateTimeFormat('en-US', options).format(date));
+// → "Thursday, December 20, 2012, GMT"
+
+// 좀 더 자세한 설정이 필요하면
+options = {
+  hour: 'numeric', minute: 'numeric', second: 'numeric',
+  timeZone: 'Australia/Sydney',
+  timeZoneName: 'short'
+};
+console.log(new Intl.DateTimeFormat('en-AU', options).format(date));
+// → "2:00:00 pm AEDT"
+
+// 미국에서도 24시간제가 필요할 때
+options = {
+  year: 'numeric', month: 'numeric', day: 'numeric',
+  hour: 'numeric', minute: 'numeric', second: 'numeric',
+  hour12: false,
+  timeZone: 'America/Los_Angeles'
+};
+console.log(new Intl.DateTimeFormat('en-US', options).format(date));
+// → "12/19/2012, 19:00:00"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES Int 1.0', '#sec-12.1', 'Intl.DateTimeFormat')}}{{Spec2('ES Int 1.0')}}Initial definition.
{{SpecName('ES Int 2.0', '#sec-12.1', 'Intl.DateTimeFormat')}}{{Spec2('ES Int 2.0')}}
{{SpecName('ES Int Draft', '#datetimeformat-objects', 'Intl.DateTimeFormat')}}{{Spec2('ES Int Draft')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Intl.DateTimeFormat")}}

+
+ +

같이 보기

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Intl', '같이_보기')}}
diff --git a/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html b/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html new file mode 100644 index 0000000000..1990621642 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/datetimeformat/prototype/index.html @@ -0,0 +1,86 @@ +--- +title: Intl.DateTimeFormat.prototype +slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/prototype +tags: + - DateTimeFormat + - Internationalization + - Intl + - JavaScript + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat +--- +
{{JSRef}}
+ +

Intl.DateTimeFormat.prototype 속성은 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} 생성자의 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

Intl.DateTimeFormat 인스턴스에 대한 설명은 {{jsxref("DateTimeFormat")}} 문서를 참고하세요.

+ +

{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} 인스턴스는 Intl.DateTimeFormat.prototype을 상속합니다. 프로토타입 객체를 변경하면 모든 {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} 인스턴스가 영향을 받습니다.

+ +

속성

+ +
+
Intl.DateTimeFormat.prototype.constructor
+
{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}에 대한 참조입니다.
+
+ +

메서드

+ +
+
{{jsxref("DateTimeFormat.format", "Intl.DateTimeFormat.prototype.format()")}}
+
주어진 날짜에 {{jsxref("DateTimeFormat")}} 객체의 로케일과 서식 설정을 적용해 반환합니다.
+
+ +
+
{{jsxref("DateTimeFormat.formatToParts", "Intl.DateTimeFormat.prototype.formatToParts()")}}
+
서식을 적용한 날짜 문자열의 각 부분을 객체로 표현해서 {{jsxref("Array")}}로 반환합니다. 반환 값은 로케일별 커스텀 서식에 사용할 수 있습니다.
+
{{jsxref("DateTimeFormat.resolvedOptions", "Intl.DateTimeFormat.prototype.resolvedOptions()")}}
+
객체 인스턴스 생성 때 주어진 로케일과 서식 설정이 어떻게 반영되었나 나타내는 새로운 객체를 반환합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES Int 1.0', '#sec-12.2.1', 'Intl.DateTimeFormat.prototype')}}{{Spec2('ES Int 1.0')}}Initial definition.
{{SpecName('ES Int 2.0', '#sec-12.2.1', 'Intl.DateTimeFormat.prototype')}}{{Spec2('ES Int 2.0')}}
{{SpecName('ES Int Draft', '#sec-Intl.DateTimeFormat.prototype', 'Intl.DateTimeFormat.prototype')}}{{Spec2('ES Int Draft')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Intl.DateTimeFormat.prototype")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/intl/index.html b/files/ko/web/javascript/reference/global_objects/intl/index.html new file mode 100644 index 0000000000..569fb94b80 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/index.html @@ -0,0 +1,134 @@ +--- +title: Intl +slug: Web/JavaScript/Reference/Global_Objects/Intl +tags: + - Internationalization + - Intl + - JavaScript + - Reference + - 국제화 +translation_of: Web/JavaScript/Reference/Global_Objects/Intl +--- +
{{JSRef}}
+ +

Intl 객체는 각 언어에 맞는 문자비교, 숫자, 시간, 날짜비교를 제공하는, ECMAScript 국제화 API를 위한 이름공간입니다. {{jsxref("Collator")}}, {{jsxref("NumberFormat")}}, {{jsxref("DateTimeFormat")}}는 Intl 객체의 속성을 위한 생성자입니다. 이 페이지는 일반적인 국제화의 기능을 수행하는 객체의 생성자들과 언어를 구분하는 함수들 뿐만 아니라 이러한 속성들에 대해서도 다루고 있습니다.

+ +

속성

+ +
+
{{jsxref("Collator", "Intl.Collator")}}
+
콜레이터 생성자입니다. 콜레이터 객체는 각 언어에 맞는 문자열 비교를 가능하게 해줍니다.
+
{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}
+
각 언어에 맞는 시간과 날짜 서식을 적용할 수 있는 객체의 생성자입니다.
+
{{jsxref("ListFormat", "Intl.ListFormat")}}
+
각 언어에 맞는 목록 서식을 적용할 수 있는 객체의 생성자입니다.
+
{{jsxref("NumberFormat", "Intl.NumberFormat")}}
+
각 언어에 맞는 숫자 서식을 적용할 수 있는 객체의 생성자입니다.
+
{{jsxref("PluralRules", "Intl.PluralRules")}}
+
각 언어에 맞는 복수형 규칙 및 단수 복수 구분 서식을 적용할 수 있는 객체의 생성자입니다.
+
{{jsxref("RelativeTimeFormat", "Intl.RelativeTimeFormat")}}
+
각 언어에 맞는 상대 시간 서식을 적용할 수 있는 객체의 생성자입니다.
+
+ +

메서드

+ +
+
{{jsxref("Intl.getCanonicalLocales()")}}
+
표준 로케일 이름 목록을 반환합니다.
+
+ +

로케일 식별과 조정

+ +

The internationalization constructors as well as several language sensitive methods of other constructors (listed under {{anch("See_also", "See also")}}) use a common pattern for identifying locales and determing the one they will actually use: they all accept locales and options arguments, and negotiate the requested locale(s) against the locales they support using an algorithm specified in the options.localeMatcher property.

+ +

locales 매개변수

+ +

The locales argument must be either a string holding a BCP 47 language tag, or an array of such language tags. If the locales argument is not provided or is undefined, the runtime's default locale is used.

+ +

A BCP 47 language tag identifies a language or locale (the difference between the two is fuzzy). In their most common form it can contain, in this order: a language code, a script code, and a country code, all separated by hyphens. Examples:

+ + + +

The subtags identifying languages, scripts, countries (regions), and (rarely used) variants in BCP 47 language tags can be found in the IANA Language Subtag Registry.

+ +

BCP 47 also allows for extensions, and one of them matters to the JavaScript internationalization functions: the "u" (Unicode) extension. It can be used to request a customization of the locale-specific behavior of a {{jsxref("Collator")}}, {{jsxref("NumberFormat")}}, or {{jsxref("DateTimeFormat")}} object. Examples:

+ + + +

로케일 조정

+ +

The locales argument, after stripping off all Unicode extensions, is interpreted as a prioritized request from the application. The runtime compares it against the locales it has available and picks the best one available. Two matching algorithms exist: the "lookup" matcher follows the Lookup algorithm specified in BCP 47; the "best fit" matcher lets the runtime provide a locale that's at least, but possibly more, suited for the request than the result of the Lookup algorithm. If the application doesn't provide a locales argument, or the runtime doesn't have a locale that matches the request, then the runtime's default locale is used. The matcher can be selected using a property of the options argument (see below).

+ +

If the selected language tag had a Unicode extension substring, that extension is now used to customize the constructed object or the behavior of the function. Each constructor or function supports only a subset of the keys defined for the Unicode extension, and the supported values often depend on the language tag. For example, the "co" key (collation) is only supported by {{jsxref("Collator")}}, and its "phonebk" value is only supported for German.

+ +

options 매개변수

+ +

The options argument must be an object with properties that vary between constructors and functions. If the options argument is not provided or is undefined, default values are used for all properties.

+ +

One property is supported by all language sensitive constructors and functions: The localeMatcher property, whose value must be a string "lookup" or "best fit" and which selects one of the locale matching algorithms described above.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES Int 1.0', '#sec-8', 'Intl')}}{{Spec2('ES Int 1.0')}}Initial definition.
{{SpecName('ES Int 2.0', '#sec-8', 'Intl')}}{{Spec2('ES Int 2.0')}}
{{SpecName('ES Int Draft', '#intl-object', 'Intl')}}{{Spec2('ES Int Draft')}}Added Intl.getCanonicalLocales in the 4th edition.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Intl")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/intl/locale/index.html b/files/ko/web/javascript/reference/global_objects/intl/locale/index.html new file mode 100644 index 0000000000..a768a8bb5d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/locale/index.html @@ -0,0 +1,77 @@ +--- +title: Intl.Locale +slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale +tags: + - Internationalization + - Intl + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/Locale +--- +
{{JSRef}}
+ +

The Intl.Locale constructor is a standard built-in property of the Intl object that represents a Unicode locale identifier.

+ +

{{EmbedInteractiveExample("pages/js/intl-locale.html")}}

+ +

Syntax

+ +
new Intl.Locale(tag [, options])
+ +

Parameters

+ +
+
tag
+
The Unicode locale identifier string.
+
options
+
An object that contains configuration for the Locale. Keys are Unicode locale tags, values are valid Unicode tag values.
+
+ +

Description

+ +

The Intl.Locale object was created to allow for easier manipulation of Unicode locales. Unicode represents locales with a string, called a locale identifier. The locale identifier consists of a language identifier and extension tags. Language identifiers are the core of the locale, consisting of languagescript, and region subtags. Additional information about the locale is stored in the optional extension tags. Extension tags hold information about locale aspects such as calendar type, clock type, and numbering system type.

+ +

Traditionally, the Intl API used strings to represent locales, just as Unicode does. This is a simple and lightweight solution that works well. Adding a Locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags.

+ +

The Intl.Locale object has the following properties and methods:

+ +

Properties

+ +
+
{{jsxref("Locale.prototype", "Intl.Locale.prototype")}}
+
The prototype object for the Locale constructor.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
Intl.Locale proposalStage 3
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Intl.Locale")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/intl/locale/language/index.html b/files/ko/web/javascript/reference/global_objects/intl/locale/language/index.html new file mode 100644 index 0000000000..195b2a06a0 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/locale/language/index.html @@ -0,0 +1,62 @@ +--- +title: Intl.Locale.prototype.language +slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/language +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/Locale/language +--- +
{{JSRef}}
+ +
+ +

Intl.Locale.prototype.language 속성은 locale과 관련된 언어를 반환하는 접근자 속성입니다.

+ +

Description

+ +

언어는 locale의 핵심 기능 중 하나입니다. 유니 코드 사양은 locale의 언어 식별자를 언어와 지역으로 함께 취급합니다 (예를 들어 영국 영어와 미국 영어 등의 방언과 변형을 구별하기 위해). {{jsxref("Locale", "Locale")}}의 language 속성은 로캘의 언어 하위 태그를 엄격하게 반환합니다.

+ +

Examples

+ +

locale 식별자 문자열 인수에서 언어 설정

+ +

유효한 유니 코드 locale 식별자가 되려면 문자열이 언어 하위 태그로 시작해야합니다. {{jsxref("Locale", "Locale")}} 생성자에 대한 주요 인수는 유효한 유니 코드 locale 식별자여야하므로 생성자가 사용될 때마다 언어 하위 태그가있는 식별자를 전달해야합니다.

+ +
let langStr = new Intl.Locale("en-Latn-US");
+
+console.log(langStr.language); // Prints "en"
+ +

configuration 객체로 언어 오버라이딩 하기

+ +

언어 하위 태그를 지정해야하지만 {{jsxref("Locale", "Locale")}} 생성자는 언어 하위 태그를 재정의 할 수있는 구성 개체를 사용합니다.

+ +
let langObj = new Intl.Locale("en-Latn-US", {language: "es"});
+
+console.log(langObj.language); // Prints "es"
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
Intl.Locale.prototype.language proposalStage 3
+ +

Browser compatibility

+ +
+ +{{Compat("javascript.builtins.Intl.Locale.language")}}
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/intl/numberformat/index.html b/files/ko/web/javascript/reference/global_objects/intl/numberformat/index.html new file mode 100644 index 0000000000..6d306a0c77 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/numberformat/index.html @@ -0,0 +1,198 @@ +--- +title: Intl.NumberFormat +slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat +tags: + - Internationalization + - Intl + - JavaScript + - NumberFormat + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat +--- +
{{JSRef}}
+ +

Intl.NumberFormat은 언어에 맞는 숫자 서식을 지원하는 객체의 생성자입니다.

+ +
{{EmbedInteractiveExample("pages/js/intl-numberformat.html")}}
+ + + +

구문

+ +
new Intl.NumberFormat([locales[, options]])
+Intl.NumberFormat.call(this[, locales[, options]])
+
+ +

매개 변수

+ +
+
locales {{optional_inline}}
+
+

BCP 47 언어 태그를 포함하는 문자열이나 문자열의 배열. 로케일 매개변수의 일반적인 형식 및 해석은 {{jsxref("Intl", "Intl 문서", "#Locale_identification_and_negotiation", 1)}}를 참고하세요. 다음의 Unicode 확장 키를 사용할 수 있습니다.

+ +
+
nu
+
사용할 기수법. "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt" 등을 사용할 수 있습니다.
+
+
+
options {{optional_inline}}
+
+

다음 속성을 포함하는 객체.

+ +
+
localeMatcher
+
사용할 로케일 매칭 알고리즘. 가능한 값은 "lookup""best fit"이고, 기본값은 "best fit"입니다. 자세한 정보는 {{jsxref("Intl", "Intl 문서", "#로케일_조정", 1)}}를 참고하세요.
+
style
+
사용할 서식 스타일. 가능한 값은 평문 숫자 "decimal", 통화 서식 "currency", 백분율 서식 "percent"입니다. 기본값은 "decimal"입니다.
+
currency
+
통화 서식에 사용할 통화입니다. 가능한 값은 ISO 4217 통화 코드로 대한민국 원화 "KRW", 미국 달러화 "USD", 유럽 유로화 "EUR" 등을 포함합니다. 현재 통화 및 펀드 코드 목록을 참고하세요. 기본값은 없습니다. style 값을 "currency"로 지정했다면, currency 값도 반드시 지정해야 합니다.
+
currencyDisplay
+
통화 서식에서 통화를 표시하는 방법. 가능한 값은 €와 같이 현지 통화 기호를 사용하는 "symbol", ISO 통화 코드를 사용하는 "code", "dollar" 등 현지 통화 이름을 사용하는 "name"이 있습니다. 기본 값은 "symbol"입니다.
+
useGrouping
+
천 단위 구분자 혹은 천/라크/크로르 단위 구분자의 삽입 여부. 가능한 값은 truefalse입니다. 기본 값은 true입니다.
+
+ +

아래 속성은 두 가지 그룹으로 나뉩니다. minimumIntegerDigits, minimumFractionDigits, maximumFractionDigits가 첫 번째 그룹이고, minimumSignificantDigitsmaximumSignificantDigits가 두 번째 그룹으로, 두 번째 그룹 중 하나라도 지정하면 첫 번째 그룹은 모두 무시합니다.

+ +
+
minimumIntegerDigits
+
정수부의 최소 자릿수. 가능한 값은 1부터 21까지의 수로, 기본값은 1입니다.
+
minimumFractionDigits
+
소수부의 최소 자릿수. 가능한 값은 0부터 20까지의 수로, 평문 숫자와 백분율 서식의 기본값은 0입니다. 통화 서식의 기본값은 ISO 4217 통화 코드 목록이 제공하는 보조 단위의 자릿수에 따라 다릅니다. (목록에 정보가 없을 경우 2)
+
maximumFractionDigits
+
소수부의 최대 자릿수. 가능한 값은 0부터 20까지의 수로, 평문 숫자 서식의 기본값은 minimumFractionDigits와 3 중 더 큰 값입니다. 통화 서식의 기본값은 minimumFractionDigits와, ISO 4217 통화 코드 목록이 제공하는 보조 단위의 자릿수(목록에 정보가 없을 경우 2) 중 더 큰 값입니다. 백분율 서식의 기본값은 minimumFractionDigits와 0 중 더 큰 값입니다.
+
minimumSignificantDigits
+
유효숫자의 최소 수. 가능한 값은 1부터 21까지의 수로, 기본값은 1입니다.
+
maximumSignificantDigits
+
유효숫자의 최대 수. 가능한 값은 1부터 21까지의 수로, 기본값은 21입니다.
+
+
+
+ +

설명

+ +

속성

+ +
+
{{jsxref("NumberFormat.prototype", "Intl.NumberFormat.prototype")}}
+
모든 인스턴스에 속성을 추가할 수 있습니다.
+
+ +

메서드

+ +
+
{{jsxref("NumberFormat.supportedLocalesOf", "Intl.NumberFormat.supportedLocalesOf()")}}
+
주어진 로케일 목록 중, 런타임이 지원하는 항목을 배열로 반환합니다.
+
+ +

NumberFormat 인스턴스

+ +

속성

+ +

NumberFormat 인스턴스는 프로토타입의 다음 속성을 상속합니다.

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat/prototype', '속성')}}
+ +

메서드

+ +

NumberFormat 인스턴스는 프로토타입의 다음 메서드를 상속합니다.

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat/prototype', '메서드')}}
+ +

예제

+ +

기본적인 사용 방법

+ +

로케일을 지정하지 않고 사용하면 기본 로케일 및 기본 옵션 서식을 적용한 문자열을 반환합니다.

+ +
var number = 3500;
+
+console.log(new Intl.NumberFormat().format(number));
+// → 한국 로케일의 경우 '3,500' 표시
+
+ +

locales 사용하기

+ +

다음 예제는 지역화된 숫자 서식의 예시를 보입니다. 어플리케이션의 사용자 인터페이스 언어에 맞는 서식을 적용하려면 locales 매개변수로 적절한 언어(와, 필요한 경우 대체 언어)를 제공하는걸 잊지 마세요.

+ +
var number = 123456.789;
+
+// 독일은 소수점 구분자로 쉼표를 사용하고 천 단위 구분자로 마침표를 사용
+console.log(new Intl.NumberFormat('de-DE').format(number));
+// → 123.456,789
+
+// 대부분의 아랍어 사용 국가에서는 실제 아라비아 숫자를 사용
+console.log(new Intl.NumberFormat('ar-EG').format(number));
+// → ١٢٣٤٥٦٫٧٨٩
+
+// 인도는 천, 라크(십만), 크로르(천만) 단위에 구분자 사용
+console.log(new Intl.NumberFormat('en-IN').format(number));
+// → 1,23,456.789
+
+// nu 확장 키로 기수법 지정 (아래 예시는 중국식 숫자 표기)
+console.log(new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec').format(number));
+// → 一二三,四五六.七八九
+
+// 발리어와 같이 지원되지 않을 수도 있는 언어를 지정할 때는
+// 다음과 같이 대체 언어를 지정할 수 있음. 아래의 경우 대체 언어는 인도어
+console.log(new Intl.NumberFormat(['ban', 'id']).format(number));
+// → 123.456,789
+
+ +

options 사용

+ +

options 매개변수를 지정해 결과를 원하는 형태로 바꿀 수 있습니다.

+ +
var number = 123456.789;
+
+// 통화 서식
+console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
+// → 123.456,79 €
+
+// 한국 원화는 보조 통화 단위를 사용하지 않음
+console.log(new Intl.NumberFormat('ko-KR', { style: 'currency', currency: 'KRW' }).format(number));
+// → ₩123,457
+
+// 유효숫자를 세 개로 제한
+console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));
+// → 1,23,000
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태Comment
{{SpecName('ES Int 1.0', '#sec-11.1', 'Intl.NumberFormat')}}{{Spec2('ES Int 1.0')}}초기 정의.
{{SpecName('ES Int 2.0', '#sec-11.1', 'Intl.NumberFormat')}}{{Spec2('ES Int 2.0')}}
{{SpecName('ES Int Draft', '#numberformat-objects', 'Intl.NumberFormat')}}{{Spec2('ES Int Draft')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Intl.NumberFormat")}}

+
+ +

같이 보기

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Intl', '같이_보기')}}
diff --git a/files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html b/files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html new file mode 100644 index 0000000000..19b0b8e0e6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html @@ -0,0 +1,85 @@ +--- +title: Intl.NumberFormat.prototype +slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/prototype +tags: + - Internationalization + - Intl + - JavaScript + - NumberFormat + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat +--- +
{{JSRef}}
+ +

Intl.NumberFormat.prototype 속성은 {{jsxref("NumberFormat", "Intl.NumberFormat")}} 생성자의 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

Intl.NumberFormat 인스턴스에 대한 설명은 {{jsxref("NumberFormat")}} 문서를 참고하세요.

+ +

{{jsxref("NumberFormat", "Intl.NumberFormat")}} 인스턴스는 Intl.NumberFormat.prototype을 상속합니다. 프로토타입 객체를 변형하면 모든 {{jsxref("NumberFormat", "Intl.NumberFormat")}} 인스턴스가 영향을 받습니다.

+ +

속성

+ +
+
Intl.NumberFormat.prototype.constructor
+
Intl.NumberFormat에 대한 참조입니다.
+
+ +

메서드

+ +
+
{{jsxref("NumberFormat.format", "Intl.NumberFormat.prototype.format()")}}
+
주어진 숫자에 {{jsxref("NumberFormat")}} 객체의 로케일과 서식 설정을 적용해 반환합니다.
+
+ +
+
{{jsxref("NumberFormat.formatToParts", "Intl.NumberFormat.prototype.formatToParts()")}}
+
서식을 적용한 숫자의 각 부분을 객체로 표현해서 {{jsxref("Array")}}로 반환합니다. 반환 값은 로케일별 커스텀 서식에 사용할 수 있습니다.
+
{{jsxref("NumberFormat.resolvedOptions", "Intl.NumberFormat.prototype.resolvedOptions()")}}
+
객체 인스턴스 생성 때 주어진 로케일과 콜레이션 설정이 어떻게 반영되었나 나타내는 새로운 객체를 반환합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES Int 1.0', '#sec-11.2.1', 'Intl.NumberFormat.prototype')}}{{Spec2('ES Int 1.0')}}Initial definition.
{{SpecName('ES Int 2.0', '#sec-11.2.1', 'Intl.NumberFormat.prototype')}}{{Spec2('ES Int 2.0')}}
{{SpecName('ES Int Draft', '#sec-Intl.NumberFormat.prototype', 'Intl.NumberFormat.prototype')}}{{Spec2('ES Int Draft')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Intl.NumberFormat.prototype")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/isfinite/index.html b/files/ko/web/javascript/reference/global_objects/isfinite/index.html new file mode 100644 index 0000000000..834389e2f7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/isfinite/index.html @@ -0,0 +1,84 @@ +--- +title: isFinite() +slug: Web/JavaScript/Reference/Global_Objects/isFinite +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/isFinite +--- +
{{jsSidebar("Objects")}}
+ +

isFinite() 전역 함수는 주어진 값이 유한수인지 판별합니다. 필요한 경우 매개변수를 먼저 숫자로 변환합니다.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-isfinite.html")}}
+ + + +

구문

+ +
isFinite(testValue)
+ +

매개변수

+ +
+
testValue
+
유한한지 판별할 값.
+
+ +

반환 값

+ +

testValue가 양 또는 음의 {{jsxref("Infinity")}}, {{jsxref("NaN")}}, 또는 {{jsxref("undefined")}}면 false, 아니면 true.

+ +

설명

+ +

isFinite()은 최상위 함수로 어떤 객체와도 연결되지 않았습니다.

+ +

숫자가 유한수인지 판별하기 위해 isFinite()을 사용할 수 있습니다. isFinite()은 주어진 수를 검사해 그 값이 NaN, 양의 무한대, 또는 음의 무한대이면 false를 반환합니다. 그렇지 않으면 true를 반환합니다.

+ +

예제

+ +

isFinite() 사용하기

+ +
isFinite(Infinity);  // false
+isFinite(NaN);       // false
+isFinite(-Infinity); // false
+
+isFinite(0);         // true
+isFinite(2e64);      // true
+isFinite(910);       // true
+
+isFinite(null);      // true, would've been false with the
+                     // more robust Number.isFinite(null)
+
+isFinite('0');       // true, would've been false with the
+                     // more robust Number.isFinite("0")
+ +

명세

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-isfinite-number', 'isFinite')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.isFinite")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/isnan/index.html b/files/ko/web/javascript/reference/global_objects/isnan/index.html new file mode 100644 index 0000000000..f0b2f12a31 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/isnan/index.html @@ -0,0 +1,190 @@ +--- +title: isNaN() +slug: Web/JavaScript/Reference/Global_Objects/isNaN +tags: + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/isNaN +--- +
{{jsSidebar("Objects")}}
+ +

isNaN() 함수는 어떤 값이 {{jsxref("NaN")}}인지 판별합니다. isNaN 함수는 몇몇 {{anch("일반적이지 않은 규칙")}}을 가지고 있으므로, ECMAScript 2015에서 추가한 {{jsxref("Number.isNaN()")}}으로 바꾸는 편이 좋을 수도 있습니다.

+ +

{{EmbedInteractiveExample("pages/js/globalprops-isnan.html")}}

+ +

구문

+ +
isNaN(value)
+ +

매개변수

+ +
+
value
+
테스트되는 값.
+
+ +

반환 값

+ +

주어진 값이 {{jsxref("NaN")}}이면 true, 아니면 false.

+ +

설명

+ +

isNaN 함수의 필요성

+ +

JavaScript의 다른 모든 값과 달리, {{jsxref("NaN")}}은 같음 연산(==, ===)을 사용해 판별할 수 없습니다. NaN == NaN, NaN === NaN이기 때문입니다. 그래서 NaN을 판별하는 함수가 필요합니다.

+ +

NaN 값의 기원

+ +

NaN 값은 산술 연산이 정의되지 않은 결과 또는 표현할 수 없는 결과를 도출하면 생성되며, 반드시 오버플로 조건을 나타내는 것은 아닙니다. 숫자가 아닌 값의 변환을 시도했으나 알맞은 원시 숫자 값이 없는 경우의 결과도 NaN입니다.

+ +

예를 들어 0을 0으로 나누면 NaN이지만, 다른 수를 0으로 나누면 그렇지 않습니다.

+ +

혼란스러운 특별 케이스 행동

+ +

isNaN 함수 스펙의 아주 초기 버전 이후로, 숫자 아닌 인수를 위한 행동이 혼란스럽습니다. isNaN 함수의 인수가 Number 형이 아닌 경우, 그 값은 먼저 숫자로 강제됩니다. 결과값은 그 뒤에 {{jsxref("NaN")}}인지 결정하기 위해 테스트됩니다. 따라서 숫자 형으로 강제된 결과 유효한 비 NaN 숫자값(특히 강제될 때 숫자값이 0 또는 1을 주는 빈 문자열 및 불린 원시형)이 되는 비 숫자의 경우, "false" 반환값은 예기치 않을 수 있습니다; 예를 들어 빈 문자열은 분명히 "not a number"입니다. 혼란(confusion)은 용어 "not a number"가 IEEE-754 부동 소수점 값으로 표현된 숫자에 특정 의미가 있다는 사실에서 생깁니다. 함수는 "이 값이, 숫자값으로 강제되는 경우, IEEE-754 'Not A Number' 값인가?"라는 질문에 답하는 것으로 해석되어야 합니다.

+ +

ECMAScript (ES2015) 최근 버전은 {{jsxref("Number.isNaN()")}} 함수를 포함합니다. Number.isNaN(x)xNaN인지 아닌지 테스트하는 믿을 수 있는 방법이 됩니다. 그러나 Number.isNaN으로도, NaN의 의미는 정확한 숫자 의미로 남아있고 단순히 "not a number"는 아닙니다. 그 대신에, Number.isNaN이 없을 경우에, 식 (x != x)은 변수 xNaN인지 아닌지 테스트하는 더 믿을 수 있는 방법입니다, 그 결과는 isNaN을 믿을 수 없게 하는 오탐(false positive)의 대상이 아니기에.

+ +

당신은 isNaN을 다음과 같이 생각할 수 있습니다:

+ +
isNaN = function(value) {
+    Number.isNaN(Number(value));
+}
+ +

예제

+ +
isNaN(NaN);       // 참
+isNaN(undefined); // 참
+isNaN({});        // 참
+
+isNaN(true);      // 거짓
+isNaN(null);      // 거짓
+isNaN(37);        // 거짓
+
+// 문자열
+isNaN("37");      // 거짓: "37"은 NaN이 아닌 숫자 37로 변환됩니다
+isNaN("37.37");   // 거짓: "37.37"은 NaN이 아닌 숫자 37.37로 변환됩니다
+isNaN("123ABC");  // 참: parseInt("123ABC")는 123이지만 Number("123ABC")는 NaN입니다
+isNaN("");        // 거짓: 빈 문자열은 NaN이 아닌 0으로 변환됩니다
+isNaN(" ");       // 거짓: 공백이 있는 문자열은 NaN이 아닌 0으로 변환됩니다
+
+// dates
+isNaN(new Date());                // 거짓
+isNaN(new Date().toString());     // 참
+
+// 이것이 허위 양성이고 isNaN이 완전히 신뢰할 수 없는 이유이다.
+isNaN("blabla")   // 참: "blabla"는 숫자로 변환됩니다.
+                  // 이것을 숫자롯 parsing 하는 것을 실패하고 NaN을 반환한다.
+
+ +

유용한 특별 케이스 행동

+ +

isNaN()을 고려한 더 용도 중심 방법이 있습니다: isNaN(x)false를 반환하면, 그 식이 NaN을 반환하게 하지 않고 산술 식에 x를 쓸 수 있습니다. true를 반환하는 경우, x는 모든 산술 식이 NaN을 반환하게 합니다. 이는 JavaScript에서, isNaN(x) == trueNaN을 반환하는 x - 0과 동일함(JavaScript에서 x - 0 == NaN가 항상 거짓을 반환하여 그것을 테스트할 수 없지만)을 뜻합니다. 실제로, isNaN(x), isNaN(x - 0), isNaN(Number(x)), Number.isNaN(x - 0)Number.isNaN(Number(x))는 항상 같은 값을 반환하며 JavaScript에서 isNaN(x)는 그저 이러한 각각의 조건(terms)을 표현하는 가장 짧은 형태입니다.

+ +

예를 들어 함수에 인수가 산술 처리 가능한(숫자 "처럼" 쓸 수 있는)지를 테스트하기 위해 사용할 수 있습니다, 그렇지 않은 경우 기본 값 또는 다른 무언가를 제공해야 합니다. 이런 식으로 문맥에 따라 암시적인 값 변환을 제공하는 JavaScript의 다양성(versatility) 전체를 이용케 하는 함수를 가질 수 있습니다.

+ +

예시

+ +
function increment(x) {
+  if (isNaN(x)) x = 0;
+  return x + 1;
+};
+
+// Number.isNaN()과 같은 효과:
+function increment(x) {
+  if (Number.isNaN(Number(x))) x = 0;
+  return x + 1;
+};
+
+// 함수의 인수 x에 대해 다음 경우에,
+// isNaN(x)는 항상 거짓, x가 실제 숫자가 아닐지라도
+// 하지만 산술 식에 그대로
+// 사용될 수 있습니다
+increment("");            // 1: ""는 0으로 변환됩니다
+increment(new String());  // 1: 빈 문자열을 나타내는 String 객체는 0으로 변환됩니다
+increment([]);            // 1: []는 0으로 변환됩니다
+increment(new Array());   // 1: 빈 배열을 나타내는 Array 객체는 0으로 변환됩니다
+increment("0");           // 1: "0"은 0으로 변환됩니다
+increment("1");           // 2: "1"은 1로 변환됩니다
+increment("0.1");         // 1.1: "0.1"은 0.1로 변환됩니다
+increment("Infinity");    // Infinity: "Infinity"는 Infinity로 변환됩니다
+increment(null);          // 1: null은 0으로 변환됩니다
+increment(false);         // 1: false는 0으로 변환됩니다
+increment(true);          // 2: true는 1로 변환됩니다
+increment(new Date());    // 밀리초로 현재 date/time + 1을 반환합니다
+
+// 함수의 인수 x에 대해 다음 경우에,
+// isNaN(x)는 항상 거짓이고 x는 실제로 숫자입니다
+increment(-1);            // 0
+increment(-0.1);          // 0.9
+increment(0);             // 1
+increment(1);             // 2
+increment(2);             // 3
+// ... 등등 ...
+increment(Infinity);      // Infinity
+
+// 함수의 인수 x에 대해 다음 경우에,
+// isNaN(x)는 항상 참이고 x는 실제로 숫자가 아닙니다,
+// 따라서 함수는 인수를 0으로 대체하고 1을 반환합니다
+increment(String);            // 1
+increment(Array);             // 1
+increment("blabla");          // 1
+increment("-blabla");         // 1
+increment(0/0);               // 1
+increment("0/0");             // 1
+increment(Infinity/Infinity); // 1
+increment(NaN);               // 1
+increment(undefined);         // 1
+increment();                  // 1
+
+// isNaN(x)는 항상 isNaN(Number(x))과 같지만,
+// x의 존재는 여기서 필수입니다!
+isNaN(x) == isNaN(Number(x)) // x == undefined 포함 x의 어떤 값도 참,
+                             // isNaN(undefined) == true 및 Number(undefined)가 NaN을 반환하기에,
+                             // 하지만 ...
+isNaN() == isNaN(Number())   // 거짓, isNaN() == true 및 Number() == 0 때문에
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의.
{{SpecName('ES5.1', '#sec-15.1.2.4', 'isNaN')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-isnan-number', 'isNaN')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-isnan-number', 'isNaN')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.isNaN")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/json/index.html b/files/ko/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..ef21cfc534 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,122 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +tags: + - JSON + - JavaScript + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +
{{JSRef}}
+ +

JSON 객체는 JavaScript Object Notation({{glossary("JSON")}})을 분석하거나 값을 JSON으로 변환하는 메서드를 가지고 있습니다. JSON을 직접 호출하거나 인스턴스를 생성할 수 없으며, 두 개의 메서드를 제외하면 자신만의 흥미로운 기능은 없습니다.

+ +

JavaScript와 JSON의 차이

+ +

JSON은 객체, 배열, 숫자, 문자열, 불리언과 {{jsxref("null")}}을 직렬화하기 위한 구문으로, JavaScript 구문에 기반을 두고 있지만 분명한 차이점을 가지고 있습니다. 즉, 어떤 JavaScript는 JSON이 아닙니다.

+ +
+
객체와 배열
+
속성의 이름은 반드시 큰따옴표로 표시된 문자열이어야 합니다. 후행 쉼표는 허용하지 않습니다.
+
숫자
+
선행 0은 허용하지 않습니다. 소숫점 뒤에는 적어도 한 자릿수가 뒤따라야 합니다. {{jsxref("NaN")}}과 {{jsxref("Infinity")}}는 지원하지 않습니다.
+
모든 JSON 텍스트는 유효한 JavaScript 표현식...
+
...이지만, 모든 JSON 텍스트를 올바른 ECMA-262로 만드는 제안을 구현한 JavaScript 엔진에서만 그러합니다. 다른 엔진에서는, U+2028 LINE SEPARATOR와 U+2029 PARAGRAPH SEPARATOR를 JSON에서 스트링 리터럴과 속성의 키로 사용할 수 있지만, JavaScript 문자열 리터럴에서 사용하면 {{jsxref("SyntaxError")}}가 발생합니다.
+
+ +

{{jsxref("JSON.parse()")}}로 JSON 문자열을 분석하고 {{jsxref("eval")}}이 JavaScript 문자열로 실행하는 다음 예시를 참고하세요.

+ +
const code = '"\u2028\u2029"'
+JSON.parse(code) // 모든 엔진에서 "\u2028\u2029"로 평가
+eval(code)       // 오래된 엔진에서 SyntaxError
+
+ +

다른 차이점으로는 문자열의 작은따옴표 금지와, 주석 및 {{jsxref("undefined")}} 미지원이 있습니다. JSON에 기반한, 보다 사람 친화적인 설정 형식을 원하면 Babel 컴파일러가 사용하는 JSON5가 있고, 좀 더 많이 쓰이는 YAML도 있습니다.

+ +

전체 JSON 구문

+ +
JSON = null
+    or true or false
+    or JSONNumber
+    or JSONString
+    or JSONObject
+    or JSONArray
+
+JSONNumber = - PositiveNumber
+          or PositiveNumber
+PositiveNumber = DecimalNumber
+              or DecimalNumber . Digits
+              or DecimalNumber . Digits ExponentPart
+              or DecimalNumber ExponentPart
+DecimalNumber = 0
+             or OneToNine Digits
+ExponentPart = e Exponent
+            or E Exponent
+Exponent = Digits
+        or + Digits
+        or - Digits
+Digits = Digit
+      or Digits Digit
+Digit = 0 through 9
+OneToNine = 1 through 9
+
+JSONString = ""
+          or " StringCharacters "
+StringCharacters = StringCharacter
+                or StringCharacters StringCharacter
+StringCharacter = any character
+                  except " or \ or U+0000 through U+001F
+               or EscapeSequence
+EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
+              or \u HexDigit HexDigit HexDigit HexDigit
+HexDigit = 0 through 9
+        or A through F
+        or a through f
+
+JSONObject = { }
+          or { Members }
+Members = JSONString : JSON
+       or Members , JSONString : JSON
+
+JSONArray = [ ]
+         or [ ArrayElements ]
+ArrayElements = JSON
+             or ArrayElements , JSON
+
+ +

중요하지 않은 공백은 JSONNumber(숫자에는 공백이 없어야 함) 또는 JSONString(문자열에서 해당 문자로 해석되거나 오류를 일으킴) 내를 제외하고 어디에나 존재할 수 있습니다. 탭 문자(U+0009), 캐리지 리턴(U+000D), 라인 피드(U+000A) 및 스페이스(U+0020) 문자만이 유효한 공백 문자입니다.

+ +

메서드

+ +
+
{{jsxref("JSON.parse()")}}
+
문자열을 JSON으로서 구문 분석하고, 선택적으로 분석 결과의 값과 속성을 변환해 반환합니다.
+
{{jsxref("JSON.stringify()")}}
+
주어진 값에 해당하는 JSON 문자열을 반환합니다. 선택 사항으로 특정 속성만 포함하거나 사용자 정의 방식으로 속성을 대체합니다.
+
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.JSON")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/json/parse/index.html b/files/ko/web/javascript/reference/global_objects/json/parse/index.html new file mode 100644 index 0000000000..fa32b3711e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/json/parse/index.html @@ -0,0 +1,123 @@ +--- +title: JSON.parse() +slug: Web/JavaScript/Reference/Global_Objects/JSON/parse +tags: + - ECMAScript 5 + - JSON + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse +--- +
{{JSRef}}
+ +

JSON.parse() 메서드는 JSON 문자열의 구문을 분석하고, 그 결과에서 JavaScript 값이나 객체를 생성합니다. 선택적으로, reviver 함수를 인수로 전달할 경우, 결과를 반환하기 전에 변형할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/json-parse.html")}}
+ + + +

구문

+ +
JSON.parse(text[, reviver])
+ +

매개변수

+ +
+
text
+
JSON으로 변환할 문자열. JSON 구문은 {{jsxref("JSON")}} 객체의 설명을 참고하세요.
+
reviver {{optional_inline}}
+
함수라면, 변환 결과를 반환하기 전에 이 인수에 전달해 변형함.
+
+ +

반환 값

+ +

주어진 JSON 문자열에 대응하는 {{jsxref("Object")}}.

+ +

예외

+ +

변환할 문자열이 유효한 JSON이 아닐 경우 {{jsxref("SyntaxError")}}.

+ +

예제

+ +

JSON.parse() 사용하기

+ +
JSON.parse('{}');              // {}
+JSON.parse('true');            // true
+JSON.parse('"foo"');           // "foo"
+JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
+JSON.parse('null');            // null
+
+ +

reviver 매개변수 사용하기

+ +

reviver가 주어지면 분석한 값을 반환하기 전에 변환합니다. 구체적으로는, 분석한 값과 그 모든 속성(가장 깊게 중첩된 속성부터 시작해 제일 바깥의 원래 값까지)을 각각 reviver에 전달합니다. reviver의 this 문맥은 분석한 값으로 설정되고, 속성 명(문자열)과 값을 인자로 전달받습니다. reviver가 {{jsxref("undefined")}}를 반환하거나 반환하지 않는다면, 예컨대 함수가 중간에 실패한다면 그 속성은 최종 결과에서 제외됩니다. 그 외에는 반환 값으로 속성의 값을 재설정합니다.

+ +

만약 reviver가 일부 값만 변환하고 나머지는 건드리지 않는다면, 나머지 값을 그대로 반환하는걸 잊지 마세요. 그렇지 않으면 변환한 값 외에는 결과에서 모두 제외됩니다.

+ +
JSON.parse('{"p": 5}', (key, value) =>
+  typeof value === 'number'
+    ? value * 2 // 숫자라면 2배
+    : value     // 나머진 그대로
+);
+
+// { p: 10 }
+
+JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
+  console.log(key); // 현재 속성명 출력, 마지막은 빈 문자열("")
+  return value;     // 변환하지 않고 그대로 반환
+});
+
+// 1
+// 2
+// 4
+// 6
+// 5
+// 3
+// ""
+ +

후행 쉼표 사용 불가

+ +
// 둘 다 SyntaxError
+JSON.parse('[1, 2, 3, 4, ]');
+JSON.parse('{"foo" : 1, }');
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.JSON.parse")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/json/stringify/index.html b/files/ko/web/javascript/reference/global_objects/json/stringify/index.html new file mode 100644 index 0000000000..12de82705b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/json/stringify/index.html @@ -0,0 +1,230 @@ +--- +title: JSON.stringify() +slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify +tags: + - JSON + - JavaScript + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify +--- +
{{JSRef}}
+ +

JSON.stringify() 메서드는 JavaScript 값이나 객체를 JSON 문자열로 변환합니다. 선택적으로, replacer를 함수로 전달할 경우 변환 전 값을 변형할 수 있고, 배열로 전달할 경우 지정한 속성만 결과에 포함합니다.

+ +
{{EmbedInteractiveExample("pages/js/json-stringify.html")}}
+ + + +

구문

+ +
JSON.stringify(value[, replacer[, space]])
+ +

매개변수

+ +
+
value
+
JSON 문자열로 변환할 값.
+
replacer {{optional_inline}}
+
문자열화 동작 방식을 변경하는 함수, 혹은 JSON 문자열에 포함될 값 객체의 속성들을 선택하기 위한 화이트리스트(whitelist)로 쓰이는 {{jsxref("String")}} 과 {{jsxref("Number")}} 객체들의 배열. 이 값이 null 이거나 제공되지 않으면, 객체의 모든 속성들이 JSON 문자열 결과에 포함된다.
+
+ +
+
space {{optional_inline}}
+
가독성을 목적으로 JSON 문자열 출력에 공백을 삽입하는데 사용되는 {{jsxref("String")}} 또는 {{jsxref("Number")}} 객체. 이것이 Number 라면, 공백으로 사용되는 스페이스(space)의 수를 나타낸다; 이 수가 10 보다 크면 10 으로 제한된다. 1 보다 작은 값은 스페이스가 사용되지 않는 것을 나타낸다. 이것이 String 이라면, 그 문자열(만약 길이가 10 보다 길다면, 첫번째 10 개의 문자)이 공백으로 사용된다. 이 매개 변수가 제공되지 않는다면(또는 null 이면), 공백이 사용되지 않는다.
+
+ +

반환 값

+ +

주어진 값과 대응하는 JSON 문자열.

+ +

예외

+ +

순환 참조를 발견할 경우 {{jsxref("TypeError")}}(cyclic object value).

+ +

설명

+ +

JSON.stringify()는 값을 JSON 표기법으로 변환한다.

+ + + +
JSON.stringify({});                  // '{}'
+JSON.stringify(true);                // 'true'
+JSON.stringify('foo');               // '"foo"'
+JSON.stringify([1, 'false', false]); // '[1,"false",false]'
+JSON.stringify({ x: 5 });            // '{"x":5}'
+
+JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))
+// '"2006-01-02T15:04:05.000Z"'
+
+JSON.stringify({ x: 5, y: 6 });
+// '{"x":5,"y":6}' or '{"y":6,"x":5}'
+JSON.stringify([new Number(1), new String('false'), new Boolean(false)]);
+// '[1,"false",false]'
+
+// Symbols:
+JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
+// '{}'
+JSON.stringify({ [Symbol('foo')]: 'foo' });
+// '{}'
+JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
+// '{}'
+JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
+  if (typeof k === 'symbol') {
+    return 'a symbol';
+  }
+});
+// '{}'
+
+// Non-enumerable properties:
+JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) );
+// '{"y":"y"}'
+
+
+ +

replacer 매개 변수

+ +

replacer 매개변수는 함수 또는 배열이 될 수 있다. 함수일 때는 문자열화 될 key 와 value, 2개의 매개변수를 받는다. key 가 발견된 객체는 리플레이서의 this 매개변수로 제공된다. 맨 처음에는 문자열화될 그 객체를 나타내는 비어 있는 key와 함께 호출되고, 그 다음에는 문자열화될 그 객체나 배열의 각 속성에 대해 호출된다. 이것은 JSON 문자열에 추가되어야 하는 값을 반환해야한다:

+ + + +
유의: replacer 함수를 배열로부터 값을 제거하기위해 사용할 수 없다. 만약 undefined 나 함수를 반환한다면 null 이 대신 사용될 것이다.
+ +

함수에 대한 예제

+ +
function replacer(key, value) {
+  if (typeof value === "string") {
+    return undefined;
+  }
+  return value;
+}
+
+var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
+var jsonString = JSON.stringify(foo, replacer);
+
+ +

JSON 문자열 결과는 {"week":45,"month":7} 이다.

+ +

배열에 대한 예제

+ +

replacer 가 배열인 경우, 그 배열의 값은 JSON 문자열의 결과에 포함되는 속성의 이름을 나타낸다.

+ +
JSON.stringify(foo, ['week', 'month']);
+// '{"week":45,"month":7}', 단지 "week" 와 "month" 속성을 포함한다
+
+ +

space 매개 변수

+ +

space 매개변수는 최종 문자열의 간격을 제어한다. 숫자일 경우 최대 10자 만큼의 공백 문자 크기로 들여쓰기되며, 문자열인 경우 해당 문자열 또는 처음 10자 만큼 들여쓰기 된다.

+ +
JSON.stringify({ a: 2 }, null, ' ');
+// '{
+//  "a": 2
+// }'
+
+ +

'\t'를 사용하면 일반적으로 들여쓰기 된 코드스타일과 유사함.

+ +
JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
+// returns the string:
+// '{
+//     "uno": 1,
+//     "dos": 2
+// }'
+
+ +

toJSON() 작동

+ +

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized. For example:

+ +
var obj = {
+  foo: 'foo',
+  toJSON: function() {
+    return 'bar';
+  }
+};
+JSON.stringify(obj);        // '"bar"'
+JSON.stringify({ x: obj }); // '{"x":"bar"}'
+
+ +

Example of using JSON.stringify() with localStorage

+ +

In a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of JSON.stringify():

+ +
+

Functions are not a valid JSON data type so they will not work. However, they can be displayed if first converted to a string (e.g. in the replacer), via the function's toString method. Also, some objects like {{jsxref("Date")}} will be a string after {{jsxref("JSON.parse()")}}.

+
+ +
// Creating an example of JSON
+var session = {
+  'screens': [],
+  'state': true
+};
+session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 });
+session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 });
+session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 });
+session.screens.push({ 'name': 'screenD', 'width': 250, 'height': 60 });
+session.screens.push({ 'name': 'screenE', 'width': 390, 'height': 120 });
+session.screens.push({ 'name': 'screenF', 'width': 1240, 'height': 650 });
+
+// Converting the JSON string with JSON.stringify()
+// then saving with localStorage in the name of session
+localStorage.setItem('session', JSON.stringify(session));
+
+// Example of how to transform the String generated through
+// JSON.stringify() and saved in localStorage in JSON object again
+var restoredSession = JSON.parse(localStorage.getItem('session'));
+
+// Now restoredSession variable contains the object that was saved
+// in localStorage
+console.log(restoredSession);
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.JSON.stringify")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/map/@@tostringtag/index.html b/files/ko/web/javascript/reference/global_objects/map/@@tostringtag/index.html new file mode 100644 index 0000000000..7a1cd5002b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/@@tostringtag/index.html @@ -0,0 +1,51 @@ +--- +title: 'Map.prototype[@@toStringTag]' +slug: Web/JavaScript/Reference/Global_Objects/Map/@@toStringTag +translation_of: Web/JavaScript/Reference/Global_Objects/Map/@@toStringTag +--- +
{{JSRef}}
+ +

Map[@@toStringTag] 프로퍼티의 초기값은 "Map"입니다.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-@@tostringtag.html")}}
+ + + +
{{js_property_attributes(0,0,1)}}
+ +

문법

+ +
Map[Symbol.toStringTag]
+ +

예제

+ +
Object.prototype.toString.call(new Map()) // "[object Map]"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype-@@tostringtag', 'Map.prototype[@@toStringTag]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype-@@tostringtag', 'Map.prototype[@@toStringTag]')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Map.@@toStringTag")}}

diff --git a/files/ko/web/javascript/reference/global_objects/map/clear/index.html b/files/ko/web/javascript/reference/global_objects/map/clear/index.html new file mode 100644 index 0000000000..fc63ff96d6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/clear/index.html @@ -0,0 +1,75 @@ +--- +title: Map.prototype.clear() +slug: Web/JavaScript/Reference/Global_Objects/Map/clear +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/clear +--- +
{{JSRef}}
+ +

clear() 메서드는 Map 객체의 모든 요소를 제거합니다.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-clear.html")}}
+ + + +

구문

+ +
myMap.clear();
+
+ +

예제

+ +

clear() 사용하기

+ +
var myMap = new Map();
+myMap.set('bar', 'baz');
+myMap.set(1, 'foo');
+
+myMap.size;       // 2
+myMap.has('bar'); // true
+
+myMap.clear();
+
+myMap.size;       // 0
+myMap.has('bar')  // false
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Map.clear")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/map/delete/index.html b/files/ko/web/javascript/reference/global_objects/map/delete/index.html new file mode 100644 index 0000000000..41110a28a9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/delete/index.html @@ -0,0 +1,79 @@ +--- +title: Map.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/Map/delete +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/delete +--- +
{{JSRef}}
+ +

delete() 메서드는 Map 객체에서 특정 요소를 제거합니다.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-delete.html")}}
+ + + +

구문

+ +
myMap.delete(key);
+ +

매개변수

+ +
+
key
+
Map 객체에서 제거할 요소의 키.
+
+ +

반환 값

+ +

요소가 Map 객체에 존재해서 제거했을 경우 true, 존재하지 않았으면 false.

+ +

예제

+ +

delete() 사용하기

+ +
var myMap = new Map();
+myMap.set('bar', 'foo');
+
+myMap.delete('bar'); // Returns true. Successfully removed.
+myMap.has('bar');    // Returns false. The "bar" element is no longer present.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Map.delete")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/map/entries/index.html b/files/ko/web/javascript/reference/global_objects/map/entries/index.html new file mode 100644 index 0000000000..54242f373b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/entries/index.html @@ -0,0 +1,78 @@ +--- +title: Map.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Map/entries +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/entries +--- +
{{JSRef}}
+ +

entries() 메서드는 Map 객체의 각 요소에 해당하는 [키, 값] 쌍을 Map에 등록한 순서대로 포함한 새로운 Iterator 객체를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-entries.html")}}
+ + + +

구문

+ +
myMap.entries()
+ +

반환 값

+ +

A new {{jsxref("Map")}} iterator object.

+ +

예제

+ +

entries() 사용하기

+ +
var myMap = new Map();
+myMap.set('0', 'foo');
+myMap.set(1, 'bar');
+myMap.set({}, 'baz');
+
+var mapIter = myMap.entries();
+
+console.log(mapIter.next().value); // ["0", "foo"]
+console.log(mapIter.next().value); // [1, "bar"]
+console.log(mapIter.next().value); // [Object, "baz"]
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype.entries', 'Map.prototype.entries')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.entries', 'Map.prototype.entries')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Map.entries")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/map/foreach/index.html b/files/ko/web/javascript/reference/global_objects/map/foreach/index.html new file mode 100644 index 0000000000..48b96eb570 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/foreach/index.html @@ -0,0 +1,98 @@ +--- +title: Map.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Map/forEach +translation_of: Web/JavaScript/Reference/Global_Objects/Map/forEach +--- +
{{JSRef}}
+ +

forEach() 메소드는 Map 오브젝트 내의 key/value 쌍의 개수 만큼 주어진 함수를 순서대로 실행합니다. 

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-foreach.html")}}
+ + + +

문법

+ +
myMap.forEach(callback[, thisArg])
+ +

파라미터

+ +
+
callback
+
각각의 요소를 처리하기 위한 함수.
+
thisArg
+
 callback 을 실행할때 this 로 사용되는 값.
+
+ +

Return value

+ +

{{jsxref("undefined")}}.

+ +

설명

+ +

forEach 메서드는 map의 각각의 키마다 주어진 callback 함수를 실행합니다. 삭제된 키에대해서는 호출되지 않습니다. 그러나, 값이 존재하지만 undefined 인 값에 대해서는 실행됩니다.

+ +

callback 은 3가지 인수로 호출됩니다.

+ + + +

thisArg 파라미터가 forEach 에 제공되면, this 값으로 사용하기 위해 호출될때 callback 으로 넘겨집니다. 그렇지 않으면 undefined 값이 this 값으로 넘겨질 것입니다. 궁극적으로 callback 으로 보여지게 된 this 값은 함수에 의해 보여지는 this 를 결정하기 위한 일반적인 규칙에 따라 결정됩니다.

+ +

각각의 value는 한번씩 사용됩니다. 다만 forEach 가 끝나기 전에 value가 삭제되거나 재추가 된 경우는 예외입니다. callback 은 사용되기 전에 삭제된 value에 의해 호출되지 않습니다. forEach 가 끝나기 전에 새롭게 추가된 value가 사용 됩니다.

+ +

forEach 는 Map 오브젝트 내에 있는 각각의 요소마다 callback 함수를 실행합니다; 깂을 반환하지 않습니다.

+ +

예제

+ +

Map 오브젝트의 내용을 출력

+ +

아래의 코드는 Map 오브젝트 내의 각각 요소들을 행별로 출력합니다:

+ +
function logMapElements(value, key, map) {
+    console.log(`map.get('${key}') = ${value}`);
+}
+new Map([['foo', 3], ['bar', {}], ['baz', undefined]]).forEach(logMapElements);
+// logs:
+// "map.get('foo') = 3"
+// "map.get('bar') = [object Object]"
+// "map.get('baz') = undefined"
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype.foreach', 'Map.prototype.forEach')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.foreach', 'Map.prototype.forEach')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Map.forEach")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/map/get/index.html b/files/ko/web/javascript/reference/global_objects/map/get/index.html new file mode 100644 index 0000000000..835c8c3e6e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/get/index.html @@ -0,0 +1,80 @@ +--- +title: Map.prototype.get() +slug: Web/JavaScript/Reference/Global_Objects/Map/get +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Map/get +--- +
{{JSRef}}
+ +

get() 메서드는 Map 객체에서 지정한 요소를 회수합니다.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-get.html")}}
+ + + +

구문

+ +
myMap.get(key);
+ +

매개변수

+ +
+
key
+
Map 객체에서 회수할 요소의 키.
+
+ +

반환 값

+ +

주어진 키와 연결된 요소. 그런 요소가 없으면 {{jsxref("undefined")}}.

+ +

예제

+ +

get 사용하기

+ +
var myMap = new Map();
+myMap.set('bar', 'foo');
+
+myMap.get('bar');  // "foo" 반환.
+myMap.get('baz');  // undefined 반환.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype.get', 'Map.prototype.get')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.get', 'Map.prototype.get')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Map.get")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/map/has/index.html b/files/ko/web/javascript/reference/global_objects/map/has/index.html new file mode 100644 index 0000000000..60c5c03dfb --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/has/index.html @@ -0,0 +1,81 @@ +--- +title: Map.prototype.has() +slug: Web/JavaScript/Reference/Global_Objects/Map/has +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/has +--- +
{{JSRef}}
+ +

has() 메서드는 주어진 키를 가진 요소가 Map에 존재하는지를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-has.html")}}
+ + + +

구문

+ +
myMap.has(key);
+ +

매개변수

+ +
+
key
+
존재 여부를 판별할 키값.
+
+ +

반환 값

+ +

주어진 키를 가진 요소가 있으면 true, 아니면 false.

+ +

예제

+ +

has() 사용하기

+ +
var myMap = new Map();
+myMap.set('bar', "foo");
+
+myMap.has('bar');  // returns true
+myMap.has('baz');  // returns false
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype.has', 'Map.prototype.has')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.has', 'Map.prototype.has')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Map.has")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/map/index.html b/files/ko/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..f8b29bdf6e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,244 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +
{{JSRef}}
+ +

Map 객체는 키-값 쌍을 저장하며 각 쌍의 삽입 순서도 기억하는 콜렉션입니다. 아무 값(객체와 {{Glossary("Primitive", "원시 값")}})이라도 키와 값으로 사용할 수 있습니다.

+ +

설명

+ +

Map 객체는 요소의 삽입 순서대로 원소를 순회합니다. {{jsxref("Statements/for...of", "for...of")}} 반복문은 각 순회에서 [key, value]로 이루어진 배열을 반환합니다.

+ +

키 동일성

+ + + +

{{jsxref("Object")}}와 Map 비교

+ +

{{jsxref("Object")}}는 값에 키를 할당할 수 있고, 그 키로 값을 얻을 수 있고, 키를 삭제할 수 있으며 어떤 키에 값이 존재하는지 확인할 수 있다는 점에서 Map과 유사합니다. 이런 이유에 더해, 이전에는 내장된 대체제가 없었기 때문에, ObjectMap 대신 사용하곤 했습니다.

+ +

그러나 어떤 상황에선, Map을 선호해야 할 몇 가지 중요한 차이점이 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MapObject
의도치 않은 키Map은 명시적으로 제공한 키 외에는 어떤 키도 가지지 않습니다. +

Object는 프로토타입을 가지므로 기본 키가 존재할 수 있습니다. 주의하지 않으면 직접 제공한 키와 충돌할 수도 있습니다.

+ +
+

참고: ES5부터, 프로토타입으로 인한 키 충돌은 {{jsxref("Object.create", "Object.create(null)")}}로 해결할 수 있지만, 실제로 쓰이는 경우는 적습니다.

+
+
키 자료형Map의 키는 함수, 객체 등을 포함한 모든 값이 가능합니다.Object의 키는 반드시 {{jsxref("String")}} 또는 {{jsxref("Symbol")}}이어야 합니다.
키 순서 +

Map의 키는 정렬됩니다. 따라서 Map의 순회는 삽입순으로 이뤄집니다.

+
+

Object의 키는 정렬되지 않습니다.

+ +
+

참고: ECMAScript 201 이후로, 객체도 문자열과 Symbol 키의 생성 순서를 유지합니다. ECMEScript 2015 명세를 준수하는 JavaScript 엔진에서 문자열 키만 가진 객체를 순회하면 삽입 순을 따라갑니다.

+
+
크기Map의 항목 수는 {{jsxref("Map.prototype.size", "size")}} 속성을 통해 쉽게 알아낼 수 있습니다.Object의 항목 수는 직접 알아내야 합니다.
순회Map순회 가능하므로, 바로 순회할 수 있습니다.Object를 순회하려면 먼저 모든 키를 알아낸 후, 그 키의 배열을 순회해야 합니다.
성능잦은 키-값 쌍의 추가와 제거에서 더 좋은 성능을 보입니다.잦은 키-값 쌍의 추가와 제거를 위한 최적화가 없습니다.
+ +

생성자

+ +
+
{{jsxref("Map.Map", "Map()")}}
+
새로운 Map 객체를 생성합니다.
+
+ +

속성

+ +
+
Map.length
+
값이 0인 속성입니다.
+ 요소의 수는 {{jsxref("Map.prototype.size")}}로 알아낼 수 있습니다.
+
{{jsxref("Map.@@species", "get Map[@@species]")}}
+
파생 객체를 생성하는데 사용하는 생성자 함수입니다.
+
{{jsxref("Map.prototype")}}
+
Map 생성자의 프로토타입을 나타냅니다. 모든 Map 인스턴스에 속성을 추가할 수 있습니다.
+
+ +

Map 인스턴스

+ +

모든 Map 인스턴스는 {{jsxref("Map.prototype")}}을 상속합니다.

+ +

속성

+ +

{{page('ko/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}

+ +

메서드

+ +

{{page('ko/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}

+ +

예제

+ +

Map 객체 사용하기

+ +
let myMap = new Map()
+
+let keyString = '문자열'
+let keyObj    = {}
+let keyFunc   = function() {}
+
+// 값 설정
+myMap.set(keyString, "'문자열'과 관련된 값")
+myMap.set(keyObj, 'keyObj와 관련된 값')
+myMap.set(keyFunc, 'keyFunc와 관련된 값')
+
+myMap.size              // 3
+
+// getting the values
+myMap.get(keyString)    // "'문자열'과 관련된 값"
+myMap.get(keyObj)       // "keyObj와 관련된 값"
+myMap.get(keyFunc)      // "keyFunc와 관련된 값"
+
+myMap.get('문자열')    // "'문자열'과 관련된 값"
+                         // keyString === '문자열'이기 때문
+myMap.get({})            // undefined, keyObj !== {}
+myMap.get(function() {}) // undefined, keyFunc !== function () {}
+ +

Map의 키로 NaN 사용하기

+ +

{{jsxref("NaN")}}도 키로서 사용할 수 있습니다. 모든 NaN은 자기 자신과 동일하지 않지만(NaN !== NaN), NaN을 서로 구분할 수도 없기 때문에 아래 예제도 잘 동작합니다.

+ +
let myMap = new Map()
+myMap.set(NaN, 'not a number')
+
+myMap.get(NaN)
+// "not a number"
+
+let otherNaN = Number('foo')
+myMap.get(otherNaN)
+// "not a number"
+ +

for..ofMap 순회하기

+ +

Mapfor..of 반복문을 사용해 순회할 수 있습니다.

+ +
let myMap = new Map()
+myMap.set(0, 'zero')
+myMap.set(1, 'one')
+
+for (let [key, value] of myMap) {
+  console.log(key + ' = ' + value)
+}
+// 0 = zero
+// 1 = one
+
+for (let key of myMap.keys()) {
+  console.log(key)
+}
+// 0
+// 1
+
+for (let value of myMap.values()) {
+  console.log(value)
+}
+// zero
+// one
+
+for (let [key, value] of myMap.entries()) {
+  console.log(key + ' = ' + value)
+}
+// 0 = zero
+// 1 = one
+ +

forEach()Map 순회하기

+ +

Map은 {{jsxref("Map.prototype.forEach", "forEach()")}} 메서드로 순회할 수 있습니다.

+ +
myMap.forEach(function(value, key) {
+  console.log(key + ' = ' + value)
+})
+// 0 = zero
+// 1 = one
+ +

Array 객체와의 관계

+ +
let kvArray = [['key1', 'value1'], ['key2', 'value2']]
+
+// Use the regular Map constructor to transform a 2D key-value Array into a map
+let myMap = new Map(kvArray)
+
+myMap.get('key1') // returns "value1"
+
+// Use Array.from() to transform a map into a 2D key-value Array
+console.log(Array.from(myMap)) // Will show you exactly the same Array as kvArray
+
+// A succinct way to do the same, using the spread syntax
+console.log([...myMap])
+
+// Or use the keys() or values() iterators, and convert them to an array
+console.log(Array.from(myMap.keys())) // ["key1", "key2"]
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Map")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/map/map/index.html b/files/ko/web/javascript/reference/global_objects/map/map/index.html new file mode 100644 index 0000000000..012772eec5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/map/index.html @@ -0,0 +1,60 @@ +--- +title: Map() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/Map/Map +tags: + - Constructor + - JavaScript + - Map + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/Map +--- +
{{JSRef}}
+ +

Map() 생성자는 {{jsxref("Map")}} 객체를 생성합니다.

+ +

구문

+ +
new Map([iterable])
+ +

매개변수

+ +
+
iterable
+
요소가 키-값 쌍인, {{jsxref("Array")}} 또는 다른 순회 가능한 객체(예: [[1, 'one'], [2, 'two']]). 각 키-값 쌍은 새로운 Map에 포함됩니다.
+
+ +

예제

+ +
let myMap = new Map([
+  [1, 'one'],
+  [2, 'two'],
+  [3, 'three'],
+])
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-map-constructor', 'Map constructor')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Map.Map")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/map/prototype/index.html b/files/ko/web/javascript/reference/global_objects/map/prototype/index.html new file mode 100644 index 0000000000..633d2c785e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/prototype/index.html @@ -0,0 +1,86 @@ +--- +title: Map.prototype +slug: Web/JavaScript/Reference/Global_Objects/Map/prototype +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +
{{JSRef}}
+ +

Map.prototype property는 {{jsxref("Map")}}의 프로토 타입을 나타낸다.

+ +
{{js_property_attributes(0,0,0)}}
+ +

Description

+ +

{{jsxref("Map")}} instance는 {{jsxref("Map.prototype")}}를 상속한다. Constructor의 프로토타입에 property와 method를 추가함으로써 모든 Map 인스턴스에서 사용 가능하게끔 만들 수 있다.

+ +

Properties

+ +
+
Map.prototype.constructor
+
인스턴스의 프로토타입을 만드는 함수를 반환한다. 이것 {{jsxref("Map")}} 함수의 기본 값이다.
+
{{jsxref("Map.prototype.size")}}
+
Map 객체에 들어있는 key/value pair의 수를 반환한다.
+
+ +

Methods

+ +
+
{{jsxref("Map.prototype.clear()")}}
+
Map 객체의 모든 key/value pair를 제거한다.
+
{{jsxref("Map.delete", "Map.prototype.delete(key)")}}
+
주어진 키(Key)와 해당되는 값(Value)를 제거하고 제거하기 전에 Map.prototype.has(key)가 반환했던 값을 반환한다. 그 후의 Map.prototype.has(key)는 false를 반환한다.
+
{{jsxref("Map.prototype.entries()")}}
+
Map 객체 안의 모든 요소들을 [key, value] 형태의 array 로 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.
+
{{jsxref("Map.forEach", "Map.prototype.forEach(callbackFn[, thisArg])")}}
+
Map 객체 안에 존재하는 각각의 key/value pair에 집어넣은 순서대로 callbackFn을 부른다. 만약 thisArg 매개변수가 제공되면, 이것이 각 callback의 this 값으로 사용된다.
+
{{jsxref("Map.get", "Map.prototype.get(key)")}}
+
주어진 키(Key)에 해당되는 값(value)을 반환하고, 만약 없으면 undefined를 반환한다.
+
{{jsxref("Map.has", "Map.prototype.has(key)")}}
+
Map 객체 안에 주어진 key/value pair가 있는지 검사하고 Boolean 값을 반환한다.
+
{{jsxref("Map.prototype.keys()")}}
+
Map 객체 안의 모든 키(Key)들을 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.
+
{{jsxref("Map.set", "Map.prototype.set(key, value)")}}
+
Map 객체에 주어진 키(Key)에 값(Value)를 집어넣고, Map 객체를 반환한다.
+
{{jsxref("Map.prototype.values()")}}
+
Map 객체 안의 모든 (Value)들을 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.
+
{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}
+
Map 객체 안의 모든 요소들을 [key, value] 형태의 array 로 집어넣은 순서대로 가지고 있는 Iterator 객체를 반환한다.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype', 'Map.prototype')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype', 'Map.prototype')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{Compat("javascript.builtins.Map.prototype")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/map/set/index.html b/files/ko/web/javascript/reference/global_objects/map/set/index.html new file mode 100644 index 0000000000..a6c5afb140 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/set/index.html @@ -0,0 +1,96 @@ +--- +title: Map.prototype.set() +slug: Web/JavaScript/Reference/Global_Objects/Map/set +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Map/set +--- +
{{JSRef}}
+ +

set() 메서드는 Map 객체에서 주어진 키를 가진 요소를 추가하고, 키의 요소가 이미 있다면 대체합니다.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-set.html")}}
+ + + +

구문

+ +
myMap.set(key, value);
+ +

매개변수

+ +
+
key
+
Map에 추가하거나 변경할 요소의 키.
+
value
+
Map에 추가하거나 변경할 요소의 값.
+
+ +

반환 값

+ +

호출한 Map 객체.

+ +

예제

+ +

set() 사용하기

+ +
var myMap = new Map();
+
+// Add new elements to the map
+myMap.set('bar', 'foo');
+myMap.set(1, 'foobar');
+
+// Update an element in the map
+myMap.set('bar', 'baz');
+
+ +

set() 체이닝

+ +

set()이 같은 Map을 반환하므로 메서드를 여러 번 연속해서 호출할 수 있습니다.

+ +
// Add new elements to the map with chaining.
+myMap.set('bar', 'foo')
+     .set(1, 'foobar')
+     .set(2, 'baz');
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype.set', 'Map.prototype.set')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.set', 'Map.prototype.set')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Map.set")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/map/size/index.html b/files/ko/web/javascript/reference/global_objects/map/size/index.html new file mode 100644 index 0000000000..371d8b3110 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/map/size/index.html @@ -0,0 +1,62 @@ +--- +title: Map.prototype.size +slug: Web/JavaScript/Reference/Global_Objects/Map/size +translation_of: Web/JavaScript/Reference/Global_Objects/Map/size +--- +
{{JSRef}}
+ +

size 접근자 프로퍼티는  {{jsxref("Map")}} 객체의 요소 갯수를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-size.html")}}
+ + + +

설명

+ +

size 값은 얼마나 많은 엔트리를 Map 객체가 가지고 있는지를 표현합니다. size 를 설정할 수 있는 접근자 함수는 undefined 입니다. 당신은 이 프로퍼티를 변경할 수 없습니다.

+ +

예제

+ +

Using size

+ +
var myMap = new Map();
+myMap.set('a', 'alpha');
+myMap.set('b', 'beta');
+myMap.set('g', 'gamma');
+
+myMap.size // 3
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-get-map.prototype.size', 'Map.prototype.size')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-get-map.prototype.size', 'Map.prototype.size')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Map.size")}}

+ +

더 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/abs/index.html b/files/ko/web/javascript/reference/global_objects/math/abs/index.html new file mode 100644 index 0000000000..c66172647d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/abs/index.html @@ -0,0 +1,104 @@ +--- +title: Math.abs() +slug: Web/JavaScript/Reference/Global_Objects/Math/abs +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs +--- +
{{JSRef}}
+ +

Math.abs() 함수는 주어진 숫자의 절대값을 반환합니다. 즉,

+ +

Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ -x & \text{if} \quad x < 0 \end{cases}

+ +
{{EmbedInteractiveExample("pages/js/math-abs.html")}}
+ + + +

구문

+ +
Math.abs(x)
+ +

매개변수

+ +
+
x
+
숫자.
+
+ +

반환 값

+ +

주어진 숫자의 절대값.

+ +

설명

+ +

abs()Math의 정적 메서드이므로, 사용자가 생성한 Math 객체의 메서드로 호출할 수 없고 항상 Math.abs()를 사용해야 합니다. (Math는 생성자가 아닙니다)

+ +

예제

+ +

Math.abs()의 작동 방식

+ +

빈 객체, 하나 이상의 요소를 가진 배열, 숫자가 아닌 문자열, {{jsxref("undefined")}}나 빈 매개변수를 받으면 {{jsxref("NaN")}}을 반환합니다. {{jsxref("null")}}, 빈 문자열이나 빈 배열을 제공하면 0을 반환합니다.

+ +
Math.abs('-1');     // 1
+Math.abs(-2);       // 2
+Math.abs(null);     // 0
+Math.abs('');       // 0
+Math.abs([]);       // 0
+Math.abs([2]);      // 2
+Math.abs([1,2]);    // NaN
+Math.abs({});       // NaN
+Math.abs('string'); // NaN
+Math.abs();         // NaN
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.abs")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/acos/index.html b/files/ko/web/javascript/reference/global_objects/math/acos/index.html new file mode 100644 index 0000000000..83cc67d786 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/acos/index.html @@ -0,0 +1,103 @@ +--- +title: Math.acos() +slug: Web/JavaScript/Reference/Global_Objects/Math/acos +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/acos +--- +
{{JSRef}}
+ +

Math.acos() 함수는 주어진 수의 아크코사인 값을 숫자(라디안)로 반환합니다. 즉,

+ +

x[-1;1],Math.acos(x)=arccos(x)= the unique y[0;π]such thatcos(y)=x\forall x \in [{-1};1],\;\mathtt{\operatorname{Math.acos}(x)} = \arccos(x) = \text{ the unique } \; y \in [0; \pi] \, \text{such that} \; \cos(y) = x

+ +
{{EmbedInteractiveExample("pages/js/math-acos.html")}}
+ + + +

구문

+ +
Math.acos(x)
+ +

매개변수

+ +
+
x
+
각도를 나타내는 라디안.
+
+ +

반환 값

+ +

-1과 1 사이의 값이 주어진 경우, 그 값의 아크코사인. 아닐 경우 {{jsxref("NaN")}}

+ +

설명

+ +

The Math.acos() method returns a numeric value between 0 and π radians for x between -1 and 1. If the value of x is outside this range, it returns {{jsxref("NaN")}}.

+ +

Because acos() is a static method of Math, you always use it as Math.acos(), rather than as a method of a Math object you created (Math is not a constructor).

+ +

예제

+ +

Using Math.acos()

+ +
Math.acos(-2);  // NaN
+Math.acos(-1);  // 3.141592653589793
+Math.acos(0);   // 1.5707963267948966
+Math.acos(0.5); // 1.0471975511965979
+Math.acos(1);   // 0
+Math.acos(2);   // NaN
+
+ +

For values less than -1 or greater than 1, Math.acos() returns {{jsxref("NaN")}}.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.2', 'Math.acos')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.acos', 'Math.acos')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.acos', 'Math.acos')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.acos")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/cbrt/index.html b/files/ko/web/javascript/reference/global_objects/math/cbrt/index.html new file mode 100644 index 0000000000..20a5f3ee3a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/cbrt/index.html @@ -0,0 +1,98 @@ +--- +title: Math.cbrt() +slug: Web/JavaScript/Reference/Global_Objects/Math/cbrt +tags: + - JavaScript + - Math + - Method + - Reference + - 세제곱근 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/cbrt +--- +
{{JSRef}}
+ +

Math.cbrt() 함수는 주어진 수의 세제곱근을 반환합니다. 즉,

+ +

Math.cbrt(x)=x3=the uniqueysuch thaty3=x\mathtt{Math.cbrt(x)} = \sqrt[3]{x} = \text{the unique} \; y \; \text{such that} \; y^3 = x

+ +

구문

+ +
Math.cbrt(x)
+ +

매개변수

+ +
+
x
+
숫자.
+
+ +

반환 값

+ +

주어진 수의 세제곱근.

+ +

설명

+ +

cbrt()는 Math의 정적 메서드이므로, 사용자가 생성한 Math 객체의 메서드로 호출할 수 없고 항상 Math.cbrt()를 사용해야 합니다. (Math는 생성자가 아닙니다)

+ +

예제

+ +

Math.cbrt() 사용하기

+ +
Math.cbrt(NaN); // NaN
+Math.cbrt(-1); // -1
+Math.cbrt(-0); // -0
+Math.cbrt(-Infinity); // -Infinity
+Math.cbrt(0); // 0
+Math.cbrt(1); // 1
+Math.cbrt(Infinity); // Infinity
+Math.cbrt(null); // 0
+Math.cbrt(2);  // 1.2599210498948734
+
+ +

폴리필

+ +

모든 x0x \geq 0에서 x3=x1/3\sqrt[3]{x} = x^{1/3} 이므로, Math.cbrt()는 다음 함수로 폴리필할 수 있습니다.

+ +
if (!Math.cbrt) {
+  Math.cbrt = (function(pow) {
+    return function cbrt(){
+      // ensure negative numbers remain negative:
+      return x < 0 ? -pow(-x, 1/3) : pow(x, 1/3);
+    };
+  })(Math.pow); // localize Math.pow to increase efficiency
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-math.cbrt', 'Math.cbrt')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.cbrt', 'Math.cbrt')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.cbrt")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/ceil/index.html b/files/ko/web/javascript/reference/global_objects/math/ceil/index.html new file mode 100644 index 0000000000..ee5998fa83 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,209 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Reference/Global_Objects/Math/ceil +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +
{{JSRef}}
+ +
Math.ceil() 함수는 주어진 숫자보다 크거나 같은 숫자 중 가장 작은 숫자를 integer 로 반환합니다.
+ +
 
+ +

Syntax (문법)

+ +
Math.ceil(x)
+ +

Parameters (매개변수)

+ +
+
x
+
숫자
+
+ +

Return value (반환값)

+ +

주어진 숫자보다 크거나 같은 숫자 중 가장 작은 숫자

+ +

Description (설명)

+ +

ceil() 은 Math 의 정적 메소드이므로, 사용자가 생성하는 Math 객체의 메소드처럼 사용하지 않고, 언제나 Math.ceil() 의 형태로 사용 합니다. (Math 는 생성자가 아님)

+ +

Examples (예제)

+ +

Math.ceil() 사용 예

+ +

다음은 Math.ceil() 의 사용 예입니다.

+ +
Math.ceil(.95);    // 1
+Math.ceil(4);      // 4
+Math.ceil(7.004);  // 8
+Math.ceil(-0.95);  // -0
+Math.ceil(-4);     // -4
+Math.ceil(-7.004); // -7
+
+ +

소수점 처리

+ +
// Closure
+(function() {
+  /**
+   * Decimal adjustment of a number.
+   *
+   * @param {String}  type  The type of adjustment.
+   * @param {Number}  value The number.
+   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
+   * @returns {Number} The adjusted value.
+   */
+  function decimalAdjust(type, value, exp) {
+    // If the exp is undefined or zero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // If the value is not a number or the exp is not an integer...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

Specifications (사용법)

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility (브라우저 호환성)

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also (추가 참조)

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/e/index.html b/files/ko/web/javascript/reference/global_objects/math/e/index.html new file mode 100644 index 0000000000..d2d4060bed --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/e/index.html @@ -0,0 +1,84 @@ +--- +title: Math.E +slug: Web/JavaScript/Reference/Global_Objects/Math/E +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/E +--- +
{{JSRef}}
+ +

Math.E 속성은 자연로그의 밑 값  e를 나타내며 약 2.718의 값을 가집니다.

+ +

Math.E=e2.718\mathtt{\mi{Math.E}} = e \approx 2.718

+ +
{{EmbedInteractiveExample("pages/js/math-e.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

EMath의 정적 속성이므로, 사용자가 생성한 Math 객체의 속성으로 접근할 수 없고 항상 Math.E를 사용해야 합니다. (Math는 생성자가 아닙니다)

+ +

예제

+ +

Math.E 사용하기

+ +

다음 함수는 e 값을 반환합니다.

+ +
function getNapier() {
+  return Math.E;
+}
+
+getNapier(); // 2.718281828459045
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.1', 'Math.E')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.e', 'Math.E')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.e', 'Math.E')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.E")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/exp/index.html b/files/ko/web/javascript/reference/global_objects/math/exp/index.html new file mode 100644 index 0000000000..c00f391045 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/exp/index.html @@ -0,0 +1,90 @@ +--- +title: Math.exp() +slug: Web/JavaScript/Reference/Global_Objects/Math/exp +translation_of: Web/JavaScript/Reference/Global_Objects/Math/exp +--- +
{{JSRef}}
+ +

 Math.exp()함수는 x를 인수로 하는 ex 값을 반환합니다. 그리고 e는 {{jsxref("Math.E", "오일러 상수(또는 네이피어 상수)", "", 1)}}는 자연 로그의 밑입니다.

+ +
{{EmbedInteractiveExample("pages/js/math-exp.html")}}
+ + + +

구문

+ +
Math.exp(x)
+ +

매개변수

+ +
+
x
+
숫자
+
+ +

반환 값

+ +

e는 {{jsxref("Math.E", "오일러 상수", "", 1)}}이고 x는 인수인 ex

+ +

Description

+ +

exp()Math의 정적 메소드이기 때문에 새로 작성한 Math 오브젝트 대신에 항상 Math.exp()의 형태로 써야 합니다. (Math는 생성자가 아닙니다.)

+ +

예시

+ +

 Math.exp() 사용 예

+ +
Math.exp(-1); // 0.36787944117144233
+Math.exp(0);  // 1
+Math.exp(1);  // 2.718281828459045
+
+ +

설명

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
설명상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}최초의 정의. JavaScript 1.0.에서 첫 시행.
{{SpecName('ES5.1', '#sec-15.8.2.8', 'Math.exp')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.exp', 'Math.exp')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-math.exp', 'Math.exp')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.exp")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/floor/index.html b/files/ko/web/javascript/reference/global_objects/math/floor/index.html new file mode 100644 index 0000000000..cd749b07c8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/floor/index.html @@ -0,0 +1,171 @@ +--- +title: Math.floor() +slug: Web/JavaScript/Reference/Global_Objects/Math/floor +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor +--- +
{{JSRef}}
+ +

Math.floor() 함수는 주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/math-floor.html")}}
+ + + +

구문

+ +
Math.floor(x)
+ +

매개변수

+ +
+
x
+
숫자.
+
+ +

반환 값

+ +

주어진 수 이하의 가장 큰 정수.

+ +

설명

+ +

floor()Math의 정적 메서드이므로, 사용자가 생성한 Math 객체의 메서드로 호출할 수 없고 항상 Math.floor()를 사용해야 합니다. (Math는 생성자가 아닙니다)

+ +
+

참고: Math.floor(null)은 {{jsxref("NaN")}} 대신 0을 반환합니다.

+
+ +

예제

+ +

Math.floor() 사용하기

+ +
Math.floor( 45.95); //  45
+Math.floor( 45.05); //  45
+Math.floor(  4   ); //   4
+Math.floor(-45.05); // -46
+Math.floor(-45.95); // -46
+
+ +

십진수 조절

+ +
// Closure
+(function() {
+  /**
+   * Decimal adjustment of a number.
+   *
+   * @param {String}  type  The type of adjustment.
+   * @param {Number}  value The number.
+   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
+   * @returns {Number} The adjusted value.
+   */
+  function decimalAdjust(type, value, exp) {
+    // If the exp is undefined or zero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // If the value is not a number or the exp is not an integer...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.floor")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/fround/index.html b/files/ko/web/javascript/reference/global_objects/math/fround/index.html new file mode 100644 index 0000000000..6fd328a2db --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/fround/index.html @@ -0,0 +1,130 @@ +--- +title: Math.fround() +slug: Web/JavaScript/Reference/Global_Objects/Math/fround +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/fround +--- +
{{JSRef}}
+ +

Math.fround() 함수는 single precision 포맷으로 표현할 수 있는 실수들 중에서 가장 가까운 숫자를 리턴합니다.

+ +

문법

+ +
Math.fround(x)
+ +

파라메터

+ +
+
x
+
숫자.
+
+ +

설명

+ +

fround()Math 객체의 정적 메소드이기 때문에, 반드시 Math.fround() 같은 형태로 사용해야 합니다. Math 객체를 직접 만들어서 호출하는 방식으로 사용하지 않습니다 (Math 는 생성자가 아닙니다).

+ +

예제

+ +

Math.fround() 사용법

+ +
Math.fround(0);     // 0
+Math.fround(1);     // 1
+Math.fround(1.337); // 1.3370000123977661
+Math.fround(1.5);   // 1.5
+Math.fround(NaN);   // NaN
+
+ +

Polyfill

+ +

만약 {{jsxref("Float32Array")}} 가 지원된다면, Math.fround() 를 다음 함수로 흉내낼 수 있습니다.

+ +
Math.fround = Math.fround || (function (array) {
+  return function(x) {
+    return array[0] = x, array[0];
+  };
+})(Float32Array(1));
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태비고
{{SpecName('ES6', '#sec-math.fround', 'Math.fround')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-math.fround', 'Math.fround')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("38")}}{{CompatGeckoDesktop("26")}}{{CompatNo}}{{CompatOpera("25")}}{{CompatSafari("7.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}8
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/imul/index.html b/files/ko/web/javascript/reference/global_objects/math/imul/index.html new file mode 100644 index 0000000000..e5f7a919ab --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/imul/index.html @@ -0,0 +1,130 @@ +--- +title: Math.imul() +slug: Web/JavaScript/Reference/Global_Objects/Math/imul +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/imul +--- +
{{JSRef}}
+ +

Math.imul() 함수는 C 언어와 같은 양식으로 2개 파라메터의 32-bit 곱셈 결과를 리턴합니다.

+ +

문법

+ +
Math.imul(a, b)
+ +

파라메터

+ +
+
a
+
첫 번째 숫자.
+
b
+
두 번째 숫자.
+
+ +

설명

+ +

Math.imul() 를 쓰면 C 언어와 같은 양식의 빠른 32-bit 정수 곱셈이 가능합니다. 이 기능은 Emscripten 같은 프로젝트에 유용합니다. imul()Math 객체의 정적 메소드이기 때문에, Math 객체를 직접 만들어서 사용하지 않고 (Math 는 생성자가 아닙니다), Math.imul() 같은 형태로 사용합니다.

+ +

예제

+ +

Math.imul() 사용법

+ +
Math.imul(2, 4);          // 8
+Math.imul(-1, 8);         // -8
+Math.imul(-2, -2);        // 4
+Math.imul(0xffffffff, 5); // -5
+Math.imul(0xfffffffe, 5); // -10
+
+ +

Polyfill

+ +

다음과 같은 함수로 Math.imul() 을 흉내낼 수 있습니다.

+ +
Math.imul = Math.imul || function(a, b) {
+  var ah = (a >>> 16) & 0xffff;
+  var al = a & 0xffff;
+  var bh = (b >>> 16) & 0xffff;
+  var bl = b & 0xffff;
+  // the shift by 0 fixes the sign on the high part
+  // the final |0 converts the unsigned value into a signed value
+  return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0);
+};
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태비고
{{SpecName('ES6', '#sec-math.imul', 'Math.imul')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-math.imul', 'Math.imul')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("28")}}{{CompatGeckoDesktop("20")}}{{CompatUnknown}}{{CompatOpera("16")}}{{CompatSafari("7")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("20")}}{{CompatUnknown}}{{CompatUnknown}}7
+
diff --git a/files/ko/web/javascript/reference/global_objects/math/index.html b/files/ko/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..3ce1a0638c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,155 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +tags: + - JavaScript + - Math + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +
{{JSRef}}
+ +

Math는 수학적인 상수와 함수를 위한 속성과 메서드를 가진 내장 객체입니다. 함수 객체가 아닙니다.

+ +

Math는 {{jsxref("Number")}} 자료형만 지원하며 {{jsxref("BigInt")}}와는 사용할 수 없습니다.

+ +

설명

+ +

다른 전역 객체와 달리 Math는 생성자가 아닙니다. Math의 모든 속성과 메서드는 정적입니다. 파이 상수는 Math.PI로 참조할 수 있고, 사인 함수는 매개변수 x에 대해 Math.sin(x)와 같이 호출할 수 있습니다. 상수는 JavaScript에서 가능한 최대 실수 정밀도로 정의되어 있습니다.

+ +

속성

+ +
+
{{jsxref("Math.E")}}
+
+

오일러의 상수이며 자연로그의 밑. 약 2.718.

+
+
{{jsxref("Math.LN2")}}
+
+

2의 자연로그. 약 0.693.

+
+
{{jsxref("Math.LN10")}}
+
10의 자연로그. 약 2.303.
+
{{jsxref("Math.LOG2E")}}
+
밑이 2인 로그 E. 약 1.443.
+
{{jsxref("Math.LOG10E")}}
+
밑이 10인 로그 E. 약 0.434.
+
{{jsxref("Math.PI")}}
+
원의 둘레와 지름의 비율. 약 3.14159.
+
{{jsxref("Math.SQRT1_2")}}
+
½의 제곱근. 약 0.707.
+
{{jsxref("Math.SQRT2")}}
+
2의 제곱근. 약 1.414.
+
+ +

메서드

+ +
+

참고: 삼각 함수(sin()cos(), tan(), asin(), acos(), atan(), atan2())는 매개변수와 반환값 모두 호도법(라디안)을 사용합니다.

+ +

라디안 값을 각도 값으로 변환하려면 (Math.PI / 180)으로 나누세요. 반대로 각도 값에 곱하면 라디안 값이 됩니다.

+
+ +
+

참고: 많은 수의 Math 함수 정확도는 구현에 따라 다를 수 있습니다. 즉, 각 브라우저의 결과가 다를 수 있으며, 서로 같은 JS 엔진이라도 운영체제나 아키텍쳐에 따라서 불일치하는 값을 반환할 수 있습니다.

+
+ +
+
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
+
숫자의 절댓값을 반환합니다.
+
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
+
숫자의 아크코사인 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}} 
+
숫자의 쌍곡아크코사인 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
+
숫자의 아크사인 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}} 
+
숫자의 쌍곡아크사인 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
+
숫자의 아크탄젠트 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}} 
+
숫자의 쌍곡아크탄젠트 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
+
인수 몫의 아크탄젠트 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}} 
+
숫자의 세제곱근을 반환합니다.
+
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
+
인수보다 크거나 같은 수 중에서 가장 작은 정수를 반환합니다.
+
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}} 
+
주어진 32비트 정수의 선행 0 개수를 반환합니다.
+
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
+
숫자의 코사인 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}} 
+
숫자의 쌍곡코사인 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
+
Ex 를 반환합니다. x는 인수이며 E 는 오일러 상수(2.718...) 또는 자연로그의 밑입니다.
+
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}} 
+
exp(x)에서 1을 뺀 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
+
인수보다 작거나 같은 수 중에서 가장 큰 정수를 반환합니다.
+
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}} 
+
인수의 가장 가까운 단일 정밀도 표현을 반환합니다.
+
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}} 
+
인수의 제곱합의 제곱근을 반환합니다.
+
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}} 
+
두 32비트 정수의 곱을 반환합니다.
+
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
+
숫자의 자연로그(loge 또는 ln) 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}} 
+
숫자 x에 대해 1 + x의 자연로그(loge 또는 ln) 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}} 
+
숫자의 밑이 10인 로그를 반환합니다.
+
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}} 
+
숫자의 밑이 2인 로그를 반환합니다.
+
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
+
0개 이상의 인수에서 제일 큰 수를 반환합니다.
+
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
+
0개 이상의 인수에서 제일 작은 수를 반환합니다.
+
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
+
x의 y 제곱을 반환합니다.
+
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
+
0과 1 사이의 난수를 반환합니다.
+
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
+
숫자에서 가장 가까운 정수를 반환합니다.
+
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}} 
+
x의 양의 수인지 음의 수인지 나타내는 부호를 반환합니다.
+
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
+
숫자의 사인 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}} 
+
숫자의 쌍곡사인 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
+
숫자의 제곱근을 반환합니다.
+
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
+
숫자의 탄젠트 값을 반환합니다.
+
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}} 
+
숫자의 쌍곡탄젠트 값을 반환합니다.
+
Math.toSource() {{non-standard_inline}}
+
문자열 "Math"를 반환합니다.
+
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}} 
+
숫자의 정수 부분을 반환합니다.
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/ln10/index.html b/files/ko/web/javascript/reference/global_objects/math/ln10/index.html new file mode 100644 index 0000000000..57ab837e50 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/ln10/index.html @@ -0,0 +1,84 @@ +--- +title: Math.LN10 +slug: Web/JavaScript/Reference/Global_Objects/Math/LN10 +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LN10 +--- +
{{JSRef}}
+ +

Math.LN10 속성은 10의 자연로그 값, 약 2.302의 값을 가집니다.

+ +

Math.LN10=ln(10)2.302\mathtt{\mi{Math.LN10}} = \ln(10) \approx 2.302

+ +
{{EmbedInteractiveExample("pages/js/math-ln10.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

LN10Math의 정적 속성이므로, 사용자가 생성한 Math 객체의 속성으로 접근할 수 없고 항상 Math.LN10을 사용해야 합니다. (Math는 생성자가 아닙니다)

+ +

예제

+ +

Math.LN10 사용하기

+ +

다음 함수는 10의 자연 로그 값을 반환합니다.

+ +
function getNatLog10() {
+  return Math.LN10;
+}
+
+getNatLog10(); // 2.302585092994046
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.2', 'Math.LN10')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.LN10")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/ln2/index.html b/files/ko/web/javascript/reference/global_objects/math/ln2/index.html new file mode 100644 index 0000000000..202558fd59 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/ln2/index.html @@ -0,0 +1,86 @@ +--- +title: Math.LN2 +slug: Web/JavaScript/Reference/Global_Objects/Math/LN2 +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LN2 +--- +
{{JSRef}}
+ +

The Math.LN2 property represents the natural logarithm of 2, approximately 0.693:

+ +

Math.LN2 속성은 2의 자연로그 값, 약 0.693의 값을 가집니다.

+ +

Math.LN2=ln(2)0.693\mathtt{\mi{Math.LN2}} = \ln(2) \approx 0.693

+ +
{{EmbedInteractiveExample("pages/js/math-ln2.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

LN2Math의 정적 속성이므로, 사용자가 생성한 Math 객체의 속성으로 접근할 수 없고 항상 Math.LN2를 사용해야 합니다. (Math는 생성자가 아닙니다)

+ +

Examples

+ +

Math.LN2 사용하기

+ +

다음 함수는 2의 자연 로그 값을 반환합니다.

+ +
function getNatLog2() {
+  return Math.LN2;
+}
+
+getNatLog2(); // 0.6931471805599453
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.3', 'Math.LN2')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ln2', 'Math.LN2')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ln2', 'Math.LN2')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.LN2")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/log/index.html b/files/ko/web/javascript/reference/global_objects/math/log/index.html new file mode 100644 index 0000000000..a343fa27a6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/log/index.html @@ -0,0 +1,104 @@ +--- +title: Math.log() +slug: Web/JavaScript/Reference/Global_Objects/Math/log +translation_of: Web/JavaScript/Reference/Global_Objects/Math/log +--- +
{{JSRef}}
+ +

Math.log() 함수는 자연 로가리즘은 ({{jsxref("Math.E", "e")}} 를 기초) 의 수를 계산합니다, 이건 다음의

+ +

x>0,Math.log(x)=ln(x)=the uniqueysuch thatey=x\forall x > 0, \mathtt{\operatorname{Math.log}(x)} = \ln(x) = \text{고유값} \; y \; \text{같이} \; e^y = x

+ +

자바스크립트 Math.log() 함수는 ln(x) 수학적으로 같습니다.

+ +

문법

+ +
Math.log(x)
+ +

인자

+ +
+
x
+
실수값.
+
+ +

반환값

+ +

자연 로가리즘은 ({{jsxref("Math.E", "e")}} 를 기초) 실수값으로 줍니다. 마이너스 실수값, {{jsxref("NaN")}} 계산됩니다.

+ +

설명

+ +

만일 값 x 가 마이너스라면, 항상 다음값이 계산됩니다 {{jsxref("NaN")}}.

+ +

왜그렇냐면 Math의 log() 가 정적 메서드이기 때문,에 매번 다음처럼 Math.log() 써야합니다 (생성자로 초기화된 Math 개체가 아니기 때문입니다).

+ +

자연로그 2 나 10, 상수로쓸때 {{jsxref("Math.LN2")}} or {{jsxref("Math.LN10")}} . 로가리즘 기초값 2 나 10, 쓸때는 {{jsxref("Math.log2()")}} 혹은 {{jsxref("Math.log10()")}} . 로가리즘 다른 기초값은 Math.log(x) / Math.log(기초값) 처럼 예제참고; 미리계산하여 1 / Math.log(기초값) 할 수 있습니다.

+ +

예제

+ +

Math.log() 사용

+ +
Math.log(-1); // NaN, 정의범위 초과
+Math.log(0);  // -Infinity, 무한
+Math.log(1);  // 0
+Math.log(10); // 2.302585092994046
+
+ +

Math.log() 다른 기초값 사용

+ +

이 함수는 로가리즘 y 에 대한것으로 기초값 x (ie. logxy\log_x y): 입니다

+ +
function getBaseLog(x, y) {
+  return Math.log(y) / Math.log(x);
+}
+
+ +

다음을 실행하면 getBaseLog(10, 1000) 다음 2.9999999999999996 계산되는데 적당히 반올림하니다, 거의 3 에 가깝습니다.

+ +

명세서

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.10', 'Math.log')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.log', 'Math.log')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.log', 'Math.log')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.log")}}

+ +

같이보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/log10e/index.html b/files/ko/web/javascript/reference/global_objects/math/log10e/index.html new file mode 100644 index 0000000000..bb864c8aa3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/log10e/index.html @@ -0,0 +1,84 @@ +--- +title: Math.LOG10E +slug: Web/JavaScript/Reference/Global_Objects/Math/LOG10E +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LOG10E +--- +
{{JSRef}}
+ +

Math.LOG10E 속성은 e의 로그 10 값, 약 0.434의 값을 가집니다.

+ +

Math.LOG10E=log10(e)0.434\mathtt{\mi{Math.LOG10E}} = \log_10(e) \approx 0.434

+ +
{{EmbedInteractiveExample("pages/js/math-log10e.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

LOG10EMath의 정적 속성이므로, 사용자가 생성한 Math 객체의 속성으로 접근할 수 없고 항상 Math.LOG10E를 사용해야 합니다. (Math는 생성자가 아닙니다)

+ +

예제

+ +

Math.LOG10E 사용하기

+ +

다음 함수는 e의 로그 10 값을 반환합니다.

+ +
function getLog10e() {
+  return Math.LOG10E;
+}
+
+getLog10e(); // 0.4342944819032518
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.5', 'Math.LOG10E')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.log10e', 'Math.LOG10E')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.log10e', 'Math.LOG10E')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.LOG10E")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/log2/index.html b/files/ko/web/javascript/reference/global_objects/math/log2/index.html new file mode 100644 index 0000000000..7cfd72531c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/log2/index.html @@ -0,0 +1,96 @@ +--- +title: Math.log2() +slug: Web/JavaScript/Reference/Global_Objects/Math/log2 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/log2 +--- +
{{JSRef}}
+ +

 Math.log2() 함수는 숫자를 log2(숫자)로 반환합니다.

+ +

x>0,Math.log2(x)=log2(x)=the uniqueysuch that2y=x\forall x > 0, \mathtt{\operatorname{Math.log2}(x)} = \log_2(x) = \text{the unique} \; y \; \text{such that} \; 2^y = x

+ +

문법

+ +
Math.log2(x)
+ +

매개변수

+ +
+
x
+
숫자.
+
+ +

반환 값

+ +

주어진 숫자는 log2(숫자)로 계산합니다. 만약 숫자가 음수라면 {{jsxref("NaN")}}를 반환합니다.

+ +

설명

+ +

만약 x 의 값이 0보다 작다면(음수) 값은 항상 {{jsxref("NaN")}}로 반환합니다.

+ +

log2()는 Math의 정적 메서드이므로 만든 Math 객체의 메서드가 아니라 항상 Math.log2()함수를 사용해야합니다. (Math는 생성자가 없습니다.)

+ +

이 함수는 Math.log(x) / Math.log(2)와 같습니다.

+ +

따라서 log2(e)는 {{jsxref("Math.LOG2E")}}와 같습니다. 

+ +

그리고 위 함수는 1 / {{jsxref("Math.LN2")}}과 같습니다.

+ +

예제

+ +

Math.log2()

+ +
Math.log2(3);    // 1.584962500721156
+Math.log2(2);    // 1
+Math.log2(1);    // 0
+Math.log2(0);    // -Infinity
+Math.log2(-2);   // NaN
+Math.log2(1024); // 10
+
+ +

Polyfill

+ +

This Polyfill emulates the Math.log2 function. Note that it returns imprecise values on some inputs (like 1 << 29), wrap into {{jsxref("Math.round()")}} if working with bit masks.

+ +
Math.log2 = Math.log2 || function(x) {
+  return Math.log(x) * Math.LOG2E;
+};
+
+ +

표준

+ + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES2015', '#sec-math.log2', 'Math.log2')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.log2', 'Math.log2')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.log2")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/log2e/index.html b/files/ko/web/javascript/reference/global_objects/math/log2e/index.html new file mode 100644 index 0000000000..244224df3d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/log2e/index.html @@ -0,0 +1,84 @@ +--- +title: Math.LOG2E +slug: Web/JavaScript/Reference/Global_Objects/Math/LOG2E +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/LOG2E +--- +
{{JSRef}}
+ +

Math.LOG2E 속성은 e의 로그 2 값, 약 1.442의 값을 가집니다.

+ +

Math.LOG2E=log2(e)1.442\mathtt{\mi{Math.LOG2E}} = \log_2(e) \approx 1.442

+ +
{{EmbedInteractiveExample("pages/js/math-log2e.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

LOG2EMath의 정적 속성이므로, 사용자가 생성한 Math 객체의 속성으로 접근할 수 없고 항상 Math.LOG2E를 사용해야 합니다. (Math는 생성자가 아닙니다)

+ +

설명

+ +

Math.LOG2E 사용하기

+ +

다음 함수는 e의 로그 2 값을 반환합니다.

+ +
function getLog2e() {
+  return Math.LOG2E;
+}
+
+getLog2e(); // 1.4426950408889634
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.4', 'Math.LOG2E')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.log2e', 'Math.LOG2E')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.log2e', 'Math.LOG2E')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.LOG2E")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/max/index.html b/files/ko/web/javascript/reference/global_objects/math/max/index.html new file mode 100644 index 0000000000..e315e5027b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/max/index.html @@ -0,0 +1,110 @@ +--- +title: Math.max() +slug: Web/JavaScript/Reference/Global_Objects/Math/max +tags: + - Math + - 메소드 + - 자바스크립트 + - 참조 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/max +--- +
{{JSRef}}
+ +

Math.max()함수는 입력값으로 받은 0개 이상의 숫자 중 가장 큰 숫자를 반환합니다.

+ +

문법

+ +
Math.max([값1[, 값2[, ...]]])
+ +

매개변수

+ +
+
값1, 값2, ...
+
숫자들.
+
+ +

반환 값

+ +

입력된 숫자 중 가장 큰 숫자를 반환합니다. 만약 인수 중 하나라도 숫자로 변환하지 못한다면 {{jsxref("NaN")}}로 반환합니다.

+ +

설명

+ +

max ()는 Math의 정적 메서드이기 때문에 만든 Math 개체의 메서드가 아닌 항상 Math.max ()로 사용해야합니다. (Math는 생성자가 아닙니다).

+ +

만약 아무 요소도 주어지지 않았다면 {{jsxref("-Infinity")}}로 반환합니다.

+ +

만약 한 개 이상의 요소가 숫자로 변환되지 않는다면 {{jsxref("NaN")}}로 반환됩니다.

+ +

예제

+ +

Math.max()함수 사용하기

+ +
Math.max(10, 20);   //  20
+Math.max(-10, -20); // -10
+Math.max(-10, 20);  //  20
+
+ +

다음 함수는 {{jsxref ( "Function.prototype.apply ()")}}을 사용하여 숫자 배열에서 최대 요소를 찾습니다. getMaxOfArray ([1, 2, 3])는 Math.max (1, 2, 3)와 동일하지만 프로그래밍 방식으로 생성 된 모든 크기의 배열에서 getMaxOfArray ()를 사용할 수 있습니다.

+ +
function getMaxOfArray(numArray) {
+  return Math.max.apply(null, numArray);
+}
+
+ +

{{jsxref("Array.prototype.reduce", "Array.reduce()")}} 이 함수 또한 배열의 각 값을 비교하여 가장 큰 숫자를 얻을 수 있습니다.

+ +
var arr = [1,2,3];
+var max = arr.reduce(function(a, b) {
+    return Math.max(a, b);
+});
+
+ +

또한 {{jsxref("Operators/Spread_operator", "spread operator")}}이 함수를 사용하면 배열의 숫자들 중 가장 큰 숫자를 쉽게 얻을 수 있습니다.

+ +
var arr = [1, 2, 3];
+var max = Math.max(...arr);
+
+ +

표준

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.max', 'Math.max')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.max")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/min/index.html b/files/ko/web/javascript/reference/global_objects/math/min/index.html new file mode 100644 index 0000000000..7bf84ee57c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/min/index.html @@ -0,0 +1,103 @@ +--- +title: Math.min() +slug: Web/JavaScript/Reference/Global_Objects/Math/min +translation_of: Web/JavaScript/Reference/Global_Objects/Math/min +--- +
{{JSRef}}
+ +

Math.min() 함수는 주어진 숫자들 중 가장 작은 값을 반환합니다.

+ +

Syntax

+ +
Math.min([value1[, value2[, ...]]])
+ +

Parameters

+ +
+
value1, value2, ...
+
숫자형
+
+ +

Return value

+ +

주어진 숫자들 중 가장 작은 값. 만약 적어도 1개 이상의 인자값이 숫자형으로 변환이 불가능 한 경우 이 함수는 {{jsxref("NaN")}} 를 반환 합니다.

+ +

Description

+ +

min() 함수는 Math 의 정적 메소드 이므로, 사용자가 생성한 Math 객체의 메소드로 호출하는 것이 아닌 항상 Math.min() 으로 호출되어야 합니다. (Math 는 생성자가 아닙니다).

+ +

만약 주어진 인자값이 없을 경우, {{jsxref("Infinity")}} 가 반환됩니다.

+ +

만약 적어도 1개 이상의 인자값이 숫자형으로 변환이 불가능 한 경우, {{jsxref("NaN")}} 가 반환됩니다.

+ +

Examples

+ +

Using Math.min()

+ +

아래 수식은 x 와y 중 작은 값을 찾아 z 에 할당 합니다.     

+ +
var x = 10, y = -20;
+var z = Math.min(x, y);
+
+ +

Clipping a value with Math.min()

+ +

Math.min() 함수는 때때로 값 제한, 즉 항상 기준 보다 작거나 같은 값으로 제한하는 용도로 사용됩니다. 예를 들면,

+ +
var x = f(foo);
+
+if (x > boundary) {
+  x = boundary;
+}
+
+ +

 위 코드는 다음과 같이 쓸 수 있습니다.

+ +
var x = Math.min(f(foo), boundary);
+
+ +

{{jsxref("Math.max()")}} 함수 또한 같은 방식으로 기준보다 크거나 같은 값으로 제한하는 용도로 사용할 수 있습니다.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.12', 'Math.min')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.min', 'Math.min')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.min', 'Math.min')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math.min")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/pi/index.html b/files/ko/web/javascript/reference/global_objects/math/pi/index.html new file mode 100644 index 0000000000..8223a68df6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/pi/index.html @@ -0,0 +1,82 @@ +--- +title: Math.PI +slug: Web/JavaScript/Reference/Global_Objects/Math/PI +tags: + - JavaScript + - Math + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/PI +--- +
{{JSRef}}
+ +

Math.PI 속성은 원의 둘레와 지름의 비율, 약 3.14159의 값을 가집니다.

+ +

Math.PI=π3.14159\mathtt{\mi{Math.PI}} = \pi \approx 3.14159

+ +
{{EmbedInteractiveExample("pages/js/math-pi.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

PIMath의 정적 속성이므로, 사용자가 생성한 Math 객체의 속성으로 접근할 수 없고 항상 Math.PI를 사용해야 합니다. (Math는 생성자가 아닙니다)

+ +

예제

+ +

Math.PI 사용하기

+ +

다음 함수는 Math.PI를 사용해 주어진 원의 반지름에서 둘레를 계산합니다.

+ +
function calculateCircumference(radius) {
+  return Math.PI * (radius + radius);
+}
+
+calculateCircumference(1);  // 6.283185307179586
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
사양등급주석
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.6', 'Math.PI')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.pi', 'Math.PI')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.pi', 'Math.PI')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.PI")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/random/index.html b/files/ko/web/javascript/reference/global_objects/math/random/index.html new file mode 100644 index 0000000000..9ce02207de --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/random/index.html @@ -0,0 +1,106 @@ +--- +title: Math.random() +slug: Web/JavaScript/Reference/Global_Objects/Math/random +translation_of: Web/JavaScript/Reference/Global_Objects/Math/random +--- +
{{JSRef}}
+ +

Math.random() 함수는 0 이상 1 미만의 구간에서 근사적으로 균일한(approximately uniform) 부동소숫점 의사난수를 반환하며, 이 값은 사용자가 원하는 범위로 변형할 수 있다. 난수 생성 알고리즘에 사용되는 초기값은 구현체가 선택하며, 사용자가 선택하거나 초기화할 수 없다.

+ +
+

Math.random()은 암호학적으로 안전한 난수를 제공하지 않으므로, 보안과 관련된 어떤 것에도 이 함수를 사용해서는 안 된다. 그 대신 Web Crypto API의 {{domxref("RandomSource.getRandomValues()", "window.crypto.getRandomValues()")}} 메소드를 이용하여야 한다.

+
+ +

문법

+ +
Math.random()
+
+ +

반환 값

+ +

0 이상 1 미만의 부동소숫점 의사 난수.

+ +

예제

+ +

Math.random() 사용

+ +

JavaScript의 수(number)는 가까운 짝수로 반올림되는(round-to-nearest-even behavior) IEEE 754 부동소수점 실수이므로, 아래 함수들(Math.random() 자체에 대한 사항은 제외)에 명시된 범위는 정확하지 않음을 유의하라. 지나치게 큰 범위(253 이상)를 선택할 경우, 매우 드문 경우 원래 포함되어서는 안 될 최댓값이 포함되는 경우가 있다.

+ +

0 이상 1 미만의 난수 생성하기

+ +
function getRandom() {
+  return Math.random();
+}
+
+ +

두 값 사이의 난수 생성하기

+ +

이 예제는 주어진 두 값 사이의 난수를 생성한다. 함수의 반환값은 min보다 크거나 같으며, max보다 작다.

+ +
function getRandomArbitrary(min, max) {
+  return Math.random() * (max - min) + min;
+}
+
+ +

두 값 사이의 정수 난수 생성하기

+ +

이 예제는 주어진 두 값 사이의 정수인 난수를 생성한다. 반환값은 min(단, min이 정수가 아니면 min보다 큰 최소의 정수)보다 크거나 같으며, max보다 작다.

+ +
function getRandomInt(min, max) {
+  min = Math.ceil(min);
+  max = Math.floor(max);
+  return Math.floor(Math.random() * (max - min)) + min; //최댓값은 제외, 최솟값은 포함
+}
+
+ +
+

이 예제에서 Math.round()를 대신 사용하려고 할 수 있으나, 이렇게 하면 난수가 고르게 분포하지 않게 된다.

+
+ +

최댓값을 포함하는 정수 난수 생성하기

+ +

위의getRandomInt() 함수는 최솟값을 포함하지만, 최댓값은 포함하지 않는다. 최솟값과 최댓값을 모두 포함하는 결과가 필요할 경우, 아래의 getRandomIntInclusive() 함수를 사용할 수 있다.

+ +
function getRandomIntInclusive(min, max) {
+  min = Math.ceil(min);
+  max = Math.floor(max);
+  return Math.floor(Math.random() * (max - min + 1)) + min; //최댓값도 포함, 최솟값도 포함
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.0 (유닉스 전용) / JavaScript 1.1 (모든 플랫폼).
{{SpecName('ES5.1', '#sec-15.8.2.14', 'Math.random')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.random', 'Math.random')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-math.random', 'Math.random')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.random")}}

diff --git a/files/ko/web/javascript/reference/global_objects/math/round/index.html b/files/ko/web/javascript/reference/global_objects/math/round/index.html new file mode 100644 index 0000000000..e163c4459e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/round/index.html @@ -0,0 +1,92 @@ +--- +title: Math.round() +slug: Web/JavaScript/Reference/Global_Objects/Math/round +translation_of: Web/JavaScript/Reference/Global_Objects/Math/round +--- +
{{JSRef}}
+ +

Math.round() 함수는 입력값을 반올림한 수와 가장 가까운 정수 값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/math-round.html")}}
+ + + +

문법

+ +
Math.round(x)
+ +

매개 변수

+ +
+
x
+
+
+ +

반환 값

+ +

입력값을 반올림한 값과 가장 가까운 정수를 의미합니다.

+ +

Description

+ +

If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value.  If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞.  Note that this differs from many languages' round() functions, which often round this case to the next integer away from zero, instead giving a different result in the case of negative numbers with a fractional part of exactly 0.5.

+ +

Because round() is a static method of Math, you always use it as Math.round(), rather than as a method of a Math object you created (Math has no constructor).

+ +

Examples

+ +
Math.round( 20.49); //  20
+Math.round( 20.5 ); //  21
+Math.round( 42   ); //  42
+Math.round(-20.5 ); // -20
+Math.round(-20.51); // -21
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.15', 'Math.round')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.round', 'Math.round')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.round', 'Math.round')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math.round")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/sign/index.html b/files/ko/web/javascript/reference/global_objects/math/sign/index.html new file mode 100644 index 0000000000..adb5f15354 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sign/index.html @@ -0,0 +1,112 @@ +--- +title: Math.sign() +slug: Web/JavaScript/Reference/Global_Objects/Math/sign +tags: + - JavaScript + - Math + - 메소드 + - 참조 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sign +--- +
{{JSRef}}
+ +

Math.sign() 함수는 어떤 수의 부호를 반환합니다. 이것은 그 수가 양수, 음수 또는 0인지를 나나냅니다.

+ +

문법

+ +
Math.sign(x)
+ +

매개변수

+ +
+
x
+
수치.
+
+ +

반환 값

+ +

주어진 인수의 부호를 나타내는 수치. 인수가 양수, 음수, 양수인 영 또는 음수인 영이면, 이 함수는 1, -1, 0, -0을 각각 반환합니다. 그렇지 않으면, {{jsxref("NaN")}} 이 반환됩니다.

+ +

설명

+ +

sign() 이Math의 정적 메소드이기 때문에 항상 Math.sign()으로 사용합니다. 사용자가 만든  Math 개체의 메소드로 가 아닙니다.   (Math 는 생성자가 아닙니다).

+ +

이 함수는 반환 값이 5 가지이며, 1, -1, 0, -0, NaN 입니다. 각각 "양수", "음수", "양의 영", "음의 영", {{jsxref("NaN")}} 입니다.

+ +

이 함수에 전달된 인수는 묵시적으로 수치 로 변환됩니다.

+ +

예제

+ +

 Math.sign()을 사용하기

+ +
Math.sign(3);     //  1
+Math.sign(-3);    // -1
+Math.sign('-3');  // -1
+Math.sign(0);     //  0
+Math.sign(-0);    // -0
+Math.sign(NaN);   // NaN
+Math.sign('foo'); // NaN
+Math.sign();      // NaN
+
+ +

Polyfill

+ +
if (!Math.sign) {
+  Math.sign = function(x) {
+    // x 가 NaN 이면, 결과는 NaN 입니다.
+    // x 가 -0 이면, 결과는 -0 입니다.
+    // x 가 +0 이면, 결과는 +0 입니다.
+    // x 가 음수이면서 -0 이 아니면, 결과는 -1 입니다.
+    // x 가 양수이면서 +0 이 아니면, 결과는 +1 입니다.
+    return ((x > 0) - (x < 0)) || +x;
+    // A more aesthetical persuado-representation is shown below
+    //
+    // ( (x > 0) ? 0 : 1 )  // if x is negative then negative one
+    //          +           // else (because you cant be both - and +)
+    // ( (x < 0) ? 0 : -1 ) // if x is positive then positive one
+    //         ||           // if x is 0, -0, or NaN, or not a number,
+    //         +x           // Then the result will be x, (or) if x is
+    //                      // not a number, then x converts to number
+  };
+}
+
+ +

위의 polyfill에서는, (x > 0) 또는 (x < 0) 인 수치들을 만드는 데에 어떤 추가의 타입-강제하기도 필요하지 않은 것은  그 수치들을 서로에게서 빼는 것이 불린형에서 수치로의 형 변환을 강요하기 때문입니다.

+ +

규격명세

+ + + + + + + + + + + + + + + + + + + +
규격명세상태코멘트
{{SpecName('ES6', '#sec-math.sign', 'Math.sign')}}{{Spec2('ES6')}}최초의 정의.
{{SpecName('ESDraft', '#sec-math.sign', 'Math.sign')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.sign")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/sin/index.html b/files/ko/web/javascript/reference/global_objects/math/sin/index.html new file mode 100644 index 0000000000..1978d7f8e8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sin/index.html @@ -0,0 +1,97 @@ +--- +title: Math.sin() +slug: Web/JavaScript/Reference/Global_Objects/Math/sin +tags: + - 레퍼런스 + - 메소드 + - 수학 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sin +--- +
{{JSRef}}
+ +

 Math.sin() 함수는 숫자의 사인값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/math-sin.html")}}
+ + + +

Syntax

+ +
Math.sin(x)
+ +

파라미터

+ +
+
x
+
숫자 (라디안으로 주어짐).
+
+ +

반환 값

+ +

주어진 숫자의 사인 값

+ +

설명

+ +

Math.sin() 메소드는 라디안으로 주어진 각도의 사인 값인 -1과 1 사이의 수를 반환합니다.

+ +

 sin() 은 Math의 스태틱 메소드이기 때문에, Math 오브젝트 의 메소드로 사용하지 말고 항상 Math.sin()로 사용해야합니다.  (Math 는 생성자가 아닙니다).

+ +

+ +

Using Math.sin()

+ +
Math.sin(0);           // 0
+Math.sin(1);           // 0.8414709848078965
+
+Math.sin(Math.PI / 2); // 1
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}최초 정의. JavaScript 1.0. 에서 구현됨
{{SpecName('ES5.1', '#sec-15.8.2.16', 'Math.sin')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.sin', 'Math.sin')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.sin', 'Math.sin')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.sin")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/sinh/index.html b/files/ko/web/javascript/reference/global_objects/math/sinh/index.html new file mode 100644 index 0000000000..9a3bb3a6ab --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sinh/index.html @@ -0,0 +1,96 @@ +--- +title: Math.sinh() +slug: Web/JavaScript/Reference/Global_Objects/Math/sinh +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sinh +--- +
{{JSRef}}
+ +

Math.sinh() 함수(쌍곡선 함수)는 사인값을 반환합니다 이 값은 아래와같은 식을통해서 표현할 수 있습니다.{{jsxref("Math.E", "constant e", "", 1)}}:

+ +

Math.sinh(x)=ex-e-x2\mathtt{\operatorname{Math.sinh(x)}} = \frac{e^x - e^{-x}}{2}

+ +
{{EmbedInteractiveExample("pages/js/math-sinh.html")}}
+ + + +

Syntax

+ +
Math.sinh(x)
+ +

Parameters

+ +
+
x
+
숫자.
+
+ +

Return value

+ +

사인값.

+ +

Description

+ +

sinh() 는 Math 의 정적 함수이기 때문에, 자바스크립트 어디든 Math.sinh() 를 사용할 수 있습니다, 따라서  Math 오브젝트를 생성해서는 안됩니다. (Math 는 constructor(생성자) 가 아닙니다.).

+ +

Examples

+ +

Math.sinh() 사용하기

+ +
Math.sinh(0); // 0
+Math.sinh(1); // 1.1752011936438014
+
+ +

Polyfill

+ +

This can be emulated with the help of the {{jsxref("Math.exp()")}} function:

+ +
Math.sinh = Math.sinh || function(x) {
+  return (Math.exp(x) - Math.exp(-x)) / 2;
+}
+
+ +

or using only one call to the {{jsxref("Math.exp()")}} function:

+ +
Math.sinh = Math.sinh || function(x) {
+  var y = Math.exp(x);
+  return (y - 1 / y) / 2;
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-math.sinh', 'Math.sinh')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.sinh', 'Math.sinh')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math.sinh")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/sqrt/index.html b/files/ko/web/javascript/reference/global_objects/math/sqrt/index.html new file mode 100644 index 0000000000..f03af42e6f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sqrt/index.html @@ -0,0 +1,90 @@ +--- +title: Math.sqrt() +slug: Web/JavaScript/Reference/Global_Objects/Math/sqrt +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sqrt +--- +
{{JSRef}}
+ +

 Math.sqrt() 함수는 숫자의 제곱근을 반환합니다.

+ +

x0,Math.sqrt(x)=x=the uniquey0such thaty2=x\forall x \geq 0, \mathtt{Math.sqrt(x)} = \sqrt{x} = \text{the unique} \; y \geq 0 \; \text{such that} \; y^2 = x

+ +

문법

+ +
Math.sqrt(x)
+ +

매개변수

+ +
+
x
+
숫자.
+
+ +

반환 값

+ +

주어진 숫자에 루트(√ )를 씌웁니다. 만약 숫자가 음수이면 {{jsxref("NaN")}}를 반환합니다.

+ +

설명

+ +

만약 x 가 음수라면 Math.sqrt() 함수는 {{jsxref("NaN")}}를 반환합니다.

+ +

sqrt()는 Math의 정적 메서드 이므로 만든  Math 객체의 메서드가 아니라 항상 Math.sqrt()함수를 사용해야합니다. (Math는 생성자가 없습니다.)

+ +

예제

+ +

 Math.sqrt()

+ +
Math.sqrt(9); // 3
+Math.sqrt(2); // 1.414213562373095
+
+Math.sqrt(1);  // 1
+Math.sqrt(0);  // 0
+Math.sqrt(-1); // NaN
+
+ +

표준

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.17', 'Math.sqrt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.sqrt', 'Math.sqrt')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.sqrt', 'Math.sqrt')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.sqrt")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/sqrt1_2/index.html b/files/ko/web/javascript/reference/global_objects/math/sqrt1_2/index.html new file mode 100644 index 0000000000..ee347e46eb --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sqrt1_2/index.html @@ -0,0 +1,59 @@ +--- +title: Math.SQRT1_2 +slug: Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2 +--- +
{{JSRef}}
+ +

Math.SQRT1_2 프로퍼티는 약 0.707의 값을 나타내는 루트 1/2을 나타냅니다:

+ +

Math.SQRT1_2=12=120.707\mathtt{\mi{Math.SQRT1_2}} = \sqrt{\frac{1}{2}} = \frac{1}{\sqrt{2}} \approx 0.707

+ +
{{EmbedInteractiveExample("pages/js/math-sqrt1_2.html", "shorter")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

SQRT1_2Math의 정적 프로퍼티이기 때문에, 당신이 생성한 Math 오브젝트의 프로퍼티보다는 항상 Math.SQRT1_2의 형태로 사용합니다 (Math는 컨스트럭터가 아닙니다).

+ +

예시

+ +

Math.SQRT1_2 의 사용

+ +

다음은 루트 1/2를 출력합니다:

+ +
function getRoot1_2() {
+  return Math.SQRT1_2;
+}
+
+getRoot1_2(); // 0.7071067811865476
+
+ +

사양

+ + + + + + + + + + +
사양
{{SpecName('ESDraft', '#sec-math.sqrt1_2', 'Math.SQRT1_2')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.SQRT1_2")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/sqrt2/index.html b/files/ko/web/javascript/reference/global_objects/math/sqrt2/index.html new file mode 100644 index 0000000000..1ad86df55b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/sqrt2/index.html @@ -0,0 +1,74 @@ +--- +title: Math.SQRT2 +slug: Web/JavaScript/Reference/Global_Objects/Math/SQRT2 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/SQRT2 +--- +
{{JSRef}}
+ +

 Math.SQRT2 는 2의 제곱근을 나타내고 약 1.414 입니다:

+ +

Math.SQRT2=21.414\mathtt{\mi{Math.SQRT2}} = \sqrt{2} \approx 1.414

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

 SQRT2 는  Math의 정적 메서드 이므로 만든 Math 객체의 메서드가 아니라 항상 Math.SQRT2 함수를 사용해야합니다.  (Math는 생성자가 없습니다.)

+ +

예제

+ +

Math.SQRT2

+ +

이 함수는 2의 제곱근을 반환합니다.

+ +
function getRoot2() {
+  return Math.SQRT2;
+}
+
+getRoot2(); // 1.4142135623730951
+
+ +

표준

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.8', 'Math.SQRT2')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.sqrt2', 'Math.SQRT2')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.sqrt2', 'Math.SQRT2')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.SQRT2")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/tan/index.html b/files/ko/web/javascript/reference/global_objects/math/tan/index.html new file mode 100644 index 0000000000..64a1468020 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/tan/index.html @@ -0,0 +1,102 @@ +--- +title: Math.tan() +slug: Web/JavaScript/Reference/Global_Objects/Math/tan +tags: + - 레퍼런스 + - 메소드 + - 수학 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/tan +--- +
{{JSRef}}
+ +

Math.tan() 함수는 탄젠트 값을 반환합니다

+ +
{{EmbedInteractiveExample("pages/js/math-tan.html")}}
+ + + +

신텍스

+ +
Math.tan(x)
+ +

Parameters

+ +
+
x
+
라디안 각도 
+
+ +

반환 값

+ +

주어진 수의 탄젠트 값

+ +

설명

+ +

Math.tan() 메소드는 각도의 탄젠트 값을 수로 반환합니다.

+ +

tan()Math의 정적 메서드이므로 사용자가 만든 Math 객체의 메서드가 아닌 항상 Math.tan()으로 사용합니다 (Math 는 생성자가 아닙니다).

+ +

+ +

Using Math.tan()

+ +
Math.tan(1); // 1.5574077246549023
+
+ +

Math.tan()함수는 라디안 값으로 받지만 각도로 작업하는 것이 더 쉽기 때문에 다음 함수는 각도로 값을 받아서 라디안으로 변환하고 탄젠트를 반환합니다.

+ +
function getTanDeg(deg) {
+  var rad = deg * Math.PI/180;
+  return Math.tan(rad);
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.18', 'Math.tan')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.tan', 'Math.tan')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.tan', 'Math.tan')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.tan")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/tanh/index.html b/files/ko/web/javascript/reference/global_objects/math/tanh/index.html new file mode 100644 index 0000000000..97055e165b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/tanh/index.html @@ -0,0 +1,85 @@ +--- +title: Math.tanh() +slug: Web/JavaScript/Reference/Global_Objects/Math/tanh +tags: + - ECMAScript 2015 + - 레퍼런스 + - 메서드 + - 수학 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/tanh +--- +
{{JSRef}}
+ +

Math.tanh() 함수는 쌍곡탄젠트 값을 반환합니다. 수식으로는 아래와 같습니다.

+ +

tanhx=sinhxcoshx=ex-e-xex+e-x=e2x-1e2x+1\tanh x = \frac{\sinh x}{\cosh x} = \frac {e^x - e^{-x}} {e^x + e^{-x}} = \frac{e^{2x} - 1}{e^{2x}+1}

+ +
{{EmbedInteractiveExample("pages/js/math-tanh.html")}}
+ +

Syntax

+ +
Math.tanh(x)
+ +

파라미터

+ +
+
x
+
숫자.
+
+ +

반환 값

+ +

주어진 수의 쌍곡탄젠트 값

+ +

설명

+ +

tanh() 은 Math의 정적 메서드이므로 사용자가 만든 Math 객체의 메서드가 아닌 항상 Math.tanh() 으로 사용합니다 (Math 는 생성자가 아닙니다.).

+ +

+ +

Using Math.tanh()

+ +
Math.tanh(0);        // 0
+Math.tanh(Infinity); // 1
+Math.tanh(1);        // 0.7615941559557649
+
+ +

Polyfill

+ +

This can be emulated with the help of the {{jsxref("Math.exp()")}} function:

+ +
Math.tanh = Math.tanh || function(x){
+    var a = Math.exp(+x), b = Math.exp(-x);
+    return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (a + b);
+}
+
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-math.tanh', 'Math.tanh')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Math.tanh")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/math/trunc/index.html b/files/ko/web/javascript/reference/global_objects/math/trunc/index.html new file mode 100644 index 0000000000..0f63fd1e58 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/math/trunc/index.html @@ -0,0 +1,96 @@ +--- +title: Math.trunc() +slug: Web/JavaScript/Reference/Global_Objects/Math/trunc +translation_of: Web/JavaScript/Reference/Global_Objects/Math/trunc +--- +
{{JSRef}}
+ +

Math.trunc() 함수는 주어진 값의 소수부분을 제거하고 숫자의 정수부분을 반환합니다.

+ +

Syntax

+ +
Math.trunc(x)
+
+ +

Parameters

+ +
+
x
+
숫자형
+
+ +

Return value

+ +

주어진 숫자의 정수부분

+ +

Description

+ +

Math의 유사함수 3개 : {{jsxref("Math.floor()")}}, {{jsxref("Math.ceil()")}} and {{jsxref("Math.round()")}} 와는 다르게, Math.trunc() 함수는 주어진 값이 양수이건 음수이건 상관없이 소수점 이하 우측부분을 제거하는 매우 단순한 동작을 합니다.

+ +

함수인자는 암묵적으로 number형으로 변환되어 메소드에 전달됩니다.

+ +

trunc() 함수는 Math의 정적 메소드이기 때문에 사용자가 생성한 Math 객체의 메소드로 호출하는 것이 아닌 항상 Math.trunc() 형태로 호출해야 합니다. (Math 는 생성자가 아닙니다).

+ +

Examples

+ +

Using Math.trunc()

+ +
Math.trunc(13.37);    // 13
+Math.trunc(42.84);    // 42
+Math.trunc(0.123);    //  0
+Math.trunc(-0.123);   // -0
+Math.trunc('-1.123'); // -1
+Math.trunc(NaN);      // NaN
+Math.trunc('foo');    // NaN
+Math.trunc();         // NaN
+
+ +

Polyfill

+ +
Math.trunc = Math.trunc || function(x) {
+  if (isNaN(x)) {
+    return NaN;
+  }
+  if (x > 0) {
+    return Math.floor(x);
+  }
+  return Math.ceil(x);
+};
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-math.trunc', 'Math.trunc')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-math.trunc', 'Math.trunc')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math.trunc")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/nan/index.html b/files/ko/web/javascript/reference/global_objects/nan/index.html new file mode 100644 index 0000000000..4e6e3a8c42 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/nan/index.html @@ -0,0 +1,91 @@ +--- +title: NaN +slug: Web/JavaScript/Reference/Global_Objects/NaN +tags: + - JavaScript + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/NaN +--- +
{{jsSidebar("Objects")}}
+ +

전역 NaN 속성은 Not-A-Number(숫자가 아님)를 나타냅니다.

+ +

{{js_property_attributes(0,0,0)}}

+ +
{{EmbedInteractiveExample("pages/js/globalprops-nan.html")}}
+ + + +

설명

+ +

NaN은 전역 객체의 속성입니다. 즉 전역 스코프의 변수입니다.

+ +

NaN의 초기값은 Not-A-Number(숫자가 아님)로, {{jsxref("Number.NaN")}}의 값과 같습니다. 최신 브라우저에서 NaN은 설정 불가, 쓰기 불가 속성입니다. 그렇지 않다고 하더라도 덮어쓰는건 피하는게 좋습니다.

+ +

NaN을 반환하는 연산에는 다섯 가지 종류가 있습니다.

+ + + +

예제

+ +

NaN 판별

+ +

NaN은 다른 모든 값과 비교(==, !=, ===, !==)했을 때 같지 않으며, 다른 NaN과도 같지 않습니다. NaN의 판별은 {{jsxref("Number.isNaN()")}} 또는 {{jsxref("Global_Objects/isNaN", "isNaN()")}}을 사용하면 제일 분명하게 수행할 수 있습니다. 아니면, 오로지 NaN만이 자기자신과 비교했을 때 같지 않음을 이용할 수도 있습니다.

+ +
NaN === NaN;        // false
+Number.NaN === NaN; // false
+isNaN(NaN);         // true
+isNaN(Number.NaN);  // true
+
+function valueIsNaN(v) { return v !== v; }
+valueIsNaN(1);          // false
+valueIsNaN(NaN);        // true
+valueIsNaN(Number.NaN); // true
+
+ +

그러나 isNaN()Number.isNaN()의 차이를 주의해야 합니다. isNaN은 현재 값이 NaN이거나, 숫자로 변환했을 때 NaN이 되면 참을 반환하지만, Number.isNaN은 현재 값이 NaN이어야만 참을 반환합니다.

+ +
isNaN('hello world'); // true
+Number.isNaN('hello world'); // false
+
+ +

덧붙여서, 일부 배열 메서드는 NaN을 찾을 수 없습니다.

+ +
let arr = [2, 4, NaN, 12];
+arr.indexOf(NaN);                      // -1 (false)
+arr.includes(NaN);                     // true
+arr.findIndex(n => Number.isNaN(n));   // 2
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.NaN")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/null/index.html b/files/ko/web/javascript/reference/global_objects/null/index.html new file mode 100644 index 0000000000..e69295c9f6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/null/index.html @@ -0,0 +1,69 @@ +--- +title: 'null' +slug: Web/JavaScript/Reference/Global_Objects/null +tags: + - JavaScript + - Literal + - Primitive + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/null +--- +
{{jsSidebar("Objects")}}
+ +

null은 JavaScript의 {{Glossary("Primitive", "원시 값")}} 중 하나로, 어떤 값이 의도적으로 비어있음을 표현하며 불리언 연산에서는 {{glossary("falsy", "거짓")}}으로 취급합니다.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-null.html")}}
+ + + +

설명

+ +

null은 리터럴로서, null로 작성할 수 있습니다. null은 {{jsxref("undefined")}}와 같은 전역 객체의 식별자가 아닙니다. 대신 식별되지 않은 상태를 나타내며 해당 변수가 어떠한 객체도 가리키고 있지 않음을 표시합니다. API에서는 대개 객체를 기대했지만, 어떤 적합한 객체도 존재하지 않을 때 반환합니다.

+ +
// 정의되지 않고 초기화된 적도 없는 foo
+foo; //ReferenceError: foo is not defined
+
+// 존재하지만 값이나 자료형이 존재하지 않는 foo
+var foo = null;
+foo; //null
+
+ +

nullundefined의 차이

+ +

null 또는 undefined를 검사할 때, 동등 연산자(==)와 일치 연산자(===)의 차이를 주의하세요. 동등 연산자는 자료형 변환을 수행합니다.

+ +
typeof null          // "object" (하위호환 유지를 위해 "null"이 아님)
+typeof undefined     // "undefined"
+null === undefined   // false
+null  == undefined   // true
+null === null        // true
+null == null         // true
+!null                // true
+isNaN(1 + null)      // false
+isNaN(1 + undefined) // true
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-null-value', 'null value')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.null")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/epsilon/index.html b/files/ko/web/javascript/reference/global_objects/number/epsilon/index.html new file mode 100644 index 0000000000..730fd8ae87 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/epsilon/index.html @@ -0,0 +1,61 @@ +--- +title: Number.EPSILON +slug: Web/JavaScript/Reference/Global_Objects/Number/EPSILON +tags: + - ECMAScript6 + - JavaScript + - Number + - 속성 +translation_of: Web/JavaScript/Reference/Global_Objects/Number/EPSILON +--- +
{{JSRef}}
+ +

 Number.EPSILON 속성(property)은 {{jsxref("Number")}} 형으로 표현될 수 있는 1과 1보다 큰 값 중에서 가장 작은 값의, 차입니다.

+ +

당신은 이 정적 속성에 접근하기 위하여 {{jsxref("Number")}} 객체를 생성할 필요가 없습니다. Number.EPSILON을 쓰면 됩니다.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

이 EPSILON 속성은 대략 2.2204460492503130808472633361816E-16 또는 2-52의 값을 갖습니다.

+ +

예제

+ +

동일성 확인하기

+ +
const x = 0.2, y = 0.3, z = 0.1;
+let equal = (Math.abs(x - y + z) < Number.EPSILON);
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES6', '#sec-number.epsilon', 'Number.EPSILON')}}{{Spec2('ES6')}}최초로 정의됨.
{{SpecName('ESDraft', '#sec-number.epsilon', 'Number.EPSILON')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Number.EPSILON")}}

+ +

관련된 문서

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/index.html b/files/ko/web/javascript/reference/global_objects/number/index.html new file mode 100644 index 0000000000..2a2592dcc8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/index.html @@ -0,0 +1,177 @@ +--- +title: Number +slug: Web/JavaScript/Reference/Global_Objects/Number +tags: + - JavaScript + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +
{{JSRef}}
+ +

Number 객체는 숫자 값으로 작업할 수 있게 해주는 래퍼wrapper 객체입니다. Number 객체는 Number() 생성자를 사용하여 만듭니다. 원시 숫자 자료형은 Number() 함수를 사용해 생성합니다.

+ +

구문

+ +
new Number(value);
+var a = new Number('123'); // a === 123은 false
+var b = Number('123'); // b === 123은 true
+a instanceof Number; // true
+b instanceof Number; // false
+ +

매개변수

+ +
+
value
+
생성할 객체의 숫자 값.
+
+ +

설명

+ +

Number 객체의 주된 용도는 다음과 같습니다.

+ + + +

속성

+ +
+
{{jsxref("Number.EPSILON")}}
+
두 개의 표현 가능한 숫자 사이의 최소 간격.
+
{{jsxref("Number.MAX_SAFE_INTEGER")}}
+
JavaScript에서 안전한 최대 정수. (253 - 1)
+
{{jsxref("Number.MAX_VALUE")}}
+
표현 가능한 가장 큰 양수.
+
{{jsxref("Number.MIN_SAFE_INTEGER")}}
+
JavaScript에서 안전한 최소 정수. (-(253 - 1))
+
{{jsxref("Number.MIN_VALUE")}}
+
표현 가능한 가장 작은 양수. 즉, 0보다 크지만 0에 가장 가까운 양수.
+
{{jsxref("Number.NaN")}}
+
"숫자가 아님"을 나타내는 특별한 값.
+
{{jsxref("Number.NEGATIVE_INFINITY")}}
+
음의 무한대를 나타내는 특수한 값. 오버플로우 시 반환됩니다.
+
{{jsxref("Number.POSITIVE_INFINITY")}}
+
양의 무한대를 나타내는 특수한 값. 오버플로우 시 반환됩니다.
+
{{jsxref("Number.prototype")}}
+
Number 객체에 속성을 추가할 수 있습니다.
+
+ +

메서드

+ +
+
{{jsxref("Number.isNaN()")}}
+
주어진 값이 NaN인지 확인합니다.
+
{{jsxref("Number.isFinite()")}}
+
주어진 값이 유한수 인지 확인합니다.
+
{{jsxref("Number.isInteger()")}}
+
주어진 값이 정수인지 확인합니다.
+
{{jsxref("Number.isSafeInteger()")}}
+
주어진 값이 안전한 정수(-(253 - 1)과 253 - 1 사이의 정수)인지 확인합니다.
+
{{jsxref("Number.toInteger()")}} {{obsolete_inline}}
+
전달 된 값을 평가하고 이를 정수(혹은 {{jsxref("Infinity", "Infinity")}})로 변환하는데 사용되지만, 제거되었습니다.
+
{{jsxref("Number.parseFloat()")}}
+
전역 객체 {{jsxref("parseFloat", "parseFloat()")}}와 동일한 값입니다.
+
{{jsxref("Number.parseInt()")}}
+
전역 객체 {{jsxref("parseInt", "parseInt()")}}와 동일한 값입니다.
+
+ +

Number 인스턴스

+ +

모든 Number 인스턴스는 {{jsxref("Number.prototype")}}를 상속합니다. Number 생성자의 프로토타입 객체는 모든 Number 인스턴스에 영향을 미치도록 수정할 수 있습니다.

+ +

메서드

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/prototype', 'Methods')}}
+ +

예제

+ +

Number 객체를 사용해 숫자형 변수에 할당

+ +

다음 예제에서는 Number 객체의 속성을 사용하여, 여러 숫자 변수에 값을 할당합니다:

+ +
var biggestNum = Number.MAX_VALUE;
+var smallestNum = Number.MIN_VALUE;
+var infiniteNum = Number.POSITIVE_INFINITY;
+var negInfiniteNum = Number.NEGATIVE_INFINITY;
+var notANum = Number.NaN;
+
+ +

Number의 정수 범위

+ +

다음 예제는 Number 객체가 표현할 수 있는 정수의 최소값과 최대값을 보여줍니다. (자세한 내용은 ECMAScript 표준, 6.1.6 The Number Type 장을 참고하세요)

+ +
var biggestInt = 9007199254740992;
+var smallestInt = -9007199254740992;
+
+ +

JSON으로 직렬화한 데이터를 읽을 때, 위의 범위를 벗어나는 수는 JSON 분석기의 Number 형변환 시 손상될 수 있습니다. 이 때는 {{jsxref("String")}}을 대신 사용하는 것도 방법입니다.

+ +

Number를 사용해 Date 객체 숫자로 변환

+ +

다음 예제는 Number를 함수로 사용하여 {{jsxref("Date")}} 객체를 숫자 값으로 변환합니다.

+ +
var d = new Date('December 17, 1995 03:24:00');
+console.log(Number(d));
+
+ +

819199440000가 기록됩니다.

+ +

숫자형 문자열에서 숫자로 변환

+ +
Number('123')     // 123
+Number('12.3')    // 12.3
+Number('123e-1')  // 12.3
+Number('')        // 0
+Number(null)      // 0
+Number('0x11')    // 17
+Number('0b11')    // 3
+Number('0o11')    // 9
+Number('foo')     // NaN
+Number('100a')    // NaN
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7', 'Number')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-number-objects', 'Number')}}{{Spec2('ES6')}}New methods and properties added: ({{jsxref("Number.EPSILON", "EPSILON")}}, {{jsxref("Number.isFinite", "isFinite")}}, {{jsxref("Number.isInteger", "isInteger")}}, {{jsxref("Number.isNaN", "isNaN")}}, {{jsxref("Number.parseFloat", "parseFloat")}}, {{jsxref("Number.parseInt", "parseInt")}})
{{SpecName('ESDraft', '#sec-number-objects', 'Number')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
+

{{Compat("javascript.builtins.Number")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/isfinite/index.html b/files/ko/web/javascript/reference/global_objects/number/isfinite/index.html new file mode 100644 index 0000000000..13c76c4d8d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/isfinite/index.html @@ -0,0 +1,90 @@ +--- +title: Number.isFinite() +slug: Web/JavaScript/Reference/Global_Objects/Number/isFinite +tags: + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite +--- +
{{JSRef}}
+ +

Number.isFinite() 메서드는 주어진 값이 유한수인지 판별합니다.

+ +
{{EmbedInteractiveExample("pages/js/number-isfinite.html")}}
+ + + +

구문

+ +
Number.isFinite(value)
+ +

매개변수

+ +
+
value
+
유한수인지 판별할 값.
+
+ +

반환 값

+ +

유한수 여부에 대한 {{jsxref("Boolean")}} 값.

+ +

설명

+ +

전역 함수 {{jsxref("isFinite", "isFinite()")}}와 비교했을 때, Number.isFinite() 메서드는 매개변수를 숫자로 변환하지 않습니다. 즉 값이 숫자이며 동시에 유한수일 때만 true를 반환합니다.

+ +

예제

+ +
Number.isFinite(Infinity);  // false
+Number.isFinite(NaN);       // false
+Number.isFinite(-Infinity); // false
+
+Number.isFinite(0);         // true
+Number.isFinite(2e64);      // true
+
+Number.isFinite('0');       // false
+                            // 전역함수 isFinite('0')라면 true
+Number.isFinite(null);      // false
+                            // 전역함수 isFinite(null)라면 true
+
+ +

폴리필

+ +
if (Number.isFinite === undefined) Number.isFinite = function(value) {
+    return typeof value === 'number' && isFinite(value);
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Number.isFinite")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/isinteger/index.html b/files/ko/web/javascript/reference/global_objects/number/isinteger/index.html new file mode 100644 index 0000000000..c2be9f56f1 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/isinteger/index.html @@ -0,0 +1,96 @@ +--- +title: Number.isInteger() +slug: Web/JavaScript/Reference/Global_Objects/Number/isInteger +tags: + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isInteger +--- +
{{JSRef}}
+ +

Number.isInteger() 메서드는 주어진 값이 정수인지 판별합니다.

+ +
{{EmbedInteractiveExample("pages/js/number-isinteger.html")}}
+ + + +

구문

+ +
Number.isInteger(value)
+ +

매개변수

+ +
+
value
+
정수인지 확인하려는 값.
+
+ +

반환 값

+ +

주어진 값의 정수 여부를 나타내는 {{jsxref("Boolean")}}.

+ +

설명

+ +

매개변수의 값이 정수면 true를, 아니면 false를 반환합니다. 값이 {{jsxref("NaN")}}이거나 {{jsxref("Infinity")}}여도 false를 반환합니다.

+ +

예제

+ +
Number.isInteger(0);         // true
+Number.isInteger(1);         // true
+Number.isInteger(-100000);   // true
+Number.isInteger(99999999999999999999999); // true
+
+Number.isInteger(0.1);       // false
+Number.isInteger(Math.PI);   // false
+
+Number.isInteger(NaN);       // false
+Number.isInteger(Infinity);  // false
+Number.isInteger(-Infinity); // false
+Number.isInteger('10');      // false
+Number.isInteger(true);      // false
+Number.isInteger(false);     // false
+Number.isInteger([1]);       // false
+
+ +

폴리필

+ +
Number.isInteger = Number.isInteger || function(value) {
+  return typeof value === "number" &&
+    isFinite(value) &&
+    Math.floor(value) === value;
+};
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-number.isinteger', 'Number.isInteger')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.isinteger', 'Number.isInteger')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Number.isInteger")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/isnan/index.html b/files/ko/web/javascript/reference/global_objects/number/isnan/index.html new file mode 100644 index 0000000000..ff5ae793de --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/isnan/index.html @@ -0,0 +1,100 @@ +--- +title: Number.isNaN() +slug: Web/JavaScript/Reference/Global_Objects/Number/isNaN +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isNaN +--- +
{{JSRef}}
+ +

Number.isNaN() 메서드는 주어진 값이 {{jsxref("NaN")}}인지 판별합니다. 기존부터 존재한 전역 {{jsxref("isNaN", "isNaN()")}} 함수의 더 엄격한 버전입니다.

+ +
{{EmbedInteractiveExample("pages/js/number-isnan.html", "taller")}}
+ + + +

구문

+ +
Number.isNaN(value)
+ +

매개변수

+ +
+
value
+
{{jsxref("NaN")}}인지 판별할 값.
+
+ +

반환 값

+ +

주어진 값의 유형이 {{jsxref("Number")}}이고 값이 {{jsxref("NaN")}}이면 true, 아니면 false.

+ +

설명

+ +

{{jsxref("NaN")}}이 NaN인지 계산할 때, 두 동일 연산자 ===== 모두 false로 평가되므로 값의 NaN 여부를 알아내려면 Number.isNaN()이 필요합니다. 이 상황은 다른 모든 JavaScript와 다른 특별한 경우입니다.

+ +

전역 {{jsxref("isNaN", "isNaN()")}} 함수와 달리, Number.isNaN()은 강제로 매개변수를 숫자로 변환하는 문제를 겪지 않습니다. 이는 이제 보통{{jsxref("NaN")}}으로 변환됐을 값이 안전하게 전달되지만, 실제로는 {{jsxref("NaN")}}과 같은 값이 아님을 의미합니다. 이는 또한 오직 숫자형이고 또한 {{jsxref("NaN")}}인 값만이 true를 반환함을 뜻합니다.

+ +

예제

+ +
Number.isNaN(NaN);        // true
+Number.isNaN(Number.NaN); // true
+Number.isNaN(0 / 0)       // true
+
+// 예를 들면 이들은 global isNaN()으로는 true가 됐을 것임
+Number.isNaN("NaN");      // false
+Number.isNaN(undefined);  // false
+Number.isNaN({});         // false
+Number.isNaN("blabla");   // false
+
+// 모두
+Number.isNaN(true);
+Number.isNaN(null);
+Number.isNaN(37);
+Number.isNaN("37");
+Number.isNaN("37.37");
+Number.isNaN("");
+Number.isNaN(" ");
+
+ +

폴리필

+ +
Number.isNaN = Number.isNaN || function(value) {
+    return value !== value;
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-number.isnan', 'Number.isnan')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-number.isnan', 'Number.isnan')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Number.isNaN")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/issafeinteger/index.html b/files/ko/web/javascript/reference/global_objects/number/issafeinteger/index.html new file mode 100644 index 0000000000..8c1af0e54d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/issafeinteger/index.html @@ -0,0 +1,100 @@ +--- +title: Number.isSafeInteger() +slug: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger +--- +
{{JSRef}}
+ +

Number.isSafeInteger() 메서드는 전달된 값이 안전한 정숫값인지 확인합니다.

+ +
{{EmbedInteractiveExample("pages/js/number-issafeinteger.html")}}
+ + + +

안전한 정숫값이란 다음과 같습니다.

+ + + +

예를 들어, 253 - 1은 안전한 정수입니다. 이 정수는 정확히 표현될 수 있으며, IEEE-754 반올림 모드에서 다른 정숫값이 이 값을 반올림하지 않습니다. 반면에, 253 는 안전하지 않은 정수입니다. 이 정수는 정확히 IEEE-754로 표현될 수 있지만, 정수 253 + 1은 IEEE-754로 직접 표현될 수 없으며 가까운 수로 반올림하는 것과 0으로 반올림하는 것으로 253 을 반올림합니다.

+ +

안전한 정숫값은 -(253 - 1) 부터 253 - 1 사이의 모든 정수값으로 구성됩니다.

+ +

구문

+ +
Number.isSafeInteger(testValue)
+
+ +

매개변수

+ +
+
testValue
+
안전한 정수인지 확인할 값.
+
+ +

반환 값

+ +

주어진 값이 안전한 정숫값인지 나타내는 {{jsxref("Boolean")}}.

+ +

예시

+ +
Number.isSafeInteger(3);                    // true
+Number.isSafeInteger(Math.pow(2, 53));      // false
+Number.isSafeInteger(Math.pow(2, 53) - 1);  // true
+Number.isSafeInteger(NaN);                  // false
+Number.isSafeInteger(Infinity);             // false
+Number.isSafeInteger('3');                  // false
+Number.isSafeInteger(3.1);                  // false
+Number.isSafeInteger(3.0);                  // true
+
+ +

폴리필

+ +
Number.isSafeInteger = Number.isSafeInteger || function (value) {
+   return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
+};
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.isSafeInteger")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/max_safe_integer/index.html b/files/ko/web/javascript/reference/global_objects/number/max_safe_integer/index.html new file mode 100644 index 0000000000..c8b4d679d0 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/max_safe_integer/index.html @@ -0,0 +1,76 @@ +--- +title: Number.MAX_SAFE_INTEGER +slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER +tags: + - ECMAScript 2015 + - JavaScript + - Number + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER +--- +
{{JSRef}}
+ +

Number.MAX_SAFE_INTEGER 상수는 JavaScript에서 안전한 최대 정수값을 나타냅니다. (253 - 1).

+ +
{{EmbedInteractiveExample("pages/js/number-maxsafeinteger.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

MAX_SAFE_INTEGER 상수는 9007199254740991(9,007,199,254,740,991 또는 약 9000조)의 값을 갖고 있습니다. 이 값의 이유는 JavaScript가 IEEE 754에 기술된 배정밀도 부동소숫점 형식 숫자체계를 사용하기 때문으로, 이로 인해 -(253 - 1)253 - 1 사이의 수만 안전하게 표현할 수 있습니다.

+ +

여기서의 안전함이란 정수를 정확하고 올바르게 비교할 수 있음을 의미합니다. 예를 들어 Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2는 참으로 평가되며 이는 수학적으로 올바르지 않습니다. 더 자세한 내용은 {{jsxref("Number.isSafeInteger()")}}를 참고하세요.

+ +

MAX_SAFE_INTEGER는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 Number.MAX_SAFE_INTEGER 형식으로 사용해야 합니다.

+ +

예제

+ +
Number.MAX_SAFE_INTEGER // 9007199254740991
+Number.MAX_SAFE_INTEGER * Number.EPSILON // 2 because in floating points, the value is actually the decimal trailing "1"
+                                         // except for in subnormal precision cases such as zero
+
+ +

폴리필

+ +
if (!Number.MAX_SAFE_INTEGER) {
+    Number.MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; // 9007199254740991
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-number.max_safe_integer', 'Number.MAX_SAFE_INTEGER')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.max_safe_integer', 'Number.MAX_SAFE_INTEGER')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.MAX_SAFE_INTEGER")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/max_value/index.html b/files/ko/web/javascript/reference/global_objects/number/max_value/index.html new file mode 100644 index 0000000000..c80ae8f84a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/max_value/index.html @@ -0,0 +1,81 @@ +--- +title: Number.MAX_VALUE +slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE +tags: + - JavaScript + - Number + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE +--- +
{{JSRef}}
+ +

Number.MAX_VALUE 속성은 JavaScript가 표현할 수 있는 제일 큰 양의 숫자 값을 나타냅니다.

+ +
{{EmbedInteractiveExample("pages/js/number-maxvalue.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

MAX_VALUE의 값은 약 1.79E+308, 21024입니다. MAX_VALUE보다 큰 값은 {{jsxref("Infinity")}}로 표현됩니다.

+ +

MAX_VALUE는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 Number.MAX_VALUE 형식으로 사용해야 합니다.

+ +

예제

+ +

MAX_VALUE 사용하기

+ +

다음 코드는 두 개의 수를 곱합니다. 만약 결과가 MAX_VALUE 이하면 func1을 호출하고, 그렇지 않으면 func2를 호출합니다.

+ +
if (num1 * num2 <= Number.MAX_VALUE) {
+  func1();
+} else {
+  func2();
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.2', 'Number.MAX_VALUE')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.max_value', 'Number.MAX_VALUE')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.max_value', 'Number.MAX_VALUE')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.MAX_VALUE")}}

+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/min_safe_integer/index.html b/files/ko/web/javascript/reference/global_objects/number/min_safe_integer/index.html new file mode 100644 index 0000000000..67efd0e681 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/min_safe_integer/index.html @@ -0,0 +1,66 @@ +--- +title: Number.MIN_SAFE_INTEGER +slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER +tags: + - ECMAScript 2015 + - JavaScript + - Number + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER +--- +
{{JSRef}}
+ +

Number.MIN_SAFE_INTEGER 상수는 JavaScript에서 안전한 최소 정수값을 나타냅니다. (-(253 - 1))

+ +
{{EmbedInteractiveExample("pages/js/number-min-safe-integer.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

MIN_SAFE_INTEGER 상수는 -9007199254740991(-9,007,199,254,740,991 또는 약 -9000조)의 값을 갖고 있습니다. 이 값의 이유는 JavaScript가 IEEE 754에 기술된 배정밀도 부동소숫점 형식 숫자체계를 사용하기 때문으로, 이로 인해 -(253 - 1)253 - 1 사이의 수만 안전하게 표현할 수 있습니다.

+ +

MIN_SAFE_INTEGER는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 Number.MIN_SAFE_INTEGER 형식으로 사용해야 합니다.

+ +

설명

+ +
Number.MIN_SAFE_INTEGER // -9007199254740991
+-(Math.pow(2, 53) - 1)  // -9007199254740991
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-number.min_safe_integer', 'Number.MIN_SAFE_INTEGER')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.min_safe_integer', 'Number.MIN_SAFE_INTEGER')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.MIN_SAFE_INTEGER")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/min_value/index.html b/files/ko/web/javascript/reference/global_objects/number/min_value/index.html new file mode 100644 index 0000000000..66b4985942 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/min_value/index.html @@ -0,0 +1,84 @@ +--- +title: Number.MIN_VALUE +slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE +tags: + - JavaScript + - Number + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE +--- +
{{JSRef}}
+ +

Number.MIN_VALUE 속성은 JavaScript가 표현할 수 있는 제일 작은 양의 숫자 값을 나타냅니다.

+ +
{{EmbedInteractiveExample("pages/js/number-min-value.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

MIN_VALUE 속성은 JavaScript에서 표현할 수 있는, 0에 가장 가깝지만 음수는 아닌 수입니다.

+ +

MIN_VALUE의 값은 약 5e-324입니다. MIN_VALUE보다 작은 값("언더플로우 값")은 0으로 변환됩니다.

+ +

MIN_VALUE는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 Number.MIN_VALUE 형식으로 사용해야 합니다.

+ +

예제

+ +

MIN_VALUE 사용하기

+ +

다음 코드는 숫자를 두 개의 수를 받아 나누기 연산을 합니다. 만약 결과가 MIN_VALUE 보다 크거나 같으면 func1 함수를 호출하고, 그렇지 않으면 func2 함수를 호출합니다.

+ +
if (num1 / num2 >= Number.MIN_VALUE) {
+  func1();
+} else {
+  func2();
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.3', 'Number.MIN_VALUE')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.min_value', 'Number.MIN_VALUE')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.min_value', 'Number.MIN_VALUE')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.MIN_VALUE")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/nan/index.html b/files/ko/web/javascript/reference/global_objects/number/nan/index.html new file mode 100644 index 0000000000..348820c376 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/nan/index.html @@ -0,0 +1,62 @@ +--- +title: Number.NaN +slug: Web/JavaScript/Reference/Global_Objects/Number/NaN +tags: + - JavaScript + - Number + - Property +translation_of: Web/JavaScript/Reference/Global_Objects/Number/NaN +--- +
{{JSRef}}
+ +

Number.NaN 속성은 Not-A-Number(숫자가 아님)를 나타냅니다. {{jsxref("NaN")}}과 같습니다.

+ +

{{EmbedInteractiveExample("pages/js/number-nan.html")}}
+ 정적 속성이므로 접근하기 위해 {{jsxref("Number")}} 객체를 생성할 필요는 없습니다. (Number.NaN 사용)

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.1에서 구현됨.
{{SpecName('ES5.1', '#sec-15.7.3.4', 'Number.NaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.nan', 'Number.NaN')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.nan', 'Number.NaN')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Number.NaN")}}
+ +
 
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/negative_infinity/index.html b/files/ko/web/javascript/reference/global_objects/number/negative_infinity/index.html new file mode 100644 index 0000000000..d6567e687e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/negative_infinity/index.html @@ -0,0 +1,82 @@ +--- +title: Number.NEGATIVE_INFINITY +slug: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY +tags: + - JavaScript + - Number + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY +--- +
{{JSRef}}
+ +

Number.NEGATIVE_INFINITY 속성은 음의 무한대를 나타냅니다.

+ +
{{EmbedInteractiveExample("pages/js/number-negative-infinity.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

Number.NEGATIVE_INFINITY의 값은 전역 객체 {{jsxref("Infinity")}} 속성의 부호를 바꾼 값과 동일합니다.

+ +

NEGATIVE_INFINITY는 수학에서의 무한대와 약간 다릅니다.

+ + + +

Number.NEGATIVE_INFINITY를 사용해 성공 시 유한수를 반환하는 식의 결과를 판별할 수 있습니다. 그러나 이런 경우 {{jsxref("isFinite", "isFinite()")}}를 사용하는 편이 더 적합합니다.

+ +

NEGATIVE_INFINITY는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 Number.NEGATIVE_INFINITY의 형식으로 사용해야 합니다.

+ +

예제

+ +

NEGATIVE_INFINITY 사용하기

+ +

다음 코드에서 smallNumber는 JavaScript의 최솟값보다 작은 값을 할당받습니다. {{jsxref("Statements/if...else", "if")}} 문이 실행되면, smallNumber의 값이 -Infinity이므로 smallNumber는 계산에 좀 더 적합한 값을 다시 할당합니다.

+ +
var smallNumber = (-Number.MAX_VALUE) * 2;
+
+if (smallNumber === Number.NEGATIVE_INFINITY) {
+  smallNumber = returnFinite();
+}
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.NEGATIVE_INFINITY")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/parsefloat/index.html b/files/ko/web/javascript/reference/global_objects/number/parsefloat/index.html new file mode 100644 index 0000000000..763c28a42d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/parsefloat/index.html @@ -0,0 +1,79 @@ +--- +title: Number.parseFloat() +slug: Web/JavaScript/Reference/Global_Objects/Number/parseFloat +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Number +translation_of: Web/JavaScript/Reference/Global_Objects/Number/parseFloat +--- +
{{JSRef}}
+ +

Number.parseFloat() 메서드는 문자열을 분석해 부동소수점 실수로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/number-parsefloat.html")}}
+ + + +

구문

+ +
Number.parseFloat(string)
+ +

매개변수

+ +

{{page("ko/docs/Web/JavaScript/Reference/Global_Objects/parseFloat", "매개변수")}}

+ +

반환 값

+ +

{{page("ko/docs/Web/JavaScript/Reference/Global_Objects/parseFloat", "반환 값")}}

+ +

설명

+ +

Number.parseFloat() 메서드는 전역 {{jsxref("parseFloat", "parseFloat()")}} 함수와 같은 기능을 가지고 있습니다.

+ +
Number.parseFloat === parseFloat; // true
+ +

Number.parseFloat()는 ECMAScript 2015에서 전역 범위의 모듈화를 위해 추가됐습니다. 상세한 정보와 예제는 {{jsxref("parseFloat", "parseFloat()")}}를 참고하세요.

+ +

폴리필

+ +
if (Number.parseFloat === undefined) {
+    Number.parseFloat = parseFloat;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-number.parsefloat', 'Number.parseFloat')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.parsefloat', 'Number.parseFloat')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +
{{Compat("javascript.builtins.Number.parseFloat")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/parseint/index.html b/files/ko/web/javascript/reference/global_objects/number/parseint/index.html new file mode 100644 index 0000000000..0b0a052016 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/parseint/index.html @@ -0,0 +1,78 @@ +--- +title: Number.parseInt() +slug: Web/JavaScript/Reference/Global_Objects/Number/parseInt +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/parseInt +--- +
{{JSRef}}
+ +

Number.parseInt() 메서드는 문자열을 분석하고 특정 진수를 사용한 정수로 변환해 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/number-parseint.html")}}
+ + + +

구문

+ +
Number.parseInt(string,radix])
+
+ +

매개변수

+ +
{{page("ko/docs/Web/JavaScript/Reference/Global_Objects/parseInt", "매개변수")}}
+ +

반환 값

+ +

{{page("ko/docs/Web/JavaScript/Reference/Global_Objects/parseInt", "반환 값")}}

+ +

설명

+ +

Number.parseInt() 메서드는 전역 {{jsxref("parseInt", "parseInt()")}} 함수와 같은 기능을 가지고 있습니다.

+ +
Number.parseInt === parseInt; // true
+ +

Number.parseInt()는 ECMAScript 2015에서 전역 범위의 모듈화를 위해 추가됐습니다. 상세한 정보와 예제는 {{jsxref("parseInt", "parseInt()")}}를 참고하세요.

+ +

폴리필

+ +
if (Number.parseInt === undefined) {
+    Number.parseInt = window.parseInt;
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-number.parseint', 'Number.parseInt')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.parseint', 'Number.parseInt')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Number.parseInt")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/positive_infinity/index.html b/files/ko/web/javascript/reference/global_objects/number/positive_infinity/index.html new file mode 100644 index 0000000000..b1012fcdbf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/positive_infinity/index.html @@ -0,0 +1,82 @@ +--- +title: Number.POSITIVE_INFINITY +slug: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY +tags: + - JavaScript + - Number + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY +--- +
{{JSRef}}
+ +

Number.POSITIVE_INFINITY 속성은 양의 무한대를 나타냅니다.

+ +
{{EmbedInteractiveExample("pages/js/number-positive-infinity.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

Number.POSITIVE_INFINITY의 값은 전역 객체 {{jsxref("Infinity")}} 속성의 값과 동일합니다.

+ +

POSITIVE_INFINITY는 수학에서의 무한대와 약간 다릅니다.

+ + + +

Number.POSITIVE_INFINITY를 사용해 성공 시 유한수를 반환하는 식의 결과를 판별할 수 있습니다. 그러나 이런 경우 {{jsxref("isFinite", "isFinite()")}}를 사용하는 편이 더 적합합니다.

+ +

POSITIVE_INFINITY는 {{jsxref("Number")}}의 정적 속성이기 때문에, 직접 생성한 {{jsxref("Number")}} 객체의 속성이 아니라 Number.POSITIVE_INFINITY의 형식으로 사용해야 합니다.

+ +

예제

+ +

POSITIVE_INFINITY 사용하기

+ +

다음 코드에서 smallNumber는 JavaScript의 최댓값보다 큰 값을 할당받습니다. {{jsxref("Statements/if...else", "if")}} 문이 실행되면, bigNumber의 값이 Infinity이므로 bigNumber는 계산에 좀 더 적합한 유한값을 다시 할당합니다.

+ +
var bigNumber = (Number.MAX_VALUE) * 2;
+
+if (bigNumber === Number.POSITIVE_INFINITY) {
+  bigNumber = returnFinite();
+}
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-number.positive_infinity', 'Number.POSITIVE_INFINITY')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.POSITIVE_INFINITY")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/prototype/index.html b/files/ko/web/javascript/reference/global_objects/number/prototype/index.html new file mode 100644 index 0000000000..e9b3f20362 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/prototype/index.html @@ -0,0 +1,90 @@ +--- +title: Number.prototype +slug: Web/JavaScript/Reference/Global_Objects/Number/prototype +tags: + - JavaScript + - Number + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +
{{JSRef}}
+ +

Number.prototype 속성은 {{jsxref("Number")}} 생성자의 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

모든 {{jsxref("Number")}} 인스턴스는 Number.prototype을 상속합니다. {{jsxref("Number")}} 생성자의 프로토타입 객체는 모든 {{jsxref( "Number")}} 인스턴스에 영향을 미치도록 수정할 수 있습니다.

+ +

속성

+ +
+
Number.prototype.constructor
+
이 객체의 인스턴스를 생성한 함수를 반환합니다. 기본적으로 {{jsxref("Number")}} 객체 입니다.
+
+ +

메서드

+ +
+
{{jsxref("Number.prototype.toExponential()")}}
+
숫자의 지수표기법 표현을 문자열로 반환합니다.
+
{{jsxref("Number.prototype.toFixed()")}}
+
숫자의 고정소수점 표현을 문자열로 반환합니다.
+
{{jsxref("Number.prototype.toLocaleString()")}}
+
숫자의 표현을 특정 언어에 맞춘 형식의 문자열로 반환합니다. {{jsxref("Object.prototype.toLocaleString()")}} 메서드를 오버라이드 합니다.
+
{{jsxref("Number.prototype.toPrecision()")}}
+
지정한 정밀도로 숫자를 나타내는 문자열을 반환합니다. 고정소수점 혹은 지수표기법으로 표현합니다.
+
{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}
+
지정한 {{jsxref("Number")}} 객체를 나타내는 객체 리터럴을 반환합니다. 이 값을 사용하여 새 객체를 만들 수 있습니다. {{jsxref("Object.prototype.toSource()")}} 메서드를 오버라이드 합니다.
+
{{jsxref("Number.prototype.toString()")}}
+
지정된 기수(기본 10진수)로 지정된 객체를 문자열로 반환합니다. {{jsxref("Object.prototype.toString()")}} 메서드를 오버라이드 합니다.
+
{{jsxref("Number.prototype.valueOf()")}}
+
지정한 객체의 기본 자료형(primitive) 값을 반환합니다. {{jsxref("Object.prototype.valueOf()")}} 메서드를 오버라이드 합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.prototype")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/toexponential/index.html b/files/ko/web/javascript/reference/global_objects/number/toexponential/index.html new file mode 100644 index 0000000000..cb24e88364 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/toexponential/index.html @@ -0,0 +1,108 @@ +--- +title: Number.prototype.toExponential() +slug: Web/JavaScript/Reference/Global_Objects/Number/toExponential +tags: + - JavaScript + - Method + - Number + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toExponential +--- +
{{JSRef}}
+ +

toExponential() 메서드는 숫자를 지수 표기법으로 표기해 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/number-toexponential.html")}}
+ + + +

구문

+ +
numObj.toExponential([fractionDigits])
+ +

매개변수

+ +
+
fractionDigits {{optional_inline}}
+
소수점 이하로 표현할 자릿수입니다. 기본값은 주어진 값을 나타내는데 필요한 자릿수입니다.
+
+ +

반환 값

+ +

주어진 {{jsxref("Number")}} 값을 숫자 한자리와 소수점, 소수점 이하 fractionDigits 자릿수만큼 반올림하여 지수 표기법으로 나타낸 문자열을 반환합니다.

+ +

예외

+ +
+
{{jsxref("RangeError")}}
+
fractionDigits가 너무 작거나 너무 크면 {{jsxref("RangeError")}} 에러가 발생합니다. fractionDigits가 0에서 20 사이의 값이면 {{jsxref("RangeError")}} 에러는 발생하지 않습니다. 구현에 따라 더 크거나 작은 값도 사용 할 수 있습니다.
+
{{jsxref("TypeError")}}
+
{{jsxref("Number")}}가 아닌 객체가 이 메서드를 실행시키면 {{jsxref("RangeError")}} 에러가 발생합니다.
+
+ +

설명

+ +

fractionDigits 매개변수를 생략하면, 기본적으로 주어진 값을 특정하기 위해 필요한 자릿수만큼이 소수점 이하 자릿수가 됩니다.

+ +

지수나 소수점이 없는 숫자 리터럴에 toExponential() 메서드를 사용하려면, 점 앞에 공백을 두어 점이 소수점으로 해석되는 것을 막도록 합니다.

+ +

주어진 값의 자릿수가 fractionDigits 매개변수보다 크다면, 주어진 값은 fractionDigits에 가까운 자릿수로 반올림되어 표현됩니다. {{jsxref("Number.prototype.toFixed", "toFixed()")}} 메서드의 반올림에 관한 설명이 toExponential() 메서드에도 마찬가지로 적용됩니다.

+ +

예제

+ +

toExponential 사용하기

+ +
var numObj = 77.1234;
+
+console.log(numObj.toExponential());  // logs 7.71234e+1
+console.log(numObj.toExponential(4)); // logs 7.7123e+1
+console.log(numObj.toExponential(2)); // logs 7.71e+1
+console.log(77.1234.toExponential()); // logs 7.71234e+1
+console.log(77 .toExponential());     // logs 7.7e+1
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의. JavaScript 1.5에서 구현됨.
{{SpecName('ES5.1', '#sec-15.7.4.6', 'Number.prototype.toExponential')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.toexponential', 'Number.prototype.toExponential')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.prototype.toexponential', 'Number.prototype.toExponential')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.toExponential")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/tofixed/index.html b/files/ko/web/javascript/reference/global_objects/number/tofixed/index.html new file mode 100644 index 0000000000..cf383f2265 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/tofixed/index.html @@ -0,0 +1,109 @@ +--- +title: Number.prototype.toFixed() +slug: Web/JavaScript/Reference/Global_Objects/Number/toFixed +tags: + - JavaScript + - Method + - Number + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toFixed +--- +
{{JSRef}}
+ +

toFixed() 메서드는 숫자를 고정 소수점 표기법으로 표기해 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/number-tofixed.html")}}
+ + + +

구문

+ +
numObj.toFixed([digits])
+ +

매개변수

+ +
+
digits {{optional_inline}}
+
소수점 뒤에 나타날 자릿수. 0 이상 20 이하의 값을 사용할 수 있으며, 구현체에 따라 더 넓은 범위의 값을 지원할 수도 있습니다. 값을 지정하지 않으면 0을 사용합니다.
+
+ +

반환 값

+ +

고정 소수점 표기법을 사용하여 나타낸 수.

+ +

예외

+ +
+
{{jsxref("RangeError")}}
+
digits가 너무 작거나 너무 클 때. 값이 0과 100사이의 값이라면 {{jsxref("RangeError")}}를 유발하지 않습니다. 구현체에 따라 더 크거나 작은 값을 지원할 수 있습니다.
+
{{jsxref("TypeError")}}
+
{{jsxref("Number")}}가 아닌 객체에서 호출한 경우.
+
+ +

설명

+ +

toFixed()는 {{jsxref("Number")}} 객체를 주어진 digits 만큼의 소수점 이하 자리수를 정확하게 갖는 문자열 표현으로 반환합니다. 소수점 이하가 길면 숫자를 반올림하고, 짧아서 부족할 경우 뒤를 0으로 채울 수 있습니다. 메서드를 호출한 숫자의 크기가 1e+21보다 크다면 {{jsxref("Number.prototype.toString()")}}을 호출하여 받은 지수 표기법 결과를 대신 반환합니다.

+ +

예제

+ +

toFixed() 사용하기

+ +
var numObj = 12345.6789;
+
+numObj.toFixed();       // Returns '12346': 반올림하며, 소수 부분을 남기지 않습니다.
+numObj.toFixed(1);      // Returns '12345.7': 반올림합니다.
+numObj.toFixed(6);      // Returns '12345.678900': 빈 공간을 0으로 채웁니다.
+(1.23e+20).toFixed(2);  // Returns '123000000000000000000.00'
+(1.23e-10).toFixed(2);  // Returns '0.00'
+2.34.toFixed(1);        // Returns '2.3'
+2.35.toFixed(1);        // Returns '2.4'. 이 경우에는 올림을 합니다.
+-2.34.toFixed(1);       // Returns -2.3 (연산자의 적용이 우선이기 때문에, 음수의 경우 문자열로 반환하지 않습니다...)
+(-2.34).toFixed(1);     // Returns '-2.3' (...괄호를 사용할 경우 문자열을 반환합니다.)
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.7.4.5', 'Number.prototype.toFixed')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.toFixed")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/toprecision/index.html b/files/ko/web/javascript/reference/global_objects/number/toprecision/index.html new file mode 100644 index 0000000000..83cf3017e3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/toprecision/index.html @@ -0,0 +1,110 @@ +--- +title: Number.prototype.toPrecision() +slug: Web/JavaScript/Reference/Global_Objects/Number/toPrecision +tags: + - JavaScript + - Method + - Number + - Prototype + - toPrecision +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toPrecision +--- +
{{JSRef}}
+ +

toPrecision() 메서드는 {{jsxref("Number")}} 객체를 지정된 정밀도로 나타내는 문자열을 반환한다.

+ +
{{EmbedInteractiveExample("pages/js/number-toprecision.html")}}
+ +

문법

+ +
numObj.toPrecision([precision])
+ +

파라미터

+ +
+
precision
+
선택적 파라미터. 유효 자릿수를 지정하는 정수.
+
+ +

반환 값

+ +

고정 소수점 또는 지수 표기법의 {{jsxref("Number")}} 객체를 정밀 유효 숫자로 반올림 한 문자열입니다. toPrecision()에도 적용되는 {{jsxref("Number.prototype.toFixed()")}} 메서드에 대한 설명에서 반올림에 대한 설명을 참조하세요.

+ +

precision(정밀도) 인수가 생략되면 {{jsxref("Number.prototype.toString()")}}처럼 작동합니다. precision(정밀도) 인수가 정수가 아닌 값이면 가장 가까운 정수로 반올림됩니다.

+ +

 

+ +

예외

+ +
+
{{jsxref("Global_Objects/RangeError", "RangeError")}}
+
precision(정밀도)가 1에서 100 사이가 아닌 경우 {{jsxref("RangeError")}}가 발생합니다. 구현은 더 큰 값과 더 작은 값을 지원할 수 있습니다. ECMA-262는 최대 21 자리의 정밀도 만을 요구합니다.
+
+ +

예제

+ +

toPrecision 사용

+ +
var numObj = 5.123456;
+
+console.log(numObj.toPrecision());    // logs '5.123456'
+console.log(numObj.toPrecision(5));   // logs '5.1235'
+console.log(numObj.toPrecision(2));   // logs '5.1'
+console.log(numObj.toPrecision(1));   // logs '5'
+
+numObj = 0.000123
+
+console.log(numObj.toPrecision());    // logs '0.000123'
+console.log(numObj.toPrecision(5));   // logs '0.00012300'
+console.log(numObj.toPrecision(2));   // logs '0.00012'
+console.log(numObj.toPrecision(1));   // logs '0.0001'
+
+// 일부 상황에서는 지수 표기법이 반환 될 수 있습니다
+console.log((1234.5).toPrecision(2)); // logs '1.2e+3'
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.7.4.7', 'Number.prototype.toPrecision')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.toprecision', 'Number.prototype.toPrecision')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.prototype.toprecision', 'Number.prototype.toPrecision')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.toPrecision")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/tostring/index.html b/files/ko/web/javascript/reference/global_objects/number/tostring/index.html new file mode 100644 index 0000000000..2c1366ad5b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/tostring/index.html @@ -0,0 +1,112 @@ +--- +title: Number.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Number/toString +tags: + - JavaScript + - Method + - Number + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toString +--- +
{{JSRef}}
+ +

toString() 메서드는 특정한 {{jsxref("Number")}} 객체를 나타내는 문자열을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/number-tostring.html")}}

+ +

구문

+ +
numObj.toString([radix])
+ +

매개변수

+ +
+
radix {{optional_inline}}
+
수의 값을 나타내기 위해 사용되기 위한 기준을 정하는 2와 36사이의 정수. (진수를 나타내는 기수의 값.)
+
+ +

반환 값

+ +

{{jsxref("Number")}} 객체를 명시하는 문자열.

+ +

예외

+ +
+
{{jsxref("RangeError")}}
+
만약 toString() 2 36의 사잇 값이 아닌 radix가 주어지면, {{jsxref("RangeError")}} 에러가 발생합니다.
+
+ +

설명

+ +

{{jsxref("Number")}} 객체는 {{jsxref("Object")}} 객체의 toString() 메소드를 오버라이딩하며,  {{jsxref("Object.prototype.toString()")}} 를 상속받지 않습니다. {{jsxref( "Number")}} 객체에서 toString() 메소드는 특정 진수로 객체를 표현한 문자열을 환원합니다.

+ +

toString() 메소드는 메소드의 첫 번째 아규먼트를 파싱하여, 메소드는 특정 기수(radix)를 기준으로 한 진수 값의 문자열을 환원하기 위한 시도를 합니다. 진수를 나타내는 기수 값(radix) 이 10 이상의 값일 때는, 알파벳의 글자는 9보다 큰 수를 나타냅니다. 예를 들면, 16진수(base 16)는, 알파벳 f 까지 사용하여 표현됩니다.

+ +

만약에 radix값 이 지정되지 않으면, 임의로 10진수로 가정하게 됩니다.

+ +

또, numObj가 음수라면, - 부호는 유지됩니다. 이는 기수(radix) 값이 2일 경우에라도 적용됩니다. 리턴된 문자열은 - 부호가 앞에 있는 numObj 의 양의 2진수 표시이지, numObj의 두 개의 조합이 아니기 때문입니다.

+ +

numObj 가 정수가 아니면, 점(.) 부호는 소수 자리와 분리하기 위해 사용됩니다. 

+ +

예제

+ +

toString 사용

+ +
var count = 10;
+
+console.log(count.toString());    // displays '10'
+console.log((17).toString());     // displays '17'
+console.log((17.2).toString());   // displays '17.2'
+
+var x = 6;
+
+console.log(x.toString(2));       // displays '110'
+console.log((254).toString(16));  // displays 'fe'
+
+console.log((-10).toString(2));   // displays '-1010'
+console.log((-0xff).toString(2)); // displays '-11111111'
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.1에서 구현됨.
{{SpecName('ES5.1', '#sec-15.7.4.2', 'Number.prototype.tostring')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.tostring', 'Number.prototype.tostring')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.prototype.tostring', 'Number.prototype.tostring')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Number.toString")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/number/valueof/index.html b/files/ko/web/javascript/reference/global_objects/number/valueof/index.html new file mode 100644 index 0000000000..344fa96ca2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/number/valueof/index.html @@ -0,0 +1,86 @@ +--- +title: Number.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/Number/valueOf +tags: + - JavaScript + - Method + - Number + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/valueOf +--- +
{{JSRef}}
+ +

valueOf() 메서드는 {{jsxref("Number")}} 객체가 감싼wrapped {{Glossary("primitive", "원시")}} 값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/number-valueof.html")}}
+ + + +

구문

+ +
numObj.valueOf()
+ +

반환 값

+ +

{{jsxref("Number")}} 객체의 원시 값.

+ +

설명

+ +

valueOf() 메서드는 보통 JavaScript에 의해 내부적으로 호출되고, 웹 코드에서는 명시적으로 호출하지 않습니다.

+ +

예제

+ +

valueOf 사용하기

+ +
var numObj = new Number(10);
+console.log(typeof numObj); // object
+
+var num = numObj.valueOf();
+console.log(num);           // 10
+console.log(typeof num);    // number
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4.4', 'Number.prototype.valueOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.valueof', 'Number.prototype.valueOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.prototype.valueof', 'Number.prototype.valueOf')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Number.valueOf")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/__definegetter__/index.html b/files/ko/web/javascript/reference/global_objects/object/__definegetter__/index.html new file mode 100644 index 0000000000..2ded710fda --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/__definegetter__/index.html @@ -0,0 +1,99 @@ +--- +title: Object.prototype.__defineGetter__() +slug: Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__ +translation_of: Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__ +--- +
{{JSRef}}
+ +
+

이 기능은 object initializer 문법 혹은 {{jsxref("Object.defineProperty()")}} API를 사용한 getter 정의가 표준화됨으로써 비표준화되었습니다.
+ 이 기능은 이제까지의 ECMAScript 사양에서만 사용되고 있습니다.
+ 보다 좋은 방법이 있으므로, 이 메소드는 사용하지 말아야합니다.

+
+ +

__defineGetter__ 메소드는 오브젝트의 프로퍼티와 함수를 바인드합니다.
+ 프로퍼티의 값이 조회될 때 바인드된 함수가 호출됩니다.

+ +

문법

+ +
obj.__defineGetter__(prop, func)
+ +

인자

+ +
+
prop
+
함수와 바인드된 프로퍼티의 이름을 나타내는 문자열
+
func
+
프로퍼티 값이 조회되었을 때 호출되는 함수
+
+ +

리턴 값

+ +

{{jsxref("undefined")}}.

+ +

Description

+ +

__defineGetter__ 를 사용하여 기존 오브젝트의 {{jsxref("Operators/get", "getter", "", 1)}}를 사용할 수 있습니다.

+ +

Examples

+ +
// Non-standard and deprecated way
+
+var o = {};
+o.__defineGetter__('gimmeFive', function() { return 5; });
+console.log(o.gimmeFive); // 5
+
+
+// Standard-compliant ways
+
+// Using the get operator
+var o = { get gimmeFive() { return 5; } };
+console.log(o.gimmeFive); // 5
+
+// Using Object.defineProperty
+var o = {};
+Object.defineProperty(o, 'gimmeFive', {
+  get: function() {
+    return 5;
+  }
+});
+console.log(o.gimmeFive); // 5
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-object.prototype.__defineGetter__', 'Object.prototype.__defineGetter__()')}}{{Spec2('ESDraft')}}Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object.defineGetter")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/assign/index.html b/files/ko/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..38b25d0bd8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,284 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Reference/Global_Objects/Object/assign +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Object + - Reference + - polyfill + - 객체 + - 레퍼런스 + - 메소드 +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +
{{JSRef}}
+ +

Object.assign() 메소드는 열거할 수 있는 하나 이상의 출처 객체로부터 대상 객체로 속성을 복사할 때 사용합니다. 대상 객체를 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/object-assign.html")}}

+ + + +

구문

+ +
Object.assign(target, ...sources)
+ +

매개변수

+ +
+
target
+
대상 객체.
+
sources
+
하나 이상의 출처 객체.
+
+ +

반환 값

+ +

대상 객체.

+ +

설명

+ +

동일한 키가 존재할 경우 대상 객체의 속성은 출처 객체의 속성으로 덮어쓰여집니다. 후에 출처의 속성은 이전의 출처의 속성과 유사하게 덮어씁니다.

+ +

Object.assign() 메소드는 열거할 수 있는 출처 객체의 속성만 대상 객체로 복사합니다. 이 메소드는 출처 객체의 [[Get]], 대상 객체의 [[Set]] 을 사용하여 getter 와 setter 를 호출합니다. 따라서 이는 속성을 단순히 복사하거나 새롭게 정의하는 것이 아니라 할당하는 것입니다. 병합 출처가 getter 를 포함하는 경우 프로토타입으로 새로운 속성을 병합하는 것이 적절하지 않을 수 있습니다. 프로토타입으로 속성의 열거성을 포함한 속성의 정의를 복사하려면 대신 {{jsxref("Object.getOwnPropertyDescriptor()")}} 와 {{jsxref("Object.defineProperty()")}} 를 사용해야합니다.

+ +

{{jsxref("String")}} 과 {{jsxref("Symbol")}} 속성 모두가 복사됩니다.

+ +

에러가 발생할 수 있는 상황에서는(예, 프로퍼티가 쓰기 불가인 경우), {{jsxref("TypeError")}} 가 발생하며, 에러가 발생하기 전에 속성이 추가되었다면 target 객체는 변경될 수 있습니다.

+ +

Object.assign() 메소드는 {{jsxref("null")}} 또는 {{jsxref("undefined")}} 출처 값에 대해서는 오류를 던지지 않음을 유의하세요.

+ +

예시

+ +

객체 클로닝

+ +
const obj = { a: 1 };
+const copy = Object.assign({}, obj);
+console.log(copy); // { a: 1 }
+
+ +

깊은 클로닝에 대한 주의사항

+ +

깊은 클로닝에 대해서, Object.assign() 은 속성의 값을 복사하기때문에 다른 대안을 사용해야합니다. 출처 값이 객체에 대한 참조인 경우, 참조 값만을 복사합니다.

+ +
function test() {
+  'use strict';
+
+  let obj1 = { a: 0 , b: { c: 0}};
+  let obj2 = Object.assign({}, obj1);
+  console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}
+
+  obj1.a = 1;
+  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
+  console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}
+
+  obj2.a = 2;
+  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
+  console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 0}}
+
+  obj2.b.c = 3; // obj1, obj2 모두에 영향을 줌
+  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 3}}
+  console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 3}}
+
+  // 깊은 클론
+  obj1 = { a: 0 , b: { c: 0}};
+  let obj3 = JSON.parse(JSON.stringify(obj1));
+  obj1.a = 4;
+  obj1.b.c = 4;
+  console.log(JSON.stringify(obj3)); // { a: 0, b: { c: 0}}
+}
+
+test();
+ +

객체 병합

+ +
const o1 = { a: 1 };
+const o2 = { b: 2 };
+const o3 = { c: 3 };
+
+const obj = Object.assign(o1, o2, o3);
+console.log(obj); // { a: 1, b: 2, c: 3 }
+console.log(o1);  // { a: 1, b: 2, c: 3 }, 대상 객체 자체가 변경됨.
+ +

같은 속성을 가진 객체 병합

+ +
const o1 = { a: 1, b: 1, c: 1 };
+const o2 = { b: 2, c: 2 };
+const o3 = { c: 3 };
+
+const obj = Object.assign({}, o1, o2, o3);
+console.log(obj); // { a: 1, b: 2, c: 3 }
+ +

속성은 파라미터 순서에서 더 뒤에 위치한 동일한 속성을 가진 다른 객체에 의해 덮어쓰입니다.

+ +

심볼형 속성 복사

+ +
const o1 = { a: 1 };
+const o2 = { [Symbol('foo')]: 2 };
+
+const obj = Object.assign({}, o1, o2);
+console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
+Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
+
+ +

프로토타입 체인의 속성과 열거 불가형 속성은 복사 불가

+ +
const obj = Object.create({ foo: 1 }, { // foo 는 obj 의 프로토타입 체인상에 있음.
+  bar: {
+    value: 2  // bar 는 열거 불가능한 속성임.
+  },
+  baz: {
+    value: 3,
+    enumerable: true  // baz 는 자체 열거형 속성임.
+  }
+});
+
+const copy = Object.assign({}, obj);
+console.log(copy); // { baz: 3 }
+
+ +

원시 자료형은 객체로 래핑

+ +
var v1 = 'abc';
+var v2 = true;
+var v3 = 10;
+var v4 = Symbol('foo');
+
+var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
+// 원시 자료형은 래핑되지만, null 과 undefined 는 무시됨.
+// 스트링 래퍼만 자체 열거형 속성을 가짐을 유의.
+console.log(obj); // { "0": "a", "1": "b", "2": "c" }
+
+ +

예외에 의해 진행중인 복사 작업 중단

+ +
var target = Object.defineProperty({}, 'foo', {
+  value: 1,
+  writable: false
+}); // target.foo 는 읽기 전용 속성
+
+Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
+// TypeError: "foo" is read-only
+// target.foo 에 할당할 때 예외 발생
+
+console.log(target.bar);  // 2, 첫 번째 출처 객체는 성공적으로 복사되었음.
+console.log(target.foo2); // 3, 두 번째 출처 객체의 첫 번째 프로퍼티도 성공적으로 복사되었음.
+console.log(target.foo);  // 1, 여기에서 예외가 발생.
+console.log(target.foo3); // undefined, assign 메소드가 종료되었음, foo3 은 복사되지 않음.
+console.log(target.baz);  // undefined, 세 번째 출처도 복사되지 않음.
+
+ +

접근자 복사

+ +
var obj = {
+  foo: 1,
+  get bar() {
+    return 2;
+  }
+};
+
+var copy = Object.assign({}, obj);
+console.log(copy);
+// { foo: 1, bar: 2 }, copy.bar 의 값은 obj.bar 의 getter 의 반환 값임.
+
+// 모든 descriptors 를 복사하는 할당 함수
+function completeAssign(target, ...sources) {
+  sources.forEach(source => {
+    let descriptors = Object.keys(source).reduce((descriptors, key) => {
+      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
+      return descriptors;
+    }, {});
+    // 기본적으로, Object.assign 는 열거형 Symbol 도 복사함.
+    Object.getOwnPropertySymbols(source).forEach(sym => {
+      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
+      if (descriptor.enumerable) {
+        descriptors[sym] = descriptor;
+      }
+    });
+    Object.defineProperties(target, descriptors);
+  });
+  return target;
+}
+
+var copy = completeAssign({}, obj);
+console.log(copy);
+// { foo:1, get bar() { return 2 } }
+
+ +

폴리필

+ +

ES5 에는 심볼이 없기 때문에 다음 {{Glossary("Polyfill","폴리필")}} 은 심볼 속성을 지원하지 않습니다.

+ +
if (typeof Object.assign != 'function') {
+  // Must be writable: true, enumerable: false, configurable: true
+  Object.defineProperty(Object, "assign", {
+    value: function assign(target, varArgs) { // .length of function is 2
+      'use strict';
+      if (target == null) { // TypeError if undefined or null
+        throw new TypeError('Cannot convert undefined or null to object');
+      }
+
+      var to = Object(target);
+
+      for (var index = 1; index < arguments.length; index++) {
+        var nextSource = arguments[index];
+
+        if (nextSource != null) { // Skip over if undefined or null
+          for (var nextKey in nextSource) {
+            // Avoid bugs when hasOwnProperty is shadowed
+            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
+              to[nextKey] = nextSource[nextKey];
+            }
+          }
+        }
+      }
+      return to;
+    },
+    writable: true,
+    configurable: true
+  });
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}{{Spec2('ESDraft')}} 
{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}{{Spec2('ES2015')}}초기 정의.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.assign")}}

+ +
 
+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/constructor/index.html b/files/ko/web/javascript/reference/global_objects/object/constructor/index.html new file mode 100644 index 0000000000..0162140d9c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/constructor/index.html @@ -0,0 +1,155 @@ +--- +title: Object.prototype.constructor +slug: Web/JavaScript/Reference/Global_Objects/Object/constructor +tags: + - JavaScript + - Object + - Property + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/constructor +--- +
{{JSRef}}
+ +

인스턴스의 프로토타입을 만든 {{jsxref("Object")}} 함수의 참조를 반환합니다. 이 속성값은 함수 자체의 참조임을 주의하세요, 함수 이름을 포함하는 문자열이 아니라. 그 값은 1, true"test"와 같은 원시(primitive) 값에 대해서만 읽기 전용입니다.

+ +

설명

+ +

모든 객체는 자신의 prototype으로부터 constructor 속성을 상속합니다:

+ +
var o = {};
+o.constructor === Object; // true
+
+var o = new Object;
+o.constructor === Object; // true
+
+var a = [];
+a.constructor === Array; // true
+
+var a = new Array;
+a.constructor === Array; // true
+
+var n = new Number(3);
+n.constructor === Number; // true
+ +

예제

+ +

객체의 생성자 표시하기

+ +

다음 예는 프로토타입이 Tree인 그 형의 객체 theTree를 만듭니다. 그 다음 객체 theTreeconstructor를 표시합니다.

+ +
function Tree(name) {
+  this.name = name;
+}
+
+var theTree = new Tree('Redwood');
+console.log('theTree.constructor is ' + theTree.constructor);
+
+ +

이 예는 다음 출력을 표시합니다:

+ +
theTree.constructor is function Tree(name) {
+  this.name = name;
+}
+
+ +

객체의 생성자 바꾸기

+ +

다음 예는 일반 객체의 constructor 값을 수정하는 법을 보입니다. true, 1"test"만이 원래 읽기 전용 생성자를 갖기에 영향을 받지 않습니다. 이 예는 객체의 constructor 속성에 의존하는 게 항상 안전하지는 않음을 보입니다.

+ +
function Type () {}
+
+var types = [
+  new Array(),
+  [],
+  new Boolean(),
+  true,             // 바뀌지 않음
+  new Date(),
+  new Error(),
+  new Function(),
+  function () {},
+  Math,
+  new Number(),
+  1,                // 바뀌지 않음
+  new Object(),
+  {},
+  new RegExp(),
+  /(?:)/,
+  new String(),
+  'test'            // 바뀌지 않음
+];
+
+for (var i = 0; i < types.length; i++) {
+  types[i].constructor = Type;
+  types[i] = [types[i].constructor, types[i] instanceof Type, types[i].toString()];
+}
+
+console.log(types.join('\n'));
+
+ +

이 예는 다음 출력을 표시합니다:

+ +
function Type() {},false,
+function Type() {},false,
+function Type() {},false,false
+function Boolean() {
+    [native code]
+},false,true
+function Type() {},false,Mon Sep 01 2014 16:03:49 GMT+0600
+function Type() {},false,Error
+function Type() {},false,function anonymous() {
+
+}
+function Type() {},false,function () {}
+function Type() {},false,[object Math]
+function Type() {},false,0
+function Number() {
+    [native code]
+},false,1
+function Type() {},false,[object Object]
+function Type() {},false,[object Object]
+function Type() {},false,/(?:)/
+function Type() {},false,/(?:)/
+function Type() {},false,
+function String() {
+    [native code]
+},false,test
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.1에서 구현됨.
{{SpecName('ES5.1', '#sec-15.2.4.1', 'Object.prototype.constructor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype.constructor', 'Object.prototype.constructor')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.Object.constructor")}}
+ +
 
diff --git a/files/ko/web/javascript/reference/global_objects/object/create/index.html b/files/ko/web/javascript/reference/global_objects/object/create/index.html new file mode 100644 index 0000000000..87a672aace --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/create/index.html @@ -0,0 +1,271 @@ +--- +title: Object.create() +slug: Web/JavaScript/Reference/Global_Objects/Object/create +tags: + - ECMAScript5 + - JavaScript + - Method + - Object + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Object/create +--- +
{{JSRef}}
+ +

Object.create() 메서드는 지정된 프로토타입 객체 및 속성(property)을 갖는 새 객체를 만듭니다.

+ +

구문

+ +
Object.create(proto[, propertiesObject])
+ +

매개변수

+ +
+
proto
+
새로 만든 객체의 프로토타입이어야 할 객체.
+
propertiesObject
+
선택사항. 지정되고 {{jsxref("undefined")}}가 아니면, 자신의 속성(즉, 자체에 정의되어 그 프로토타입 체인에서 열거가능하지 않은 속성)이 열거가능한 객체는 해당 속성명으로 새로 만든 객체에 추가될 속성 설명자(descriptor)를 지정합니다. 이러한 속성은 {{jsxref("Object.defineProperties()")}}의 두 번째 인수에 해당합니다.
+
+ +

반환값

+ +

지정된 프로토타입 개체와 속성을 갖는 새로운 개체.

+ +

예외

+ +

proto 매개변수가 {{jsxref("null")}} 또는 객체가 아닌 경우 {{jsxref("TypeError")}} 예외가 발생(throw).

+ +

+ +

Object.create()를 사용한 고전적인 상속방법

+ +

아래는 고전적인 상속방법으로 사용된 Object.create() 사용 예입니다. 이는 단일 상속 용으로, JavaScript가 지원하는 전부입니다.

+ +
// Shape - 상위클래스
+function Shape() {
+  this.x = 0;
+  this.y = 0;
+}
+
+// 상위클래스 메서드
+Shape.prototype.move = function(x, y) {
+  this.x += x;
+  this.y += y;
+  console.info('Shape moved.');
+};
+
+// Rectangle - 하위클래스
+function Rectangle() {
+  Shape.call(this); // super 생성자 호출.
+}
+
+// 하위클래스는 상위클래스를 확장
+Rectangle.prototype = Object.create(Shape.prototype);
+Rectangle.prototype.constructor = Rectangle;
+
+var rect = new Rectangle();
+
+console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle); // true
+console.log('Is rect an instance of Shape?', rect instanceof Shape); // true
+rect.move(1, 1); // Outputs, 'Shape moved.'
+
+ +

여러 객체에서 상속하고 싶은 경우엔 mixin이 사용가능합니다.

+ +
function MyClass() {
+  SuperClass.call(this);
+  OtherSuperClass.call(this);
+}
+
+MyClass.prototype = Object.create(SuperClass.prototype); // 상속
+mixin(MyClass.prototype, OtherSuperClass.prototype); // mixin
+
+MyClass.prototype.myMethod = function() {
+  // 기능 수행
+};
+
+ +

mixin 함수는 상위(super)클래스 프로토타입에서 하위(sub)클래스 프로토타입으로 함수를 복사하고, mixin 함수는 사용자에 의해 공급될 필요가 있습니다. mixin 같은 함수의 예는 jQuery.extend()입니다.

+ +

Object.create()와 함께 propertiesObject 인수 사용하기

+ +
var o;
+
+// 프로토타입이 null인 객체 생성
+o = Object.create(null);
+
+
+o = {};
+// 위는 아래와 같습니다:
+o = Object.create(Object.prototype);
+
+
+// 샘플 속성 두개를 갖는 객체를 만드는 예.
+// (두 번째 매개변수는 키를 *속성 설명자*에 맵핑함을 주의하세요.)
+o = Object.create(Object.prototype, {
+  // foo는 정규 '값 속성'
+  foo: { writable: true, configurable: true, value: 'hello' },
+  // bar는 접근자(accessor, getter-및-setter) 속성
+  bar: {
+    configurable: false,
+    get: function() { return 10; },
+    set: function(value) { console.log('Setting `o.bar` to', value); }
+/* ES5 접근자로 코드는 이렇게 할 수 있습니다
+    get function() { return 10; },
+    set function(value) { console.log('setting `o.bar` to', value); } */
+  }
+});
+
+
+function Constructor() {}
+o = new Constructor();
+// 위는 아래와 같습니다:
+o = Object.create(Constructor.prototype);
+// 물론, 생성자 함수에 실제 초기화 코드가 있다면
+// Object.create()는 그것을 반영할 수 없습니다
+
+
+// 빈 새 객체가 프로토타입인 새 객체를 만들고
+// 값이 42인 단일 속성 'p' 추가.
+o = Object.create({}, { p: { value: 42 } });
+
+// 기본으로 writable, enumerable 또는 configurable 속성은 false:
+o.p = 24;
+o.p;
+// 42
+
+o.q = 12;
+for (var prop in o) {
+  console.log(prop);
+}
+// 'q'
+
+delete o.p;
+// false
+
+// ES3 속성을 지정하기 위해
+o2 = Object.create({}, {
+  p: {
+    value: 42,
+    writable: true,
+    enumerable: true,
+    configurable: true
+  }
+});
+
+ +

폴리필

+ +

이 폴리필에서는 새 개체에 대한 프로토타입이 선택되었지만 두번째 인수가 없이 개체를 생성하는 사례를 보여줍니다.

+ +

[[Prototype]]에 null 을 설정하는 것이 실제 ES5 Object.create에서는 지원되지만, ECMAScript 5 보다 낮은 버전에서는 상속에 제한이 있기 때문에 이 폴리필에서는 지원할 수 없음에 주의하세요.

+ +
if (typeof Object.create != 'function') {
+  Object.create = (function(undefined) {
+    var Temp = function() {};
+    return function (prototype, propertiesObject) {
+      if(prototype !== Object(prototype) && prototype !== null) {
+        throw TypeError('Argument must be an object, or null');
+      }
+      Temp.prototype = prototype || {};
+      if (propertiesObject !== undefined) {
+        Object.defineProperties(Temp.prototype, propertiesObject);
+      }
+      var result = new Temp();
+      Temp.prototype = null;
+      // Object.create(null)인 경우 모방
+      if(prototype === null) {
+         result.__proto__ = null;
+      }
+      return result;
+    };
+  })();
+}
+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES5.1', '#sec-15.2.3.5', 'Object.create')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.8.5에서 구현됨.
{{SpecName('ES6', '#sec-object.create', 'Object.create')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.create', 'Object.create')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2")}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}{{CompatVersionUnknown}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/ko/web/javascript/reference/global_objects/object/defineproperties/index.html new file mode 100644 index 0000000000..a0949f78f2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/defineproperties/index.html @@ -0,0 +1,191 @@ +--- +title: Object.defineProperties() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +--- +
{{JSRef}}
+ +

Object.defineProperties() 메서드는 객체에 새로운 속성을 정의하거나 기존의 속성을 수정하고, 그 객체를 반환한다.

+ +
{{EmbedInteractiveExample("pages/js/object-defineproperties.html")}}
+ + + +

문법

+ +
Object.defineProperties(obj, props)
+ +

인자

+ +
+
obj
+
속성을 정의하거나 수정할 객체.
+
props
+
정의하거나 수정할 속성의 이름을 키로, 그 속성을 서술하는 객체를 값으로 갖는 객체. props의 각 값은 데이터 서술자(data descriptor) 혹은 접근자 서술자(accessor descriptor) 중 하나여야 하며, 동시에 두 유형을 포함할 수 없다({{jsxref("Object.defineProperty()")}} 참조).
+
데이터 서술자와 접근자 서술자 모두 다음 키를 선택적으로 포함할 수 있다:
+
+
+
configurable
+
true일 경우 이 속성 서술자의 형태를 변경하거나, 속성을 해당 객체에서 삭제할 수 있다.
+ 기본값은 false이다.
+
enumerable
+
true일 경우 해당 객체의 속성을 열거할 때 이 속성이 열거된다.
+ 기본값은 false이다.
+
+ +

데이터 서술자의 경우 다음 키를 추가로 포함할 수 있다:

+ +
+
value
+
이 속성에 설정할 값. 올바른 자바스크립트 값(숫자, 객체, 함수 등)이면 무엇이든 설정할 수 있다.
+ 기본값은 {{jsxref("undefined")}}이다.
+
writable
+
true일 경우 이 속성에 설정된 값을 {{jsxref("Operators/Assignment_Operators", "할당 연산자", "", 1)}}로 수정할 수 있다.
+ 기본값은 false이다.
+
+ +

접근자 서술자의 경우 다음 키를 추가로 포함할 수 있다:

+ +
+
get
+
해당 속성의 getter가 될 함수, 혹은 getter가 없을 경우 {{jsxref("undefined")}}. 이 함수의 반환값이 속성의 값으로 사용된다.
+ 기본값은 {{jsxref("undefined")}}이다.
+
set
+
해당 속성의 setter가 될 함수, 혹은 setter가 없을 경우 {{jsxref("undefined")}}. 이 함수는 이 속성에 할당되는 새로운 값을 유일한 인자로 받는다.
+ 기본값은 {{jsxref("undefined")}}이다.
+
+ +

서술자가 value, writable, get, set 키를 모두 가지고 있지 않을 경우 데이터 서술자로 취급한다. 서술자가 value이나 writableget이나 set 키를 모두 가지고 있을 경우 예외가 발생한다.

+
+
+ +

반환값

+ +

함수에 넘겨주었던 객체.

+ +

설명

+ +

Object.defineProperties는 기본적으로 props의 모든 열거가능한 속성에 따라 객체 obj의 속성을 정의한다.

+ +

예시

+ +
var obj = {};
+Object.defineProperties(obj, {
+  'property1': {
+    value: true,
+    writable: true
+  },
+  'property2': {
+    value: 'Hello',
+    writable: false
+  }
+  // 등등
+});
+
+ +

폴리필

+ +

모든 이름과 속성이 원래 값을 가리키는 깨끗한 실행 환경에서 Object.defineProperties는 다음 자바스크립트 재구현과 거의 완벽하게 똑같이(isCallable의 주석에 주목) 실행된다.

+ +
function defineProperties(obj, properties) {
+  function convertToDescriptor(desc) {
+    function hasProperty(obj, prop) {
+      return Object.prototype.hasOwnProperty.call(obj, prop);
+    }
+
+    function isCallable(v) {
+      // NB: 함수가 아닌 값이 호출가능할 경우 필요할 시 수정할 것
+      return typeof v === 'function';
+    }
+
+    if (typeof desc !== 'object' || desc === null)
+      throw new TypeError('bad desc');
+
+    var d = {};
+
+    if (hasProperty(desc, 'enumerable'))
+      d.enumerable = !!desc.enumerable;
+    if (hasProperty(desc, 'configurable'))
+      d.configurable = !!desc.configurable;
+    if (hasProperty(desc, 'value'))
+      d.value = desc.value;
+    if (hasProperty(desc, 'writable'))
+      d.writable = !!desc.writable;
+    if (hasProperty(desc, 'get')) {
+      var g = desc.get;
+
+      if (!isCallable(g) && typeof g !== 'undefined')
+        throw new TypeError('bad get');
+      d.get = g;
+    }
+    if (hasProperty(desc, 'set')) {
+      var s = desc.set;
+      if (!isCallable(s) && typeof s !== 'undefined')
+        throw new TypeError('bad set');
+      d.set = s;
+    }
+
+    if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d))
+      throw new TypeError('identity-confused descriptor');
+
+    return d;
+  }
+
+  if (typeof obj !== 'object' || obj === null)
+    throw new TypeError('bad obj');
+
+  properties = Object(properties);
+
+  var keys = Object.keys(properties);
+  var descs = [];
+
+  for (var i = 0; i < keys.length; i++)
+    descs.push([keys[i], convertToDescriptor(properties[keys[i]])]);
+
+  for (var i = 0; i < descs.length; i++)
+    Object.defineProperty(obj, descs[i][0], descs[i][1]);
+
+  return obj;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}{{Spec2('ES5.1')}}초기 정의. 자바스크립트 1.8.5에 구현됨
{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ESDraft')}}
+ +

브라우저 지원 현황

+ + + +

{{Compat("javascript.builtins.Object.defineProperties")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/ko/web/javascript/reference/global_objects/object/defineproperty/index.html new file mode 100644 index 0000000000..0d4a803316 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/defineproperty/index.html @@ -0,0 +1,417 @@ +--- +title: Object.defineProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +--- +
{{JSRef}}
+ +

Object.defineProperty() 정적 메서드는 객체에 직접 새로운 속성을 정의하거나 이미 존재하는 속성을 수정한 후, 그 객체를 반환합니다.

+ +
+

참고: defineProperty는 {{jsxref("Object")}} 인스턴스가 아니라 생성자에서 바로 호출해야 합니다.

+
+ +
{{EmbedInteractiveExample("pages/js/object-defineproperty.html")}}
+ + + +

구문

+ +
Object.defineProperty(obj, prop, descriptor)
+ +

매개변수

+ +
+
obj
+
속성을 정의할 객체.
+
prop
+
새로 정의하거나 수정하려는 속성의 이름 또는 {{jsxref("Symbol")}}.
+
descriptor
+
새로 정의하거나 수정하려는 속성을 기술하는 객체.
+
+ +

반환 값

+ +

주어진 대상 obj.

+ +

설명

+ +

defineProperty는 객체의 속성을 정교하게 추가하거나 수정할 수 있습니다. 할당을 통해 속성을 추가하는 일반적인 방법을 사용하면 속성 열거enumeration({{jsxref("Statements/for...in", "for...in")}} 반복문이나 {{jsxref("Object.keys")}} 메서드)를 통해 노출되어 값을 변경하거나 {{jsxref("Operators/delete", "delete")}} 연산자로 삭제할 수 있습니다. defineProperty를 사용하면 이런 부분을 상세하게 조절할 수 있습니다. Object.defineProperty()로 추가한 속성은 기본적으로 불변합니다.

+ +

속성 서술자property descriptors는 객체로 나타내며 데이터 서술자data descriptors와 접근자 서술자accessor descriptors의 두 가지 유형을 갖습니다. 데이터 서술자는 값을 가지는 속성으로, 덮어쓰거나 쓸 수 없습니다. 접근자 서술자는 접근자getter-설정자setter 한 쌍을 가지는 속성입니다. 서술자는 두 유형 중 하나여야 하며, 동시에 두 유형일 수는 없습니다.

+ +

데이터 서술자와 접근자 서술자 모두 객체이며 다음과 같은 키를 공유합니다.

+ +
+
configurable
+
이 속성의 값을 변경할 수 있고, 대상 객체에서 삭제할 수도 있다면 true.
+ 기본값은 false.
+
enumerable
+
이 속성이 대상 객체의 속성 열거 시 노출된다면 true.
+ 기본값은 false.
+
+ +

데이터 서술자는 다음 키를 선택사항으로 가집니다.

+ +
+
value
+
속성에 연관된 값. 아무 유효한 JavaScript 값(숫자, 객체, 함수 등)이나 가능합니다.
+ 기본값은 {{jsxref("undefined")}}
+
writable
+
{{jsxref("Operators/Assignment_Operators", "할당 연산자", "", 1)}}로 속성의 값을 바꿀 수 있다면 true.
+ 기본값은 false.
+
+ +

접근자 서술자는 다음 키를 선택사항으로 가집니다.

+ +
+
get
+
속성 접근자로 사용할 함수, 접근자가 없다면 {{jsxref("undefined")}}. 속성에 접근하면 이 함수를 매개변수 없이 호출하고, 그 반환값이 속성의 값이 됩니다. 이 때 this 값은 이 속성을 가진 객체(상속으로 인해 원래 정의한 객체가 아닐 수 있음)입니다.
+ 기본값은 {{jsxref("undefined")}}.
+
set
+
속성 설정자로 사용할 함수, 설정자가 없다면 {{jsxref("undefined")}}. 속성에 값을 할당하면 이 함수를 하나의 매개변수(할당하려는 값)로 호출합니다. 이 때 this 값은 이 속성을 가진 객체입니다.
+ 기본값은 {{jsxref("undefined")}}.
+
+ +

서술자가 value, writable, get, set 키를 모두 지니고 있지 않으면 데이터 서술자로 간주합니다. 반면 value 또는 writable과 동시에 get 또는 set 키를 함께 가지고 있으면 오류가 발생합니다.

+ +

각 설정값이 서술자 스스로의 속성일 필요는 없습니다. 따라서 서술자가 상속받은 값도 영향을 줍니다. 기본 설정값을 확실하게 보존하려면 {{jsxref("Object.prototype")}}을 먼저 동결하거나, 모든 속성을 명시적으로 지정하거나, {{jsxref("Object.create", "Object.create(null)")}}로 {{jsxref("null")}}을 가리키세요.

+ +
// __proto__ 사용
+var obj = {};
+var descriptor = Object.create(null); // 상속받은 속성 없음
+// 기본으로 열거 불가, 설정 불가, 변경 불가
+descriptor.value = 'static';
+Object.defineProperty(obj, 'key', descriptor);
+
+// 명시적
+Object.defineProperty(obj, 'key', {
+  enumerable: false,
+  configurable: false,
+  writable: false,
+  value: 'static'
+});
+
+// 같은 객체를 재활용하기
+function withValue(value) {
+  var d = withValue.d || (
+    withValue.d = {
+      enumerable: false,
+      writable: false,
+      configurable: false,
+      value: null
+    }
+  );
+  d.value = value;
+  return d;
+}
+Object.defineProperty(obj, 'key', withValue('static'));
+
+// Object.freeze가 존재하면
+// 속성의 추가/제거 방지
+// (value, get, set, enumerable, writable, configurable)
+(Object.freeze || Object)(Object.prototype);
+
+ +

예제

+ +

이진 플래그 형태로 defineProperty를 사용하는 예제는 additional examples에 있습니다.

+ +

속성 생성하기

+ +

Object.defineProperty()는 지정한 속성이 객체에 존재하지 않으면 주어진 서술자를 사용해 새로 생성합니다. 서술자의 일부 항목은 생략 가능하며, 생략한 항목은 기본값을 대신 사용합니다.

+ +
var o = {}; // 새로운 객체 생성
+
+// 데이터 속성 서술자와 defineProperty로
+// 새로운 속성을 추가하는 예시
+Object.defineProperty(o, 'a', {
+  value: 37,
+  writable: true,
+  enumerable: true,
+  configurable: true
+});
+// 'a' 속성이 o 객체에 존재하고 값은 37
+
+// 접근자 속성 기술자와 defineProperty로
+// 새로운 속성을 추가하는 예시
+var bValue = 38;
+Object.defineProperty(o, 'b', {
+  // ES2015 단축 메서드명 사용
+  // 아래 코드와 같음
+  // get: function() { return bValue; }
+  // set: function(newValue) { bValue = newValue; },
+  get() { return bValue; },
+  set(newValue) { bValue = newValue; },
+  enumerable: true,
+  configurable: true
+});
+o.b; // 38
+// 'b' 속성이 o 객체에 존재하고 값은 38
+// o.b를 재정의하지 않는 이상
+// o.b의 값은 항상 bValue와 동일함
+
+// 두 가지를 혼용할 수 없음
+Object.defineProperty(o, 'conflict', {
+  value: 0x9f91102,
+  get: function() { return 0xdeadbeef; }
+});
+// TypeError 발생
+// value는 데이터 서술자에만,
+// get은 접근자 서술자에만 나타날 수 있음
+ +

속성 수정하기

+ +

ObjectdefineProperty()는 지정한 속성이 객체에 이미 존재하면 주어진 서술자와 객체의 기존 설정을 사용해 속성의 수정을 시도합니다. 기존 속성 서술자의 configurablefalse이면 속성이 "설정 불가능"하다고 말하고, 이 속성의 어떤 특성도 수정할 수 없습니다. 다만 쓰기 가능한 데이터 속성의 경우 값을 바꾸거나 writable 특성을 true에서 false로 바꾸는건 가능합니다. 속성이 설정 불가능한 경우 속성의 유형을 데이터에서 접근자, 또는 접근자에서 데이터로 바꿀 수 없습니다.

+ +

설정 불가능한 속성의 특성을 바꾸려고 시도하면 {{jsxref("TypeError")}}가 발생합니다. 단, 기존 값과 신규 값이 같은 경우, 혹은 쓰기 가능한 속성의 valuewritable은 수정할 수 있습니다.

+ +

writable 특성

+ +

속성의 writable 특성이 false인 경우는 "쓰기 불가능"하여 다시 할당할 수 없습니다.

+ +
var o = {}; // 새로운 객체 생성
+
+Object.defineProperty(o, 'a', {
+  value: 37,
+  writable: false
+});
+
+console.log(o.a); // 37 기록
+o.a = 25; // 오류 발생하지 않음
+// 엄격 모드에서는 값이 같더라도
+// 오류가 발생함
+console.log(o.a); // 37 기록, 할당하지 못했음
+
+// 엄격 모드
+(function() {
+  'use strict';
+  var o = {};
+  Object.defineProperty(o, 'b', {
+    value: 2,
+    writable: false
+  });
+  o.b = 3; // TypeError: "b" is read-only
+  return o.b; // 윗줄이 없다면 2 반환
+}());
+
+ +

위의 예제가 보이듯, 비엄격 모드에서는 쓰기 불가능한 속성의 값에 쓰려고 시도하면 값이 바뀌지 않고, 오류도 발생하지도 않습니다.

+ +

Enumerable 속성

+ +

enumerable은 해당 속성이 {{jsxref("Statements/for...in", "for...in")}} 루프나 {{jsxref("Object.keys()")}} 에서 노출될지 말지를 정의한다.

+ +
var o = {};
+Object.defineProperty(o, 'a', {
+  value: 1,
+  enumerable: true
+});
+Object.defineProperty(o, 'b', {
+  value: 2,
+  enumerable: false
+});
+Object.defineProperty(o, 'c', {
+  value: 3
+}); // enumerable defaults to false
+o.d = 4; // enumerable defaults to true
+         // when creating a property by setting it
+Object.defineProperty(o, Symbol.for('e'), {
+  value: 5,
+  enumerable: true
+});
+Object.defineProperty(o, Symbol.for('f'), {
+  value: 6,
+  enumerable: false
+});
+
+for (var i in o) {
+  console.log(i);
+}
+// logs 'a' and 'd' (in undefined order)
+
+Object.keys(o); // ['a', 'd']
+
+o.propertyIsEnumerable('a'); // true
+o.propertyIsEnumerable('b'); // false
+o.propertyIsEnumerable('c'); // false
+o.propertyIsEnumerable('d'); // true
+o.propertyIsEnumerable(Symbol.for('e')); // true
+o.propertyIsEnumerable(Symbol.for('f')); // false
+
+var p = { ...o }
+p.a // 1
+p.b // undefined
+p.c // undefined
+p.d // 4
+p[Symbol.for('e')] // 5
+p[Symbol.for('f')] // undefined
+
+ +

Configurable 속성

+ +

configurable 은 객체에서 해당키가 제거될 수 있는지와 (writable을 제외한)기술속성을 변경할 수 있는지에 대한 여부를 동시에 통제한다.

+ +
var o = {};
+Object.defineProperty(o, 'a', {
+  get() { return 1; },
+  configurable: false
+});
+
+Object.defineProperty(o, 'a', {
+  configurable: true
+}); // throws a TypeError
+Object.defineProperty(o, 'a', {
+  enumerable: true
+}); // throws a TypeError
+Object.defineProperty(o, 'a', {
+  set() {}
+}); // throws a TypeError (set was undefined previously)
+Object.defineProperty(o, 'a', {
+  get() { return 1; }
+}); // throws a TypeError
+// (even though the new get does exactly the same thing)
+Object.defineProperty(o, 'a', {
+  value: 12
+}); // throws a TypeError
+
+console.log(o.a); // logs 1
+delete o.a; // Nothing happens
+console.log(o.a); // logs 1
+
+ +

o.aconfigurabletrue라면, 위의 예외는 발생하지 않고 속성은 마지막에 제거되었을 것이다.

+ +

속성에 기본값 추가하기

+ +

속성을 정의할 때 기본값을 제공하는 방식은 중요하다. 간단히 점구문을 이용해 할당한 값과 Object.defineProperty를 사용한 경우는 꽤 다르다. 아래 예를 보자.

+ +
var o = {};
+
+o.a = 1;
+// 위의 표현은 아래와 같다:
+Object.defineProperty(o, 'a', {
+  value: 1,
+  writable: true,
+  configurable: true,
+  enumerable: true
+});
+
+
+// 만약 다음과 같이 표현한다면,
+Object.defineProperty(o, 'a', { value: 1 });
+// 아래의 의미를 지니게 된다:
+Object.defineProperty(o, 'a', {
+  value: 1,
+  writable: false,
+  configurable: false,
+  enumerable: false
+});
+
+ +

사용자 정의 Setters 와 Getters

+ +

아래의 예는 어떻게 스스로 변화를 기록해두는 객체를 만드는지 보여준다. temperature 속성의 값을 바꾸면 archive 배열에도 로그가 쌓인다.

+ +
function Archiver() {
+  var temperature = null;
+  var archive = [];
+
+  Object.defineProperty(this, 'temperature', {
+    get: function() {
+      console.log('get!');
+      return temperature;
+    },
+    set: function(value) {
+      temperature = value;
+      archive.push({ val: temperature });
+    }
+  });
+
+  this.getArchive = function() { return archive; };
+}
+
+var arc = new Archiver();
+arc.temperature; // 'get!'
+arc.temperature = 11;
+arc.temperature = 13;
+arc.getArchive(); // [{ val: 11 }, { val: 13 }]
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.defineProperty")}}

+ +

호환성 참고사항

+ +

Redefining the length property of an Array object

+ +

It is possible to redefine the {{jsxref("Array.length", "length")}} property of arrays, subject to the usual redefinition restrictions. (The {{jsxref("Array.length", "length")}} property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array it is possible to change the {{jsxref("Array.length", "length")}} property's value, or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.

+ +

Firefox 4 through 22 will throw a {{jsxref("Global_Objects/TypeError", "TypeError")}} on any attempt whatsoever (whether permitted or not) to redefine the {{jsxref("Array.length", "length")}} property of an array.

+ +

Versions of Chrome which implement Object.defineProperty() in some circumstances ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like {{jsxref("Array.prototype.push")}} don't respect a non-writable length.

+ +

Versions of Safari which implement Object.defineProperty() ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property, and attempts to change writability execute without error but do not actually change the property's writability.

+ +

Only Internet Explorer 9 and later, and Firefox 23 and later, appear to fully and correctly implement redefinition of the {{jsxref("Array.length", "length")}} property of arrays. For now, don't rely on redefining the {{jsxref("Array.length", "length")}} property of an array to either work, or to work in a particular manner. And even when you can rely on it, there's really no good reason to do so.

+ +

Internet Explorer 8 specific notes

+ +

Internet Explorer 8 implemented a Object.defineProperty() method that could only be used on DOM objects. A few things need to be noted:

+ + + +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/entries/index.html b/files/ko/web/javascript/reference/global_objects/object/entries/index.html new file mode 100644 index 0000000000..3056d99d31 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/entries/index.html @@ -0,0 +1,145 @@ +--- +title: Object.entries() +slug: Web/JavaScript/Reference/Global_Objects/Object/entries +translation_of: Web/JavaScript/Reference/Global_Objects/Object/entries +--- +
{{JSRef}}
+ +

Object.entries() 메서드는 {{jsxref("Statements/for...in", "for...in")}}와 같은 순서로 주어진 객체 자체의 enumerable 속성 [key, value] 쌍의 배열을 반환합니다. (for-in 루프가 다른점은 프로토 타입 체인의 속성도 열거한다는 점입니다).

+ +

Object.entries() 에 의해 반환된 배열(array)의 순서는 객체가 정의된 방법과 관련이 없습니다.  배열 순서가 쓸 곳이 있다면, 다음과 같이 정렬을 먼저 하시는 것이 좋습니다 Object.entries(obj).sort((a, b) => b[0].localeCompare(a[0]));.

+ +
{{EmbedInteractiveExample("pages/js/object-entries.html", "taller")}}
+ + + +

Syntax

+ +
Object.entries(obj)
+ +

Parameters

+ +
+
obj
+
객체 자체의 열거 가능한 문자열 키를 가진 속성 [key, value] 쌍이 반환되는 객체입니다.
+
+ +

Return value

+ +

지정된 객체 자체의 열거 가능한 문자속성 [key, value] 쌍의 배열입니다.

+ +

Description

+ +

Object.entries()object에 직접있는 enumerable 속성 [key, value] 쌍에 해당하는 배열을 반환합니다. 속성의 순서는 개체의 속성 값을 수동으로 반복하여 주어진 순서와 동일합니다.

+ +

Polyfill

+ +

기본적으로 지원하지 않는 이전 환경에서 호환 가능한 Object.entries 지원을 추가하려면 tc39/proposal-object-values-entries에 Object.entries의 데모 구현을 찾을 수 있습니다 (IE에 대한 지원이 필요하지 않은 경우) , es-shims/Object.entries 저장소에있는 polyfill을 사용하거나 아래에 나열된 polyfill을 간단하게 배치 할 수 있습니다.

+ +
if (!Object.entries)
+  Object.entries = function( obj ){
+    var ownProps = Object.keys( obj ),
+        i = ownProps.length,
+        resArray = new Array(i); // preallocate the Array
+    while (i--)
+      resArray[i] = [ownProps[i], obj[ownProps[i]]];
+
+    return resArray;
+  };
+
+ +

For the above polyfill code snippet, if you need support for IE < 9, then you will also need an Object.keys polyfill (such as the one found on the {{jsxref("Object.keys")}} page).

+ +

위의 polyfill 코드 스 니펫의 경우 Internet Explorer (9버전 이전)를 지원해야하는 경우 Object.keys polyfill ( {{jsxref("Object.keys")}} 페이지에 있는 것과 같은)도 필요합니다.

+ +

Examples

+ +
const obj = { foo: 'bar', baz: 42 };
+console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
+
+// array like object
+const obj = { 0: 'a', 1: 'b', 2: 'c' };
+console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
+
+// array like object with random key ordering
+const anObj = { 100: 'a', 2: 'b', 7: 'c' };
+console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]
+
+// getFoo is property which isn't enumerable
+const myObj = Object.create({}, { getFoo: { value() { return this.foo; } } });
+myObj.foo = 'bar';
+console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]
+
+// non-object argument will be coerced to an object
+console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]
+
+// returns an empty array for any primitive type, since primitives have no own properties
+console.log(Object.entries(100)); // [ ]
+
+// iterate through key-value gracefully
+const obj = { a: 5, b: 7, c: 9 };
+for (const [key, value] of Object.entries(obj)) {
+  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
+}
+
+// Or, using array extras
+Object.entries(obj).forEach(([key, value]) => {
+console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
+});
+
+ +

Converting an Object to a Map

+ +

{{jsxref("Map", "new Map()")}} 생성자는 반복 가능한 항목을 허용합니다. Object.entries를 사용하면 {{jsxref("Object")}}에서 {{jsxref("Map")}}로 쉽게 변환 할 수 있습니다.

+ + + +
const obj = { foo: 'bar', baz: 42 };
+const map = new Map(Object.entries(obj));
+console.log(map); // Map { foo: "bar", baz: 42 }
+
+ +

Iterating through an Object

+ +

Array Destructuring을 사용하면 객체를 쉽게 반복 할 수 있습니다.

+ +
const obj = { foo: 'bar', baz: 42 };
+Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`)); // "foo: bar", "baz: 42"
+
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-object.entries', 'Object.entries')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object.entries")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/freeze/index.html b/files/ko/web/javascript/reference/global_objects/object/freeze/index.html new file mode 100644 index 0000000000..6eaca7b708 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/freeze/index.html @@ -0,0 +1,257 @@ +--- +title: Object.freeze() +slug: Web/JavaScript/Reference/Global_Objects/Object/freeze +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object + - Reference + - 동결 + - 변경 + - 변경가능성 + - 불변 + - 불변성 + - 잠금 +translation_of: Web/JavaScript/Reference/Global_Objects/Object/freeze +--- +
{{JSRef}}
+ +

Object.freeze() 메서드는 객체를 동결합니다. 동결된 객체는 더 이상 변경될 수 없습니다. 즉, 동결된 객체는 새로운 속성을 추가하거나 존재하는 속성을 제거하는 것을 방지하며 존재하는 속성의 불변성, 설정 가능성(configurability), 작성 가능성이 변경되는 것을 방지하고, 존재하는 속성의 값이 변경되는 것도 방지합니다. 또한, 동결 객체는 그 프로토타입이 변경되는것도 방지합니다. freeze()는 전달된 동일한 객체를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/object-freeze.html")}}
+ + + +

구문

+ +
Object.freeze(obj)
+ +

매개변수

+ +
+
obj
+
동결할 객체.
+
+ +

반환 값

+ +

함수로 전달된 객체.

+ +

설명

+ +

동결 객체의 속성 집합에는 어떠한 것도 추가하거나 제거할 수 없으며, 그리 하려는 모든 시도는 조용히 넘어가거나, {{jsxref("TypeError")}} 예외가 발생하며 실패합니다. 예외 발생은 보통 {{jsxref("Strict_mode", "엄격 모드", "", 1)}}인 경우 발생하지만, 반드시 엄격 모드로만 제한되는 것은 아닙니다.

+ +

동결 객체가 가진 데이터 속성에 대해선, 값을 변경할 수 없으며 설정 가능 여부와 쓰기 가능 여부 속성 모두 거짓이 됩니다. 접근자 속성(접근자와 설정자)도 동일하게 동작합니다(또한 값을 변경하고 있다는 환상을 줍니다). 수정되는 값이 객체이고 동결된 것이 아니라면 여전히 수정이 가능함을 유의하세요. 객체로써, 배열도 동결될 수 있습니다. 동결한 이후에는 그 엘리먼트를 변경할 수 없으며 배열에 어떠한 엘리먼트도 추가하거나 제거할 수 없습니다.

+ +

freeze()는 함수에 전달한 객체를 그대로 반환하며, 동결된 객체 사본을 생성하는 것이 아닙니다.

+ +

예제

+ +

객체 동결하기

+ +
var obj = {
+  prop: function() {},
+  foo: 'bar'
+};
+
+// 동결 이전: 새 속성을 추가할 수 있고,
+// 기존 속성을 변경하거나 제거할 수 있음
+obj.foo = 'baz';
+obj.lumpy = 'woof';
+delete obj.prop;
+
+// 동결
+var o = Object.freeze(obj);
+
+// 반환 값은 전달된 객체와 동일함.
+o === obj; // true
+
+// 객체가 동결 상태가 됨.
+Object.isFrozen(obj); // === true
+
+// 이제 모든 변경 시도는 실패함
+obj.foo = 'quux'; // 조용하게 아무것도 하지 않음
+// 조용하게 속성을 추가하지 않음
+obj.quaxxor = 'the friendly duck';
+
+// 엄격 모드에서는 이러한 시도에 대해 TypeError 발생
+function fail(){
+  'use strict';
+  obj.foo = 'sparky'; // TypeError 발생
+  delete obj.foo;     // TypeError 발생
+  delete obj.quaxxor; // 'quaxxor' 속성은 추가된 적이 없으므로 true 반환
+  obj.sparky = 'arf'; // TypeError 발생
+}
+
+fail();
+
+// Object.defineProperty를 통한 변경 시도
+// 아래 두 구문 모두에서 TypeError 발생
+Object.defineProperty(obj, 'ohai', { value: 17 });
+Object.defineProperty(obj, 'foo', { value: 'eit' });
+
+// 프로토타입을 변경하는 것 또한 불가함
+// 아래 두 구문 모두에서 TypeError 발생
+Object.setPrototype(obj, { x: 20 });
+obj.__proto__ = { x: 20 };
+
+
+ +

배열 동결

+ +
let a = [0];
+Object.freeze(a); // 이제 배열을 수정할 수 없음.
+
+a[0]=1; // 조용하게 실패
+a.push(2); // 조용하게 실패
+
+// 엄격 모드에서는 이런 시도에 대해 TypeError 발생
+function fail() {
+  "use strict"
+  a[0] = 1;
+  a.push(2);
+}
+
+fail();
+ +

동결된 객체는 변경할 수 없습니다. 하지만, 꼭 그렇지만은 않습니다. 다음 예제는 동결된 객체가 변경될 수 있음을(얕은 동결) 보여줍니다.

+ +
obj = {
+  internal: {}
+};
+
+Object.freeze(obj);
+obj.internal.a = 'aValue';
+
+obj.internal.a // 'aValue'
+
+ +

변경될 수 없는 객체가 되려면, 모든 참조 그래프(다른 객체로의 직간접적 참조)가 오로지 불변의 동결 객체만을 참조해야 합니다. 동결된 객체는 객체 내의 모든 상태(다른 객체로의 값과 참조)가 고정되기 때문에 불변하다고 합니다. 문자열, 숫자, 불리언 값은 언제나 불변하고, 함수와 배열은 객체임을 유의하세요.

+ +

"얕은 동결"이 무엇인가요?

+ +

Object.freeze(object) 호출의 결과는 object 스스로의 직속 속성에만 적용되며, object에 대해서만 속성 추가, 제거, 재할당 연산을 방지합니다. 만약 그 속성의 값이 객체라면, 그 객체는 동결되지 않으며 속성 추가, 제거, 재할당의 대상이 될 수 있습니다.

+ +
var employee = {
+  name: "Mayank",
+  designation: "Developer",
+  address: {
+    street: "Rohini",
+    city: "Delhi"
+  }
+};
+
+Object.freeze(employee);
+
+employee.name = "Dummy"; // 비엄격 모드에서 조용하게 실패
+employee.address.city = "Noida"; // 자식 객체의 속성은 수정 가능
+
+console.log(employee.address.city) // 출력: "Noida"
+
+ +

객체를 불변하게 만들려면, 각 객체 타입의 속성을 재귀적으로 동결해야합니다(깊은 동결). 객체가 그 참조 그래프에서 {{interwiki("wikipedia", "Cycle_(graph_theory)", "순환")}}을 포함하지 않는다는 것을 인지하고 있을 때, 디자인을 기반으로 상황에 따라 패턴을 적용해야하며, 그렇지 않을 경우 반복문이 무한히 실행될 수 있습니다. deepFreeze()에 대한 개선은 객체가 불변하게 되는 과정에 있을 때 deepFreeze()의 재귀적인 호출을 차단할 수 있도록 경로(예, 배열) 인자를 받는 내부 함수를 소유하는 것입니다. [window]와 같은, 동결되면 안되는 객체를 동결하는 것에 대한 위험은 여전히 남아 있습니다.

+ +
function deepFreeze(object) {
+
+  // 객체에 정의된 속성명을 추출
+  var propNames = Object.getOwnPropertyNames(object);
+
+  // 스스로를 동결하기 전에 속성을 동결
+
+  for (let name of propNames) {
+    let value = object[name];
+
+    object[name] = value && typeof value === "object" ?
+      deepFreeze(value) : value;
+  }
+
+  return Object.freeze(object);
+}
+
+var obj2 = {
+  internal: {
+    a: null
+  }
+};
+
+deepFreeze(obj2);
+
+obj2.internal.a = 'anotherValue'; // 비엄격 모드에서 조용하게 실패
+obj2.internal.a; // null
+
+ +

사용 노트

+ +

ES5에서는, 이 메소드에 대한 인자가 객체(원시형)가 아닐 경우, {{jsxref("TypeError")}}가 발생합니다. ES2015에서는, 비객체 인자가 동결된 평범한 객체인것처럼 다루어져 반환됩니다.

+ +
> Object.freeze(1)
+TypeError: 1 is not an object // ES5 code
+
+> Object.freeze(1)
+1                             // ES2015 code
+
+ +

엘리먼트를 갖는 {{domxref("ArrayBufferView")}}는 메모리를 통한 뷰이므로 다른 가능한 문제를 유발 할 수 있어 {{jsxref("TypeError")}}가 발생합니다.

+ +
> Object.freeze(new Uint8Array(0)) // 엘리먼트가 없음
+Uint8Array []
+
+> Object.freeze(new Uint8Array(1)) // 엘리먼트를 가짐
+TypeError: Cannot freeze array buffer views with elements
+
+> Object.freeze(new DataView(new ArrayBuffer(32))) // 엘리먼트가 없음
+DataView {}
+
+> Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // 엘리먼트가 없음
+Float64Array []
+
+> Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // 엘리먼트를 가짐
+TypeError: Cannot freeze array buffer views with elements
+ +

세 가지 표준 속성(buf.byteLengthbuf.byteOffsetbuf.buffer)은 읽기 전용(이들은 {jsxref("ArrayBuffer")}} 또는 {{jsxref("SharedArrayBuffer")}}이므로)이므로, 이러한 속성에 대해 동결을 시도할 이유가 없음을 유의합니다.

+ +

Object.seal()과의 비교

+ +

{{jsxref("Object.seal()")}}을 사용해 봉인된 객체는 존재하는 속성을 변경할 수 있습니다. Object.freeze()로 동결된 객체에서는 존재하는 속성이 불변입니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('ES5.1', '#sec-15.2.3.9', 'Object.freeze')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.8.5에서 구현됨.
{{SpecName('ES6', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Object.freeze")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/fromentries/index.html b/files/ko/web/javascript/reference/global_objects/object/fromentries/index.html new file mode 100644 index 0000000000..4d74fc326a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/fromentries/index.html @@ -0,0 +1,98 @@ +--- +title: Object.fromEntries() +slug: Web/JavaScript/Reference/Global_Objects/Object/fromEntries +tags: + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/fromEntries +--- +
{{JSRef}}
+ +

Object.fromEntries() 메서드는 키값 쌍의 목록을 객체로 바꿉니다.

+ +
{{EmbedInteractiveExample("pages/js/object-fromentries.html")}}
+ +

구문

+ +
Object.fromEntries(iterable);
+ +

매개변수

+ +
+
iterable
+
반복 가능한 객체. 즉, {{jsxref("Array")}}, {{jsxref("Map")}} 또는 반복 규약을 구현한 기타 객체.
+
+ +

반환 값

+ +

속성의 키와 값을 반복 가능한 객체에서 가져온 새로운 객체.

+ +

설명

+ +

Object.fromEntries() 메서드는 키값 쌍 목록을 받고, 그 목록을 사용해 속성을 부여한 새로운 객체를 반환합니다. iterable 인자는 @@iterator 메서드를 구현하여 반복기 객체를 반환해야 하고, 그 반복기는 또 배열 형태의 객체로 요소 2개를 반환해야 합니다. 반환된 요소 중 첫 번째는 생성할 객체의 속성 키로, 두 번째는 속성 값으로 사용합니다.

+ +

Object.fromEntries()는{{jsxref("Object.entries()")}}의 역을 수행합니다.

+ +

예제

+ +

Map에서 Object

+ +
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
+const obj = Object.fromEntries(map);
+console.log(obj); // { foo: "bar", baz: 42 }
+
+ +

Array에서 Object

+ +
const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ];
+const obj = Object.fromEntries(arr);
+console.log(obj); // { 0: "a", 1: "b", 2: "c" }
+
+ +

객체 변환

+ +

Object.fromEntries()와 그 역인 {{jsxref("Object.entries()")}}, 그리고 배열 변형 메서드를 통해 객체를 변환할 수 있습니다.

+ +
const object1 = { a: 1, b: 2, c: 3 };
+
+const object2 = Object.fromEntries(
+  Object.entries(object1)
+  .map(([ key, val ]) => [ key, val * 2 ])
+);
+
+console.log(object2);
+// { a: 2, b: 4, c: 6 }
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatus
https://tc39.github.io/proposal-object-from-entriesStage 3
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Object.fromEntries")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html b/files/ko/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html new file mode 100644 index 0000000000..c3be0cbaae --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html @@ -0,0 +1,126 @@ +--- +title: Object.getOwnPropertyDescriptor() +slug: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor +tags: + - ECMAScript5 + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor +--- +
{{JSRef}}
+ +

Object.getOwnPropertyDescriptor() 메서드는 주어진 객체 자신의 속성(즉, 객체에 직접 제공하는 속성, 객체의 프로토타입 체인을 따라 존재하는 덕택에 제공하는 게 아닌)에 대한 속성 설명자(descriptor)를 반환합니다.

+ +

구문

+ +
Object.getOwnPropertyDescriptor(obj, prop)
+ +

매개변수

+ +
+
obj
+
속성을 찾을 대상 객체.
+
prop
+
설명이 검색될 속성명.
+
+ +

반환값

+ +

객체에 존재하는 경우 주어진 속성의 속성 설명자, 없으면 {{jsxref("undefined")}}.

+ +

설명

+ +

이 메서드는 정확한 속성 설명의 검사를 허용합니다. JavaScript에서 속성은 문자열 값인 이름과 속성 설명자로 구성됩니다. 속성 설명자 유형과 attribute에 관한 자세한 정보는 {{jsxref("Object.defineProperty()")}}에서 찾을 수 있습니다.

+ +

속성 설명자는 다음 attribute 중 일부의 기록입니다:

+ +
+
value
+
속성과 관련된 값 (데이터 설명자만).
+
writable
+
속성과 관련된 값이 변경될 수 있는 경우에만 true (데이터 설명자만).
+
get
+
속성에 대해 getter로서 제공하는 함수 또는 getter가 없는 경우 {{jsxref("undefined")}} (접근자 설명자만).
+
set
+
속성에 대해 setter로서 제공하는 함수 또는 setter가 없는 경우 {{jsxref("undefined")}} (접근자 설명자만).
+
configurable
+
이 속성 설명자의 유형이 바뀔 수 있는 경우에만 그리고 속성이 해당 객체에서 삭제될 수 있는 경우 true.
+
enumerable
+
이 속성이 해당 객체의 속성 열거 중에 나타나는 경우에만 true.
+
+ +

+ +
var o, d;
+
+o = { get foo() { return 17; } };
+d = Object.getOwnPropertyDescriptor(o, 'foo');
+// d는 { configurable: true, enumerable: true, get: /* getter 함수 */, set: undefined }
+
+o = { bar: 42 };
+d = Object.getOwnPropertyDescriptor(o, 'bar');
+// d는 { configurable: true, enumerable: true, value: 42, writable: true }
+
+o = {};
+Object.defineProperty(o, 'baz', { value: 8675309, writable: false, enumerable: false });
+d = Object.getOwnPropertyDescriptor(o, 'baz');
+// d는 { value: 8675309, writable: false, enumerable: false, configurable: false }
+
+ +

주의

+ +

ES5에서, 이 메서드의 첫 번째 인수가 비객체(원시형)인 경우, 그러면 {{jsxref("TypeError")}}가 발생합니다. ES6에서, 비객체 첫 번째 인수는 먼저 객체로 강제됩니다.

+ +
Object.getOwnPropertyDescriptor("foo", 0);
+// TypeError: "foo"는 객체가 아닙니다  // ES5 코드
+
+Object.getOwnPropertyDescriptor("foo", 0);
+// {configurable:false, enumerable:true, value:"f", writable:false}  // ES6 코드
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES5.1', '#sec-15.2.3.3', 'Object.getOwnPropertyDescriptor')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.8.5에서 구현됨.
{{SpecName('ES6', '#sec-object.getownpropertydescriptor', 'Object.getOwnPropertyDescriptor')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.getownpropertydescriptor', 'Object.getOwnPropertyDescriptor')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
+
+ + +

{{Compat("javascript.builtins.Object.getOwnPropertyDescriptor")}}

+
+
+ +

 

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/ko/web/javascript/reference/global_objects/object/getprototypeof/index.html new file mode 100644 index 0000000000..12a65e24de --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/getprototypeof/index.html @@ -0,0 +1,134 @@ +--- +title: Object.getPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +tags: + - ECMAScript5 + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +--- +
{{JSRef}}
+ +

Object.getPrototypeOf() 메서드는 지정된 객체의 프로토타입(가령 내부 [[Prototype]] 속성값)을 반환합니다.

+ +

구문

+ +
Object.getPrototypeOf(obj)
+ +

매개변수

+ +
+
obj
+
자신의 프로토타입이 반환되는 객체.
+
+ +

+ +
var proto = {};
+var obj = Object.create(proto);
+Object.getPrototypeOf(obj) === proto; // true
+
+ +

주의

+ +

ES5에서, obj 매개변수가 객체가 아닌 경우 {{jsxref("TypeError")}} 예외가 발생합니다. ES6에서, 매개변수는 {{jsxref("Object")}}로 강제됩니다.

+ +
Object.getPrototypeOf("foo");
+// TypeError: "foo"는 객체가 아닙니다 (ES5 코드)
+Object.getPrototypeOf("foo");
+// String.prototype                  (ES6 코드)
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}초기 정의.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Opera 전용 주의사항

+ +

이전 Opera 버전이 Object.getPrototypeOf()를 아직 지원하지 않지만, Opera는 Opera 10.50 이후로 비표준 {{jsxref("Object.proto", "__proto__")}} 속성을 지원합니다.

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/ko/web/javascript/reference/global_objects/object/hasownproperty/index.html new file mode 100644 index 0000000000..40a544043c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/hasownproperty/index.html @@ -0,0 +1,146 @@ +--- +title: Object.prototype.hasOwnProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +tags: + - JavaScript + - Method + - Object + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +--- +
{{JSRef}}
+ +

hasOwnProperty() 메소드는 객체가 특정 프로퍼티를 가지고 있는지를  나타내는 불리언 값을 반환한다.

+ +
{{EmbedInteractiveExample("pages/js/object-prototype-hasownproperty.html")}}
+ + + +

구문

+ +
obj.hasOwnProperty(prop)
+ +

매개변수

+ +
+
prop
+
테스트하려는 프로퍼티의 명칭
+
+ +

설명

+ +

모든 객체는 hasOwnProperty 를 상속하는 {{jsxref("Object")}}의 자식이다. 이 메소드는 객체가 특정 프로퍼티를 자기만의 직접적인 프로퍼티로서 소유하고 있는지를 판단하는데 사용된다.  {{jsxref("Operators/in", "in")}} 연산과는 다르게, 이 메소드는 객체의 프로토타입 체인을 확인하지는 않는다.

+ +

예제

+ +

프로퍼티의 존재 여부를 테스트하기 위한 hasOwnProperty의 사용

+ +

다음은 o 객체가 prop라는 명칭을 지닌 프로퍼티를 포함하는지를 판단하는 예제이다.

+ +
o = new Object();
+o.prop = 'exists';
+
+function changeO() {
+  o.newprop = o.prop;
+  delete o.prop;
+}
+
+o.hasOwnProperty('prop');   // returns true
+changeO();
+o.hasOwnProperty('prop');   // returns false
+
+ +

직접 프로퍼티와 상속된 프로퍼티의 비교

+ +

다음은 직접 프로퍼티와 프로토타입 체인에서 상속된 프로퍼티 간의 차이점을 비교하는 예제이다.

+ +
o = new Object();
+o.prop = 'exists';
+o.hasOwnProperty('prop');             // returns true
+o.hasOwnProperty('toString');         // returns false
+o.hasOwnProperty('hasOwnProperty');   // returns false
+
+ +

객체의 프로퍼티들을 순환하기

+ +

The following example shows how to iterate over the properties of an object without executing on inherit properties. Note that the {{jsxref("Statements/for...in", "for...in")}} loop is already only iterating enumerable items, so one should not assume based on the lack of non-enumerable properties shown in the loop that hasOwnProperty itself is confined strictly to enumerable items (as with {{jsxref("Object.getOwnPropertyNames()")}}).

+ +
var buz = {
+  fog: 'stack'
+};
+
+for (var name in buz) {
+  if (buz.hasOwnProperty(name)) {
+    console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]);
+  }
+  else {
+    console.log(name); // toString or something else
+  }
+}
+
+ +

프로퍼티의 명칭으로서 hasOwnProperty 를 사용하기

+ +

자바스크립트는 프로퍼티 명칭으로서 hasOwnProperty를 보호하지 않습니다. 그러므로, 이 명칭을 사용하는 프로퍼티를 가지는 객체가 존재하려면,  올바른 결과들을 얻기 위해서는 외부 hasOwnProperty 를 사용해야합니다.

+ +
var foo = {
+  hasOwnProperty: function() {
+    return false;
+  },
+  bar: 'Here be dragons'
+};
+
+foo.hasOwnProperty('bar'); // always returns false
+
+// Use another Object's hasOwnProperty and call it with 'this' set to foo
+({}).hasOwnProperty.call(foo, 'bar'); // true
+
+// It's also possible to use the hasOwnProperty property from the Object prototype for this purpose
+Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
+
+ +

Note that in the last case there are no newly created objects.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES6')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.hasOwnProperty")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/index.html b/files/ko/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..ce7e6c6603 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,177 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef}}
+ +

Object 생성자는 객체 래퍼(wrapper)를 생성합니다.

+ +

구문

+ +
// 객체 초기자 또는 리터럴
+{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
+
+// 생성자
+new Object([value])
+ +

매개변수

+ +
+
nameValuePair1, nameValuePair2, ... nameValuePairN
+
콜론으로 나뉘어져 있는 키(문자열)와 값(어떤 값이나 가능)의 쌍.
+
value
+
아무 값.
+
+ +

설명

+ +

Object 생성자는 주어진 값의 객체 래퍼를 생성합니다. 주어진 값이 {{jsxref("null")}}이거나 {{jsxref("undefined")}}면 빈 객체를 생성해 반환하고, 그렇지 않으면 값에 맞는 자료형의 객체를 반환합니다. 만약 값이 이미 객체이면 그 값을 그대로 반환합니다.

+ +

생성자가 아닌 맥락에서 호출하면 Object는 new Object()와 동일하게 동작합니다.

+ +

객체 초기자(리터럴 구문)도 참고하세요.

+ +

Object 생성자의 속성

+ +
+
Object.length
+
1의 값을 가집니다.
+
+ +
+
{{jsxref("Object.prototype")}}
+
Object 형의 모든 객체에 속성을 추가할 수 있습니다.
+
+ +

Object 생성자의 메서드

+ +
+
{{jsxref("Object.assign()")}}
+
하나 이상의 원본 객체들로부터 모든 열거가능한 속성들을 대상 객체로 복사합니다.
+
{{jsxref("Object.create()")}}
+
주어진 프로토타입(prototype)의 객체와 속성들을 갖고 있는 새 객체를 생성합니다.
+
{{jsxref("Object.defineProperty()")}}
+
주어진 기술자(descriptor)에 의해 기술된(described) 이름붙은 속성을 객체에 추가합니다.
+
{{jsxref("Object.defineProperties()")}}
+
주어진 기술자들에 맞는 이름붙은 속성들을 객체에 추가합니다.
+
{{jsxref("Object.freeze()")}}
+
객체를 프리징(freeze)합니다. 즉, 다른 곳의 코드에서 객체의 속성을 지우거나 바꿀 수 없습니다.
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
객체의 이름붙은 속성의 기술자를 반환합니다.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
주어진 객체 자신만의 열거가능하거나 열거불가능한 속성들의 이름을 포함하는 배열(array)을 반환합니다.
+
{{jsxref("Object.getOwnPropertySymbols()")}}
+
주어진 객체에서 바로 찾을 수 있는 모든 심볼 속성을 배열로 반환합니다.
+
{{jsxref("Object.getPrototypeOf()")}}
+
명시된 객체의 프로토타입을 반환.
+
{{jsxref("Object.is()")}}
+
두 값이 같은지를 비교합니다. 모든 NaN 값은 같다고 처리됩니다.(다른 추상적 또는 엄격한 등호 비교에서는 다르게 처리됩니다)
+
{{jsxref("Object.isExtensible()")}}
+
객체의 확장이 가능한지 확인합니다.
+
{{jsxref("Object.isFrozen()")}}
+
객체가 프리징 되었는지 확인합니다.
+
{{jsxref("Object.isSealed()")}}
+
객체가 실링(seal) 되었는지 확인합니다.
+
{{jsxref("Object.keys()")}}
+
주어진 객체 자신의 열거가능한 속성들의 이름의 배열을 반환합니다.
+
{{jsxref("Object.preventExtensions()")}}
+
객체가 확장되는 것을 못하도록 합니다.
+
{{jsxref("Object.seal()")}}
+
다른 코드가 객체의 속성을 삭제하지 못하도록 합니다.
+
{{jsxref("Object.setPrototypeOf()")}}
+
프로토타입(즉, 내부의 [[Prototype]] 속성)을 설정합니다.
+
+ +
+
{{jsxref("Object.values()")}}
+
주어진 객체의 열거가능한 모든 스트링 속성들의 값들을 포함하고 있는 배열을 반환합니다.
+
+ +

Object 인스턴스와 Object 프로토타입 객체

+ +

JavaScript에서 모든 객체들은 Object의 자손입니다. 모든 객체는 {{jsxref("Object.prototype")}}으로부터 메서드와 속성을 상속하는데, 나중에 덮어 쓸 수도 있습니다. 예를 들어, 다른 생성자의 프로토타입은 그 constructor 속성을 덮어쓰고 자신의 toString() 메소드들을 제공합니다. Object 프로토타입 객체에 대한 변경 내용은  그 변경 내용에 영향을 받는 속성들과 메소드들이 프로토타입 체인(chain)을 따라 더이상 무시되지 않는한,  모든 객체들로 전달됩니다.

+ +

속성

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', '속성') }}
+ +

메서드

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', '메서드') }}
+ +

예제

+ +

undefinednull을 지정

+ +

다음 예제는 변수 o에 빈 Object 객체를 저장합니다.

+ +
var o = new Object();
+
+ +
var o = new Object(undefined);
+
+ +
var o = new Object(null);
+
+ +

ObjectBoolean 객체 생성하기

+ +

다음 예제는 변수 o에 {{jsxref("Boolean")}} 객체를 저장합니다.

+ +
// o = new Boolean(true)과 같음
+var o = new Object(true);
+
+ +
// o = new Boolean(false)과 같음
+var o = new Object(Boolean());
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}}Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/is/index.html b/files/ko/web/javascript/reference/global_objects/object/is/index.html new file mode 100644 index 0000000000..2ead91a88a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/is/index.html @@ -0,0 +1,124 @@ +--- +title: Object.is() +slug: Web/JavaScript/Reference/Global_Objects/Object/is +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/is +--- +
{{JSRef}}
+ +

Object.is() 메서드는 두 값이 같은 값인지 결정합니다.

+ +

구문

+ +
Object.is(value1, value2);
+ +

매개변수

+ +
+
value1
+
비교할 첫 번째 값.
+
value2
+
비교할 두 번째 값.
+
+ +

반환 값

+ +

두 인수가 같은 값인지 여부를 나타내는 {{jsxref("Boolean")}}.

+ +

설명

+ +

Object.is()는 두 값이 같은 값인지 결정합니다. 다음 중 하나를 만족하면 두 값은 같습니다.

+ + + +

이는 {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} 연산자에 따른 같음과 같지 않습니다. {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} 연산자는 같음을 테스트하기 전에 양 쪽(이 같은 형이 아니라면)에 다양한 강제(coercion)를 적용하지만("" == falsetrue가 되는 그런 행동을 초래), Object.is는 어느 값도 강제하지 않습니다.

+ +

이는 {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}} 연산자에 따른 같음과도 같지 않습니다. {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}} 연산자(와 {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} 연산자 역시)는 숫자값 -0+0을 같게 {{jsxref("Number.NaN")}}은 {{jsxref("NaN")}}과 같지 않게 여깁니다.

+ +

예제

+ +
Object.is('foo', 'foo');     // true
+Object.is(window, window);   // true
+
+Object.is('foo', 'bar');     // false
+Object.is([], []);           // false
+
+var test = { a: 1 };
+Object.is(test, test);       // true
+
+Object.is(null, null);       // true
+
+// 특별한 경우
+Object.is(0, -0);            // false
+Object.is(-0, -0);           // true
+Object.is(NaN, 0/0);         // true
+
+ +

폴리필

+ +
if (!Object.is) {
+  Object.is = function(x, y) {
+   // SameValue 알고리즘
+    if (x === y) { // Steps 1-5, 7-10
+     // Steps 6.b-6.e: +0 != -0
+      return x !== 0 || 1 / x === 1 / y;
+   } else {
+     // Step 6.a: NaN == NaN
+     return x !== x && y !== y;
+   }
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-object.is', 'Object.is')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-object.is', 'Object.is')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.is")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/isextensible/index.html b/files/ko/web/javascript/reference/global_objects/object/isextensible/index.html new file mode 100644 index 0000000000..bfe247c6e8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/isextensible/index.html @@ -0,0 +1,110 @@ +--- +title: Object.isExtensible() +slug: Web/JavaScript/Reference/Global_Objects/Object/isExtensible +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isExtensible +--- +
{{JSRef}}
+ +

Object.isExtensible() 메서드는 객체가 확장 가능한지(객체에 새 속성을 추가할 수 있는지 여부)를 결정합니다.

+ +
{{EmbedInteractiveExample("pages/js/object-isextensible.html")}}
+ + + +

구문

+ +
Object.isExtensible(obj)
+ +

매개변수

+ +
+
obj
+
판별할 객체.
+
+ +

반환 값

+ +

객체의 확장 가능 여부를 나타내는 {{jsxref("Boolean")}}.

+ +

설명

+ +

객체는 기본으로 확장 가능입니다: 새로운 속성이 추가될 수 있고 ({{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} 속성을 지원하는 엔진에서는) 수정될 수 있습니다. 객체는 {{jsxref("Object.preventExtensions()")}}, {{jsxref("Object.seal()")}} 또는 {{jsxref("Object.freeze()")}}를 사용하여 확장 불가로 표시될 수 있습니다.

+ +

예제

+ +
// 새로운 객체는 확장 가능입니다.
+var empty = {};
+Object.isExtensible(empty); // === true
+
+// ...하지만 변경될 수 있습니다.
+Object.preventExtensions(empty);
+Object.isExtensible(empty); // === false
+
+// 봉인된 객체는 정의에 의해 확장 불가입니다.
+var sealed = Object.seal({});
+Object.isExtensible(sealed); // === false
+
+// 동결된 객체 또한 정의에 의해 확장 불가입니다.
+var frozen = Object.freeze({});
+Object.isExtensible(frozen); // === false
+
+ +

주의

+ +

ES5에서, 이 메서드의 인수가 비객체(원시형)인 경우, 그러면 {{jsxref("TypeError")}}가 발생합니다. ES6에서, 비객체 인수는 확장 불가인 보통 객체처럼 다뤄집니다, 그저 false를 반환하는.

+ +
Object.isExtensible(1);
+// TypeError: 1은 객체가 아닙니다 (ES5 코드)
+
+Object.isExtensible(1);
+// false                         (ES6 코드)
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES5.1', '#sec-15.2.3.13', 'Object.isExtensible')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.8.5에서 구현됨.
{{SpecName('ES6', '#sec-object.isextensible', 'Object.isExtensible')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.isextensible', 'Object.isExtensible')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.isExtensible")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/isfrozen/index.html b/files/ko/web/javascript/reference/global_objects/object/isfrozen/index.html new file mode 100644 index 0000000000..0d8999fc4f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/isfrozen/index.html @@ -0,0 +1,155 @@ +--- +title: Object.isFrozen() +slug: Web/JavaScript/Reference/Global_Objects/Object/isFrozen +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isFrozen +--- +
{{JSRef}}
+ +

Object.isFrozen()은 객체가 {{jsxref("Object.freeze()", "동결", "", 1)}}됐는지 판별합니다.

+ +
{{EmbedInteractiveExample("pages/js/object-isfrozen.html")}}
+ + + +

구문

+ +
Object.isFrozen(obj)
+ +

매개변수

+ +
+
obj
+
판별할 객체.
+
+ +

반환 값

+ +

객체의 동결 여부를 나타내는 {{jsxref("Boolean")}}.

+ +

설명

+ +

객체는 {{jsxref("Object.isExtensible()", "확장 불가", "", 1)}}이며 모든 속성이 설정 불가 및 모든 데이터 속성(즉, getter 또는 setter 요소가 있는 접근자 속성이 아닌 속성)이 쓰기 불가인 경우에만 동결됩니다.

+ +

예제

+ +
// 새로운 객체는 확장 가능해서 동결되지 않습니다.
+Object.isFrozen({}); // === false
+
+// 확장 불가인 빈 객체는 빈 채로 동결됩니다.
+var vacuouslyFrozen = Object.preventExtensions({});
+Object.isFrozen(vacuouslyFrozen); // === true
+
+// 속성이 하나 있는 새 객체도 확장 가능하므로 동결되지 않습니다.
+var oneProp = { p: 42 };
+Object.isFrozen(oneProp); // === false
+
+// 객체 확장을 막아도 여전히 동결되지 않습니다,
+// 속성이 여전히 설정 가능(및 쓰기 가능)하기에.
+Object.preventExtensions(oneProp);
+Object.isFrozen(oneProp); // === false
+
+// ...그렇지만 그 속성 삭제는 객체를 빈 채로 동결되게 합니다.
+delete oneProp.p;
+Object.isFrozen(oneProp); // === true
+
+// 쓰기 불가지만 여전히 설정 가능한 속성이 있는 확장 불가 객체는 동결되지 않습니다.
+var nonWritable = { e: 'plep' };
+Object.preventExtensions(nonWritable);
+Object.defineProperty(nonWritable, 'e', { writable: false }); // 쓰기 불가로 함
+Object.isFrozen(nonWritable); // === false
+
+// 그 속성을 설정 불가로 바꾸면 객체를 동결되게 합니다.
+Object.defineProperty(nonWritable, 'e', { configurable: false }); // 설정 불가로 함
+Object.isFrozen(nonWritable); // === true
+
+// 설정 불가지만 여전히 쓰기 가능 속성이 있는 확장 불가 객체도 동결되지 않습니다.
+var nonConfigurable = { release: 'the kraken!' };
+Object.preventExtensions(nonConfigurable);
+Object.defineProperty(nonConfigurable, 'release', { configurable: false });
+Object.isFrozen(nonConfigurable); // === false
+
+// 그 속성을 쓰기 불가로 바꾸면 객체를 동결되게 합니다.
+Object.defineProperty(nonConfigurable, 'release', { writable: false });
+Object.isFrozen(nonConfigurable); // === true
+
+// 설정 가능 접근자 속성이 있는 확장 불가 객체는 동결되지 않습니다.
+var accessor = { get food() { return 'yum'; } };
+Object.preventExtensions(accessor);
+Object.isFrozen(accessor); // === false
+
+// ...하지만 그 속성을 설정 불가로 하면 동결됩니다.
+Object.defineProperty(accessor, 'food', { configurable: false });
+Object.isFrozen(accessor); // === true
+
+// 하지만 동결되는 객체를 위한 가장 쉬운 방법은 객체에 Object.freeze가 호출된 경우입니다.
+var frozen = { 1: 81 };
+Object.isFrozen(frozen); // === false
+Object.freeze(frozen);
+Object.isFrozen(frozen); // === true
+
+// 정의에 의해, 동결된 객체는 확장 불가입니다.
+Object.isExtensible(frozen); // === false
+
+// 또한 정의에 의해, 동결된 객체는 봉인됩니다.
+Object.isSealed(frozen); // === true
+
+ +

주의

+ +

ES5에서, 이 메서드의 인수가 비객체(원시형)인 경우, 그러면 {{jsxref("TypeError")}}가 발생합니다. ES6에서, 비객체 인수는 마치 동결된 보통 객체였던 것처럼 취급됩니다, 그저 true를 반환하는.

+ +
Object.isFrozen(1);
+// TypeError: 1은 객체가 아닙니다 (ES5 코드)
+
+Object.isFrozen(1);
+// true                          (ES6 코드)
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES5.1', '#sec-15.2.3.12', 'Object.isFrozen')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.8.5에서 구현됨.
{{SpecName('ES6', '#sec-object.isfrozen', 'Object.isFrozen')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.isfrozen', 'Object.isFrozen')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.isFrozen")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/isprototypeof/index.html b/files/ko/web/javascript/reference/global_objects/object/isprototypeof/index.html new file mode 100644 index 0000000000..0e9de96b41 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/isprototypeof/index.html @@ -0,0 +1,111 @@ +--- +title: Object.prototype.isPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf +tags: + - JavaScript + - Method + - Object + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf +--- +
{{JSRef}}
+ +

isPrototypeOf() 메소드는 해당 객체가 다른 객체의 프로토타입 체인에 속한 객체인지 확인하기 위해 사용됩니다.

+ +
+

Note: isPrototypeOf 는 {{jsxref("Operators/instanceof", "instanceof")}} 연산자와 다릅니다. "object instanceof AFunction"표현식에서는 object의 프로토타입 체인을 AFunction 자체가 아니라 AFunction.prototype에 대해 확인을 합니다.

+
+ +

구문

+ +
prototypeObj.isPrototypeOf(obj)
+ +

매개변수

+ +
+
object
+
프로토타입 체인을 가지고 있는 객체가 검색될 것 입니다.
+
+ +

설명

+ +

isPrototypeOf 메소드는 또 다른 객체의 프로토타입 체인에 해당 객체가 존재하는지 여부를 확인할수 있습니다.

+ +

예를들어, 다음의 프로토타입체인을 고려해봅시다.

+ +
function Fee() {
+  // ...
+}
+
+function Fi() {
+  // ...
+}
+Fi.prototype = new Fee();
+
+function Fo() {
+  // ...
+}
+Fo.prototype = new Fi();
+
+function Fum() {
+  // ...
+}
+Fum.prototype = new Fo();
+
+ +

실행되고 나면 Fum 인스턴스의 프로토타입체인이 Fi의 프로토타입과 연결되어있는지를 확인할 필요가 있습니다. 다음과 같은 방법으로 확인할 수 있습니다:

+ +
var fum = new Fum();
+// ...
+
+if (Fi.prototype.isPrototypeOf(fum)) {
+  // do something safe
+}
+
+ +

이 메소드는 {{jsxref("Operators/instanceof", "instanceof")}} 연산자와 함께 특정 프로토타입으로부터 상속된 객체만 작동하게 하려는(예를 들어 특정 메소드나 속성이 객체에 있다는걸 보장하려는 때) 코드에서 특히 쓸모가 많다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 3rd Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES6')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.isPrototypeOf")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/issealed/index.html b/files/ko/web/javascript/reference/global_objects/object/issealed/index.html new file mode 100644 index 0000000000..38fc953828 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/issealed/index.html @@ -0,0 +1,128 @@ +--- +title: Object.isSealed() +slug: Web/JavaScript/Reference/Global_Objects/Object/isSealed +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isSealed +--- +
{{JSRef}}
+ +

Object.isSealed() 메서드는 객체가 봉인됐는지 판별합니다.

+ +
{{EmbedInteractiveExample("pages/js/object-issealed.html")}}
+ + + +

구문

+ +
Object.isSealed(obj)
+ +

매개변수

+ +
+
obj
+
판별할 객체.
+
+ +

반환 값

+ +

객체의 봉인 여부를 나타내는 {{jsxref("Boolean")}}.

+ +

설명

+ +

객체가 봉인된 경우 true를 반환하고, 그렇지 않으면 false. 객체는 {{jsxref("Object.isExtensible", "확장 불가", "", 1)}}이고 모든 속성이 설정 불가이며 따라서 삭제할 수 없(지만 반드시 쓰기 불가일 필요는 없)는 경우 봉인됩니다.

+ +

예제

+ +
// 객체는 기본으로 봉인되지 않습니다.
+var empty = {};
+Object.isSealed(empty); // === false
+
+// 빈 객체를 확장 불가하게 한 경우, 빈 채로 봉인됩니다.
+Object.preventExtensions(empty);
+Object.isSealed(empty); // === true
+
+// 비어 있지 않은 객체는 다릅니다, 그 속성이 모두 설정 불가가 아닌 한.
+var hasProp = { fee: 'fie foe fum' };
+Object.preventExtensions(hasProp);
+Object.isSealed(hasProp); // === false
+
+// 그러나 모두 설정 불가하게 하면 객체는 봉인됩니다.
+Object.defineProperty(hasProp, 'fee', { configurable: false });
+Object.isSealed(hasProp); // === true
+
+// 객체를 봉인하는 가장 쉬운 방법은 물론 Object.seal 입니다.
+var sealed = {};
+Object.seal(sealed);
+Object.isSealed(sealed); // === true
+
+// 봉인된 객체는 정의에 의해 확장 불가입니다.
+Object.isExtensible(sealed); // === false
+
+// 봉인된 객체는 동결될 수 있지만 꼭 그럴 필요는 없습니다.
+Object.isFrozen(sealed); // === true (모든 속성도 쓰기 불가)
+
+var s2 = Object.seal({ p: 3 });
+Object.isFrozen(s2); // === false ('p'는 여전히 쓰기 가능)
+
+var s3 = Object.seal({ get p() { return 0; } });
+Object.isFrozen(s3); // === true (설정 가능성만이 접근자 속성에게 중요함)
+
+ +

주의

+ +

ES5에서, 이 메서드의 인수가 비객체(원시형)인 경우, 그러면 {{jsxref("TypeError")}}가 발생합니다. ES6에서, 비객체 인수는 마치 봉인된 보통 객체였던 것처럼 취급됩니다, 그저 true를 반환하는.

+ +
Object.isSealed(1);
+// TypeError: 1은 객체가 아닙니다 (ES5 코드)
+
+Object.isSealed(1);
+// true                          (ES6 코드)
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES5.1', '#sec-15.2.3.11', 'Object.isSealed')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.8.5에서 구현됨.
{{SpecName('ES6', '#sec-object.issealed', 'Object.isSealed')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.issealed', 'Object.isSealed')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.isSealed")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/observe/index.html b/files/ko/web/javascript/reference/global_objects/object/observe/index.html new file mode 100644 index 0000000000..bf3b004d8c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/observe/index.html @@ -0,0 +1,193 @@ +--- +title: Object.observe() +slug: Web/JavaScript/Reference/Global_Objects/Object/observe +tags: + - 감시 객체 +translation_of: Archive/Web/JavaScript/Object.observe +--- +
{{JSRef}}
+ +

Object.observe() 메소드는 객체의 변화를 비동기로 감시하는데에 사용된다. 이 메소드는 변화들이 발생한 순서대로 그 흐름을 제공한다.

+ +

문법

+ +
Object.observe(obj, callback[, acceptList])
+ +

파라미터

+ +
+
obj
+
감시될 객체입니다.
+
callback
+
obj의 변경이 일어났을 때마다 호출될 함수입니다. 다음과 같은 인자를 갖습니다. +
+
changes
+
변경 사항을 나타내는 객체의 배열입니다. 그 객체의 프로퍼티는 다음과 같습니다. +
    +
  • name: 변경된 프로퍼티의 이름입니다.
  • +
  • object: 변경이 일어난 뒤의 객체입니다.
  • +
  • type: 변경의 종류를 의미하는 string입니다. "add", "update", "delete" 중 하나입니다.
  • +
  • oldValue: 변경되기 이전의 값입니다. "update"와 "delete" 타입에만 존재합니다.
  • +
+
+
+
+
acceptList
+
감시할 변경의 종류를 의미하는 리스트입니다.  주어지지 않은 경우, 배열 ["add", "update", "delete", "reconfigure", "setPrototype", "preventExtensions"] 이 이용될 것입니다.
+
+ +

설명

+ +

callbackobj에 변경이 있을 때마다 실행되며, 모든 변경 사항이 일어난 순서대로 담긴 배열이 전달됩니다.

+ +

예제

+ +

Logging all six different types

+ +
var obj = {
+  foo: 0,
+  bar: 1
+};
+
+Object.observe(obj, function(changes) {
+  console.log(changes);
+});
+
+obj.baz = 2;
+// [{name: 'baz', object: <obj>, type: 'add'}]
+
+obj.foo = 'hello';
+// [{name: 'foo', object: <obj>, type: 'update', oldValue: 0}]
+
+delete obj.baz;
+// [{name: 'baz', object: <obj>, type: 'delete', oldValue: 2}]
+
+Object.defineProperty(obj, 'foo', {writable: false});
+// [{name: 'foo', object: <obj>, type: 'reconfigure'}]
+
+Object.setPrototypeOf(obj, {});
+// [{name: '__proto__', object: <obj>, type: 'setPrototype', oldValue: <prototype>}]
+
+Object.seal(obj);
+// [
+//   {name: 'foo', object: <obj>, type: 'reconfigure'},
+//   {name: 'bar', object: <obj>, type: 'reconfigure'},
+//   {object: <obj>, type: 'preventExtensions'}
+// ]
+
+ +

데이터 바인딩

+ +
// A user model
+var user = {
+  id: 0,
+  name: 'Brendan Eich',
+  title: 'Mr.'
+};
+
+// Create a greeting for the user
+function updateGreeting() {
+  user.greeting = 'Hello, ' + user.title + ' ' + user.name + '!';
+}
+updateGreeting();
+
+Object.observe(user, function(changes) {
+  changes.forEach(function(change) {
+    // Any time name or title change, update the greeting
+    if (change.name === 'name' || change.name === 'title') {
+      updateGreeting();
+    }
+  });
+});
+
+ +

Custom change type

+ +
// A point on a 2D plane
+var point = {x: 0, y: 0, distance: 0};
+
+function setPosition(pt, x, y) {
+  // Performing a custom change
+  Object.getNotifier(pt).performChange('reposition', function() {
+    var oldDistance = pt.distance;
+    pt.x = x;
+    pt.y = y;
+    pt.distance = Math.sqrt(x * x + y * y);
+    return {oldDistance: oldDistance};
+  });
+}
+
+Object.observe(point, function(changes) {
+  console.log('Distance change: ' + (point.distance - changes[0].oldDistance));
+}, ['reposition']);
+
+setPosition(point, 3, 4);
+// Distance change: 5
+
+ +

Specifications

+ +

Strawman proposal for ECMAScript 7.

+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("36")}}{{CompatNo}} [1]{{CompatNo}} [2]{{CompatOpera("23")}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("36")}}{{CompatNo}} [1]{{CompatNo}} [2]{{CompatOpera("23")}}{{CompatNo}}
+
+ +

[1]: See {{bug(800355)}}

+ +

[2]: See relevant MS Edge platform status entry

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/preventextensions/index.html b/files/ko/web/javascript/reference/global_objects/object/preventextensions/index.html new file mode 100644 index 0000000000..b23c6f33e6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/preventextensions/index.html @@ -0,0 +1,126 @@ +--- +title: Object.preventExtensions() +slug: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +tags: + - ECMAScript 5 + - JavaScript + - Method + - Object + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +--- +
{{JSRef}}
+ +

Object.preventExtensions() 메서드는 새로운 속성이 이제까지 객체에 추가되는 것을 방지합니다 (즉 객체의 장래 확장을 막습니다).

+ +
{{EmbedInteractiveExample("pages/js/object-preventextensions.html")}}
+ + + +

구문

+ +
Object.preventExtensions(obj)
+ +

매개변수

+ +
+
obj
+
확장 불가로 해야 할 객체.
+
+ +

설명

+ +

객체는 새로운 속성이 추가될 수 있는 경우 확장 가능입니다. Object.preventExtensions()는 객체를 이제 확장 불가로 표시하므로 표시된 그 시점에 있던 것 이외의 속성을 갖지 않습니다. 보통 확장 불가인 객체의 속성은 여전히 삭제될 수 있음을 주의하세요. 확장 불가인 객체에 새로운 속성을 추가하려는 시도는 실패합니다, 조용히든 {{jsxref("TypeError")}}가 발생해서든 (가장 흔하나 오로지 {{jsxref("Functions_and_function_scope/Strict_mode", "엄격 모드", "", 1)}}인 경우에서만은 아님).

+ +

Object.preventExtensions()는 자신의 속성 추가만을 방지합니다. 속성은 여전히 객체의 프로토타입에 추가될 수 있습니다. 그러나, 객체에 Object.preventExtensions()를 호출하면 그 {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} 속성의 확장 또한 막습니다.

+ +

ECMAScript 5에서 확장 가능 객체를 확장 불가로 바꾸는 법이 있더라도, 반대로 하는 법은 없습니다.

+ +

예제

+ +
// Object.preventExtensions는 확장 불가된 객체를 반환합니다.
+var obj = {};
+var obj2 = Object.preventExtensions(obj);
+obj === obj2; // true
+
+// 객체는 기본으로 확장 가능입니다.
+var empty = {};
+Object.isExtensible(empty); // === true
+
+// ...하지만 바뀔 수 있습니다.
+Object.preventExtensions(empty);
+Object.isExtensible(empty); // === false
+
+// Object.defineProperty는 확장 불가 객체에 새 속성을 추가할 때 오류가 발생합니다.
+var nonExtensible = { removable: true };
+Object.preventExtensions(nonExtensible);
+Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // TypeError 발생
+
+// 엄격 모드에서, 확장 불가 객체에 새 속성을 추가하려는 시도는 TypeError가 발생합니다.
+function fail() {
+  'use strict';
+  nonExtensible.newProperty = 'FAIL'; // TypeError 발생
+}
+fail();
+
+// 확장 (__proto__(는 사라집니다. 대신 Object.getPrototypeOf를 쓰세요)를
+// 지원하는 엔진에서만 동작합니다):
+// 확장 불가 객체의 프로토타입은 불변합니다.
+var fixed = Object.preventExtensions({});
+fixed.__proto__ = { oh: 'hai' }; // TypeError 발생
+
+ +

참고

+ +

ES5에서, 이 메서드의 인수가 비객체(원시형)인 경우, 그러면 {{jsxref("TypeError")}}가 발생합니다. ES6에서, 비객체 인수는 마치 확장 불가인 보통 객체였던 것처럼 취급됩니다, 그저 자신을 반환하는.

+ +
Object.preventExtensions(1);
+// TypeError: 1은 객체가 아닙니다 (ES5 코드)
+
+Object.preventExtensions(1);
+// 1                            (ES6 코드)
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES5.1', '#sec-15.2.3.10', 'Object.preventExtensions')}}{{Spec2('ES5.1')}}초기 정의. JavaScript 1.8.5에서 구현됨.
{{SpecName('ES6', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.preventExtensions")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/propertyisenumerable/index.html b/files/ko/web/javascript/reference/global_objects/object/propertyisenumerable/index.html new file mode 100644 index 0000000000..fde6780ffd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/propertyisenumerable/index.html @@ -0,0 +1,146 @@ +--- +title: Object.prototype.propertyIsEnumerable() +slug: Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable +tags: + - JavaScript + - Method + - Object + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable +--- +
{{JSRef}}
+ +

propertyIsEnumerable() 메서드는 특정 속성이 열거가능한지 여부를 나타내는 불리언 값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/object-prototype-propertyisenumerable.html")}}
+ + + +

구문

+ +
obj.propertyIsEnumerable(prop)
+ +

매개변수

+ +
+
prop
+
테스트 할 속성의 이름.
+
+ +

반환 값

+ +

특정 속성이 열거가능한지 여부를 나타내는 {{jsxref("Boolean")}}.

+ +

설명

+ +

모든 객체는 propertyIsEnumerable 메소드를 가지고 있습니다. 이 메소드는 프로토타입 체인을 통해 상속된 특성을 제외하고 개체에 지정된 속성을 {{jsxref("Statements/for...in", "for...in")}} 루프로 열거할 수 있는지 여부를 확인할 수 있습니다. 개체에 지정된 속성이 없으면 이 메소드는 false를 반환합니다.

+ +

예제

+ +

A basic use of propertyIsEnumerable

+ +

The following example shows the use of propertyIsEnumerable on objects and arrays:

+ +
var o = {};
+var a = [];
+o.prop = 'is enumerable';
+a[0] = 'is enumerable';
+
+o.propertyIsEnumerable('prop');   // returns true
+a.propertyIsEnumerable(0);        // returns true
+
+ +

User-defined versus built-in objects

+ +

The following example demonstrates the enumerability of user-defined versus built-in properties:

+ +
var a = ['is enumerable'];
+
+a.propertyIsEnumerable(0);          // returns true
+a.propertyIsEnumerable('length');   // returns false
+
+Math.propertyIsEnumerable('random');   // returns false
+this.propertyIsEnumerable('Math');     // returns false
+
+ +

Direct versus inherited properties

+ +
var a = [];
+a.propertyIsEnumerable('constructor');         // returns false
+
+function firstConstructor() {
+  this.property = 'is not enumerable';
+}
+
+firstConstructor.prototype.firstMethod = function() {};
+
+function secondConstructor() {
+  this.method = function method() { return 'is enumerable'; };
+}
+
+secondConstructor.prototype = new firstConstructor;
+secondConstructor.prototype.constructor = secondConstructor;
+
+var o = new secondConstructor();
+o.arbitraryProperty = 'is enumerable';
+
+o.propertyIsEnumerable('arbitraryProperty');   // returns true
+o.propertyIsEnumerable('method');              // returns true
+o.propertyIsEnumerable('property');            // returns false
+
+o.property = 'is enumerable';
+
+o.propertyIsEnumerable('property');            // returns true
+
+// These return false as they are on the prototype which
+// propertyIsEnumerable does not consider (even though the last two
+// are iteratable with for-in)
+o.propertyIsEnumerable('prototype');   // returns false (as of JS 1.8.1/FF3.6)
+o.propertyIsEnumerable('constructor'); // returns false
+o.propertyIsEnumerable('firstMethod'); // returns false
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition
{{SpecName('ES5.1', '#sec-15.2.4.7', 'Object.prototype.propertyIsEnumerable')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-object.prototype.propertyisenumerable', 'Object.prototype.propertyIsEnumerable')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-object.prototype.propertyisenumerable', 'Object.prototype.propertyIsEnumerable')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Object.propertyIsEnumerable")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/prototype/index.html b/files/ko/web/javascript/reference/global_objects/object/prototype/index.html new file mode 100644 index 0000000000..4fdc17bc49 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/prototype/index.html @@ -0,0 +1,218 @@ +--- +title: Object.prototype +slug: Web/JavaScript/Reference/Global_Objects/Object/prototype +tags: + - JavaScript + - Object + - Property + - Reference + - 프로토타입 +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef}}
+ +

Object.prototype 속성은 {{jsxref("Object")}} 프로토타입(원형) 객체를
+ 나타냅니다.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

JavaScript에서 거의 모든 객체는 {{jsxref("Object")}}의 인스턴스입니다. 일반적인 객체는 Object.prototype 에서 속성과 메서드를 상속받으며, 그 중 일부는 (오버라이드 등으로 인해) 숨겨질 수 있습니다. 그러나, 의도적으로 Object를 생성할 때 ({{jsxref("Object.create", "Object.create(null)")}} 처럼) 이를 피할 수도 있고, {{jsxref("Object.setPrototypeOf")}} 등을 통해 나중에 무효화할 수도 있습니다.

+ +

Object 프로토타입에 가하는 변경은 프로토타입 체인을 통해, 더 아래쪽 체인에서 덮어 쓴 경우가 아니라면 모든 객체에서 관측할 수 있습니다. 이는 객체를 확장하거나 행동을 바꿀 수 있는 매우 강력하면서도 위험한 방법을 제공합니다.

+ + + +

속성

+ +
+
{{jsxref("Object.prototype.constructor")}}
+
객체의 프로토타입을 생성하는 함수를 지정합니다.
+
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
+
객체가 초기화될 때 프로토타입으로 사용된 객체를 가리킵니다.
+
{{jsxref("Object.prototype.__noSuchMethod__")}} {{obsolete_inline}}
+
정의되지 않은 객체 멤버가 메소드로서 호출될 때 실행되는 함수를 정의하는 데 쓰였지만 제거되었습니다.
+
{{jsxref("Object.prototype.count","Object.prototype.__count__")}} {{obsolete_inline}}
+
사용자 정의 객체 상에 직접 있는 열거가능 속성의 수를 반환하는 데 쓰였지만 제거되었습니다.
+
{{jsxref("Object.prototype.parent","Object.prototype.__parent__")}} {{obsolete_inline}}
+
객체 문맥을 가리키는 데 쓰였지만 제거되었습니다.
+
+ +

메서드

+ +
+
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
함수를 속성에 연결합니다, 접근했을 때 그 함수를 실행해 그 결과값을 반환하는.
+
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
함수를 속성에 연결합니다, 설정했을 때 그 속성을 수정하는 함수를 실행하는.
+
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
{{jsxref("Object.prototype.__defineGetter__()", "__defineGetter__()")}} 메소드에 의해 지정된 속성과 관련된 함수를 반환합니다.
+
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
{{jsxref("Object.prototype.__defineSetter__()", "__defineSetter__()")}} 메소드에 의해 지정된 속성과 관련된 함수를 반환합니다.
+
{{jsxref("Object.prototype.hasOwnProperty()")}}
+
객체가 지정된 속성을 프로토타입 체인을 통해 상속되지 않은 그 객체의 직접 속성으로 포함하는지를 나타내는 boolean을 반환합니다.
+
{{jsxref("Object.prototype.isPrototypeOf()")}}
+
지정된 객체가 이 메소드가 호출된 객체의 프로토타입 체인 내에 있는지를 나타내는 boolean을 반환합니다.
+
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
+
내부 ECMAScript [[Enumerable]] attribute가 설정된 경우를 나타내는 boolean을 반환합니다.
+
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
+
이 메소드가 호출된 객체를 나타내는 객체 리터럴의 출처를 포함하는 문자열을 반환합니다; 새로운 객체를 만들기 위해 이 값을 쓸 수 있습니다.
+
{{jsxref("Object.prototype.toLocaleString()")}}
+
{{jsxref("Object.toString", "toString()")}}을 호출합니다.
+
{{jsxref("Object.prototype.toString()")}}
+
객체의 문자열 표현을 반환합니다.
+
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
+
객체 속성에서 감시점을 제거합니다.
+
{{jsxref("Object.prototype.valueOf()")}}
+
지정된 객체의 원시값을 반환합니다.
+
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
+
객체 속성에 감시점을 추가합니다.
+
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
+
지정된 객체의 문맥에서 JavaScript 코드 문자열을 평가하는 데 쓰였지만 제거되었습니다.
+
+ +

예제

+ +

Object.prototype의 기본 메서드를 변경할 때, 기존 조직의 앞 또는 후에 확장(extension) 을 포장하여 코드를 주입시키는 것을 고려하자. 예를 들어서, 이 (시험받지
+ 않은) 코드는 내장된 로직 또는 어떤 다른 확장이 실행되기 전에 커스텀 로직을 전제조건적으로 실행시킬 것이다.

+ +

함수가 호출되었을 때, 불러온 매개변수들은 배열과 같은 형태로 '변수' arguments에 보관된다. 예를 들어 myFn(a, b, c) 라는 함수를 부를 때, 이 함수 내부에 배열형태로 매개변수 (a, b, c) 를 담게 된다. prototype을 훅을 이용해 수정할 때, 함수에서 apply()를 호출하여 단순하게 this와 arguments(호출 상태)에 현재 동작을 전달하면 된다. 이 패턴은 Node.prototype, Function.prototype등 prototype에도 사용할 수 있다.

+ +
var current = Object.prototype.valueOf;
+
+// 현재 설정한 "-prop-value" 속성은 cross-cutting 이고 
+// 항상 같은 prototype chain이 아니기 때문에, 이 Object.prototype을 바꾸고 싶다.
+Object.prototype.valueOf = function() {
+  if (this.hasOwnProperty('-prop-value')) {
+    return this['-prop-value'];
+  } else {
+    // 이 객체 내 속성(property)이 하나가 아니라면, 현재 동작을 재구성한 것으로부터
+    // 기본 동작으로 되돌리자(복구). 
+    // apply 동작은 다른 언어에서의 "super"와 유사하다.
+    // 비록 valueOf()가 매개변수를 받지못하더라도, 다른 훅에서 있을 것이다.
+    return current.apply(this, arguments);
+  }
+}
+
+ +

JavaScript는 엄밀히 말해서 하위클래스(sub-class) 객체가 없기에, prototype은 객체 역할을 하는 특정 함수의 "기반 클래스" 객체를 만드는 유용한 차선책입니다. 예를 들어:

+ +
var Person = function() {
+  this.canTalk = true;
+};
+
+Person.prototype.greet = function() {
+  if (this.canTalk) {
+    console.log('Hi, I am ' + this.name);
+  }
+};
+
+var Employee = function(name, title) {
+  Person.call(this);
+  this.name = name;
+  this.title = title;
+};
+
+Employee.prototype = Object.create(Person.prototype);
+Employee.prototype.constructor = Employee;
+
+Employee.prototype.greet = function() {
+  if (this.canTalk) {
+    console.log('Hi, I am ' + this.name + ', the ' + this.title);
+  }
+};
+
+var Customer = function(name) {
+  Person.call(this);
+  this.name = name;
+};
+
+Customer.prototype = Object.create(Person.prototype);
+Customer.prototype.constructor = Customer;
+
+var Mime = function(name) {
+  Person.call(this);
+  this.name = name;
+  this.canTalk = false;
+};
+
+Mime.prototype = Object.create(Person.prototype);
+Mime.prototype.constructor = Mime;
+
+var bob = new Employee('Bob', 'Builder');
+var joe = new Customer('Joe');
+var rg = new Employee('Red Green', 'Handyman');
+var mike = new Customer('Mike');
+var mime = new Mime('Mime');
+
+bob.greet();
+// Hi, I am Bob, the Builder
+
+joe.greet();
+// Hi, I am Joe
+
+rg.greet();
+// Hi, I am Red Green, the Handyman
+
+mike.greet();
+// Hi, I am Mike
+
+mime.greet();
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.0에서 구현됨.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Object.prototype")}}

+ +

참조

+ + + +
+
<dicword style="user-select: text;">Even though valueOf() doesn't take arguments, some other hook may.</dicword><dicword style="user-select: text;"><dicimg id="play" style="background-image: url(chrome-extension://bmbdcffdhebhecemcchbkfnjlmdiiepe/play.gif);"></dicimg> Eng<dicimg id="copy" style="background-image: url(chrome-extension://bmbdcffdhebhecemcchbkfnjlmdiiepe/copy.png);" title="copy"></dicimg></dicword>
+
+
+
+valueOf ()가 인수를받지 않더라도 다른 후크가있을 수 있습니다.
+ +
+
+ + + +
diff --git a/files/ko/web/javascript/reference/global_objects/object/seal/index.html b/files/ko/web/javascript/reference/global_objects/object/seal/index.html new file mode 100644 index 0000000000..c97f71c26d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/seal/index.html @@ -0,0 +1,135 @@ +--- +title: Object.seal() +slug: Web/JavaScript/Reference/Global_Objects/Object/seal +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Object + - Reference + - 봉인 +translation_of: Web/JavaScript/Reference/Global_Objects/Object/seal +--- +
{{JSRef}}
+ +

Object.seal() 메서드는 객체를 밀봉합니다. 객체를 밀봉하면 그 객체에는 새로운 속성을 추가할 수 없고, 현재 존재하는 모든 속성을 설정 불가능 상태로 만들어줍니다. 하지만 쓰기 가능한 속성의 값은 밀봉 후에도 변경할 수 있습니다(역자 주 : 바로 이 점이 Object.freeze()와의 차이라고 할 수 있습니다).

+ +
{{EmbedInteractiveExample("pages/js/object-prototype-seal.html")}}
+ + + +

구문

+ +
Object.seal(obj)
+ +

매개변수

+ +
+
obj
+
봉인할 객체.
+
+ +

반환 값

+ +

봉인한 객체.

+ +

설명

+ +

객체는 기본적으로 확장이 가능({{jsxref("Object.isExtensible()", "extensible", "", 1)}})합니다. 즉, 새로운 속성을 추가할 수 있습니다. 하지만 객체를 밀봉하면 그 객체에 새로운 속성을 추가할 수 없게되고, 그 객체 내에 존재하는 모든 속성이 설정 불가능(non-configurable)해 집니다. 객체를 밀봉하면 객체의 속성을 고정된 불변의 상태로 만듭니다. 모든 속성을 설정 불가능한 상태로 만드는 것은 데이터 속성(data properties)을 접근자 속성(accessor properties)으로, 또는 접근자 속성을 데이터 속성으로 변경할 수 없게 만듭니다. 하지만 객체를 완전히 얼려서 데이터 속성의 값도 변경할 수 없게 만드는 Object.freeze()와 달리, Object.seal()은 객체를 밀봉한 후에도 그 객체의 데이터 속성의 값은 여전히 변경할 수 있게 해줍니다. 다만, 밀봉한 후에는 객체를 얼리는 것과 마찬가지로 속성의 추가/삭제나 데이터 속성과 접근자 속성 사이의 전환은 암묵적이든, 아니면 {{jsxref("Strict_mode", "strict mode", "", 1)}} 에서와 같이 명시적으로 {{jsxref("Global_Objects/TypeError", "TypeError")}} 예외를 발생시키든 모두 실패로 끝납니다.

+ +

프로토타입 체인은 밀봉 전이나 후나 달라지지 않습니다. 하지만 {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} 속성은 함께 밀봉됩니다.

+ +

예제

+ +
var obj = {
+  prop: function() {},
+  foo: 'bar'
+};
+
+// 새 속성이 추가되고, 기존 속성은 변경되거나 제거될 수 있음
+obj.foo = 'baz';
+obj.lumpy = 'woof';
+delete obj.prop;
+
+var o = Object.seal(obj);
+
+assert(o === obj);
+assert(Object.isSealed(obj) === true);
+
+// 밀봉한 객체의 속성값은 밀봉 전과 마찬가지로 변경할 수 있음
+obj.foo = 'quux';
+obj.foo // 'quux' 가 출력됨
+
+// 데이터 속성과 접근자 속성 사이의 전환은 불가
+Object.defineProperty(obj, 'foo', { get: function() { return 'g'; } }); // TypeError 발생
+
+// 속성값의 변경을 제외한 어떤 변경도 적용되지 않음
+obj.quaxxor = 'the friendly duck'; // 에러가 나지는 않지만 속성은 추가되지 않음
+delete obj.foo; // 에러가 나지는 않지만 속성이 삭제되지 않음
+
+// strict mode 에서는 속성값의 변경을 제외한 모든 변경은 TypeError 발생
+function fail() {
+  'use strict';
+  delete obj.foo; // TypeError 발생
+  obj.sparky = 'arf'; // TypeEror 발생
+}
+fail();
+
+// Object.defineProperty() 메서드를 이용한 속성의 추가도 TypeError 발생
+Object.defineProperty(obj, 'ohai', { value: 17 }); // TypeErorr 발생
+Object.defineProperty(obj, 'foo', { value: 'eit' }); // 속성값의 변경은 가능함
+
+ +

참고

+ +

ES5에서는 Object.seal() 메서드의 인자가 객체가 아닐 때(즉, 원시형일 때)는 {{jsxref("Global_Objects/TypeError", "TypeError")}}가 발생합니다. ES6에서는 원시형 인자도 밀봉된 객체라고 취급해서 {{jsxref("Global_Objects/TypeError", "TypeError")}}를 발생시키지 않고 원시형 인자를 그대로 반환합니다.

+ +
> Object.seal(1)
+TypeError: 1 is not an object // ES5 code
+
+> Object.seal(1)
+1                             // ES6 code
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.8', 'Object.seal')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.seal', 'Object.seal')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.seal', 'Object.seal')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.seal")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/setprototypeof/index.html b/files/ko/web/javascript/reference/global_objects/object/setprototypeof/index.html new file mode 100644 index 0000000000..332f857361 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/setprototypeof/index.html @@ -0,0 +1,242 @@ +--- +title: Object.setPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf +translation_of: Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf +--- +

{{JSRef}}

+ +

Object.setPrototypeOf() 메소드는  지정된 객체의 프로토타입 (즉, 내부 [[Prototype]] 프로퍼티)을 다른 객체 또는 {{jsxref("null")}} 로 설정합니다.

+ +
+

Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, a very slow operation, in every browser and JavaScript engine. The effects on performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered. If you care about performance you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using {{jsxref("Object.create()")}}.

+
+ +

Syntax

+ +
Object.setPrototypeOf(obj, prototype);
+ +

Parameters

+ +
+
obj
+
프로토타입을 설정을 가지는 객체
+
prototype
+
객체의 새로운 프로토 타입  (객체 or {{jsxref("null")}}).
+
+ +

Return value

+ +

지정된 객체 

+ +

Description

+ +

만일 프로토타입이 변경될 객체가 {{jsxref("Object.isExtensible()")}} 에 의해서 non-extensible 하다면,  {{jsxref("TypeError")}} 예외처리를 해라. 만일 프로토타입 파라미터가 객체가 아니거나 {{jsxref("null")}} (i.e., number, string, boolean,  {{jsxref("undefined")}}) 인 경우가 아니라면 어떠한 작업도 하지마라. 이 방법을 통해서 객제의 프로토타입이 새로운 값으로 변경될 것이다.

+ +

Object.setPrototypeOf는 ECMAScript 2015 스펙으로 규정되어 있다. 해당 메소드는 일반적으로 객체의 프로토타입과 논쟁이 되는 {{jsxref("Object.prototype.__proto__")}} 프로퍼티를 설정하는 적절한 방법으로 고려된다. 

+ +

Examples

+ +
var dict = Object.setPrototypeOf({}, null);
+
+ +

Polyfill

+ +

예전 버전의 프로퍼티 {{jsxref("Object.prototype.__proto__")}} 를 사용한다면, 우리는 쉽게 Object.setPrototypeOf 가 쉽게 정의 할수 있다.

+ +
// Only works in Chrome and FireFox, does not work in IE:
+Object.setPrototypeOf = Object.setPrototypeOf || function(obj, proto) {
+  obj.__proto__ = proto;
+  return obj;
+}
+
+ +

Appending Prototype Chains

+ +

Object.getPrototypeOf() and {{jsxref("Object.proto", "Object.prototype.__proto__")}} 의 결합은 새로운 프로토타입 오브젝트에 전반적인 프로토타입 Chain을 설정하도록 할수 있다.

+ +
/**
+*** Object.appendChain(@object, @prototype)
+*
+* Appends the first non-native prototype of a chain to a new prototype.
+* Returns @object (if it was a primitive value it will transformed into an object).
+*
+*** Object.appendChain(@object [, "@arg_name_1", "@arg_name_2", "@arg_name_3", "..."], "@function_body")
+*** Object.appendChain(@object [, "@arg_name_1, @arg_name_2, @arg_name_3, ..."], "@function_body")
+*
+* Appends the first non-native prototype of a chain to the native Function.prototype object, then appends a
+* new Function(["@arg"(s)], "@function_body") to that chain.
+* Returns the function.
+*
+**/
+
+Object.appendChain = function(oChain, oProto) {
+  if (arguments.length < 2) {
+    throw new TypeError('Object.appendChain - Not enough arguments');
+  }
+  if (typeof oProto !== 'object' && typeof oProto !== 'string') {
+    throw new TypeError('second argument to Object.appendChain must be an object or a string');
+  }
+
+  var oNewProto = oProto,
+      oReturn = o2nd = oLast = oChain instanceof this ? oChain : new oChain.constructor(oChain);
+
+  for (var o1st = this.getPrototypeOf(o2nd);
+    o1st !== Object.prototype && o1st !== Function.prototype;
+    o1st = this.getPrototypeOf(o2nd)
+  ) {
+    o2nd = o1st;
+  }
+
+  if (oProto.constructor === String) {
+    oNewProto = Function.prototype;
+    oReturn = Function.apply(null, Array.prototype.slice.call(arguments, 1));
+    this.setPrototypeOf(oReturn, oLast);
+  }
+
+  this.setPrototypeOf(o2nd, oNewProto);
+  return oReturn;
+}
+
+ +

Usage

+ +

First example: 프로토타입에 Chain 설정하기

+ +
function Mammal() {
+  this.isMammal = 'yes';
+}
+
+function MammalSpecies(sMammalSpecies) {
+  this.species = sMammalSpecies;
+}
+
+MammalSpecies.prototype = new Mammal();
+MammalSpecies.prototype.constructor = MammalSpecies;
+
+var oCat = new MammalSpecies('Felis');
+
+console.log(oCat.isMammal); // 'yes'
+
+function Animal() {
+  this.breathing = 'yes';
+}
+
+Object.appendChain(oCat, new Animal());
+
+console.log(oCat.breathing); // 'yes'
+
+ +

Second example: 객체 Constructor의 인스턴스에 존재하는 원래 값을 변경 및 해당 객체 프로토타입에 Chain 설정하기

+ +
function MySymbol() {
+  this.isSymbol = 'yes';
+}
+
+var nPrime = 17;
+
+console.log(typeof nPrime); // 'number'
+
+var oPrime = Object.appendChain(nPrime, new MySymbol());
+
+console.log(oPrime); // '17'
+console.log(oPrime.isSymbol); // 'yes'
+console.log(typeof oPrime); // 'object'
+
+ +

Third example: Function.prototype객체에 Chain을 설정하고 그 Chain에 새로운 함수를 설정하기

+ +
function Person(sName) {
+  this.identity = sName;
+}
+
+var george = Object.appendChain(new Person('George'),
+                                'console.log("Hello guys!!");');
+
+console.log(george.identity); // 'George'
+george(); // 'Hello guys!!'
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-object.setprototypeof', 'Object.setProtoypeOf')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-object.setprototypeof', 'Object.setProtoypeOf')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("34")}}{{CompatGeckoDesktop("31")}}{{CompatIE("11")}}{{CompatVersionUnknown}}{{CompatSafari("9")}}
+ + +
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("31")}}{{CompatUnknown}}{{CompatNo}}{{CompatSafari("9")}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/tolocalestring/index.html b/files/ko/web/javascript/reference/global_objects/object/tolocalestring/index.html new file mode 100644 index 0000000000..809daad824 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/tolocalestring/index.html @@ -0,0 +1,86 @@ +--- +title: Object.prototype.toLocaleString() +slug: Web/JavaScript/Reference/Global_Objects/Object/toLocaleString +tags: + - JavaScript + - Method + - Object + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toLocaleString +--- +
{{JSRef}}
+ +

toLocaleString() 메서드는 객체로 된 문자열을 반환합니다. 이 메서드는 지역별로 다른 객체로 재정의되어 표시됩니다.

+ +
{{EmbedInteractiveExample("pages/js/object-prototype-tolocalestring.html")}}
+ + + +

구문

+ +
obj.toLocaleString()
+ +

반환 값

+ +

객체를 나타내는 문자열.

+ +

설명

+ +

{{jsxref("Object")}}의 toLocaleString은 {{jsxref("Object.toString", "toString()")}}을 호출 한 결과를 반환합니다.

+ +

이 함수는 모든 객체가 사용할 수는 없지만 객체에 일반 toLocaleString 메소드를 제공하기 위해 제공됩니다. 아래 목록을 참조하십시오.

+ +

toLocaleString()을 재정의하는 객체

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.2.4.3', 'Object.prototype.toLocaleString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.tolocalestring', 'Object.prototype.toLocaleString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype.tolocalestring', 'Object.prototype.toLocaleString')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Object.toLocaleString")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/tostring/index.html b/files/ko/web/javascript/reference/global_objects/object/tostring/index.html new file mode 100644 index 0000000000..77e4284ff7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/tostring/index.html @@ -0,0 +1,134 @@ +--- +title: Object.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Object/toString +tags: + - JavaScript + - Method + - Object + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString +--- +
+ +
{{JSRef}}
+ +

The toString() 은 문자열을 반환하는 object의 대표적인 방법이다

+ +
{{EmbedInteractiveExample("pages/js/object-prototype-tostring.html")}}
+ + + +

구문

+ +
obj.toString()
+ +

Description

+ +

모든 객체에는 객체가 텍스트 값으로 표시되거나 객체가 문자열이 예상되는 방식으로 참조 될 때 자동으로 호출되는 toString() 메서드가 있습니다. 기본적으로 toString() 메서드는 Object에서 비롯된 모든 객체에 상속됩니다. 이 메서드가 사용자 지정 개체에서 재정의되지 않으면 toString()은 "[object type]"을 반환합니다. 여기서 type은 object type입니다. 다음 코드는 이것을 설명합니다

+ +
var o = new Object();
+o.toString(); // returns [object Object]
+
+ +
+

Note: 자바스크립트 1.8.5부터 {{jsxref("null")}}의 toString()을 호출하는 경우 [object Null]을 반환하며, {{jsxref("undefined")}}는 [object Undefined]를 반환합니다. 이는 ECMAScript 제 5판과 후속 정오표에 정의되어 있습니다.  See {{anch("toString으로_객체_클래스_검사", "toString으로_객체_클래스_검사")}}.

+
+ +

Examples

+ +

기본 toString 메소드 재정의

+ +

기본 toString() 메서드 대신에 호출될 함수를 정의할 수 있습니다. toString() 메서드는 인자를 취하지 않고 문자열을 반환합니다. 직접 생성한 toString() 메서드는 원하는 어떤 값이든 될 수 있지만 해당 객체에 대한 정보를 전달하고 있을 때 가장 유용할 것입니다.

+ +

다음 코드는 Dog 객체 타입을 정의하고 Dog 타입을 따르는 theDog를 생성합니다:

+ +
function Dog(name, breed, color, sex) {
+  this.name = name;
+  this.breed = breed;
+  this.color = color;
+  this.sex = sex;
+}
+
+theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female');
+
+ +

커스텀 객체의 toString() 메서드를 호출하는 경우 {{jsxref("Object")}}로부터 상속받은 기본 값을 반환하게 됩니다:

+ +
theDog.toString(); // returns [object Object]
+
+ +

다음 코드는 기본 toString() 메서드를 재정의하는 dogToString()을 생성하고 할당합니다. 이 함수는 객체의 name, breed, color, sex를 포함하는 문자열을 "property = value;"의 형태로 만들어냅니다.

+ +
Dog.prototype.toString = function dogToString() {
+  var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed;
+  return ret;
+}
+
+ +

앞선 코드를 사용하면 문자열 컨텍스트에서 theDog가 사용될 때마다 자바스크립트는 자동으로 dogToString() 함수를 호출하여 다음 문자열을 반환합니다:

+ +
"Dog Gabby is a female chocolate Lab"
+
+ +

toString()으로 객체 클래스 검사

+ +

toString()은 모든 객체에 사용되어 해당 객체의 클래스를 가져올 수 있습니다. Object.prototype.toString()을 모든 객체에 사용하기 위해서는 {{jsxref("Function.prototype.call()")}} 나 {{jsxref("Function.prototype.apply()")}}를 사용해서 검사하고자 하는 객체를 thisArg로 불리는 첫번째 파라미터로 넘겨야 합니다.

+ +
var toString = Object.prototype.toString;
+
+toString.call(new Date);    // [object Date]
+toString.call(new String);  // [object String]
+toString.call(Math);        // [object Math]
+
+// Since JavaScript 1.8.5
+toString.call(undefined);   // [object Undefined]
+toString.call(null);        // [object Null]
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.4.2', 'Object.prototype.toString')}}{{Spec2('ES5.1')}}Call on {{jsxref("null")}} returns [object Null], and {{jsxref("undefined")}} returns [object Undefined]
{{SpecName('ES6', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.toString")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/valueof/index.html b/files/ko/web/javascript/reference/global_objects/object/valueof/index.html new file mode 100644 index 0000000000..7bef3bd48c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/valueof/index.html @@ -0,0 +1,118 @@ +--- +title: Object.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/valueOf +tags: + - JavaScript + - Method + - Object + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Object/valueOf +--- +
{{JSRef}}
+ +

valueOf() 메서드는 특정 객체의 원시 값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/object-prototype-valueof.html")}}
+ + + +

구문

+ +
object.valueOf()
+ +

반환 값

+ +

객체의 원시 값.

+ +
+

 (단항) 더하기 기호 는 가끔  valueOf 의 단축 표현으로 사용됩니다. 예를 들면, 다음과 같은 표현을 보세요. +new Number()단항 더하기 사용하기.도 참조 하세요.

+
+ +

설명

+ +

JavaScript는 객체를 원시 값으로 변환할 때 valueOf 메서드를 호출합니다. 보통 원시 값을 필요로 할 때 알아서 사용하므로 직접 호출해야 하는 경우는 매우 드뭅니다.

+ +

기본적으로 {{jsxref("Object")}}의 모든 후손 객체는 valueOf를 상속받습니다. 내장된 핵심 객체는 모두 valueOf를 재정의override해 적합한 값을 반환합니다. 어떤 객체가 원시 값을 가지고 있지 않다면, valueOf는 객체 스스로를 반환합니다.

+ +

여러분의 코드에서 valueOf를 호출해 내장 객체를 원시 값으로 변환할 수 있습니다. 사용자 정의 객체를 만들 땐 valueOf를 재정의해 {{jsxref("Object")}}의 메서드 대신 다른 행동을 부여할 수도 있습니다.

+ +

사용자 정의 객체의 valueOf 오버라이딩

+ +

기본 valueOf 메서드 대신 사용할 함수를 생성할 수 있습니다. 이 때 함수는 매개변수를 받지 않아야 합니다.

+ +

MyNumberType이라는 객체 형태가 존재하고, 이 객체의 valueOf 메서드를 만들고 싶다고 가정하겠습니다. 다음의 코드는 객체의 valueOf 메서드에 사용자 정의 함수를 할당합니다.

+ +
MyNumberType.prototype.valueOf = function() { return customPrimitiveValue; };
+ +

위의 코드가 활성화된 상태에서 어떤 MyNumberType 객체를 원시 값으로 표현해야 하면 JavaScript가 자동으로 저 함수를 실행합니다.

+ +

이 객체의 valueOf 메서드는 보통 JavaScript가 호출하겠지만 다음처럼 직접 호출할 수도 있습니다.

+ +
myNumberType.valueOf()
+ +
+

참고: 문자열 문맥에서 객체-문자열 변환은 {{jsxref("Object.toString", "toString()")}} 메서드를 사용하며, {{jsxref("String")}} 객체의 valueOf를 사용해 원시 문자열로 변환하는 것과는 다릅니다. 모든 객체는, 비록 결과가 "[object type]" 뿐이라도 문자열 변환 기능을 가지고 있습니다. 그러나 대다수의 객체는 숫자, 불리언, 함수 등으로 변환되지 않습니다.

+
+ +

예제

+ +

커스텀 타입에 valueOf 사용하기

+ +
function MyNumberType(n) {
+    this.number = n;
+}
+
+MyNumberType.prototype.valueOf = function() {
+    return this.number;
+};
+
+var myObj = new MyNumberType(4);
+myObj + 3; // 7
+ +

단항 더하기 사용하기

+ +
+"5" // 5 (string to number)
++"" // 0 (string to number)
++"1 + 2" // NaN (doesn't evaluate)
++new Date() // same as (new Date()).getTime()
++"foo" // NaN (string to number)
++{} // NaN
++[] // 0 (toString() returns an empty string list)
++[1] // 1
++[1,2] // NaN
++new Set([1]) // NaN
++BigInt(1) // Uncaught TypeError: Cannot convert a BigInt value to a number
++undefined // NaN
++null // 0
++true // 1
++false // 0
+ +

명세

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}
+ +

라우저 호환성

+ + + +

{{Compat("javascript.builtins.Object.valueOf")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/object/values/index.html b/files/ko/web/javascript/reference/global_objects/object/values/index.html new file mode 100644 index 0000000000..af8f159a53 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/object/values/index.html @@ -0,0 +1,98 @@ +--- +title: Object.values() +slug: Web/JavaScript/Reference/Global_Objects/Object/values +translation_of: Web/JavaScript/Reference/Global_Objects/Object/values +--- +
{{JSRef}}
+ +

Object.values() 메소드는 전달된 파라미터 객체가 가지는 (열거 가능한) 속성의 값들로 이루어진 배열을 리턴합니다. 이 배열은 {{jsxref("Statements/for...in", "for...in")}} 구문과 동일한 순서를 가집니다. (for in 반복문은 프로토타입 체인 또한 열거한다는 점에서 차이가 있습니다.)

+ +
{{EmbedInteractiveExample("pages/js/object-values.html")}}
+ + + +

Syntax

+ +
Object.values(obj)
+ +

Parameters

+ +
+
obj
+
배열로 변환할 열거 가능한 속성을 가지는 객체
+
+ +

Return value

+ +

전달된 객체의 속성 값들을 포함하는 배열

+ +

Description

+ +

Object.values() 는 파라매터로 전달된 객체가 가지는 열거 가능한 속성의 값들로 구성된 배열을 반환합니다. 배열의 값들이 순서는 오브젝트의 속성을 for in 구문등으로 반복한 결과와 동일합니다. (참고로 for in 구문은 순서를 보장하지 않습니다)

+ +

Examples

+ +
var obj = { foo: 'bar', baz: 42 };
+console.log(Object.values(obj)); // ['bar', 42]
+
+// 유사 배열 (숫자를 속성으로 사용하는 객체)
+var obj = { 0: 'a', 1: 'b', 2: 'c' };
+console.log(Object.values(obj)); // ['a', 'b', 'c']
+
+// 유사 배열의 경의 속성으로 사용한 숫자의 크기 순으로 정렬되어 반환됩니다.
+var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
+console.log(Object.values(an_obj)); // ['b', 'c', 'a']
+
+// getFoo는 열거 가능한 속성이 아니라서 배열에 포함되지 않습니다.
+var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
+my_obj.foo = 'bar';
+console.log(Object.values(my_obj)); // ['bar']
+
+// 객체가 아닌 경우에는 객체로 강제로 변환되어 적용됩니다.
+console.log(Object.values('foo')); // ['f', 'o', 'o']
+
+ +

Polyfill

+ +

Object.values 메소드는 구형 브라우저에서 지원하지 않습니다. 구형 브라우저와의 호환성을 고려하기 위해 폴리필을 찾아 볼 수 있습니다. tc39/proposal-object-values-entries 혹은 es-shims/Object.values 를 참조해보세요.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-object.values', 'Object.values')}}{{Spec2('ESDraft')}}Initial definition.
{{SpecName('ES8', '#sec-object.values', 'Object.values')}}{{Spec2('ES8')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object.values")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/parsefloat/index.html b/files/ko/web/javascript/reference/global_objects/parsefloat/index.html new file mode 100644 index 0000000000..bfc5b2d41e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/parsefloat/index.html @@ -0,0 +1,120 @@ +--- +title: parseFloat() +slug: Web/JavaScript/Reference/Global_Objects/parseFloat +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/parseFloat +--- +
{{jsSidebar("Objects")}}
+ +

parseFloat() 함수는 문자열을 분석해 부동소수점 실수로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-parsefloat.html")}}
+ + + +

구문

+ +
parseFloat(value)
+ +

매개변수

+ +
+
value
+
변환할 값.
+
+ +

반환 값

+ +

주어진 값에서 분석한 부동소수점 수. 분석할 수 없으면 {{jsxref("NaN")}}.

+ +

설명

+ +

parseFloat()은 최상위 함수로 어떠한 객체와도 연결되어 있지 않습니다.

+ +

parseFloat()은 매개변수로 주어진 값 분석하고 부동소수점 수를 반환합니다. 기호(+, -), 숫자(0-9), 소수점 또는 지수 이외의 문자를 발견하면, 그 전까지의 결과만 반환하고 문제의 문자와 그 이후는 모두 무시합니다. 위치에 상관하지 않고, 그런 문자를 발견하면 {{jsxref("NaN")}}을 반환하는 더 엄격한 방법이 필요하면 {{jsxref("Number", "Number(value)")}}를 고려하세요.

+ +

값이 문자열인데 첫 번째 문자를 숫자로 변환할 수 없는 경우 parseFloat()NaN을 반환합니다.

+ +

수학적으로 NaN은 어떤 진법에도 속하지 않습니다. {{jsxref("isNaN", "isNaN()")}} 함수를 사용해 결과 값이 NaN인지 확인할 수 있습니다. NaN을 다른 값과의 수학 연산에 사용하면 그 결과도 언제나 NaN이 됩니다.

+ +

parseFloat()은 {{jsxref("Infinity")}}도 분석 및 반환할 수 있습니다. {{jsxref("isFinite", "isFinite()")}} 함수를 사용해 결과 값이 유한수(Infinity, -Infinity, NaN이 아닌 수)인지 알 수 있습니다.

+ +

parseFloat()toString이나 valueOf 메서드를 구현한 객체도 분석할 수 있습니다. 이 때의 결과는 객체의 toString(), valueOf()의 반환 값을 parseFloat()에 전달한 것과 동일합니다.

+ +

예제

+ +

숫자를 반환하는 경우

+ +

아래 예제는 모두 3.14를 반환합니다.

+ +
parseFloat(3.14);
+parseFloat('3.14');
+parseFloat('314e-2');
+parseFloat('0.0314E+2');
+parseFloat('3.14와 숫자가 아닌 문자들');
+
+var foo = Object.create(null);
+foo.toString = function () { return "3.14"; };
+parseFloat(foo);
+
+var foo = Object.create(null);
+foo.valueOf = function () { return "3.14"; };
+parseFloat(foo);​​​​​
+
+ +

NaN을 반환하는 경우

+ +

다음 예제는 {{jsxref("NaN")}}을 반환합니다.

+ +
parseFloat('FF2');
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.2.3', 'parseFloat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-parsefloat-string', 'parseFloat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-parsefloat-string', 'parseFloat')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.parseFloat")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/parseint/index.html b/files/ko/web/javascript/reference/global_objects/parseint/index.html new file mode 100644 index 0000000000..0539e1ba53 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/parseint/index.html @@ -0,0 +1,220 @@ +--- +title: parseInt() +slug: Web/JavaScript/Reference/Global_Objects/parseInt +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/parseInt +--- +
{{jsSidebar("Objects")}}
+ +

parseInt() 함수는 문자열 인자를 구문분석하여 특정 진수(수의 진법 체계에 기준이 되는 값)의 정수를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-parseint.html")}}
+ + + +

구문

+ +
parseInt(string, radix);
+ +

매개변수

+ +
+
string
+
분석할 값. 만약 string이 문자열이 아니면 문자열로 변환(ToString 추상 연산을 사용)합니다. 문자열의 선행 공백은 무시합니다.
+
+ +
+
radix{{optional_inline}}
+
string이 표현하는 정수를 나타내는 2와 36 사이의 진수(수의 진법 체계에 기준이 되는 값). 주의하세요-기본값이 10이 아닙니다!
+
+
+
+

아래의 설명은 radix가 제공되지 않았을때 무엇이 발생하는지 상세하게 설명하고 있습니다.

+
+
+
+ +

반환 값

+ +

주어진 string로부터 분석한 정수.

+ +

또는 아래의 경우에는 {{jsxref("NaN")}}을 반환합니다

+ + + +

설명

+ +

parseInt 함수는 첫 번째 인자를 문자열로 변환하고 파싱하고,  그 문자열을 파싱하여 정수나 NaN을 리턴합니다.

+ +

만약 NaN이 아니면, 첫번째 인자를 특정 radix(진수) 값으로 표현한 정수가 반환됩니다. (예를 들면, radix가 10인 경우 십진수로 변환하며, 8인 경우는 8진수로, 16인 경우 16진수 등등으로  변환합니다.)

+ +

radix 가 10 이상인 경우, 9보다 큰 숫자들은 알파벳 문자로 나타내집니다. 예를 들면, 16 진수의 경우, A부터 F가 사용됩니다.

+ +

만약 parseInt 함수가 특정 진수를 나타내는 숫자가 아닌 글자를 마주치게 되면, 이 글자와 계속되는 글자들은 전부 무시되며, 파싱된 정수값을 리턴합니다. parseInt 함수는 정수값으로 숫자를 잘라버립니다. 맨 앞의 공백과 그 뒤의 공백들은 허용됩니다.

+ +

일부 숫자들은 문자열 표현에 e 문자를 사용하기 때문에(예: 6.022 × 1023의 경우 6.022e23 ) 숫자를 자르기 위하여 parseInt를 사용하는 것은 매우 크거나 매우 작은 숫자에 사용하는 경우 예기치 않은 결과가 발생합니다. parseInt는 {{jsxref("Math.floor()")}}의 대체품으로 사용해서는 안 됩니다.

+ +

parseInt는 양수를 의미하는 기호와 음수를 나타내는 - 기호를 정확히 이해합니다(ECMAScript 1 이후). 공백이 제거된 후 구문 분석의 초기 단계로 수행됩니다. 기호를 찾을 수 없으면 알고리즘이 다음 단계로 이동하고, 그렇지 않으면 기호를 제거하고 문자열의 나머지 부분에서 숫자 파싱을 실행합니다.

+ +

만약 radixundefined 이거나 0이라면, (또는 없다면), JavaScript 는 아래와 같이 임의 처리합니다. :

+ +
    +
  1. 인풋 값 string 이 "0x" 나 "0X"로 시작한다면, radix 는 16(16진)이며, 나머지 문자열은 파싱됩니다.
  2. +
  3. 인풋 값 string 이 "0"으로 시작한다면, radix 는 8(8진)이거나, 10(십진)입니다. 정확히 이 선택된 radix 는 구현 의존적적입니다. ECMAScript 5 는 10(십진)이 사용되는 것을 명시하지만, 모든 브라우저가 아직 이렇게 되지 않습니다. 이러한 이유로 항상 parseInt를 사용할 때는 radix 값을 명시해야 합니다.
  4. +
  5. 인풋 값 string 이 다른 값으로 시작 된다면, radix 는 10(십진)입니다.
  6. +
+ +

첫 번째 글자가 숫자로 변환될 수 없다면, parseIntNaN을 리턴할 것입니다.

+ +

연산의 경우, NaN 값은 어떠한 radix 숫자도 아닙니다. parseInt 값이 NaN인지 알아내기 위해 {{jsxref("isNaN")}} 함수를 호출할 수 있습니다. 만약 NaN이 산술 연산으로 넘겨진다면, 이 연산의 결과 또한 NaN이 될 것입니다.

+ +

특정 진수의 스트링 리터럴로 숫자를 변환하는 것은 intValue.toString(radix)를 사용합니다.

+ +
+

{{jsxref("BigInt")}} 주의: parseInt는 {{jsxref("BigInt")}}를 {{jsxref("Number")}}으로 변환하여 정확성을 떨어뜨립니다. 이는 "n"을 포함한 숫자가 아닌 값은 삭제되기 때문입니다.

+
+ +

radix가 없는 8진 해석

+ +

비록 ECMAScript 3 에서 권장되지 않고, ECMAScript 5 에서 금지되었지만, 많은 구현들은 0으로 시작하는 8진수 문자열을 해석합니다. 다음의 코드는 8진 결과를 가질 수도 있으며, 10진의 결과를 가질 수도 있습니다. 항상 이러한 명확하지 않은 표현은 피하고 radix를 명시하도록 합니다.

+ +
parseInt("0e0"); // 0
+parseInt("08"); // 0, '8' 은 8진수가 아니다.
+
+ +

ECMAScript 5는 8진수 해석을 삭제하였습니다.

+ +

ECMAScript 5의 parseInt 함수 스펙은 더 이상 0 으로 시작하는 8진수 값의 문자열을 다루는 구현을 허용하지 않습니다. ECMAScript 5는 다음을 발표했습니다. :

+ +

parseInt 함수는 특정 radix(진수)값에 따라 문자열 아규먼트 내용의 해석을 하고, 그 영향을 받은 정수 값을 생성합니다. 문자열 내에서 시작되는 부분에 위치한 공백은 무시됩니다. 만약 radix 값이 정의되지 않거나, 0이라면, 이것은 10진수로 여겨집니다. 0x 이나 0X 으로 시작되는 숫자 일 때는 16진수로 여겨집니다.

+ +

ECMAScript 3 와의 차이는 8진수의 해석을 허용하고 있느냐의 차이입니다.

+ +

많은 구현들이 2013부터 이 방식을 채택하고 있지 않아 왔습니다. 오래된 브라우저는 지원되어야 하기 때문에 항상 radix 값을 명시 해야합니다.

+ +

더 엄격한 파싱 함수

+ +

가끔은 int 값을 파싱할 때 더 엄격한 방식을 이용하는 것이유용합니다. 정규 표현식이 도움이 될 것입니다. :

+ +
filterInt = function (value) {
+  if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
+    return Number(value);
+  return NaN;
+}
+
+console.log(filterInt('421'));               // 421
+console.log(filterInt('-421'));              // -421
+console.log(filterInt('+421'));              // 421
+console.log(filterInt('Infinity'));          // Infinity
+console.log(filterInt('421e+0'));            // NaN
+console.log(filterInt('421hop'));            // NaN
+console.log(filterInt('hop1.61803398875'));  // NaN
+console.log(filterInt('1.61803398875'));     // NaN
+
+ +

예제

+ +

parseInt() 사용하기

+ +

다음의 예제는 모두 15를 리턴합니다.

+ +
parseInt(" 0xF", 16);
+parseInt(" F", 16);
+parseInt("17", 8);
+parseInt(021, 8);
+parseInt("015", 10);   // parseInt(015, 10);  13이 리턴될 것입니다.
+parseInt(15.99, 10);
+parseInt("15,123", 10);
+parseInt("FXX123", 16);
+parseInt("1111", 2);
+parseInt("15*3", 10);
+parseInt("15e2", 10);
+parseInt("15px", 10);
+parseInt("12", 13);
+
+ +

다음의 예제는 모두 NaN을 리턴합니다.

+ +
parseInt("Hello", 8); // 전부 숫자가 아님.
+parseInt("546", 2);   // 숫자는 2진법 표현이 불가능함.
+
+ +

다음의 예제는 모두 -15을 리턴합니다. :

+ +
parseInt("-F", 16);
+parseInt("-0F", 16);
+parseInt("-0XF", 16);
+parseInt(-15.1, 10)
+parseInt(" -17", 8);
+parseInt(" -15", 10);
+parseInt("-1111", 2);
+parseInt("-15e1", 10);
+parseInt("-12", 13);
+
+ +

다음의 예제는 모두 4를 리턴합니다.

+ +
parseInt(4.7, 10)
+parseInt(4.7 * 1e22, 10)        // 매우 큰 숫자가 4가 됨
+parseInt(0.00000000000434, 10)  // 매우 작은 숫자가 4가 됨
+
+ +

만약 숫자가 1e+21과 같거나 큰 경우, 또는 1e-7과 같거나 작은 경우, 1을 리턴합니다.(radix가 10인 경우)

+ +
parseInt(0.0000001,10);
+parseInt(0.000000123,10);
+parseInt(1e-7,10);
+parseInt(1000000000000000000000,10);
+parseInt(123000000000000000000000,10);
+parseInt(1e+21,10);
+
+ +

다음의 예제는 모두 224를 리턴합니다.

+ +
parseInt("0e0", 16);
+
+ +

{{jsxref("BigInt")}} 는 정확성을 잃습니다.

+ +
parseInt('900719925474099267n')
+// 900719925474099300
+ +

parseInt 는 숫자구분자와 같이 작동하지 않습니다.

+ +
parseInt('123_456')
+// 123
+ +

명세

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-parseint-string-radix', 'parseInt')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.parseInt")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/promise/all/index.html b/files/ko/web/javascript/reference/global_objects/promise/all/index.html new file mode 100644 index 0000000000..c8a458a665 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/all/index.html @@ -0,0 +1,239 @@ +--- +title: Promise.all() +slug: Web/JavaScript/Reference/Global_Objects/Promise/all +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Promise +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all +--- +
{{JSRef}}
+ +

Promise.all() 메서드는 순회 가능한 객체에 주어진 모든 프로미스가 이행한 후, 혹은 프로미스가 주어지지 않았을 때 이행하는 {{jsxref("Promise")}}를 반환합니다. 주어진 프로미스 중 하나가 거부하는 경우, 첫 번째로 거절한 프로미스의 이유를 사용해 자신도 거부합니다.

+ +
{{EmbedInteractiveExample("pages/js/promise-all.html")}}
+ + + +

구문

+ +
Promise.all(iterable);
+
+ +

매개변수

+ +
+
iterable
+
{{jsxref("Array")}}와 같이 순회 가능한(iterable) 객체.
+
+ +

반환 값

+ + + +

설명

+ +

Promise.all은 여러 프로미스의 결과를 집계할 때 유용하게 사용할 수 있습니다.

+ +

이행

+ +

반환한 프로미스의 이행 결과값은 (프로미스가 아닌 값을 포함하여) 매개변수로 주어진 순회 가능한 객체에 포함된 모든 값을 담은 배열입니다.

+ + + +

거부

+ +

주어진 프로미스 중 하나라도 거부하면, 다른 프로미스의 이행 여부에 상관없이 첫 번째 거부 이유를 사용해 거부합니다.

+ +

예제

+ +

Promise.all 사용하기

+ +

Promise.all은 배열 내 모든 값의 이행(또는 첫 번째 거부)을 기다립니다.

+ +
var p1 = Promise.resolve(3);
+var p2 = 1337;
+var p3 = new Promise((resolve, reject) => {
+  setTimeout(() => {
+    resolve("foo");
+  }, 100);
+});
+
+Promise.all([p1, p2, p3]).then(values => {
+  console.log(values); // [3, 1337, "foo"]
+});
+ +

순회 가능한 객체에 프로미스가 아닌 값이 들어있다면 무시하지만, 이행 시 결과 배열에는 포함합니다.

+ +
// 매개변수 배열이 빈 것과 동일하게 취급하므로 이행함
+var p = Promise.all([1,2,3]);
+// 444로 이행하는 프로미스 하나만 제공한 것과 동일하게 취급하므로 이행함
+var p2 = Promise.all([1,2,3, Promise.resolve(444)]);
+// 555로 거부하는 프로미스 하나만 제공한 것과 동일하게 취급하므로 거부함
+var p3 = Promise.all([1,2,3, Promise.reject(555)]);
+
+// setTimeout()을 사용해 스택이 빈 후에 출력할 수 있음
+setTimeout(function() {
+    console.log(p);
+    console.log(p2);
+    console.log(p3);
+});
+
+// 출력
+// Promise { <state>: "fulfilled", <value>: Array[3] }
+// Promise { <state>: "fulfilled", <value>: Array[4] }
+// Promise { <state>: "rejected", <reason>: 555 }
+ +

Promise.all의 동기성/비동기성

+ +

다음 예제는 Promise.all의 비동기성(주어진 인자가 빈 경우엔 동기성)을 보입니다.

+ +
// Promise.all을 최대한 빨리 완료시키기 위해
+// 이미 이행된 프로미스로 배열을 만들어 인자로 전달
+var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)];
+
+var p = Promise.all(resolvedPromisesArray);
+// 실행 즉시 p의 값을 기록
+console.log(p);
+
+// 호출 스택을 비운 다음 실행하기 위해 setTimeout을 사용
+setTimeout(function() {
+    console.log('the stack is now empty');
+    console.log(p);
+});
+
+// 로그 출력 결과 (순서대로):
+// Promise { <state>: "pending" }
+// the stack is now empty
+// Promise { <state>: "fulfilled", <value>: Array[2] }
+
+ +

Promise.all()이 거부하는 경우에도 동일한 일이 발생합니다:

+ +
var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)];
+var p = Promise.all(mixedPromisesArray);
+console.log(p);
+setTimeout(function() {
+    console.log('the stack is now empty');
+    console.log(p);
+});
+
+// 출력
+// Promise { <state>: "pending" }
+// the stack is now empty
+// Promise { <state>: "rejected", <reason>: 44 }
+
+ +

그러나, Promise.all은 주어진 순회 가능한 객체가 비어있는 경우에만 동기적으로 이행됩니다.

+ +
var p = Promise.all([]); // 즉시 이행함
+var p2 = Promise.all([1337, "hi"]); // 프로미스가 아닌 값은 무시하지만 비동기적으로 실행됨
+console.log(p);
+console.log(p2);
+setTimeout(function() {
+    console.log('the stack is now empty');
+    console.log(p2);
+});
+
+// 출력
+// Promise { <state>: "fulfilled", <value>: Array[0] }
+// Promise { <state>: "pending" }
+// the stack is now empty
+// Promise { <state>: "fulfilled", <value>: Array[2] }
+
+ +

Promise.all() 실패 우선성

+ +

Promise.all()은 배열 내 요소 중 어느 하나라도 거부하면 즉시 거부합니다. 예를 들어, 일정 시간이 지난 이후 이행하는 네 개의 프로미스와, 즉시 거부하는 하나의 프로미스를 전달한다면 Promise.all()도 즉시 거부합니다.

+ +
var p1 = new Promise((resolve, reject) => {
+  setTimeout(() => resolve('하나'), 1000);
+});
+var p2 = new Promise((resolve, reject) => {
+  setTimeout(() => resolve('둘'), 2000);
+});
+var p3 = new Promise((resolve, reject) => {
+  setTimeout(() => resolve('셋'), 3000);
+});
+var p4 = new Promise((resolve, reject) => {
+  setTimeout(() => resolve('넷'), 4000);
+});
+var p5 = new Promise((resolve, reject) => {
+  reject(new Error('거부'));
+});
+
+
+// .catch 사용:
+Promise.all([p1, p2, p3, p4, p5])
+.then(values => {
+  console.log(values);
+})
+.catch(error => {
+  console.log(error.message)
+});
+
+// 콘솔 출력값:
+// "거부"
+
+ +

발생할 수 있는 거부를 사전에 처리해 동작 방식을 바꿀 수 있습니다.

+ +
var p1 = new Promise((resolve, reject) => {
+  setTimeout(() => resolve('p1_지연_이행'), 1000);
+});
+
+var p2 = new Promise((resolve, reject) => {
+  reject(new Error('p2_즉시_거부'));
+});
+
+Promise.all([
+  p1.catch(error => { return error }),
+  p2.catch(error => { return error }),
+]).then(values => {
+  console.log(values[0]) // "p1_지연_이행"
+  console.log(values[1]) // "Error: p2_즉시_거부"
+})
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.all', 'Promise.all')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Promise.all")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/promise/allsettled/index.html b/files/ko/web/javascript/reference/global_objects/promise/allsettled/index.html new file mode 100644 index 0000000000..a063f29c7c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/allsettled/index.html @@ -0,0 +1,66 @@ +--- +title: Promise.allSettled() +slug: Web/JavaScript/Reference/Global_Objects/Promise/allSettled +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/allSettled +--- +

{{JSRef}}

+ +

Promise.allSettled() 메소드는 배열이나 별도의 나열 가능한 객체를 통해 나열된 Promise모음이 모두 이행하거나 거부했을 때에 대한 대응을 할 수 있는 Promise 객체를 반환한다.

+ +
{{EmbedInteractiveExample("pages/js/promise-allsettled.html")}}
+ +

문법

+ +
Promise.allSettled(iterable);
+ +

인자

+ +
+
iterable
+
iterable 객체로, 주로 배열({{jsxref("Array")}})을 사용하며, 이들의 요소들은 모두 Promise 객체.
+
+ +

반환 값

+ +

실행할 {{jsxref("Promise")}} 객체로 비동기 방식으로 이행(Resolved) 및 거부(Rejected)된 결과의 모음을 담아 인자로 전달된다. 이 때 반환된 Promise 객체의 핸들러는 각 본래 Promise 객체가 담긴 배열을 전달할 것이다.

+ +

각 출력 객체는 status 속성을 통해,  fulfilled,상태로 전달되면 value 속성이 전달되고, rejected 상태로 전달 시 reason 속성으로 전달된다. 각 Promise가 어떻게 이행(또는 거부)됐는지 value 속성 및 reason 속성을 통해 알 수 있다.

+ +

문서 표준

+ + + + + + + + + + + + + + +
SpecificationStatusComment
Promise.allSettled() (TC39 Stage 4 Draft){{Spec2('ESDraft')}}
+ +

지원 브라우저

+ + + +

{{Compat("javascript.builtins.Promise.allSettled")}}

+ +

구현 진행 상태

+ +

The following table provides a daily implementation status for this feature, because this feature has not yet reached cross-browser stability. The data is generated by running the relevant feature tests in Test262, the standard test suite of JavaScript, in the nightly build, or latest release of each browser's JavaScript engine.

+ +
{{EmbedTest262ReportResultsTable("Promise.allSettled")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/promise/finally/index.html b/files/ko/web/javascript/reference/global_objects/promise/finally/index.html new file mode 100644 index 0000000000..c75d73ab06 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/finally/index.html @@ -0,0 +1,100 @@ +--- +title: Promise.prototype.finally() +slug: Web/JavaScript/Reference/Global_Objects/Promise/finally +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/finally +--- +
{{JSRef}}
+ +

finally() 메소드는 {{jsxref("Promise")}} 객체를 반환합니다. Promise가 처리되면 충족되거나 거부되는지 여부에 관계없이 지정된 콜백 함수가 실행됩니다. 이것은 Promise가 성공적으로 수행 되었는지 거절되었는지에 관계없이 Promise가 처리 된 후에 코드가 무조건 한 번은 실행되는 것을 제공합니다.

+ +

이것은 Promise의 {{jsxref("Promise.then", "then()")}}과 {{jsxref("Promise.catch", "catch()")}} 핸들러에서의 코드 중복을 피하게 합니다.

+ +

문법

+ +
p.finally(onFinally);
+
+p.finally(function() {
+   // settled (fulfilled or rejected)
+});
+
+ +

Parameters

+ +
+
onFinally
+
Promise가 처리된 후 {{jsxref("Function")}} 이 호출됩니다.
+
+ +

Return value

+ +

finally 핸들러는 onFinally 라는 지정된 함수의 {{jsxref("Promise")}}가 반환됩니다.

+ +

설명

+ +

 

+ +

finally() 메서드는 결과에 관계없이 promise가 처리되면 무언가를 프로세싱 또는 정리를 수행하려는 경우에 유용합니다.

+ +

finally() 메서드는 .then(onFinally, onFinally) 를 호출하는 것과 매우 비슷하지만 몇 가지 차이점이 있습니다:

+ +

 

+ + + +
+

Note:  finally 콜백에서 throw (또는 거부된 promise를 반환)하면 throw()를 호출 할 때 지정된 거부 이유로 새롭게 만들어진 promise를 반환합니다.

+
+ +

예제

+ +
let isLoading = true;
+
+fetch(myRequest).then(function(response) {
+    var contentType = response.headers.get("content-type");
+    if(contentType && contentType.includes("application/json")) {
+      return response.json();
+    }
+    throw new TypeError("Oops, we haven't got JSON!");
+  })
+  .then(function(json) { /* process your JSON further */ })
+  .catch(function(error) { console.log(error); })
+  .finally(function() { isLoading = false; });
+
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
TC39 proposalStage 4 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Promise.finally")}}

+ +

더보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/promise/index.html b/files/ko/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..d3dbf076c5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,226 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +tags: + - ECMAScript 2015 + - JavaScript + - Promise + - Reference + - 프로미스 +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +
{{JSRef}}
+ +

Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.

+ +

Promise의 작동 방식과 Promise 사용 방법에 대해 알아보려면 먼저 Promise 사용 방법을 읽어 보십시오.

+ +

설명

+ +

Promise는 프로미스가 생성될 때 꼭 알 수 있지는 않은 값을 위한 대리자로, 비동기 연산이 종료된 이후의 결과값이나 실패 이유를 처리하기 위한 처리기를 연결할 수 있도록 합니다. 프로미스를 사용하면 비동기 메서드에서 마치 동기 메서드처럼 값을 반환할 수 있습니다. 다만 최종 결과를 반환하지는 않고, 대신 프로미스를 반환해서 미래의 어떤 시점에 결과를 제공합니다.

+ +

Promise는 다음 중 하나의 상태를 가집니다.

+ + + +

대기 중인 프로미스는 값과 함께 이행할 수도, 어떤 이유(오류)로 인해 거부될 수 있습니다. 이행이나 거부될 때, 프로미스에 연결한 처리기는 그 프로미스의 then 메서드에 의해 대기열에 오릅니다. 이미 이행했거나 거부된 프로미스에 연결한 처리기도 호출하므로, 비동기 연산과 처리기 연결 사이에 경합 조건race condition은 없습니다.

+ +

{{jsxref("Promise.prototype.then()")}} 및 {{jsxref("Promise.prototype.catch()")}} 메서드의 반환 값은 다른 프로미스이므로, 서로 연결할 수 있습니다.

+ +

+ +
+

혼동 주의: 느긋한 계산법 및 연산 연기를 위한 방법을 프로미스라고 부르는 다른 언어(예: Scheme)가 여럿 있습니다. 반면 JavaScript에서 프로미스는 콜백 함수를 연결할 수 있는 이미 진행 중인 프로세스를 나타냅니다. 표현식을 느긋하게 평가하려면 인수 없는 화살표 함수 f = () => expression를 사용하고, f()를 사용해 평가하세요.

+
+ +
+

참고: 프로미스는 대기 중이지 않으며 이행 또는 거부됐을 때 처리(settled)됐다고 말합니다. 프로미스와 함께 쓰이는 단어 resolved는 프로미스가 다른 프로미스의 상태에 맞춰 처리됨, 또는 상태가 "잠김"되었다는 의미입니다. 용어에 관한 더 자세한 설명은 Domenic Denicola의 글 States and fates에서 볼 수 있습니다.

+
+ +

생성자

+ +
+
{{jsxref("Promise.Promise", "Promise()")}}
+
이미 프로미스를 지원하지 않는 함수를 감쌀 때 주로 사용합니다.
+
+ +

속성

+ +
+
Promise.length
+
값이 언제나 1인 길이 속성입니다. (생성자 인수의 수)
+
{{jsxref("Promise.prototype")}}
+
Promise 생성자의 프로토타입을 나타냅니다.
+
+ +

메서드

+ +
+
{{jsxref("Promise.all", "Promise.all(iterable)")}}
+
iterable 내의 모든 프로미스가 이행한 뒤 이행하고, 어떤 프로미스가 거부하면 즉시 거부하는 프로미스를 반환합니다. 반환된 프로미스가 이행하는 경우 iterable 내의 프로미스가 결정한 값을 모은 배열이 이행 값입니다. 반환된 프로미스가 거부하는 경우 iterable 내의 거부한 프로미스의 이유를 그대로 사용합니다. 이 메서드는 여러 프로미스의 결과를 모을 때 유용합니다.
+
{{jsxref("Promise.race", "Promise.race(iterable)")}}
+
iterable 내의 어떤 프로미스가 이행하거나 거부하는 즉시 스스로 이행하거나 거부하는 프로미스를 반환합니다. 이행 값이나 거부 이유는 원 프로미스의 값이나 이유를 그대로 사용합니다.
+
+ +
+
{{jsxref("Promise.reject()")}}
+
주어진 이유로 거부하는 Promise 객체를 반환합니다.
+
+ +
+
{{jsxref("Promise.resolve()")}}
+
주어진 값으로 이행하는 Promise 객체를 반환합니다. 값이 then 가능한 (즉, then 메서드가 있는) 경우, 반환된 프로미스는 then 메서드를 따라가고 마지막 상태를 취합니다. 그렇지 않은 경우 반환된 프로미스는 주어진 값으로 이행합니다. 어떤 값이 프로미스인지 아닌지 알 수 없는 경우, {{jsxref("Promise.resolve", "Promise.resolve(value)")}} 후 반환값을 프로미스로 처리할 수 있습니다.
+
+ +

Promise 프로토타입

+ +

속성

+ +

{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype','속성')}}

+ +

메서드

+ +

{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype','메서드')}}

+ +

예제

+ +

기본 예제

+ +
let myFirstPromise = new Promise((resolve, reject) => {
+  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
+  // In this example, we use setTimeout(...) to simulate async code.
+  // In reality, you will probably be using something like XHR or an HTML5 API.
+  setTimeout(function(){
+    resolve("Success!"); // Yay! Everything went well!
+  }, 250);
+});
+
+myFirstPromise.then((successMessage) => {
+  // successMessage is whatever we passed in the resolve(...) function above.
+  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
+  console.log("Yay! " + successMessage);
+});
+ +

고급 예제

+ + + +

다음의 작은 예제는 Promise의 동작 방식을 보여줍니다. testPromise() 함수는 {{HTMLElement("button")}}을 클릭할 때마다 호출되며, {{domxref("window.setTimeout()")}}을 사용해 1~3초의 무작위 간격 이후 프로미스 횟수(1부터 시작하는 숫자)로 이행하는 프로미스를 생성합니다. Promise() 생성자는 프로미스를 만드는 데 쓰입니다.

+ +

프로미스 이행은 {{jsxref("Promise.prototype.then()","p1.then()")}}을 사용하는 이행 콜백 세트를 통해 단순히 로그에 남습니다. 약간의 로그를 통해, 함수의 동기 부분이 비동기적 프로미스의 완료와 어떻게 분리되어 있는지 확인할 수 있습니다.

+ +
'use strict';
+var promiseCount = 0;
+
+function testPromise() {
+    var thisPromiseCount = ++promiseCount;
+
+    var log = document.getElementById('log');
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') 시작 (<small>동기적 코드 시작</small>)<br/>');
+
+    // 새 프로미스 생성 - 프로미스의 생성 순서를 전달하겠다는 약속을 함 (3초 기다린 후)
+    var p1 = new Promise(
+        // 실행 함수는 프로미스를 이행(resolve)하거나
+        // 거부(reject)할 수 있음
+        function(resolve, reject) {
+            log.insertAdjacentHTML('beforeend', thisPromiseCount +
+                ') 프로미스 시작 (<small>비동기적 코드 시작</small>)<br/>');
+            // setTimeout은 비동기적 코드를 만드는 예제에 불과
+            window.setTimeout(
+                function() {
+                    // 프로미스 이행 !
+                    resolve(thisPromiseCount);
+                }, Math.random() * 2000 + 1000);
+        }
+    );
+
+    // 프로미스를 이행했을 때 할 일은 then() 호출로 정의하고,
+    // 거부됐을 때 할 일은 catch() 호출로 정의
+    p1.then(
+        // 이행 값 기록
+        function(val) {
+            log.insertAdjacentHTML('beforeend', val +
+                ') 프로미스 이행 (<small>비동기적 코드 종료</small>)<br/>');
+        })
+    .catch(
+        // 거부 이유 기록
+        function(reason) {
+            console.log('여기서 거부된 프로미스(' + reason + ')를 처리하세요.');
+        });
+
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') 프로미스 생성 (<small>동기적 코드 종료</small>)<br/>');
+}
+
+ + + +

이 예제는 버튼을 클릭하면 실행됩니다. Promise를 지원하는 브라우저가 필요합니다. 짧은 시간 안에 버튼을 여러 번 클릭하여, 서로 다른 프로미스가 번갈아 이행되는 것을 볼 수도 있습니다.

+ +

{{EmbedLiveSample("고급_예제", "500", "200")}}

+ +

XHR로 이미지 불러오기

+ +

이미지를 로드하기 위해 Promise 및 {{domxref("XMLHttpRequest")}}를 사용하는 또 다른 간단한 예는 MDN GitHub js-examples 저장소에서 이용할 수 있습니다. 실제 예를 볼 수도 있습니다. 각 단계에 주석이 붙어있어, 프로미스 및 XHR 구조를 차근차근 따라갈 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}{{Spec2('ES6')}}ECMA 표준에서 초기 정의.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.Promise")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/promise/promise/index.html b/files/ko/web/javascript/reference/global_objects/promise/promise/index.html new file mode 100644 index 0000000000..531b82dbca --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/promise/index.html @@ -0,0 +1,78 @@ +--- +title: Promise() 생성자 +slug: Web/JavaScript/Reference/Global_Objects/Promise/Promise +tags: + - Constructor + - JavaScript + - Promise + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/Promise +--- +
{{JSRef}}
+ +

Promise 생성자는 주로 프로미스를 지원하지 않는 함수를 감쌀 때 사용합니다.

+ +
{{EmbedInteractiveExample("pages/js/promise-constructor.html")}}
+ + + +

구문

+ +
new Promise(executor)
+ +

매개변수

+ +
+
executor
+
resolvereject 인수를 전달할 실행 함수. 실행 함수는 프로미스 구현에 의해 resolvereject 함수를 받아 즉시 실행됩니다(실행 함수는 Promise 생성자가 생성한 객체를 반환하기도 전에 호출됩니다). resolvereject 함수는 호출할 때 각각 프로미스를 이행하거나 거부합니다. 실행 함수는 보통 어떤 비동기 작업을 시작한 후 모든 작업을 끝내면 resolve를 호출해 프로미스를 이행하고, 오류가 발생한 경우 reject를 호출해 거부합니다. 실행 함수에서 오류를 던지면 프로미스는 거부됩니다. 실행 함수의 반환값은 무시됩니다.
+
+ +

예제

+ +

Promise 객체는 new 키워드와 생성자를 사용해 만듭니다. 생성자는 매개변수로 "실행 함수"를 받습니다. 이 함수는 매개 변수로 두 가지 함수를 받아야 하는데, 첫 번째 함수(resolve)는 비동기 작업을 성공적으로 완료해 결과를 값으로 반환할 때 호출해야 하고, 두 번째 함수(reject)는 작업이 실패하여 오류의 원인을 반환할 때 호출하면 됩니다. 두 번째 함수는 주로 오류 객체를 받습니다.

+ +
const myFirstPromise = new Promise((resolve, reject) => {
+  // do something asynchronous which eventually calls either:
+  //
+  //   resolve(someValue)        // fulfilled
+  // or
+  //   reject("failure reason")  // rejected
+});
+
+ +

함수에 프로미스 기능을 추가하려면, 간단하게 프로미스를 반환하도록 하면 됩니다.

+ +
function myAsyncFunction(url) {
+  return new Promise((resolve, reject) => {
+    const xhr = new XMLHttpRequest()
+    xhr.open("GET", url)
+    xhr.onload = () => resolve(xhr.responseText)
+    xhr.onerror = () => reject(xhr.statusText)
+    xhr.send()
+  });
+}
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-promise-constructor', 'Promise constructor')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Promise.Promise")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/promise/prototype/index.html b/files/ko/web/javascript/reference/global_objects/promise/prototype/index.html new file mode 100644 index 0000000000..4569b4d26a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/prototype/index.html @@ -0,0 +1,71 @@ +--- +title: Promise.prototype +slug: Web/JavaScript/Reference/Global_Objects/Promise/prototype +tags: + - JavaScript + - Promise + - Property + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +
{{JSRef}}
+ +

Promise.prototype 속성은 {{jsxref("Promise")}} 생성자의 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0,0,0)}}
+ +

설명

+ +

{{jsxref("Promise")}} 인스턴스는 {{jsxref("Promise.prototype")}}을 상속합니다. 모든 Promise 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.

+ +

속성

+ +
+
Promise.prototype.constructor
+
인스턴스의 프로토타입을 만드는 함수를 반환합니다. 기본값은 {{jsxref("Promise")}} 함수입니다.
+
+ +

메서드

+ +
+
{{jsxref("Promise.prototype.catch()")}}
+
프로미스(promise)에 거부 처리기 콜백을 추가하고 호출된 경우 콜백의 반환값 또는 프로미스가 대신 이행된 경우 그 원래 이행(fulfillment)값으로 결정하는(resolving) 새 프로미스를 반환합니다.
+
{{jsxref("Promise.prototype.then()")}}
+
프로미스에 이행 또는 거부 처리기를 추가하고 호출된 처리기의 반환값 또는 프로미스가 처리되지 않은 경우 그 원래 처리된(settled) 값으로 결정하는 새 프로미스를 반환합니다 (즉 관련 처리기 onFulfilled 또는 onRejectedundefined인 경우).
+
{{jsxref("Promise.prototype.finally()")}}
+
Appends a handler to the promise, and returns a new promise which is resolved when the original promise is resolved. The handler is called when the promise is settled, whether fulfilled or rejected.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-promise.prototype', 'Promise.prototype')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-promise.prototype', 'Promise.prototype')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Promise.prototype")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/promise/race/index.html b/files/ko/web/javascript/reference/global_objects/promise/race/index.html new file mode 100644 index 0000000000..0874d619dd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/race/index.html @@ -0,0 +1,187 @@ +--- +title: Promise.race() +slug: Web/JavaScript/Reference/Global_Objects/Promise/race +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Promise + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/race +--- +
{{JSRef}}
+ +

Promise.race() 메소드는 Promise 객체를 반환합니다. 이 프로미스 객체는 iterable 안에 있는 프로미스 중에 가장 먼저 완료된 것의 결과값으로 그대로 이행하거나 거부합니다.

+ +
{{EmbedInteractiveExample("pages/js/promise-race.html")}}
+ + + +

구문

+ +
Promise.race(iterable);
+ +

매개변수

+ +
+
iterable
+
{{jsxref("Array")}}와 같은 iterable 객체. iterable을 참고하세요.
+
+ +

반환값

+ +

주어진 iterable에서 처음으로 이행하거나 거부한 프로미스의 값을 비동기적으로 전달받는 대기 중인 {{jsxref("Promise")}}.

+ +

설명

+ +

race 함수는 인자로 주어진 iterable의 프로미스 중 가장 먼저 완료(settle)되는 것과 같은 방식으로 완료(이행/거부)되고, 같은 결과값을 전달하는 Promise를 반환합니다.

+ +

전달받은 iterable이 비어 있을 경우, 반환한 프로미스는 영원히 대기 상태가 됩니다.

+ +

Iterable에 프로미스가 아닌 값이나 이미 완료된 프로미스가 포함되어 있을 경우, Promise.race는 전달받은 iterable에서 처음으로 등장하는 이러한 값을 결과값으로 이행합니다.

+ +

예제

+ +

Promise.race의 비동기성

+ +

다음 예제에서 Promise.race의 비동기성을 확인할 수 있습니다.

+ +
// Promise.race를 최대한 빨리 완료시키기 위해
+// 이미 이행된 프로미스로 배열을 만들어 인자로 전달
+var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)];
+
+var p = Promise.race(resolvedPromisesArray);
+// 실행 즉시 p의 값을 기록
+console.log(p);
+
+// 호출 스택을 비운 다음 실행하기 위해 setTimeout을 사용
+setTimeout(function(){
+    console.log('the stack is now empty');
+    console.log(p);
+});
+
+// 로그 출력 결과 (순서대로):
+// Promise { <state>: "pending" }
+// the stack is now empty
+// Promise { <state>: "fulfilled", <value>: 33 }
+ +

비어 있는 iterable을 전달하면 반환한 프로미스는 영원히 대기 상태가 됩니다.

+ +
var foreverPendingPromise = Promise.race([]);
+console.log(foreverPendingPromise);
+setTimeout(function(){
+    console.log('the stack is now empty');
+    console.log(foreverPendingPromise);
+});
+
+// 로그 출력 결과 (순서대로):
+// Promise { <state>: "pending" }
+// the stack is now empty
+// Promise { <state>: "pending" }
+
+ +

Iterable에 프로미스가 아닌 값이나 이미 완료된 프로미스가 포함되어 있을 경우, Promise.race는 전달받은 iterable에서 처음으로 등장하는 이러한 값을 결과값으로 이행합니다.

+ +
var foreverPendingPromise = Promise.race([]);
+var alreadyFulfilledProm = Promise.resolve(666);
+
+var arr = [foreverPendingPromise, alreadyFulfilledProm, "프로미스 아님"];
+var arr2 = [foreverPendingPromise, "프로미스 아님", Promise.resolve(666)];
+var p = Promise.race(arr);
+var p2 = Promise.race(arr2);
+
+console.log(p);
+console.log(p2);
+setTimeout(function(){
+    console.log('the stack is now empty');
+    console.log(p);
+    console.log(p2);
+});
+
+// 로그 출력 결과 (순서대로):
+// Promise { <state>: "pending" }
+// Promise { <state>: "pending" }
+// the stack is now empty
+// Promise { <state>: "fulfilled", <value>: 666 }
+// Promise { <state>: "fulfilled", <value>: "프로미스 아님" }
+
+ +

setTimeout과 함께 Promise.race 사용 예

+ +
var p1 = new Promise(function(resolve, reject) {
+    setTimeout(() => resolve('하나'), 500);
+});
+var p2 = new Promise(function(resolve, reject) {
+    setTimeout(() => resolve('둘'), 100);
+});
+
+Promise.race([p1, p2])
+.then(function(value) {
+  console.log(value); // "둘"
+  // 둘 다 이행하지만 p2가 더 빠르므로
+});
+
+var p3 = new Promise(function(resolve, reject) {
+    setTimeout(() => resolve('셋'), 100);
+});
+var p4 = new Promise(function(resolve, reject) {
+    setTimeout(() => reject(new Error('넷')), 500);
+});
+
+Promise.race([p3, p4])
+.then(function(value) {
+  console.log(value); // "셋"
+  // p3이 더 빠르므로 이행함
+}, function(reason) {
+  // 실행되지 않음
+});
+
+var p5 = new Promise(function(resolve, reject) {
+    setTimeout(() => resolve('다섯'), 500);
+});
+var p6 = new Promise(function(resolve, reject) {
+    setTimeout(() => reject(new Error('여섯')), 100);
+});
+
+Promise.race([p5, p6])
+.then(function(value) {
+  // 실행되지 않음
+}, function(error) {
+  console.log(error.message); // "여섯"
+  // p6이 더 빠르므로 거부함
+});
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-promise.race', 'Promise.race')}}{{Spec2('ES6')}}ECMA 표준에서 초기 정의.
{{SpecName('ESDraft', '#sec-promise.race', 'Promise.race')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Promise.race")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/promise/reject/index.html b/files/ko/web/javascript/reference/global_objects/promise/reject/index.html new file mode 100644 index 0000000000..a376940d7e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/reject/index.html @@ -0,0 +1,81 @@ +--- +title: Promise.reject() +slug: Web/JavaScript/Reference/Global_Objects/Promise/reject +tags: + - ECMAScript6 + - JavaScript + - Method + - Promise +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/reject +--- +
{{JSRef}}
+ +

Promise.reject(reason) 메서드는 주어진 이유(reason)로 거부된 Promise 객체를 반환합니다.

+ +

구문

+ +
Promise.reject(reason);
+ +

매개변수

+ +
+
reason
+
Promise를 거부한 이유.
+
+ +

설명

+ +

정적 Promise.reject 함수는 거부된 Promise를 반환합니다. 디버깅 목적 및 선택된 오류를 잡기 위해, reasoninstanceof {{jsxref("Error")}} 이게 하는데 유용합니다.

+ +

+ +

정적 Promise.reject() 메서드 사용

+ +
Promise.reject("Testing static reject").then(function(reason) {
+  // 호출되지 않음
+}, function(reason) {
+  console.log(reason); // "Testing static reject"
+});
+
+Promise.reject(new Error("fail")).then(function(error) {
+  // 호출되지 않음
+}, function(error) {
+  console.log(error); // Stacktrace
+});
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ES6')}}ECMA 표준에서 초기 정의.
{{SpecName('ESDraft', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Promise.reject")}}

+ +

 

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/promise/resolve/index.html b/files/ko/web/javascript/reference/global_objects/promise/resolve/index.html new file mode 100644 index 0000000000..64180ef2bf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/resolve/index.html @@ -0,0 +1,162 @@ +--- +title: Promise.resolve() +slug: Web/JavaScript/Reference/Global_Objects/Promise/resolve +tags: + - ECMAScript6 + - JavaScript + - Method + - Promise + - 레퍼런스 +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/resolve +--- +
{{JSRef}}
+ +

Promise.resolve(value) 메서드는 주어진 값으로 이행하는 {{jsxref("Promise.then")}} 객체를 반환합니다. 그 값이 프로미스인 경우, 해당 프로미스가 반환됩니다. 그 값이 thenable(예, {{jsxref("Promise.then", "\"then\" 메소드")}} 가 있음)인 경우, 반환된 프로미스는 그 thenable을 "따르며", 그 최종 상태를 취합니다. 그렇지 않으면 반환된 프로미스는 그 값으로 이행합니다. 이 함수는 프로미스형의 객체(무언가를 결정하는 프로미스를 결정하는 프로미스 등)의 중첩된 레이어를 단일 레이어로 펼칩니다.

+ +
+

주의: 스스로를 결정하는 thenable 에서 Promise.resolve 를 호출하면 안됩니다. 이는 무한히 중첩된 프로미스를 펼치려고하므로 무한 재귀를 유발할 것입니다. Angular 에서 async Pipe 를 함께 사용한 예제입니다. 자세한 내용은 여기에서 확인하세요.

+
+ +
{{EmbedInteractiveExample("pages/js/promise-resolve.html")}}
+ + + +

구문

+ +
Promise.resolve(value);
+
+ +

파라미터

+ +
+
value
+
Promise에 의해 결정되는 인수. Promise 또는 이행할 thenable 일수도 있습니다.
+
+ +

반환 값

+ +
+
+

주어진 값으로 이행된 {{jsxref("Promise")}} 또는 값이 promise 객체인 경우, 값으로 전달된 promise. 

+
+
+ +

설명

+ +

정적 Promise.resolve 함수는 이행된 Promise 를 반환합니다.

+ +

예시

+ +

정적 Promise.resolve 메소드 사용

+ +
Promise.resolve("Success").then(function(value) {
+  console.log(value); // "Success"
+}, function(value) {
+  // 호출되지 않음
+});
+
+ +

배열 이행

+ +
var p = Promise.resolve([1,2,3]);
+p.then(function(v) {
+  console.log(v[0]); // 1
+});
+
+ +

또 다른 Promise 이행

+ +
var original = Promise.resolve(33);
+var cast = Promise.resolve(original);
+cast.then(function(value) {
+  console.log('value: ' + value);
+});
+console.log('original === cast ? ' + (original === cast));
+
+// 로그 순서:
+// original === cast ? true
+// value: 33
+
+ +

로그의 순서가 반대인 이유는 then 핸들러가 비동기로 호출되기 때문입니다. 여기에서 then 이 동작하는 방식에 대해 확인하세요.

+ +

thenable 이행 및 오류 발생

+ +
// thenable 객체 이행
+var p1 = Promise.resolve({
+  then: function(onFulfill, onReject) { onFulfill("fulfilled!"); }
+});
+console.log(p1 instanceof Promise) // true, 객체는 Promise 로 변환됨
+
+p1.then(function(v) {
+    console.log(v); // "fulfilled!"
+  }, function(e) {
+    // 호출되지 않음
+});
+
+// thenable 이 콜백 이전에 오류를 throw
+// Promise 거부
+var thenable = { then: function(resolve) {
+  throw new TypeError("Throwing");
+  resolve("Resolving");
+}};
+
+var p2 = Promise.resolve(thenable);
+p2.then(function(v) {
+  // 호출되지 않음
+}, function(e) {
+  console.log(e); // TypeError: Throwing
+});
+
+// thenable 이 콜백 이후에 오류를 throw
+// Promise 이행
+var thenable = { then: function(resolve) {
+  resolve("Resolving");
+  throw new TypeError("Throwing");
+}};
+
+var p3 = Promise.resolve(thenable);
+p3.then(function(v) {
+  console.log(v); // "Resolving"
+}, function(e) {
+  // 호출되지 않음
+});
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('ES6', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ES6')}}ECMA 표준에서 초기 정의.
{{SpecName('ESDraft', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Promise.resolve")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/promise/then/index.html b/files/ko/web/javascript/reference/global_objects/promise/then/index.html new file mode 100644 index 0000000000..b7f79eee9c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/promise/then/index.html @@ -0,0 +1,308 @@ +--- +title: Promise.prototype.then() +slug: Web/JavaScript/Reference/Global_Objects/Promise/then +tags: + - ECMAScript6 + - JavaScript + - Method + - Promise + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/then +--- +
{{JSRef}}
+ +

then() 메서드는 {{domxref("Promise")}}를 리턴하고 두 개의 콜백 함수를 인수로 받습니다. 하나는 Promise이행했을 때, 다른 하나는 거부했을 때를 위한 콜백 함수입니다.

+ +
{{EmbedInteractiveExample("pages/js/promise-then.html")}}
+ + + +
+

매개변수 중 하나 이상을 생략했거나 함수가 아닌 값을 전달한 경우, then은 핸들러가 없는 것이 되지만 오류를 발생하지는 않습니다. then 바로 이전의 Promisethen에 핸들러가 없는 상태로 완료(이행이나 거부)했을 경우, 추가 핸들러가 없는 Promise가 생성되며, 원래 Promise의 마지막 상태를 그대로 물려받습니다.

+
+ +

구문

+ +
p.then(onFulfilled, onRejected);
+
+p.then(function(value) {
+  // 이행
+}, function(reason) {
+  // 거부
+});
+
+ +

매개변수

+ +
+
onFulfilled
+
Promise가 수행될 때 호출되는 {{jsxref("Function")}}으로, 이행 값(fulfillment value) 하나를 인수로 받습니다.
+
onRejected
+
Promise가 거부될 때 호출되는 {{jsxref("Function")}}으로, 거부 이유(rejection reason) 하나를 인수로 받습니다.
+
+ +

반환값

+ +

{{jsxref("Promise")}}가 이행하거나 거부했을 때, 각각에 해당하는 핸들러 함수(onFulfilledonRejected)가 비동기적으로 실행됩니다. 핸들러 함수는 다음 규칙을 따라 실행됩니다.

+ + + +

다음 예제에서 then 메서드의 비동기성을 확인할 수 있습니다.

+ +
// 이행한 프로미스를 받으면 'then' 블록도 바로 실행되지만,
+// 핸들러는 아래 console.log에서와 같이 비동기적으로 실행됨
+const resolvedProm = Promise.resolve(33);
+
+let thenProm = resolvedProm.then(value => {
+    console.log("이 부분은 호출 스택 이후에 실행됩니다. 전달받은 값이자 반환값은 " + value + "입니다.");
+    return value;
+});
+// thenProm의 값을 즉시 기록
+console.log(thenProm);
+
+// setTimeout으로 함수 실행을 호출 스택이 빌 때까지 미룰 수 있음
+setTimeout(() => {
+    console.log(thenProm);
+});
+
+
+// 로그 출력 결과 (순서대로):
+// Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
+// "이 부분은 호출 스택 이후에 실행됩니다. 전달받은 값이자 반환값은 33입니다."
+// Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: 33}
+ +

설명

+ +

then과 {{jsxref("Promise.prototype.catch()")}} 메서드는 프로미스를 반환하기 때문에, 체이닝이 가능합니다. 이를 합성이라고도 합니다.

+ +

예제

+ +

then 메서드 사용

+ +
var p1 = new Promise(function(resolve, reject) {
+  resolve("성공!");
+  // 또는
+  // reject("오류!");
+});
+
+p1.then(function(value) {
+  console.log(value); // 성공!
+}, function(reason) {
+  console.log(reason); // 오류!
+});
+
+ +

체이닝

+ +

then 메서드는 Promise를 리턴하기 때문에, 이어지는 then 호출들을 손쉽게 연결할 수 있습니다.

+ +

then에 핸들러로 전달된 함수가 프로미스를 반환할 경우, 이와 동등한 프로미스가 메서드 체인의 그다음 then에 노출됩니다. 아래 예제에서는 setTimeout 함수로 비동기 코드를 흉내냅니다.

+ +
Promise.resolve('foo')
+  // 1. "foo"를 받고 "bar"를 추가한 다음 그 값으로 이행하여 다음 then에 넘겨줌
+  .then(function(string) {
+    return new Promise(function(resolve, reject) {
+      setTimeout(function() {
+        string += 'bar';
+        resolve(string);
+      }, 1);
+    });
+  })
+  // 2. "foobar"를 받고 그대로 다음 then에 넘겨준 뒤,
+  // 나중에 콜백 함수에서 가공하고 콘솔에 출력
+  .then(function(string) {
+    setTimeout(function() {
+      string += 'baz';
+      console.log(string);
+    }, 1)
+    return string;
+  })
+  // 3. 이 부분의 코드는 이전의 then 블록 안의 (가짜) 비동기 코드에서
+  // 실제로 문자열을 가공하기 전에 실행됨
+  .then(function(string) {
+    console.log("마지막 Then: 앗... 방금 then에서 프로미스 만들고 반환하는 걸 까먹어서 " +
+                "출력 순서가 좀 이상할지도 몰라요");
+
+    // 'baz' 부분은 setTimeout 함수로 비동기적으로 실행되기 때문에
+    // 이곳의 string에는 아직 'baz' 부분이 없음
+    console.log(string);
+  });
+
+// 로그 출력 결과 (순서대로):
+// 마지막 Then: 앗... 방금 then에서 프로미스 만들고 반환하는 걸 까먹어서 출력 순서가 좀 이상할지도 몰라요
+// foobar
+// foobarbaz
+ +

then 핸들러에서 값을 그대로 반환한 경우에는 Promise.resolve(<핸들러에서 반환한 값>)을 반환하는 것과 같습니다.

+ +
var p2 = new Promise(function(resolve, reject) {
+  resolve(1);
+});
+
+p2.then(function(value) {
+  console.log(value); // 1
+  return value + 1;
+}).then(function(value) {
+  console.log(value + ' - 동기적으로 짜도 돌아감');
+});
+
+p2.then(function(value) {
+  console.log(value); // 1
+});
+
+ +

함수에서 오류가 발생하거나 거부한 프로미스를 반환한 경우 then에서는 거부한 프로미스를 반환합니다.

+ +
Promise.resolve()
+  .then(() => {
+    // .then()에서 거부한 프로미스를 반환함
+    throw new Error('으악!');
+  })
+  .then(() => {
+    console.log('실행되지 않는 코드');
+  }, error => {
+    console.error('onRejected 함수가 실행됨: ' + error.message);
+  });
+ +

이외의 모든 경우에는 곧 이행할(비동기적으로 실행되는) 프로미스를 반환합니다. 다음 예제에서는 바로 이전의 프로미스가 거부했음에도 첫 번째 then에서는 42의 값을 갖는 곧 이행할 프로미스를 반환합니다.

+ +
Promise.reject()
+  .then(() => 99, () => 42) // onRejected에서는 42를 곧 이행할 프로미스로 감싸서 반환함
+  .then(solution => console.log(solution + '로 이행함')); // 42로 이행함
+ +

실제 개발 시에는 아래와 같이 거부한 프로미스를 then의 2단 핸들러보다는 catch를 사용해 처리하는 경우가 많습니다.

+ +
Promise.resolve()
+  .then(() => {
+    // .then()에서 거부한 프로미스를 반환함
+    throw new Error('으악!');
+  })
+  .catch(error => {
+    console.error('onRejected 함수가 실행됨: ' + error.message);
+  })
+  .then(() => {
+    console.log("처음 then의 프로미스가 거부했지만 그래도 이 코드는 실행됨");
+  });
+ +


+ 체이닝을 이용해 프로미스 기반 함수 위에 다른 프로미스 기반 함수를 구현할 수도 있습니다.

+ +
function fetch_current_data() {
+  // fetch() API는 프로미스를 반환합니다. 이 함수도
+  // API가 비슷하지만, 이 함수의 프로미스는
+  // 추가 작업을 거친 이후에 이행값을 반환합니다.
+  return fetch('current-data.json').then(response => {
+    if (response.headers.get('content-type') != 'application/json') {
+      throw new TypeError();
+    }
+    var j = response.json();
+    // j 가공하기
+    return j; // fetch_current_data().then()을 통해
+              // 이행값을 사용할 수 있음
+  });
+}
+
+ +

onFulfilled가 프로미스를 반환할 경우, then의 반환값 역시 그 프로미스에 의해 이행/거부합니다.

+ +
function resolveLater(resolve, reject) {
+  setTimeout(function() {
+    resolve(10);
+  }, 1000);
+}
+function rejectLater(resolve, reject) {
+  setTimeout(function() {
+    reject(new Error('오류'));
+  }, 1000);
+}
+
+var p1 = Promise.resolve('foo');
+var p2 = p1.then(function() {
+  // 1초 뒤에 10으로 이행할 프로미스 반환
+  return new Promise(resolveLater);
+});
+p2.then(function(v) {
+  console.log('이행', v);  // "이행", 10
+}, function(e) {
+  // 실행되지 않음
+  console.log('거부', e);
+});
+
+var p3 = p1.then(function() {
+  // 1초 뒤에 '오류'로 거부할 프로미스 반환
+  return new Promise(rejectLater);
+});
+p3.then(function(v) {
+  // 실행되지 않음
+  console.log('이행', v);
+}, function(e) {
+  console.log('거부', e); // "거부", '오류'
+});
+
+ +

{{domxref("window.setImmediate")}}의 프로미스 기반 폴리필

+ +

{{jsxref("Function.prototype.bind()")}} Reflect.apply ({{jsxref("Reflect.apply()")}}) 메서드를 사용하여 (취소할 수 없는) setImmedate와 비슷한 함수를 생성합니다.

+ +
const nextTick = (() => {
+  const noop = () => {}; // literally
+  const nextTickPromise = () => Promise.resolve().then(noop);
+
+  const rfab = Reflect.apply.bind; // (thisArg, fn, thisArg, [...args])
+  const nextTick = (fn, ...args) => (
+    fn !== undefined
+    ? Promise.resolve(args).then(rfab(null, fn, null))
+    : nextTickPromise(),
+    undefined
+  );
+  nextTick.ntp = nextTickPromise;
+
+  return nextTick;
+})();
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ES6')}}ECMA 표준에서 초기 정의.
{{SpecName('ESDraft', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + + + +

{{Compat("javascript.builtins.Promise.then")}}

+ + + +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html b/files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html new file mode 100644 index 0000000000..b4928da1d8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/proxy/handler/apply/index.html @@ -0,0 +1,154 @@ +--- +title: handler.apply() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply +tags: + - apply트랩 + - 트랩 + - 프록시 +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply +--- +
{{JSRef}}
+ +

handler.apply() 메소드는 함수호출 시를 위한 트랩(trap)이다.

+ +

문법

+ +
var p = new Proxy(target, {
+  apply: function(target, thisArg, argumentsList) {
+  }
+});
+
+ +

인자

+ +

apply 메소드에는 다음과 같은 인자가 들어온다.. this는 handler를 가리킨다.

+ +
+
target
+
대상이 되는 객체(함수)
+
thisArg
+
호출 시 바인딩 된 this
+
argumentsList
+
호출 시 전달된 인자목록.
+
+ +

반환 값

+ +

apply 메소드는 어떤 값이든 반환할 수 있다.

+ +

설명

+ +

handler.apply 메소드는 함수호출 시를 위한 트랩이다.

+ +

가로채기

+ +

이 트랩은 다음과 같은 것들을 가로챌 수 있다:

+ + + +

기본(불변)조건

+ +

handler.apply 메소드에 대한 특별히 지켜야 할 기본조건은 없다.

+ +

예제

+ +

다음의 코드는 함수 호출 시에 트랩을 건다.

+ +
var p = new Proxy(function() {}, {
+  apply: function(target, thisArg, argumentsList) {
+    console.log('호출됨: ' + argumentsList.join(', '));
+    return argumentsList[0] + argumentsList[1] + argumentsList[2];
+  }
+});
+
+console.log(p(1, 2, 3)); // "호출됨: 1, 2, 3"
+                         // 6
+
+ +

관련 명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}{{Spec2('ESDraft')}} 
+ +

브라우저별 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop("18")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("18")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

관련 내용

+ + diff --git a/files/ko/web/javascript/reference/global_objects/proxy/handler/index.html b/files/ko/web/javascript/reference/global_objects/proxy/handler/index.html new file mode 100644 index 0000000000..9eebe33b2f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/proxy/handler/index.html @@ -0,0 +1,81 @@ +--- +title: Proxy handler +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler +tags: + - ECMAScript 2015 + - JavaScript + - Proxy +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy +--- +
{{JSRef}}
+ +

The proxy's handler object is a placeholder object which contains traps for {{jsxref("Proxy", "proxies", "", 1)}}.

+ +

Methods

+ +

All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target.

+ +
+
{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}}
+
A trap for {{jsxref("Object.getPrototypeOf")}}.
+
{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}}
+
A trap for {{jsxref("Object.setPrototypeOf")}}.
+
{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}
+
A trap for {{jsxref("Object.isExtensible")}}.
+
{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}
+
A trap for {{jsxref("Object.preventExtensions")}}.
+
{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}
+
A trap for {{jsxref("Object.getOwnPropertyDescriptor")}}.
+
{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}
+
A trap for {{jsxref("Object.defineProperty")}}.
+
{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}
+
A trap for the {{jsxref("Operators/in", "in")}} operator.
+
{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}
+
A trap for getting property values.
+
{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}
+
A trap for setting property values.
+
{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}
+
A trap for the {{jsxref("Operators/delete", "delete")}} operator.
+
{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}
+
A trap for {{jsxref("Object.getOwnPropertyNames")}} and {{jsxref("Object.getOwnPropertySymbols")}}.
+
{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}
+
A trap for a function call.
+
{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}
+
A trap for the {{jsxref("Operators/new", "new")}} operator.
+
+ +

Some non-standard traps are obsolete and have been removed.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}{{Spec2('ESDraft')}}The enumerate handler has been removed.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Proxy.handler")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/proxy/index.html b/files/ko/web/javascript/reference/global_objects/proxy/index.html new file mode 100644 index 0000000000..777b4648d0 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/proxy/index.html @@ -0,0 +1,394 @@ +--- +title: Proxy +slug: Web/JavaScript/Reference/Global_Objects/Proxy +tags: + - ECMAScript 2015 + - JavaScript + - Proxy + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy +--- +
{{JSRef}}
+ +

Proxy 객체는 기본적인 동작(속성 접근, 할당, 순회, 열거, 함수 호출 등)의 새로운 행동을 정의할 때 사용합니다.

+ +

용어

+ +
+
handler
+
trap들을 가지고 있는 Placeholder 객체.
+
traps
+
프로퍼티에 접근할 수 있는 메소드. 운영체제에서 trap 이라는 컨셉과 유사하다.
+
target
+
proxy가 가상화하는 실제 객체. 이것은 proxy를 위한  backend 저장소로 사용된다.   Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.
+
+ +

구문

+ +
new Proxy(target, handler);
+
+ +

매개변수

+ +
+
target
+
proxy와 함께 감싸진 target  객체 (native array, function, 다른 proxy을 포함한 객체)
+
handler
+
프로퍼티들이 function 인  객체이다. 동작이 수행될 때, handler는 proxy의 행동을 정의한다.
+
+ +

메서드

+ +
+
{{jsxref("Proxy.revocable()")}}
+
폐기할 수 있는(revocable) Proxy 객체를 생성.
+
+ +

Methods of the handler object

+ +

handler객체는 Proxy를 위한 trap들을 포함하고 있는 placeholder 객체이다.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler', 'Methods') }}
+ +

예제

+ +

Basic example

+ +

프로퍼티 이름이 객체에 없을때, 기본값을 숫자 37로 리턴받는 간단한 예제이다. 이것은 get handler 를 사용하였다. 

+ +
var handler = {
+    get: function(target, name){
+        return name in target?
+            target[name] :
+            37;
+    }
+};
+
+var p = new Proxy({}, handler);
+p.a = 1;
+p.b = undefined;
+
+console.log(p.a, p.b); // 1, undefined
+console.log('c' in p, p.c); // false, 37
+
+ +

No-op forwarding proxy

+ +

이 예제에서는, native JavaScript를 사용하겠다. proxy는 적용된 모든 동작으로 보낼 것이다.

+ +
var target = {};
+var p = new Proxy(target, {});
+
+p.a = 37; // target으로 동작이 전달
+
+console.log(target.a); // 37. 동작이 제대로 전달됨
+
+ +

Validation (검증)

+ +

Proxy에서, 객체에 전달된 값을 쉽게 검증할 수 있다. 이 예제는 set handler 를 사용하였다.

+ +
let validator = {
+  set: function(obj, prop, value) {
+    if (prop === 'age') {
+      if (!Number.isInteger(value)) {
+        throw new TypeError('The age is not an integer');
+      }
+      if (value > 200) {
+        throw new RangeError('The age seems invalid');
+      }
+    }
+
+    // The default behavior to store the value
+    obj[prop] = value;
+  }
+};
+
+let person = new Proxy({}, validator);
+
+person.age = 100;
+console.log(person.age); // 100
+person.age = 'young'; // Throws an exception
+person.age = 300; // Throws an exception
+
+ +

Extending constructor (생성자 확장)

+ +

function proxy는 쉽게 새로운 생성자와 함께 생성자를 확장할 수 있다. 이 예제에서는 construct 와 apply handlers 를 사용하였다.

+ +
function extend(sup,base) {
+  var descriptor = Object.getOwnPropertyDescriptor(
+    base.prototype,"constructor"
+  );
+  base.prototype = Object.create(sup.prototype);
+  var handler = {
+    construct: function(target, args) {
+      var obj = Object.create(base.prototype);
+      this.apply(target,obj,args);
+      return obj;
+    },
+    apply: function(target, that, args) {
+      sup.apply(that,args);
+      base.apply(that,args);
+    }
+  };
+  var proxy = new Proxy(base,handler);
+  descriptor.value = proxy;
+  Object.defineProperty(base.prototype, "constructor", descriptor);
+  return proxy;
+}
+
+var Person = function(name){
+  this.name = name;
+};
+
+var Boy = extend(Person, function(name, age) {
+  this.age = age;
+});
+
+Boy.prototype.sex = "M";
+
+var Peter = new Boy("Peter", 13);
+console.log(Peter.sex);  // "M"
+console.log(Peter.name); // "Peter"
+console.log(Peter.age);  // 13
+ +

Manipulating DOM nodes (DOM nodes 조작)

+ +

가끔씩, 두 개의 다른 element의 속성이나 클래스 이름을 바꾸고 싶을 것이다. 아래는 set handler 를 사용하였다.

+ +
let view = new Proxy({
+  selected: null
+},
+{
+  set: function(obj, prop, newval) {
+    let oldval = obj[prop];
+
+    if (prop === 'selected') {
+      if (oldval) {
+        oldval.setAttribute('aria-selected', 'false');
+      }
+      if (newval) {
+        newval.setAttribute('aria-selected', 'true');
+      }
+    }
+
+    // The default behavior to store the value
+    obj[prop] = newval;
+  }
+});
+
+let i1 = view.selected = document.getElementById('item-1');
+console.log(i1.getAttribute('aria-selected')); // 'true'
+
+let i2 = view.selected = document.getElementById('item-2');
+console.log(i1.getAttribute('aria-selected')); // 'false'
+console.log(i2.getAttribute('aria-selected')); // 'true'
+
+ +

Value correction and an extra property (값 정정과 추가적인 property)

+ +

products 라는 proxy 객체는 전달된 값을 평가하고, 필요할 때 배열로 변환한다. 이 객체는 latestBrowser 라는 추가적인 property를 지원하는데, getter와 setter 모두 지원한다. 

+ +
let products = new Proxy({
+  browsers: ['Internet Explorer', 'Netscape']
+},
+{
+  get: function(obj, prop) {
+    // An extra property
+    if (prop === 'latestBrowser') {
+      return obj.browsers[obj.browsers.length - 1];
+    }
+
+    // The default behavior to return the value
+    return obj[prop];
+  },
+  set: function(obj, prop, value) {
+    // An extra property
+    if (prop === 'latestBrowser') {
+      obj.browsers.push(value);
+      return;
+    }
+
+    // Convert the value if it is not an array
+    if (typeof value === 'string') {
+      value = [value];
+    }
+
+    // The default behavior to store the value
+    obj[prop] = value;
+  }
+});
+
+console.log(products.browsers); // ['Internet Explorer', 'Netscape']
+products.browsers = 'Firefox'; // pass a string (by mistake)
+console.log(products.browsers); // ['Firefox'] <- no problem, the value is an array
+
+products.latestBrowser = 'Chrome';
+console.log(products.browsers); // ['Firefox', 'Chrome']
+console.log(products.latestBrowser); // 'Chrome'
+
+ +

Finding an array item object by its property (property로 배열의 객체를 찾기)

+ +

proxy 는 유용한 특성을 가진 배열로 확장할 것이다. Object.defineProperties를 사용하지 않고, 유연하게 property들을 유연하게 "정의"할 수 있다. 이 예제는 테이블의 cell을 이용해서 row(열)을 찾는데 적용할 수 있다. 이 경우, target은 table.rows가 될 것이다.

+ +
let products = new Proxy([
+  { name: 'Firefox', type: 'browser' },
+  { name: 'SeaMonkey', type: 'browser' },
+  { name: 'Thunderbird', type: 'mailer' }
+],
+{
+  get: function(obj, prop) {
+    // The default behavior to return the value; prop is usually an integer
+    if (prop in obj) {
+      return obj[prop];
+    }
+
+    // Get the number of products; an alias of products.length
+    if (prop === 'number') {
+      return obj.length;
+    }
+
+    let result, types = {};
+
+    for (let product of obj) {
+      if (product.name === prop) {
+        result = product;
+      }
+      if (types[product.type]) {
+        types[product.type].push(product);
+      } else {
+        types[product.type] = [product];
+      }
+    }
+
+    // Get a product by name
+    if (result) {
+      return result;
+    }
+
+    // Get products by type
+    if (prop in types) {
+      return types[prop];
+    }
+
+    // Get product types
+    if (prop === 'types') {
+      return Object.keys(types);
+    }
+
+    return undefined;
+  }
+});
+
+console.log(products[0]); // { name: 'Firefox', type: 'browser' }
+console.log(products['Firefox']); // { name: 'Firefox', type: 'browser' }
+console.log(products['Chrome']); // undefined
+console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }]
+console.log(products.types); // ['browser', 'mailer']
+console.log(products.number); // 3
+
+ +

A complete traps list example (완벽한 traps 리스트 예제)

+ +

이제 완벽한 traps 리스트를 생성하기 위해서, non native 객체를 프록시화 할 것이다. 이것은 특히, 다음과 같은 동작에 적합하다 : the "little framework" published on the document.cookie page 에 의해 생성된 docCookies 는 글로벌 객체

+ +
/*
+  var docCookies = ... get the "docCookies" object here:
+  https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support
+*/
+
+var docCookies = new Proxy(docCookies, {
+  get: function (oTarget, sKey) {
+    return oTarget[sKey] || oTarget.getItem(sKey) || undefined;
+  },
+  set: function (oTarget, sKey, vValue) {
+    if (sKey in oTarget) { return false; }
+    return oTarget.setItem(sKey, vValue);
+  },
+  deleteProperty: function (oTarget, sKey) {
+    if (sKey in oTarget) { return false; }
+    return oTarget.removeItem(sKey);
+  },
+  enumerate: function (oTarget, sKey) {
+    return oTarget.keys();
+  },
+  ownKeys: function (oTarget, sKey) {
+    return oTarget.keys();
+  },
+  has: function (oTarget, sKey) {
+    return sKey in oTarget || oTarget.hasItem(sKey);
+  },
+  defineProperty: function (oTarget, sKey, oDesc) {
+    if (oDesc && "value" in oDesc) { oTarget.setItem(sKey, oDesc.value); }
+    return oTarget;
+  },
+  getOwnPropertyDescriptor: function (oTarget, sKey) {
+    var vValue = oTarget.getItem(sKey);
+    return vValue ? {
+      value: vValue,
+      writable: true,
+      enumerable: true,
+      configurable: false
+    } : undefined;
+  },
+});
+
+/* Cookies test */
+
+console.log(docCookies.my_cookie1 = "First value");
+console.log(docCookies.getItem("my_cookie1"));
+
+docCookies.setItem("my_cookie1", "Changed value");
+console.log(docCookies.my_cookie1);
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ES2016')}} 
{{SpecName('ES2017', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ES2017')}} 
{{SpecName('ESDraft', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.Proxy", 2)}}

+ +

같이 보기

+ + + +

라이센스 참고사항

+ +

Some content (text, examples) in this page has been copied or adapted from the ECMAScript wiki which content is licensed CC 2.0 BY-NC-SA.

diff --git a/files/ko/web/javascript/reference/global_objects/rangeerror/index.html b/files/ko/web/javascript/reference/global_objects/rangeerror/index.html new file mode 100644 index 0000000000..7413433c34 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/rangeerror/index.html @@ -0,0 +1,163 @@ +--- +title: RangeError +slug: Web/JavaScript/Reference/Global_Objects/RangeError +translation_of: Web/JavaScript/Reference/Global_Objects/RangeError +--- +
{{JSRef}}
+ +

RangeError 객체는 값이 집합에 없거나 허용되지 않은 값의 범위일 때 에러를 나타냅니다.

+ +

구문 

+ +
new RangeError([message[, fileName[, lineNumber]]])
+ +

파라메터

+ +
+
message
+
선택적 파라메터. 에러에 대한 설명.
+
fileName {{non-standard_inline}}
+
선택적 파라메터. 예외(exception)가 발생한 코드를 포함하고 있는 파일의 이름.
+
lineNumber {{non-standard_inline}}
+
선택적 파라메터. 예외(exception)가 발생한 코드의 라인 넘버.
+
+ +

설명

+ +

RangeError 는 허용되지 않은 범위의 수를 포함한 아규먼트를 함수에 넘기려고 할 때 던져집니다. {{jsxref("Array")}} 생성자로 허용범위를 초과한 길이의 배열 생성을 시도하려 하거나,  적절하지 않은 값을 numeric method({{jsxref("Number.toExponential()")}}, {{jsxref("Number.toFixed()")}} 또는 {{jsxref("Number.toPrecision()")}})에 넘기려 할 때, 이 에러를 만날 수 있을 것입니다.  

+ +

속성

+ +
+
{{jsxref("RangeError.prototype")}}
+
RangeError 객체에 속성을 추가하도록 해준다. 
+
+ +

메소드

+ +

전역(global)의 RangeError는 자신의 메소드를 가지고 있지 않습니다. 하지만, 몇 가지의 메소드를 프로토타입 체인을 통해 상속받습니다.

+ +

RangeError 인스턴스

+ +

속성

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError/prototype', 'Properties')}}
+ +

메소드

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError/prototype', 'Methods')}}
+ +

+ +

RangeError 사용하기

+ +
var check = function(num) {
+  if (num < MIN || num > MAX) {
+    throw new RangeError('Parameter must be between ' + MIN + ' and ' + MAX);
+  }
+};
+
+try {
+  check(500);
+}
+catch (e) {
+  if (e instanceof RangeError) {
+    // Handle range error
+  }
+}
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의.
{{SpecName('ES5.1', '#sec-15.11.6.2', 'RangeError')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-rangeerror', 'RangeError')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-rangeerror', 'RangeError')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/referenceerror/index.html b/files/ko/web/javascript/reference/global_objects/referenceerror/index.html new file mode 100644 index 0000000000..ed5fee8c48 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/referenceerror/index.html @@ -0,0 +1,129 @@ +--- +title: ReferenceError +slug: Web/JavaScript/Reference/Global_Objects/ReferenceError +translation_of: Web/JavaScript/Reference/Global_Objects/ReferenceError +--- +
{{JSRef}}
+ +
+

ReferenceError 객체는 존재하지 않는 변수를 참조했을 때 발생하는 에러를 나타냅니다.

+
+ +

문법

+ +
new ReferenceError([message[, fileName[, lineNumber]]])
+ +

파라미터

+ +
+
message
+
선택사항. 에러에 대한 설명문
+
fileName {{non-standard_inline}}
+
선택사항. 예외가 발생한 코드를 포함하는 파일의 이름
+
lineNumber {{non-standard_inline}}
+
선택사항. 예외가 발생한 코드의 줄 번호
+
+ +

설명

+ +

ReferenceError는 선언된 적이 없는 변수를 참조하려고 할 때 발생합니다.

+ +

프로퍼티

+ +
+
{{jsxref("ReferenceError.prototype")}}
+
ReferenceError 객체에 프로퍼티를 추가할 수 있습니다.
+
+ +

메서드

+ +

전역 ReferenceError는 메서드를 가지고 있지 않습니다. 그러나 상속 관계에서 프로토타입 체인을 통해 일부 메서드를 가질 수 있습니다.

+ +

ReferenceError 인스턴스

+ +

프로퍼티

+ +
{{page('/ko-KR/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError/prototype', 'Properties')}}
+ +

메서드

+ +
{{page('/ko-KR/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError/prototype', 'Methods')}}
+ +

예제

+ +

ReferenceError 처리하기

+ +
try {
+  var a = undefinedVariable;
+} catch (e) {
+  console.log(e instanceof ReferenceError); // true
+  console.log(e.message);                   // "undefinedVariable is not defined"
+  console.log(e.name);                      // "ReferenceError"
+  console.log(e.fileName);                  // "Scratchpad/1"
+  console.log(e.lineNumber);                // 2
+  console.log(e.columnNumber);              // 6
+  console.log(e.stack);                     // "@Scratchpad/2:2:7\n"
+}
+
+ +

ReferenceError 생성하기

+ +
try {
+  throw new ReferenceError('Hello', 'someFile.js', 10);
+} catch (e) {
+  console.log(e instanceof ReferenceError); // true
+  console.log(e.message);                   // "Hello"
+  console.log(e.name);                      // "ReferenceError"
+  console.log(e.fileName);                  // "someFile.js"
+  console.log(e.lineNumber);                // 10
+  console.log(e.columnNumber);              // 0
+  console.log(e.stack);                     // "@Scratchpad/2:2:9\n"
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.11.6.3', 'ReferenceError')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-referenceerror', 'ReferenceError')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-referenceerror', 'ReferenceError')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.ReferenceError")}}

+
+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/apply/index.html b/files/ko/web/javascript/reference/global_objects/reflect/apply/index.html new file mode 100644 index 0000000000..a9146a0952 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/apply/index.html @@ -0,0 +1,93 @@ +--- +title: Reflect.apply() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/apply +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/apply +--- +
{{JSRef}}
+ +

Reflect.apply() 정적 메서드는 대상 함수를 주어진 매개변수로 호출합니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-apply.html")}}
+ + + +

구문

+ +
Reflect.apply(target, thisArgument, argumentsList)
+
+ +

매개변수

+ +
+
target
+
호출할 대상 함수.
+
thisArgument
+
호출에서 targetthis로 사용할 값.
+
argumentsList
+
target을 호출할 때 매개변수로 전달할 배열형 객체.
+
+ +

반환 값

+ +

주어진 this 값과 매개변수로 대상 함수를 호출한 결과.

+ +

예외

+ +

target이 호출 가능한 객체가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

ES5에서는 {{jsxref("Function.prototype.apply()")}} 메서드를 사용해, 함수를 호출할 때 this 값을 지정하거나 매개변수를 배열(또는 배열형 객체)에서 넘겨줄 수 있었습니다.

+ +
Function.prototype.apply.call(Math.floor, undefined, [1.75]);
+ +

Reflect.apply() 메서드를 사용해 같은 작업을 더 쉽고 유려하게 수행할 수 있습니다.

+ +

예제

+ +

Reflect.apply() 사용하기

+ +
Reflect.apply(Math.floor, undefined, [1.75]);
+// 1;
+
+Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]);
+// "hello"
+
+Reflect.apply(RegExp.prototype.exec, /ab/, ['confabulation']).index;
+// 4
+
+Reflect.apply(''.charAt, 'ponies', [3]);
+// "i"
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-reflect.apply', 'Reflect.apply')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.apply")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/construct/index.html b/files/ko/web/javascript/reference/global_objects/reflect/construct/index.html new file mode 100644 index 0000000000..e98f3204de --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/construct/index.html @@ -0,0 +1,154 @@ +--- +title: Reflect.construct() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/construct +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/construct +--- +
{{JSRef}}
+ +

Reflect.construct() 정적 메서드는 new 연산자처럼 동작하는 함수입니다. new target(...args)를 호출하는 것과 같습니다. 추가 기능으로 다른 프로토타입을 지정할 수도 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-construct.html")}}
+ + + +

구문

+ +
Reflect.construct(target, argumentsList[, newTarget])
+
+ +

매개변수

+ +
+
target
+
호출할 대상 함수.
+
argumentsList
+
target의 매개변수로 전달할 배열형 객체.
+
newTarget {{optional_inline}}
+
프로토타입으로 사용할 생성자. new.target 연산자도 확인하세요. newTarget이 주어지지 않았을 땐 target을 사용합니다.
+
+ +

반환 값

+ +

target을 생성자로 하고 주어진 매개변수를 전달해 생성한 target(또는, 지정했다면 newTarget)의 새로운 인스턴스.

+ +

예외

+ +

target 또는 newTarget이 생성자가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

Reflect.construct()는 생성자를 가변 길이의 매개변수로 호출할 수 있습니다. (new 연산자전개 구문을 사용해도 가능합니다)

+ +
var obj = new Foo(...args);
+var obj = Reflect.construct(Foo, args);
+
+ +

Reflect.construct() vs Object.create()

+ +

Reflect의 도입 이전에는 임의의 생성자와 프로토타입에 {{jsxref("Object.create()")}}를 사용해 객체를 생성할 수 있었습니다.

+ +
function OneClass() {
+    this.name = 'one';
+}
+
+function OtherClass() {
+    this.name = 'other';
+}
+
+// Calling this:
+var obj1 = Reflect.construct(OneClass, args, OtherClass);
+
+// ...has the same result as this:
+var obj2 = Object.create(OtherClass.prototype);
+OneClass.apply(obj2, args);
+
+console.log(obj1.name); // 'one'
+console.log(obj2.name); // 'one'
+
+console.log(obj1 instanceof OneClass); // false
+console.log(obj2 instanceof OneClass); // false
+
+console.log(obj1 instanceof OtherClass); // true
+console.log(obj2 instanceof OtherClass); // true
+
+ +

그러나, 결과는 동일하더라도 과정에는 중요한 차이가 하나 존재합니다. Object.create()와 {{jsxref("Function.prototype.apply()")}}를 사용할 땐, 객체 생성에 new 키워드가 관여하지 않으므로 new.target 연산자가 undefined를 가리킵니다.

+ +

반면 Reflect.construct()를 호출하면, newTarget이 존재하면 new.target 연산자가 newTarget을, 아니면 target을 가리킵니다.

+ +
function OneClass() {
+    console.log('OneClass');
+    console.log(new.target);
+}
+function OtherClass() {
+    console.log('OtherClass');
+    console.log(new.target);
+}
+
+var obj1 = Reflect.construct(OneClass, args);
+// Output:
+//     OneClass
+//     function OneClass { ... }
+
+var obj2 = Reflect.construct(OneClass, args, OtherClass);
+// Output:
+//     OneClass
+//     function OtherClass { ... }
+
+var obj3 = Object.create(OtherClass.prototype);
+OneClass.apply(obj3, args);
+// Output:
+//     OneClass
+//     undefined
+
+ +

예제

+ +

Reflect.construct() 사용하기

+ +
var d = Reflect.construct(Date, [1776, 6, 4]);
+d instanceof Date; // true
+d.getFullYear(); // 1776
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.construct', 'Reflect.construct')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.construct', 'Reflect.construct')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.construct")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/defineproperty/index.html b/files/ko/web/javascript/reference/global_objects/reflect/defineproperty/index.html new file mode 100644 index 0000000000..a88d2bd722 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/defineproperty/index.html @@ -0,0 +1,100 @@ +--- +title: Reflect.defineProperty() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty +--- +
{{JSRef}}
+ +

Reflect.defineProperty() 정적 메서드는 {{jsxref("Object.defineProperty()")}}와 같은 동작을 하지만 {{jsxref("Boolean")}}을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-defineproperty.html")}}
+ + + +

구문

+ +
Reflect.defineProperty(target, propertyKey, attributes)
+
+ +

매개변수

+ +
+
target
+
속성을 정의할 대상 객체.
+
propertyKey
+
정의하거나 수정할 속성의 이름.
+
attributes
+
정의하거나 수정하는 속성을 기술하는 객체.
+
+ +

반환 값

+ +

속성이 성공적으로 정의됐는지 나타내는 {{jsxref("Boolean")}}.

+ +

예외

+ +

target이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

Reflect.defineProperty 메서드는 객체에 속성을 정교하게 추가하거나 수정할 수 있습니다. 자세한 내용은 유사한 메서드인 {{jsxref("Object.defineProperty")}}를 참고하세요. Object.defineProperty는 성공 시 대상 객체를 반환하고 실패하면 {{jsxref("TypeError")}}를 던지지만, Reflect.defineProperty는 성공 여부를 나타내는 {{jsxref("Boolean")}}을 반환합니다.

+ +

예제

+ +

Reflect.defineProperty() 사용하기

+ +
var obj = {};
+Reflect.defineProperty(obj, 'x', {value: 7}); // true
+obj.x; // 7
+
+ +

속성 정의의 성공 여부 알아내기

+ +

{{jsxref("Object.defineProperty")}}는 성공 시 객체를 반환하고, 실패 시 {{jsxref("TypeError")}}를 던지므로 속성 정의 과정에 발생할 수 있는 오류를 try...catch 블록으로 잡아야 합니다. 반면 Reflect.defineProperty는 성공 여부를 나타내는 {{jsxref("Boolean")}}을 반환하므로, 간단하게 if...else 블록만 사용하면 됩니다.

+ +
if (Reflect.defineProperty(target, property, attributes)) {
+  // 성공
+} else {
+  // 실패
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.defineproperty', 'Reflect.defineProperty')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.defineproperty', 'Reflect.defineProperty')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.defineProperty")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/deleteproperty/index.html b/files/ko/web/javascript/reference/global_objects/reflect/deleteproperty/index.html new file mode 100644 index 0000000000..de3b8f8ed8 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/deleteproperty/index.html @@ -0,0 +1,98 @@ +--- +title: Reflect.deleteProperty() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/deleteProperty +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/deleteProperty +--- +
{{JSRef}}
+ +

Reflect.deleteProperty() 정적 메서드는 속성을 제거할 수 있습니다. delete 연산자의 함수판이라고 할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-deleteproperty.html", "taller")}}
+ + + +

구문

+ +
Reflect.deleteProperty(target, propertyKey)
+
+ +

매개변수

+ +
+
target
+
속성을 제거할 대상 객체.
+
propertyKey
+
제거할 속성의 이름.
+
+ +

반환 값

+ +

속성이 성공적으로 제거됐는지 나타내는 {{jsxref("Boolean")}}.

+ +

Exceptions

+ +

target이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

Reflect.deleteProperty 메서드는 객체의 속성을 제거할 수 있습니다. 반환값은 속성의 제거 성공 여부를 나타내는 {{jsxref("Boolean")}}입니다. 비엄격 모드의 delete 연산자와 거의 동일합니다.

+ +

예제

+ +

Reflect.deleteProperty() 사용하기

+ +
var obj = { x: 1, y: 2 };
+Reflect.deleteProperty(obj, 'x'); // true
+obj; // { y: 2 }
+
+var arr = [1, 2, 3, 4, 5];
+Reflect.deleteProperty(arr, '3'); // true
+arr; // [1, 2, 3, , 5]
+
+// 주어진 속성이 존재하지 않으면 true 반환
+Reflect.deleteProperty({}, 'foo'); // true
+
+// 주어진 속성이 설정 불가능하면 false 반환
+Reflect.deleteProperty(Object.freeze({foo: 1}), 'foo'); // false
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.deleteproperty', 'Reflect.deleteProperty')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.deleteproperty', 'Reflect.deleteProperty')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.deleteProperty")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/get/index.html b/files/ko/web/javascript/reference/global_objects/reflect/get/index.html new file mode 100644 index 0000000000..2d5007b113 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/get/index.html @@ -0,0 +1,100 @@ +--- +title: Reflect.get() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/get +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/get +--- +
{{JSRef}}
+ +

Reflect.get() 정적 메서드는 객체의 속성을 가져오는 함수입니다. target[propertyKey]와 비슷합니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-get.html")}}
+ + + +

구문

+ +
Reflect.get(target, propertyKey[, receiver])
+
+ +

매개변수

+ +
+
target
+
속성을 가져올 대상 객체.
+
propertyKey
+
가져올 속성의 이름.
+
receiver {{optional_inline}}
+
대상 속성이 접근자라면 this의 값으로 사용할 값. {{jsxref("Proxy")}}와 함께 사용하면, 대상을 상속하는 객체를 사용할 수 있습니다.
+
+ +

반환 값

+ +

속성의 값.

+ +

예외

+ +

target이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

Reflect.get 메서드는 객체 속성의 값을 가져올 수 있습니다. 속성 접근자의 함수판이라고 할 수 있습니다.

+ +

예제

+ +

Reflect.get() 사용하기

+ +
// Object
+var obj = { x: 1, y: 2 };
+Reflect.get(obj, 'x'); // 1
+
+// Array
+Reflect.get(['zero', 'one'], 1); // "one"
+
+// handler 매개변수와 Proxy
+var x = {p: 1};
+var obj = new Proxy(x, {
+  get(t, k, r) { return k + 'bar'; }
+});
+Reflect.get(obj, 'foo'); // "foobar"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.get', 'Reflect.get')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.get', 'Reflect.get')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.get")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.html b/files/ko/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.html new file mode 100644 index 0000000000..273f5b7011 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/getownpropertydescriptor/index.html @@ -0,0 +1,103 @@ +--- +title: Reflect.getOwnPropertyDescriptor() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/getOwnPropertyDescriptor +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/getOwnPropertyDescriptor +--- +
{{JSRef}}
+ +

Reflect.getOwnPropertyDescriptor() 정적 메서드는 객체에 주어진 속성이 존재하면, 해당 속성의 서술자를 반환합니다. {{jsxref("Object.getOwnPropertyDescriptor()")}}와 유사합니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-getownpropertydescriptor.html")}}
+ + + +

구문

+ +
Reflect.getOwnPropertyDescriptor(target, propertyKey)
+
+ +

매개변수

+ +
+
target
+
속성을 탐색할 객체.
+
propertyKey
+
자체 속성 서술자를 가져올 속성의 이름.
+
+ +

반환 값

+ +

대상 속성이 객체에 존재하면, 그 속성의 서술자. 존재하지 않으면 {{jsxref("undefined")}}.

+ +

예제

+ +

target이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

Reflect.getOwnPropertyDescriptor 메서드는 객체 속성의 서술자를 반환합니다. 만약 존재하지 않는 속성이라면 {{jsxref("undefined")}}를 대신 반환합니다. {{jsxref("Object.getOwnPropertyDescriptor()")}}와의 유일한 차이는 객체가 아닌 대상의 처리 방법입니다.

+ +

예제

+ +

Reflect.getOwnPropertyDescriptor() 사용하기

+ +
Reflect.getOwnPropertyDescriptor({x: 'hello'}, 'x');
+// {value: "hello", writable: true, enumerable: true, configurable: true}
+
+Reflect.getOwnPropertyDescriptor({x: 'hello'}, 'y');
+// undefined
+
+Reflect.getOwnPropertyDescriptor([], 'length');
+// {value: 0, writable: true, enumerable: false, configurable: false}
+
+ +

Object.getOwnPropertyDescriptor()와의 차이점

+ +

Reflect.getOwnPropertyDescriptor()의 첫 번째 매개변수가 객체가 아니고 {{glossary("Primitive", "원시값")}}이라면 {{jsxref("TypeError")}}가 발생합니다. 반면 {{jsxref("Object.getOwnPropertyDescriptor()")}}는 같은 상황에서 값을 우선 객체로 변환합니다.

+ +
Reflect.getOwnPropertyDescriptor('foo', 0);
+// TypeError: "foo" is not non-null object
+
+Object.getOwnPropertyDescriptor('foo', 0);
+// { value: "f", writable: false, enumerable: true, configurable: false }
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.getownpropertydescriptor', 'Reflect.getOwnPropertyDescriptor')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.getownpropertydescriptor', 'Reflect.getOwnPropertyDescriptor')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.getOwnPropertyDescriptor")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/getprototypeof/index.html b/files/ko/web/javascript/reference/global_objects/reflect/getprototypeof/index.html new file mode 100644 index 0000000000..f0d2f2d19c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/getprototypeof/index.html @@ -0,0 +1,104 @@ +--- +title: Reflect.getPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/getPrototypeOf +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/getPrototypeOf +--- +
{{JSRef}}
+ +

Reflect.getPrototypeOf() 정적 메서드는 주어진 객체의 프로토타입을 반환합니다. {{jsxref("Object.getPrototypeOf()")}}와 거의 동일합니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-getprototypeof.html")}}
+ + + +

구문

+ +
Reflect.getPrototypeOf(target)
+
+ +

매개변수

+ +
+
target
+
프로토타입을 가져올 대상 객체.
+
+ +

반환 값

+ +

주어진 객체의 프로토타입. 상속한 속성이 없으면 {{jsxref("null")}}을 반환합니다.

+ +

예외

+ +

target이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

Reflect.getPrototypeOf() 메서드는 주어진 객체의 프로토타입([[Prototype]] 내부 객체의 값 등)을 반환합니다.

+ +

예제

+ +

Reflect.getPrototypeOf() 사용하기

+ +
Reflect.getPrototypeOf({}); // Object.prototype
+Reflect.getPrototypeOf(Object.prototype); // null
+Reflect.getPrototypeOf(Object.create(null)); // null
+
+ +

Object.getPrototypeOf()와 비교

+ +
// 객체에는 동일한 결과
+Object.getPrototypeOf({});  // Object.prototype
+Reflect.getPrototypeOf({}); // Object.prototype
+
+// ES5에서는 비객체 대상에서 모두 오류
+Object.getPrototypeOf('foo');  // Throws TypeError
+Reflect.getPrototypeOf('foo'); // Throws TypeError
+
+// ES2015에서는 Reflect만 오류, Object는 객체로 변환
+Object.getPrototypeOf('foo');  // String.prototype
+Reflect.getPrototypeOf('foo'); // Throws TypeError
+
+// ES2015 Object 동작을 따라하려면 객체 변환과정 필요
+Reflect.getPrototypeOf(Object('foo')); // String.prototype
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.getprototypeof', 'Reflect.getPrototypeOf')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.getprototypeof', 'Reflect.getPrototypeOf')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.getPrototypeOf")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/has/index.html b/files/ko/web/javascript/reference/global_objects/reflect/has/index.html new file mode 100644 index 0000000000..363b4d0366 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/has/index.html @@ -0,0 +1,97 @@ +--- +title: Reflect.has() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/has +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/has +--- +
{{JSRef}}
+ +

Reflect.has() 정적 메서드는 in 연산자의 함수판입니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-has.html")}}
+ + + +

구문

+ +
Reflect.has(target, propertyKey)
+
+ +

매개변수

+ +
+
target
+
속성을 탐색할 객체.
+
propertyKey
+
탐색할 속성의 이름.
+
+ +

반환 값

+ +

객체가 속성을 가지고 있는지 나타내는 {{jsxref("Boolean")}}.

+ +

예외

+ +

target이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

Reflect.has() 메서드는 객체에 속성이 존재하는지 판별할 수 있습니다. in 연산자처럼 동작합니다.

+ +

예제

+ +

Reflect.has() 사용하기

+ +
Reflect.has({x: 0}, 'x'); // true
+Reflect.has({x: 0}, 'y'); // false
+
+// 프로토타입 체인에 존재하는 속성도 true 반환
+Reflect.has({x: 0}, 'toString');
+
+// .has() 처리기 메서드를 가진 Proxy
+obj = new Proxy({}, {
+  has(t, k) { return k.startsWith('door'); }
+});
+Reflect.has(obj, 'doorbell'); // true
+Reflect.has(obj, 'dormitory'); // false
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.has', 'Reflect.has')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.has', 'Reflect.has')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.has")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/index.html b/files/ko/web/javascript/reference/global_objects/reflect/index.html new file mode 100644 index 0000000000..728dcd74c3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/index.html @@ -0,0 +1,106 @@ +--- +title: Reflect +slug: Web/JavaScript/Reference/Global_Objects/Reflect +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect +--- +
{{JSRef}}
+ +

Reflect는 중간에서 가로챌 수 있는 JavaScript 작업에 대한 메서드를 제공하는 내장 객체입니다. 메서드의 종류는 프록시 처리기와 동일합니다. Reflect는 함수 객체가 아니므로 생성자로 사용할 수 없습니다.

+ +

설명

+ +

다른 대부분의 전역 객체와 다르게, Reflect는 생성자가 아닙니다. 따라서 함수처럼 호출하거나 new 연산자로 인스턴스를 만들 수 없습니다. {{jsxref("Math")}} 객체처럼, Reflect의 모든 속성과 메서드는 정적입니다.

+ +

Reflect 객체의 정적 메서드 이름은 프록시 처리기 메서드의 이름과 같습니다.

+ +

일부 메서드는 {{jsxref("Object")}}에도 존재하는 메서드이지만 약간의 차이가 있습니다.

+ +

정적 메서드

+ +
+
{{jsxref("Reflect.apply()")}}
+
대상 함수를 주어진 매개변수로 호출합니다. {{jsxref("Function.prototype.apply()")}}도 참고하세요.
+
{{jsxref("Reflect.construct()")}}
+
함수로 사용하는 new 연산자입니다. new target(...args)을 호출하는 것과 같습니다. 다른 프로토타입을 지정하는 추가 기능도 가지고 있습니다.
+
{{jsxref("Reflect.defineProperty()")}}
+
{{jsxref("Object.defineProperty()")}}와 비슷합니다. {{jsxref("Boolean")}}을 반환합니다.
+
{{jsxref("Reflect.deleteProperty()")}}
+
함수로 사용하는 delete 연산자입니다. delete target[name]을 호출하는 것과 같습니다.
+
{{jsxref("Reflect.get()")}}
+
대상 속성의 값을 반환하는 함수입니다.
+
{{jsxref("Reflect.getOwnPropertyDescriptor()")}}
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}와 비슷합니다. 주어진 속성이 대상 객체에 존재하면, 그 속성의 서술자를 반환합니다. 그렇지 않으면 {{jsxref("undefined")}}를 반환합니다.
+
{{jsxref("Reflect.getPrototypeOf()")}}
+
{{jsxref("Object.getPrototypeOf()")}}와 같습니다.
+
{{jsxref("Reflect.has()")}}
+
함수로 사용하는 in 연산자입니다. 자신의, 혹은 상속한 속성이 존재하는지 나타내는 {{jsxref("Boolean")}}을 반환합니다.
+
{{jsxref("Reflect.isExtensible()")}}
+
{{jsxref("Object.isExtensible()")}}과 같습니다.
+
{{jsxref("Reflect.ownKeys()")}}
+
대상 객체의 자체 키(상속하지 않은 키) 목록을 배열로 반환합니다.
+
{{jsxref("Reflect.preventExtensions()")}}
+
{{jsxref("Object.preventExtensions()")}}와 비슷합니다. {{jsxref("Boolean")}}을 반환합니다.
+
{{jsxref("Reflect.set()")}}
+
속성에 값을 할당하는 함수입니다. 할당 성공 여부를 나타내는 {{jsxref("Boolean")}}을 반환합니다.
+
{{jsxref("Reflect.setPrototypeOf()")}}
+
객체의 프로토타입을 지정하는 함수입니다. 지정 성공 여부를 나타내는 {{jsxref("Boolean")}}을 반환합니다.
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-reflect-object', 'Reflect')}}
+ +

예제

+ +

객체가 특정 속성을 가지고 있는지 검사하기

+ +
const duck = {
+  name: 'Maurice',
+  color: 'white',
+  greeting: function() {
+    console.log(`Quaaaack! My name is ${this.name}`);
+  }
+}
+
+Reflect.has(duck, 'color');
+// true
+Reflect.has(duck, 'haircut');
+// false
+ +

객체 자체 키를 반환하기

+ +
Reflect.ownKeys(duck);
+// [ "name", "color", "greeting" ]
+ +

객체에 새로운 속성 추가하기

+ +
Reflect.set(duck, 'eyes', 'black');
+// returns "true" if successful
+// "duck" now contains the property "eyes: 'black'"
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/isextensible/index.html b/files/ko/web/javascript/reference/global_objects/reflect/isextensible/index.html new file mode 100644 index 0000000000..68d168eb65 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/isextensible/index.html @@ -0,0 +1,111 @@ +--- +title: Reflect.isExtensible() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/isExtensible +--- +
{{JSRef}}
+ +

Reflect.isExtensible() 정적 메서드는 객체의 확장 가능 여부, 즉 속성을 추가할 수 있는지 판별합니다. {{jsxref("Object.isExtensible()")}}과 유사하지만 {{anch("Object.isExtensible()과의 차이", "차이점")}}도 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-isextensible.html", "taller")}}
+ + + +

구문

+ +
Reflect.isExtensible(target)
+
+ +

매개변수

+ +
+
target
+
확장 가능 여부를 판별할 대상 객체.
+
+ +

반환 값

+ +

객체의 확장 가능 여부를 나타내는 {{jsxref("Boolean")}}.

+ +

예외

+ +

target이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

Reflect.isExtensible() 메서드는 {{jsxref("Object.isExtensible()")}}와 유사하게, 객체에 새로운 속성을 추가할 수 있는지 판별합니다.

+ +

예제

+ +

Reflect.isExtensible() 사용하기

+ +

{{jsxref("Object.isExtensible()")}}도 참고하세요.

+ +
// 새로운 객체는 확장 가능
+var empty = {};
+Reflect.isExtensible(empty); // === true
+
+// ...하지만 바꿀 수 있음
+Reflect.preventExtensions(empty);
+Reflect.isExtensible(empty); // === false
+
+// 봉인한 객체는 확장 불가능함
+var sealed = Object.seal({});
+Reflect.isExtensible(sealed); // === false
+
+// 동결한 객체도 확장 불가능함
+var frozen = Object.freeze({});
+Reflect.isExtensible(frozen); // === false
+
+ +

Object.isExtensible()과의 차이점

+ +

Reflect.isExtensible()은 첫 번째 매개변수가 {{glossary("Primitive", "원시값")}}이면 {{jsxref("TypeError")}}를 던집니다. 반면 {{jsxref("Object.isExtensible()")}}은 우선 객체로 변환을 시도합니다.

+ +
Reflect.isExtensible(1);
+// TypeError: 1 is not an object
+
+Object.isExtensible(1);
+// false
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.isextensible', 'Reflect.isExtensible')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.isextensible', 'Reflect.isExtensible')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.isExtensible")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/ownkeys/index.html b/files/ko/web/javascript/reference/global_objects/reflect/ownkeys/index.html new file mode 100644 index 0000000000..41c350ca60 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/ownkeys/index.html @@ -0,0 +1,95 @@ +--- +title: Reflect.ownKeys() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys +--- +
{{JSRef}}
+ +

Reflect.ownKeys() 정적 메서드는 대상 객체의 자체 속성 키를 배열로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-ownkeys.html")}}
+ + + +

구문

+ +
Reflect.ownKeys(target)
+
+ +

매개변수

+ +
+
target
+
자체 키를 가져올 대상 객체.
+
+ +

반환 값

+ +

주어진 객체의 자체 속성 키를 담은 {{jsxref("Array")}}.

+ +

예외

+ +

target이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

The Reflect.ownKeys() 메서드는 대상 객체의 자체 속성 키를 배열로 반환합니다. 반환 값은 {{jsxref("Object.getOwnPropertyNames", "Object.getOwnPropertyNames(target)", "", 1)}}.concat({{jsxref("Object.getOwnPropertySymbols", "Object.getOwnPropertySymbols(target)", "", 1)}})와 동일합니다.

+ +

예제

+ +

Reflect.ownKeys() 사용하기

+ +
Reflect.ownKeys({z: 3, y: 2, x: 1}); // [ "z", "y", "x" ]
+Reflect.ownKeys([]); // ["length"]
+
+var sym = Symbol.for('comet');
+var sym2 = Symbol.for('meteor');
+var obj = {[sym]: 0, 'str': 0, '773': 0, '0': 0,
+           [sym2]: 0, '-1': 0, '8': 0, 'second str': 0};
+Reflect.ownKeys(obj);
+// [ "0", "8", "773", "str", "-1", "second str", Symbol(comet), Symbol(meteor) ]
+// Indexes in numeric order,
+// strings in insertion order,
+// symbols in insertion order
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.ownkeys', 'Reflect.ownKeys')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.ownkeys', 'Reflect.ownKeys')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.ownKeys")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/preventextensions/index.html b/files/ko/web/javascript/reference/global_objects/reflect/preventextensions/index.html new file mode 100644 index 0000000000..364b46a5fa --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/preventextensions/index.html @@ -0,0 +1,103 @@ +--- +title: Reflect.preventExtensions() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/preventExtensions +--- +
{{JSRef}}
+ +

Reflect.preventExtensions() 정적 메서드는 새로운 속성을 객체에 추가하지 못하도록 완전히 막습니다. 즉, 미래의 객체 확장을 막습니다. {{jsxref("Object.preventExtensions()")}}와 유사하지만 {{anch("Object.preventExtensions()와의 차이점", "차이점")}}도 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-preventextensions.html")}}
+ + + +

구문

+ +
Reflect.preventExtensions(target)
+
+ +

매개변수

+ +
+
target
+
확장을 방지할 대상 객체.
+
+ +

반환 값

+ +

대상의 확장을 성공적으로 방지했는지 나타내는 {{jsxref("Boolean")}}.

+ +

예외

+ +

target이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

Reflect.preventExtensions() 메서드는 새로운 속성을 객체에 추가하지 못하도록 완전히 막습니다. 즉, 미래의 객체 확장을 막습니다. {{jsxref("Object.preventExtensions()")}}와 유사합니다.

+ +

예제

+ +

Reflect.preventExtensions() 사용하기

+ +

{{jsxref("Object.preventExtensions()")}}도 참고하세요.

+ +
// 객체는 기본적으로 확장 가능
+var empty = {};
+Reflect.isExtensible(empty); // === true
+
+// ...하지만 바꿀 수 있음
+Reflect.preventExtensions(empty);
+Reflect.isExtensible(empty); // === false
+
+ +

Object.preventExtensions()와의 차이점

+ +

Reflect.preventExtensions()는 첫 번째 매개변수가 {{glossary("Primitive", "원시값")}}이면 {{jsxref("TypeError")}}를 던집니다. 반면 {{jsxref("Object.preventExtensions()")}}는 우선 객체로 변환을 시도합니다.

+ +
Reflect.preventExtensions(1);
+// TypeError: 1 is not an object
+
+Object.preventExtensions(1);
+// 1
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.preventextensions', 'Reflect.preventExtensions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.preventextensions', 'Reflect.preventExtensions')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.preventExtensions")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/set/index.html b/files/ko/web/javascript/reference/global_objects/reflect/set/index.html new file mode 100644 index 0000000000..f3cfc3a532 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/set/index.html @@ -0,0 +1,108 @@ +--- +title: Reflect.set() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/set +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/set +--- +
{{JSRef}}
+ +

Reflect.set() 정적 메서드는 객체 속성의 값을 설정합니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-set.html")}}
+ + + +

구문

+ +
Reflect.set(target, propertyKey, value[, receiver])
+
+ +

매개변수

+ +
+
target
+
속성의 값을 설정할 대상 객체.
+
propertyKey
+
값을 설정할 속성의 이름.
+
value
+
설정할 값.
+
receiver {{optional_inline}}
+
속성이 설정자일 경우, this로 사용할 값.
+
+ +

반환 값

+ +

값 설정의 성공 여부를 나타내는 {{jsxref("Boolean")}}.

+ +

예외

+ +

target이 {{jsxref("Object")}}가 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

Reflect.set() 메서드는 객체 속성의 값을 설정할 수 있습니다. 속성 추가도 할 수 있으며, 함수라는 점을 제외하면 동작 방식은 속성 접근자와 같습니다.

+ +

예제

+ +

Reflect.set() 사용하기

+ +
// Object
+var obj = {};
+Reflect.set(obj, 'prop', 'value'); // true
+obj.prop; // "value"
+
+// Array
+var arr = ['duck', 'duck', 'duck'];
+Reflect.set(arr, 2, 'goose'); // true
+arr[2]; // "goose"
+
+// 배열 자르기
+Reflect.set(arr, 'length', 1); // true
+arr; // ["duck"];
+
+// 매개변수를 하나만 제공하면 속성 키 이름은 문자열 "undefined", 값은 undefined
+var obj = {};
+Reflect.set(obj); // true
+Reflect.getOwnPropertyDescriptor(obj, 'undefined');
+// { value: undefined, writable: true, enumerable: true, configurable: true }
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect.set', 'Reflect.set')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect.set', 'Reflect.set')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.set")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/reflect/setprototypeof/index.html b/files/ko/web/javascript/reference/global_objects/reflect/setprototypeof/index.html new file mode 100644 index 0000000000..3e97b9b385 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/reflect/setprototypeof/index.html @@ -0,0 +1,88 @@ +--- +title: Reflect.setPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Reflect/setPrototypeOf +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/setPrototypeOf +--- +
{{JSRef}}
+ +

Reflect.setPrototypeOf() 정적 메서드는 주어진 객체의 프로토타입(내부 [[Prototype]] 속성)을 다른 객체나 {{jsxref("null")}}로 바꿉니다. 반환 값을 제외하면 {{jsxref("Object.setPrototypeOf()")}} 메서드와 같습니다.

+ +
{{EmbedInteractiveExample("pages/js/reflect-setprototypeof.html")}}
+ + + +

구문

+ +
Reflect.setPrototypeOf(target, prototype)
+
+ +

매개변수

+ +
+
target
+
프로토타입을 지정할 대상 객체.
+
prototype
+
대상 객체의 새로운 프로토타입. (객체 또는 {{jsxref("null")}}
+
+ +

반환 값

+ +

프로토타입 설정 성공 여부를 나타내는 {{jsxref("Boolean")}}.

+ +

예외

+ +

target이 {{jsxref("Object")}}가 아니거나, prototype이 객체도 {{jsxref("null")}}도 아니면 {{jsxref("TypeError")}}.

+ +

설명

+ +

Reflect.setPrototypeOf() 메서드는 주어진 객체의 프로토타입(즉, 내부 [[Prototype]] 속성)을 변경합니다.

+ +

예제

+ +

Reflect.setPrototypeOf() 사용하기

+ +
Reflect.setPrototypeOf({}, Object.prototype); // true
+
+// It can change an object's [[Prototype]] to null.
+Reflect.setPrototypeOf({}, null); // true
+
+// Returns false if target is not extensible.
+Reflect.setPrototypeOf(Object.freeze({}), null); // false
+
+// Returns false if it cause a prototype chain cycle.
+const target = {};
+const proto = Object.create(target);
+Reflect.setPrototypeOf(target, proto); // false
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-reflect.setprototypeof', 'Reflect.setPrototypeOf')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Reflect.setPrototypeOf")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html b/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html new file mode 100644 index 0000000000..4659688c51 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html @@ -0,0 +1,188 @@ +--- +title: RegExp.prototype.exec() +slug: Web/JavaScript/Reference/Global_Objects/RegExp/exec +tags: + - JavaScript + - Method + - Prototype + - Reference + - RegExp + - 정규 표현식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/exec +--- +
{{JSRef}}
+ +

exec() 메서드는 주어진 문자열에서 일치 탐색을 수행한 결과를 배열 혹은 {{jsxref("null")}}로 반환합니다.

+ +

JavaScript {{jsxref("RegExp")}} 객체는 {{jsxref("RegExp.global", "global")}} 또는 {{jsxref("RegExp.sticky", "sticky")}} 플래그를 설정(/foo/g, /foo/y 등)한 경우 이전 일치의 인덱스를 저장하므로 상태를 가지고(stateful) 있습니다. 이를 내부적으로 사용하여, {{jsxref("String.prototype.match()")}}와는 다르게 (캡처 그룹을 포함한) 문자열 내의 일치 다수를 반복해 순회할 수 있습니다.

+ +

(캡처 그룹을 포함한) 문자열 내의 다수 일치를 수행할 수 있는 보다 간편한 신규 메서드,  {{jsxref("String.prototype.matchAll()")}}이 제안된 상태입니다.

+ +

단순히 true/false가 필요한 경우 {{jsxref("RegExp.prototype.text()")}} 메서드 혹은 {{jsxref("String.prototype.search()")}}를 사용하세요.

+ +
{{EmbedInteractiveExample("pages/js/regexp-prototype-exec.html")}}
+ + + +

구문

+ +
regexObj.exec(str)
+ +

매개변수

+ +
+
str
+
정규 표현식 검색을 수행할 대상 문자열.
+
+ +

반환 값

+ +

정규 표현식이 일치하면, exec() 메서드는 배열(추가 속성 indexinput 포함, 아래 설명을 참고하세요)을 반환하고, 정규 표현식 객체의 {{jsxref("RegExp.lastIndex", "lastIndex")}} 속성을 업데이트합니다. 반환하는 배열은 일치한 텍스트를 첫 번째 원소로, 각각의 괄호 캡처 그룹을 이후 원소로 포함합니다.

+ +

정규표현식 검색에 실패하면, exec() 메서드는 {{jsxref("null")}}을 반환하고 {{jsxref("RegExp.lastIndex", "lastIndex")}}를 0으로 설정합니다.

+ +

설명

+ +

다음과 같은 예제를 고려해보세요.

+ +
// Match "quick brown" followed by "jumps", ignoring characters in between
+// Remember "brown" and "jumps"
+// Ignore case
+let re = /quick\s(brown).+?(jumps)/ig;
+let result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');
+ +

다음의 표는 이 스크립트의 결과에 대해 보여줍니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
객체속성/인덱스설명예제
result[0]일치한 전체 문자."Quick Brown Fox Jumps"
[1], ...[n] +

(존재하는 경우) 괄호로 감싼 부분문자열.

+ +

괄호로 감싼 부분문자열 숫자의 제한은 없습니다.

+
+

result[1] === "Brown"

+ +

result[2] === "Jumps"

+
index일치가 문자열에서 위치하는 인덱스. (0 시작)4
input원본 문자열."The Quick Brown Fox Jumps Over The Lazy Dog"
relastIndex +

다음 일치를 시작할 인덱스.

+ +

g를 누락하면 항상 0입니다.

+
25
ignoreCasei 플래그로 대소문자를 무시했는지 여부.true
globalg 플래그로 전역 일치를 수행하는지 여부.true
multilinem 플래그로 여러 줄에 걸친 탐색을 수행하는지 여부.false
source패턴 문자열."quick\s(brown).+?(jumps)"
+ +

예제

+ +

Finding successive matches

+ +

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's {{jsxref("RegExp.lastIndex", "lastIndex")}} property ({{jsxref("RegExp.prototype.test()", "test()")}} will also advance the {{jsxref("RegExp.lastIndex", "lastIndex")}} property). For example, assume you have this script:

+ +
var myRe = /ab*/g;
+var str = 'abbcdefabh';
+var myArray;
+while ((myArray = myRe.exec(str)) !== null) {
+  var msg = 'Found ' + myArray[0] + '. ';
+  msg += 'Next match starts at ' + myRe.lastIndex;
+  console.log(msg);
+}
+
+ +

This script displays the following text:

+ +
Found abb. Next match starts at 3
+Found ab. Next match starts at 9
+
+ +

Note: Do not place the regular expression literal (or {{jsxref("RegExp")}} constructor) within the while condition or it will create an infinite loop if there is a match due to the {{jsxref("RegExp.lastIndex", "lastIndex")}} property being reset upon each iteration. Also be sure that the global flag is set or a loop will occur here also.

+ +

Using exec() with RegExp literals

+ +

You can also use exec() without creating a {{jsxref("RegExp")}} object:

+ +
var matches = /(hello \S+)/.exec('This is a hello world!');
+console.log(matches[1]);
+
+ +

This will log a message containing 'hello world!'.

+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-regexp.prototype.exec', 'RegExp.exec')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.RegExp.exec")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/regexp/index.html b/files/ko/web/javascript/reference/global_objects/regexp/index.html new file mode 100644 index 0000000000..541d3585db --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/index.html @@ -0,0 +1,233 @@ +--- +title: RegExp +slug: Web/JavaScript/Reference/Global_Objects/RegExp +tags: + - Constructor + - JavaScript + - Reference + - RegExp + - 정규 표현식 + - 정규식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp +--- +
{{JSRef}}
+ +

RegExp 생성자는 패턴을 사용해 텍스트를 판별할 때 사용합니다.

+ +

정규 표현식에 대한 소개는 JavaScript 안내서의 정규 표현식 장을 참고하세요.

+ +

설명

+ +

리터럴 표기법과 생성자

+ +

RegExp 객체는 리터럴 표기법과 생성자로써 생성할 수 있습니다.

+ + + +

다음의 세 표현식은 모두 같은 정규 표현식을 생성합니다.

+ +
/ab+c/i
+new RegExp(/ab+c/, 'i') // 리터럴
+new RegExp('ab+c', 'i') // 생성자
+
+ +

리터럴 표기법은 표현식을 평가할 때 정규 표현식을 컴파일합니다. 정규 표현식이 변하지 않으면 리터럴 표기법을 사용하세요. 예를 들어, 반복문 안에서 사용할 정규 표현식을 리터럴 표기법으로 생성하면 정규 표현식을 매번 다시 컴파일하지 않습니다.

+ +

정규 표현식 객체의 생성자(new RegExp('ab+c'))를 사용하면 정규 표현식이 런타임에 컴파일됩니다. 패턴이 변할 가능성이 있거나, 사용자 입력과 같이 알 수 없는 외부 소스에서 가져오는 정규 표현식의 경우 생성자 함수를 사용하세요.

+ +

생성자의 플래그

+ +

ECMAScript 6부터는 new RegExp(/ab+c/, 'i')처럼, 첫 매개변수가 RegExp이면서 flags를 지정해도 {{jsxref("TypeError")}} ("can't supply flags when constructing one RegExp from another")가 발생하지 않고, 매개변수로부터 새로운 정규 표현식을 생성합니다.

+ +

생성자 함수를 사용할 경우 보통의 문자열 이스케이프 규칙(특수 문자를 문자열에 사용할 때 앞에 역빗금(\)을 붙이는 것)을 준수해야 합니다.

+ +

예를 들어 다음 두 줄은 동일한 정규 표현식을 생성합니다.

+ +
let re = /\w+/
+let re = new RegExp('\\w+')
+ +

Perl  형태의 RegExp 속성

+ +

일부 {{JSxRef("RegExp")}} 속성은 같은 값에 대해 긴 이름과 짧은 (Perl 형태의) 이름 모두 가지고 있습니다. (Perl은 JavaScript가 정규 표현식을 만들 때 참고한 프로그래밍 언어입니다.)  사용하지 않는 RegExp 속성을 참고하세요.

+ +

생성자

+ +
+
{{jsxref("RegExp/RegExp", "RegExp()")}}
+
새로운 RegExp 객체를 생성합니다.
+
+ +

정적 속성

+ +
+
{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}
+
파생 객체를 생성할 때 사용하는 생성자입니다.
+
{{jsxref("RegExp.lastIndex")}}
+
다음 판별을 시작할 인덱스입니다.
+
+ +

인스턴스 속성

+ +
+
{{JSxRef("RegExp.prototype.flags")}}
+
RegExp 객체의 플래그를 담은 문자열입니다.
+
{{JSxRef("RegExp.prototype.dotAll")}}
+
.이 줄 바꿈에 일치하는지 여부를 나타냅니다.
+
{{JSxRef("RegExp.prototype.global")}}
+
정규 표현식이 문자열 내에서 가능한 모든 경우에 일치하는지, 아니면 최초에 대해서만 일치하는지 나타냅니다.
+
{{JSxRef("RegExp.prototype.ignoreCase")}}
+
문자열의 대소문자를 구분하는지 나타냅니다.
+
{{JSxRef("RegExp.prototype.multiline")}}
+
여러 줄에 걸쳐 탐색할 것인지 나타냅니다.
+
{{JSxRef("RegExp.prototype.source")}}
+
패턴을 나타내는 문자열입니다.
+
{{JSxRef("RegExp.prototype.sticky")}}
+
검색이 접착(sticky)되어있는지 나타냅니다.
+
{{JSxRef("RegExp.prototype.unicode")}}
+
Unicode 기능의 활성화 여부입니다.
+
+ +

인스턴스 메서드

+ +
+
{{JSxRef("RegExp.prototype.compile()")}}
+
스크립트 실행 중 정규 표현식을 (다시) 컴파일합니다.
+
{{JSxRef("RegExp.prototype.exec()")}}
+
문자열 매개변수에 대해 검색을 실행합니다.
+
{{JSxRef("RegExp.prototype.test()")}}
+
문자열 매개변수에 대해 판별을 실행합니다.
+
{{JSxRef("RegExp.prototype.toString()")}}
+
객체의 문자열 표현을 반환합니다. {{JSxRef("Object.prototype.toString()")}} 메서드를 재정의합니다.
+
{{JSxRef("RegExp.prototype.@@match()", "RegExp.prototype[@@match]()")}}
+
주어진 문자열에 대해 일치하는 결과를 반환합니다.
+
{{JSxRef("RegExp.prototype.@@matchAll()", "RegExp.prototype[@@matchAll]()")}}
+
주어진 문자열에 대해 일치하는 모든 결과를 반환합니다.
+
{{JSxRef("RegExp.prototype.@@replace()", "RegExp.prototype[@@replace]()")}}
+
주어진 문자열 내의 일치를 새로운 문자열로 대치합니다.
+
{{JSxRef("RegExp.prototype.@@search()", "RegExp.prototype[@@search]()")}}
+
주어진 문자열에 대해 일치하는 인덱스를 반환합니다.
+
{{JSxRef("RegExp.prototype.@@split()", "RegExp.prototype[@@split]()")}}
+
주어진 문자열을 분할해 배열로 반환합니다.
+
+ +

예제

+ +

정규 표현식을 사용해서 데이터 형식 바꾸기

+ +

다음 스크립트에서는 {{jsxref("String")}} 객체의 {{jsxref("String.prototype.replace()", "replace()")}} 메서드를 사용하여 이름 성씨 형태의 이름을 성씨, 이름 형태 바꿔 반환합니다.

+ +

대치 문자열에는 $1$2를 사용하여 정규 표현식 패턴의 각 괄호에 일치한 결과를 받아옵니다.

+ +
let re = /(\w+)\s(\w+)/
+let str = 'John Smith'
+let newstr = str.replace(re, '$2, $1')
+console.log(newstr)
+ +

실행 결과는 "Smith, John"입니다.

+ +

정규 표현식을 사용해서 여러 가지 줄 바꿈 문자가 있는 문자열 나누기

+ +

기본 줄 바꿈 문자는 플랫폼(Unix, Windows 등)마다 다릅니다. 아래의 분할 스크립트는 모든 플랫폼의 줄 바꿈을 인식합니다.

+ +
let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'
+let lines = text.split(/\r\n|\r|\n/)
+console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
+ +

정규 표현식 패턴의 순서를 바꾸면 작동하지 않을 수 있습니다.

+ +

여러 줄에서 정규 표현식 사용하기

+ +
let s = 'Please yes\nmake my day!'
+
+s.match(/yes.*day/);
+// Returns null
+
+s.match(/yes[^]*day/);
+// Returns ["yes\nmake my day"]
+ +

접착 플래그와 함께 사용하기

+ +

{{JSxRef("Global_Objects/RegExp/sticky", "sticky")}} 플래그는 해당 정규 표현식이 접착 판별, 즉 {{jsxref("RegExp.prototype.lastIndex")}}에서 시작하는 일치만 확인하도록 할 수 있습니다.

+ +
let str = '#foo#'
+let regex = /foo/y
+
+regex.lastIndex = 1
+regex.test(str)      // true
+regex.lastIndex = 5
+regex.test(str)      // false (lastIndex is taken into account with sticky flag)
+regex.lastIndex      // 0 (reset after match failure)
+ +

접착과 전역 플래그의 차이

+ +

접착 플래그 y의 일치는 정확히 lastIndex 위치에서만 발생할 수 있으나, 전역 플래그 g의 경우 lastIndex 또는 그 이후에서도 발생할 수 있습니다.

+ +
re = /\d/y;
+while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex);
+
+// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
+// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
+// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
+//   ... and no more match.
+ +

전역 플래그 g를 사용했다면, 3개가 아니고 6개 숫자 모두 일치했을 것입니다.

+ +

정규 표현식과 Unicode 문자

+ +

 \w\Wa부터 z, A부터 Z, 0부터 9 _ 등의 {{glossary("ASCII")}} 문자에만 일치합니다.

+ +

러시아어나 히브리어와 같은 다른 언어의 문자까지 일치하려면 \uhhhh(이때 hhhh는 해당 문자의 16진법 Unicode 값) 문법을 사용하세요. 아래 예제에서는 문자열에서 Unicode 문자를 추출합니다.

+ +
let text = 'Образец text на русском языке'
+let regex = /[\u0400-\u04FF]+/g
+
+let match = regex.exec(text)
+console.log(match[0])        // logs 'Образец'
+console.log(regex.lastIndex) // logs '7'
+
+let match2 = regex.exec(text)
+console.log(match2[0])       // logs 'на' [did not log 'text']
+console.log(regex.lastIndex) // logs '15'
+
+// and so on
+ +

유니코드 속성 이스케이프 기능을 사용해 \p{scx=Cyrl}과 같은 간단한 구문으로 이 문제를 해결할 수 있습니다.

+ +

URL에서 서브도메인 추출하기

+ +
let url = 'http://xxx.domain.com'
+console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'
+ +
+

이 때는 정규표현식보단 URL API를 통해 브라우저에 내장된 URL 구문 분석기를 사용하는 것이 좋습니다.

+
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}
+ +

브라우저 호환성

+ + + +
{{Compat("javascript.builtins.RegExp")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/regexp/n/index.html b/files/ko/web/javascript/reference/global_objects/regexp/n/index.html new file mode 100644 index 0000000000..5b6706cad2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/n/index.html @@ -0,0 +1,66 @@ +--- +title: RegExp.$1-$9 +slug: Web/JavaScript/Reference/Global_Objects/RegExp/n +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/n +--- +
{{JSRef}} {{non-standard_header}}
+ +

비표준 $1, $2, $3, $4, $5, $6, $7, $8, $9 속성들은 정적이며, 괄호로 묶인 하위 문자열 match들을 포함하는 정규 표현식의 읽기 전용 속성들입니다.

+ +

Syntax

+ +
RegExp.$1
+RegExp.$2
+RegExp.$3
+RegExp.$4
+RegExp.$5
+RegExp.$6
+RegExp.$7
+RegExp.$8
+RegExp.$9
+
+ +

Description

+ +

$1, ..., $9 properties are static, they are not a property of an individual regular expression object. Instead, you always use them as RegExp.$1, ..., RegExp.$9.

+ +

The values of these properties are read-only and modified whenever successful matches are made.

+ +

The number of possible parenthesized substrings is unlimited, but the RegExp object can only hold the first nine. You can access all parenthesized substrings through the returned array's indexes.

+ +

These properties can be used in the replacement text for the {{jsxref("String.replace")}} method. When used this way, do not prepend them with RegExp. The example below illustrates this. When parentheses are not included in the regular expression, the script interprets $n's literally (where n is a positive integer).

+ +

Examples

+ +

Using $n with String.replace

+ +

아래의 script는 first last 포맷의 이름과 매치하기 위해 {{jsxref("String")}} 인스턴스의 {{jsxref("String.prototype.replace()", "replace()")}} 메소드를 사용하고 그것을 last, first 포맷으로 출력한다. 대체 텍스트에서, 이 script는 정규 표현식 패턴에서 매칭되는 괄호들에 해당하는 결과들을 나타내는 $1 과 $2 를 사용한다.

+ +
var re = /(\w+)\s(\w+)/;
+var str = 'John Smith';
+str.replace(re, '$2, $1'); // "Smith, John"
+RegExp.$1; // "John"
+RegExp.$2; // "Smith"
+
+ +

Specifications

+ +

Non-standard. Not part of any current specification.

+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.RegExp.n")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html b/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html new file mode 100644 index 0000000000..387b5bceff --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html @@ -0,0 +1,114 @@ +--- +title: RegExp() constructor +slug: Web/JavaScript/Reference/Global_Objects/RegExp/RegExp +tags: + - Constructor + - JavaScript + - Reference + - RegExp +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/RegExp +--- +
{{JSRef}}
+ +

RegExp 생성자는 패턴을 사용해 텍스트를 판별할 때 사용하는 정규 표현식 객체를 생성합니다.

+ +

정규 표현식에 대한 소개는 JavaScript 안내서의 정규 표현식 장을 참고하세요.

+ +
{{EmbedInteractiveExample("pages/js/regexp-constructor.html")}}
+ + + +

구문

+ +

리터럴, 생성자, 팩토리 표기법이 가능합니다.

+ +
/pattern/flags
+new RegExp(pattern[, flags])
+RegExp(pattern[, flags])
+
+ +

매개변수

+ +
+
pattern
+
정규 표현식을 나타내는 텍스트.
+
ES5부터는, 생성자 표기법에 한정하여 다른 RegExp 객체 혹은 리터럴을 사용할 수 있습니다. 패턴은 특수 문자를 포함할 수 있어서 일반적인 문자열 리터럴보다 더 넓은 범위의 값을 판별할 수 있습니다.
+
flags
+
+

정규 표현식에 추가할 플래그.

+ +

정규 표현식 객체를 패턴으로 제공한 경우 flags 문자열은 제공한 객체의 플래그를 모두 대체하며 lastIndex0으로 초기화합니다. (ES2015 이후)

+ +

flags를 지정하지 않았으면서 정규 표현식 객체를 제공한 경우, 해당 객체의 플래그와 lastIndex를 복제합니다.

+ +

flags는 다음 문자를 조합하여 지정할 수 있습니다.

+ +
+
g (global, 전역 판별)
+
처음 일치에서 중단하지 않고, 문자열 전체를 판별합니다.
+
i (ignore case, 대소문자 무시)
+
u 플래그까지 활성화된 경우, Unicode 대소문자 폴딩을 사용합니다.
+
m (multiline, 여러 줄)
+
시작과 끝 문자(^$)가 여러 줄에 걸쳐 동작합니다. 즉, 전체 입력 문자열의 맨 처음과 맨 끝 뿐만 아니라 (\n이나 \r로 구분되는) 각각의 줄의 처음과 끝도 일치합니다.
+
s ("dotAll")
+
.이 줄 바꿈에도 일치합니다.
+
u (unicode)
+
pattern을 Unicode 코드 포인트 시퀀스로 처리합니다. (이진 문자열 참고)
+
y (sticky, 접착)
+
이 정규 표현식의 lastIndex 속성에 명시된 인덱스에서만 판별하고, 이전/이후 인덱스에서 판별을 시도하지 않습니다.
+
+
+
+ +

예제

+ +

리터럴 표기법과 생성자

+ +

RegExp 객체는 리터럴 표기법과 생성자로써 생성할 수 있습니다.

+ + + +

다음의 세 표현식은 모두 같은 정규 표현식을 생성합니다.

+ +
/ab+c/i
+new RegExp(/ab+c/, 'i') // 리터럴
+new RegExp('ab+c', 'i') // 생성자
+
+ +

리터럴 표기법은 표현식을 평가할 때 정규 표현식을 컴파일합니다. 정규 표현식이 변하지 않으면 리터럴 표기법을 사용하세요. 예를 들어, 반복문 안에서 사용할 정규 표현식을 리터럴 표기법으로 생성하면 정규 표현식을 매번 다시 컴파일하지 않습니다.

+ +

정규 표현식 객체의 생성자(new RegExp('ab+c'))를 사용하면 정규 표현식이 런타임에 컴파일됩니다. 패턴이 변할 가능성이 있거나, 사용자 입력과 같이 알 수 없는 외부 소스에서 가져오는 정규 표현식의 경우 생성자 함수를 사용하세요.

+ +

명세

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-regexp-constructor', 'RegExp constructor')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.RegExp.RegExp")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/regexp/test/index.html b/files/ko/web/javascript/reference/global_objects/regexp/test/index.html new file mode 100644 index 0000000000..07569e7eaf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/test/index.html @@ -0,0 +1,129 @@ +--- +title: RegExp.prototype.test() +slug: Web/JavaScript/Reference/Global_Objects/RegExp/test +tags: + - JavaScript + - Method + - Prototype + - Reference + - RegExp + - 정규 표현식 + - 정규식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/test +--- +
{{JSRef}}
+ +

test() 메서드는 주어진 문자열이 정규 표현식을 만족하는지 판별하고, 그 여부를 true 또는 false로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/regexp-prototype-test.html", "taller")}}
+ + + +

구문

+ +
regexObj.test(str)
+ +

매개변수

+ +
+
str
+
정규 표현식 일치를 수행할 문자열.
+
+ +

반환 값

+ +

주어진 문자열 str 중 정규 표현식이 일치하는 부분이 있으면 true, 아니면, false.

+ +

설명

+ +

패턴이 문자열 내에 존재하는지에 대한 여부를 알아보고자 할 때 test()를 사용하세요. 일치의 위치 인덱스, 또는 일치하지 않으면 -1을 반환하는 {{jsxref("String.prototype.search()")}}와 달리 test()는 불리언을 반환합니다.

+ +

더 느리지만 더 많은 정보가 필요하면 {{jsxref("RegExp.prototype.exec()", "exec()")}} 메서드를 사용하세요. ({{jsxref("String.prototype.match()")}} 메서드와 비슷합니다.)

+ +

exec()처럼, test()도 전역 탐색 플래그를 제공한 정규 표현식에서 여러 번 호출하면 이전 일치 이후부터 탐색합니다. exec()test()를 혼용해 사용하는 경우에도 해당됩니다.

+ +

예제

+ +

test() 사용하기

+ +

문자열의 맨 처음에 "hello"가 포함됐는지 알아보는 간단한 예제 코드입니다.

+ +
const str = 'hello world!';
+const result = /^hello/.test(str);
+
+console.log(result); // true
+
+ +

다음은 일치 여부에 따라 다른 메시지를 기록하는 예제입니다.

+ +
function testInput(re, str) {
+  let midstring;
+  if (re.test(str)) {
+    midstring = 'contains';
+  } else {
+    midstring = 'does not contain';
+  }
+  console.log(`${str} ${midstring} ${re.source}`);
+}
+
+ +

전역 플래그와 test()

+ +

정규 표현식에 전역 플래그를 설정한 경우, test() 메서드는 정규 표현식의 {{jsxref("RegExp.lastIndex", "lastIndex")}}를 업데이트합니다. ({{jsxref("RegExp.prototype.exec()")}}도 lastIndex 속성을 업데이트합니다.)

+ +

test(str)을 또 호출하면 str 검색을 lastIndex부터 계속 진행합니다. lastIndex 속성은 매 번 test()true를 반환할 때마다 증가하게 됩니다.

+ +
+

참고: test()true를 반환하기만 하면 lastIndex는 초기화되지 않습니다. 심지어 이전과 다른 문자열을 매개변수로 제공해도 그렇습니다!

+
+ +

test()false를 반환할 땐 lastIndex 속성이 0으로 초기화됩니다.

+ +

이 행동에 대한 예제가 다음 코드입니다.

+ +
const regex = /foo/g; // the "global" flag is set
+
+// regex.lastIndex is at 0
+regex.test('foo')     // true
+
+// regex.lastIndex is now at 3
+regex.test('foo')     // false
+
+// regex.lastIndex is at 0
+regex.test('barfoo')  // true
+
+// regex.lastIndex is at 6
+regex.test('foobar')  //false
+
+// regex.lastIndex is at 0
+// (...and so on)
+
+ +

명세

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-regexp.prototype.test', 'RegExp.test')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.RegExp.test")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/set/add/index.html b/files/ko/web/javascript/reference/global_objects/set/add/index.html new file mode 100644 index 0000000000..622b3d876c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/add/index.html @@ -0,0 +1,83 @@ +--- +title: Set.prototype.add() +slug: Web/JavaScript/Reference/Global_Objects/Set/add +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/add +--- +
{{JSRef}}
+ +

add() 메서드는 Set 개체의 맨 뒤에 주어진 value의 새 요소를 추가합니다.

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-add.html")}}
+ + + +

구문

+ +
mySet.add(value);
+ +

매개변수

+ +
+
value
+
Set 객체에 추가할 요소의 값.
+
+ +

반환 값

+ +

Set 객체.

+ +

예제

+ +

add 메서드 사용하기

+ +
var mySet = new Set();
+
+mySet.add(1);
+mySet.add(5).add('어떤 문자열'); // 계속 붙일 수 있음
+
+console.log(mySet);
+// Set [1, 5, "어떤 문자열"]
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES2015', '#sec-set.prototype.add', 'Set.prototype.add')}}{{Spec2('ES2015')}}최초 정의
{{SpecName('ESDraft', '#sec-set.prototype.add', 'Set.prototype.add')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Set.add")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/set/clear/index.html b/files/ko/web/javascript/reference/global_objects/set/clear/index.html new file mode 100644 index 0000000000..3ecdb98895 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/clear/index.html @@ -0,0 +1,76 @@ +--- +title: Set.prototype.clear() +slug: Web/JavaScript/Reference/Global_Objects/Set/clear +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/clear +--- +
{{JSRef}}
+ +

clear() 메서드는 Set 객체를 비웁니다.

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-clear.html")}}
+ + + +

구문

+ +
mySet.clear();
+
+ +

예제

+ +

clear() 사용하기

+ +
var mySet = new Set();
+mySet.add(1);
+mySet.add('foo');
+
+mySet.size;       // 2
+mySet.has('foo'); // true
+
+mySet.clear();
+
+mySet.size;       // 0
+mySet.has('bar')  // false
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-set.prototype.clear', 'Set.prototype.clear')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.clear', 'Set.prototype.clear')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Set.clear")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/set/delete/index.html b/files/ko/web/javascript/reference/global_objects/set/delete/index.html new file mode 100644 index 0000000000..a138736b46 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/delete/index.html @@ -0,0 +1,98 @@ +--- +title: Set.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/Set/delete +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/delete +--- +
{{JSRef}}
+ +

delete() 메서드는 지정한 요소를 Set 객체에서 제거합니다.

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-delete.html")}}
+ + + +

구문

+ +
mySet.delete(value);
+ +

매개변수

+ +
+
value
+
Set 객체에서 제거할 요소의 값.
+
+ +

반환 값

+ +

요소를 제거했으면 true, 아니면 false.

+ +

예제

+ +

delete() 사용하기

+ +
var mySet = new Set();
+mySet.add('foo');
+
+mySet.delete('bar'); // Returns false. No "bar" element found to be deleted.
+mySet.delete('foo'); // Returns true.  Successfully removed.
+
+mySet.has('foo');    // Returns false. The "foo" element is no longer present.
+
+ +

다음 예제는 Set에서 객체를 제거하는 방법을 보입니다.

+ +
var setObj = new Set(); // Create a New Set.
+
+setObj.add({x: 10, y: 20}); // Add object in the set.
+
+setObj.add({x: 20, y: 30}); // Add object in the set.
+
+// Delete any point with `x > 10`.
+setObj.forEach(function(point){
+  if(point.x > 10){
+    setObj.delete(point)
+  }
+})
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-set.prototype.delete', 'Set.prototype.delete')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.delete', 'Set.prototype.delete')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Set.delete")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/set/foreach/index.html b/files/ko/web/javascript/reference/global_objects/set/foreach/index.html new file mode 100644 index 0000000000..fbfa4963c5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/foreach/index.html @@ -0,0 +1,117 @@ +--- +title: Set.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Set/forEach +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/forEach +--- +
{{JSRef}}
+ +

forEach() 메서드는 주어진 함수를 Set 요소 각각에 대해 삽입 순서대로 실행합니다.

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-foreach.html")}}
+ + + +

구문

+ +
mySet.forEach(callback[, thisArg])
+ +

매개변수

+ +
+
callback
+
각 요소에 대해 실행할 함수. 다음 세 가지 인수를 받습니다.
+
+
+
currentValue, currentKey
+
처리할 현재 요소. Set은 키를 갖지 않으므로 두 인수 모두에 값을 전달합니다.
+
set
+
forEach()를 호출한 Set.
+
+
+
thisArg
+
callback을 실행할 때 this로 사용할 값.
+
+ +

반환 값

+ +

{{jsxref("undefined")}}.

+ +

설명

+ +

forEach() 메서드는 주어진 callbackSet에 존재하는 요소에 대해 한 번씩 실행합니다. 삭제한 값에 대해선 실행하지 않습니다. 그러나 존재하되 값이 {{jsxref("undefined")}}인 경우엔 실행합니다.

+ +

callback은 다음 세 인수와 함께 호출됩니다.

+ + + +

그러나 Set은 키 값을 사용하지 않으므로, 처음 두 개의 매개변수 모두 요소 값을 받습니다. 이는 {{jsxref("Map.foreach", "Map")}}과 {{jsxref("Array.forEach","Array")}}에서 사용하는 forEach()와 동일한 형태를 유지하기 위해서입니다.

+ +

thisArg 매개변수를 forEach()에 제공한 경우 callback을 호출할 때 전달해 this의 값으로 쓰입니다. 전달하지 않으면 undefined를 사용하며, 최종 this 값은 {{jsxref("Operators/this", "함수의 this를 결정하는 평소 규칙", "", 0)}}을 따릅니다.

+ +

forEach()는 각각의 값을 한 번씩 방문하지만, 순회를 끝내기 전에 제거하고 다시 추가한 값은 예외입니다. 방문하기 전 제거한 값에 대해서는 callback을 호출하지 않습니다. forEach()가 끝나기 전 추가한 요소는 방문합니다.

+ +

forEach()Set 객체의 요소에 대해 callback을 실행만 하며 값을 반환하지는 않습니다.

+ +

예제

+ +

Set의 내용물 기록하기

+ +

다음 코드는 Set의 요소 각각을 새로운 줄에 기록합니다.

+ +
function logSetElements(value1, value2, set) {
+    console.log('s[' + value1 + '] = ' + value2);
+}
+
+new Set(['foo', 'bar', undefined]).forEach(logSetElements);
+
+// 콘솔 로그:
+// "s[foo] = foo"
+// "s[bar] = bar"
+// "s[undefined] = undefined"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-set.prototype.foreach', 'Set.prototype.forEach')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.foreach', 'Set.prototype.forEach')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Set.forEach")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/set/has/index.html b/files/ko/web/javascript/reference/global_objects/set/has/index.html new file mode 100644 index 0000000000..016da46cfd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/has/index.html @@ -0,0 +1,93 @@ +--- +title: Set.prototype.has() +slug: Web/JavaScript/Reference/Global_Objects/Set/has +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/has +--- +
{{JSRef}}
+ +

has() 메서드는 Set 객체에 주어진 요소가 존재하는지 여부를 판별해 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-has.html")}}
+ + + +

구문

+ +
mySet.has(value);
+ +

매개변수

+ +
+
value
+
Set 객체에서 존재 여부를 판별할 값.
+
+ +

반환 값

+ +

Set 객체에 값이 존재하면 true, 아니면 false.

+ +
+

참고: 기술적으로, has()sameValueZero 알고리즘을 사용해 요소의 존재 여부를 판별합니다.

+
+ +

예제

+ +

has() 사용하기

+ +
var mySet = new Set();
+mySet.add('foo');
+
+mySet.has('foo');  // true
+mySet.has('bar');  // false
+
+var set1 = new Set();
+var obj1 = {'key1': 1};
+set1.add(obj1);
+
+set1.has(obj1);        // true
+set1.has({'key1': 1}); // false, 형태만 같은 서로 다른 객체의 참조이기 때문
+set1.add({'key1': 1}); // set1의 요소가 2개로 늘어남
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-set.prototype.has', 'Set.prototype.has')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.has', 'Set.prototype.has')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Set.has")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/set/index.html b/files/ko/web/javascript/reference/global_objects/set/index.html new file mode 100644 index 0000000000..b8086f89bd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/index.html @@ -0,0 +1,237 @@ +--- +title: Set +slug: Web/JavaScript/Reference/Global_Objects/Set +tags: + - ECMAScript 2015 + - Global Objects + - JavaScript + - Object + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set +--- +
{{JSRef}}
+ +

Set 객체는 자료형에 관계 없이 {{Glossary("Primitive", "원시 값")}}과 객체 참조 모두 유일한 값을 저장할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-constructor.html")}}
+ + + +

구문

+ +
new Set([iterable]);
+ +

매개변수

+ +
+
iterable
+
반복 가능한 객체가 전달된 경우, 그 요소는 모두 새로운 Set에 추가됩니다. 만약 매개변수를 명시하지 않거나 null을 전달하면, 새로운 Set은 비어 있는 상태가 됩니다.
+
+ +

반환 값

+ +

새로운 Set 객체.

+ +

설명

+ +

Set 객체는 값 콜렉션으로, 삽입 순서대로 요소를 순회할 수 있습니다. 하나의 Set 내 값은 한 번만 나타날 수 있습니다. 즉, 어떤 값은 그 Set 콜렉션 내에서 유일합니다.

+ +

값 같음

+ +

Set 내의 값은 유일해야 하기 때문에 값이 같은지 검사를 수행합니다. 이전 ECMAScript 명세에서는 검사 알고리즘이 === 연산자와는 다른 것이었습니다. 특히, +0 === -0이었지만 Set에서는 +0-0이 다른 값이었습니다. 그러나 이는 ECMAScript 2015 명세에서 변경되었습니다. {{anch("브라우저 호환성", "브라우저 호환성")}}의 "Key equality for -0 and 0"을 참고하세요.

+ +

{{jsxref("NaN")}}과 {{jsxref("undefined")}}도 Set에 저장할 수 있습니다. 원래 NaN !== NaN이지만, Set에서 NaNNaN과 같은 것으로 간주됩니다.

+ +

속성

+ +
+
Set.length
+
값이 0인 속성입니다.
+
{{jsxref("Set.@@species", "get Set[@@species]")}}
+
파생 객체를 생성하는데 사용하는 생성자 함수입니다.
+
{{jsxref("Set.prototype")}}
+
Set 생성자의 프로토타입을 나타냅니다. 모든  Set 객체에 속성을 추가할 수 있습니다.
+
+ +

Set 인스턴스

+ +

모든 Set 인스턴스는 {{jsxref("Set.prototype")}}을 상속받습니다.

+ +

속성

+ +

{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Set/prototype','속성')}}

+ +

메서드

+ +

{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/Set/prototype','메서드')}}

+ +

예제

+ +

Set 객체 사용

+ +
var mySet = new Set();
+
+mySet.add(1); // Set { 1 }
+mySet.add(5); // Set { 1, 5 }
+mySet.add(5); // Set { 1, 5 }
+mySet.add('some text'); // Set { 1, 5, 'some text' }
+var o = {a: 1, b: 2};
+mySet.add(o);
+
+mySet.add({a: 1, b: 2}); // o와 다른 객체를 참조하므로 괜찮음
+
+mySet.has(1); // true
+mySet.has(3); // false, 3은 set에 추가되지 않았음
+mySet.has(5);              // true
+mySet.has(Math.sqrt(25));  // true
+mySet.has('Some Text'.toLowerCase()); // true
+mySet.has(o); // true
+
+mySet.size; // 5
+
+mySet.delete(5); // set에서 5를 제거함
+mySet.has(5);    // false, 5가 제거되었음
+
+mySet.size; // 4, 방금 값을 하나 제거했음
+console.log(mySet);// Set {1, "some text", Object {a: 1, b: 2}, Object {a: 1, b: 2}}
+
+ +

Set 반복

+ +
// set 내 항목에 대해 반복
+// 순서대로 항목을 (콘솔에) 기록: 1, "some text", {"a": 1, "b": 2}
+for (let item of mySet) console.log(item);
+
+// 순서대로 항목을 기록: 1, "some text", {"a": 1, "b": 2}
+for (let item of mySet.keys()) console.log(item);
+
+// 순서대로 항목을 기록: 1, "some text", {"a": 1, "b": 2}
+for (let item of mySet.values()) console.log(item);
+
+// 순서대로 항목을 기록: 1, "some text", {"a": 1, "b": 2}
+// (여기서 key와 value는 같음)
+for (let [key, value] of mySet.entries()) console.log(key);
+
+// Set 객체를 배열 객체로 변환 (Array.from으로)
+var myArr = Array.from(mySet); // [1, "some text", {"a": 1, "b": 2}]
+
+// 다음도 HTML 문서에서 실행하는 경우 작동함
+mySet.add(document.body);
+mySet.has(document.querySelector('body')); // true
+
+// Set과 Array 사이 변환
+mySet2 = new Set([1, 2, 3, 4]);
+mySet2.size; // 4
+[...mySet2]; // [1, 2, 3, 4]
+
+// 교집합은 다음으로 흉내(simulate)낼 수 있음
+var intersection = new Set([...set1].filter(x => set2.has(x)));
+
+// 차집합은 다음으로 흉내낼 수 있음
+var difference = new Set([...set1].filter(x => !set2.has(x)));
+
+// forEach로 set 항목 반복
+mySet.forEach(function(value) {
+  console.log(value);
+});
+
+// 1
+// 2
+// 3
+// 4
+ +

기본 집합 연산 구현

+ +
Set.prototype.isSuperset = function(subset) {
+    for (var elem of subset) {
+        if (!this.has(elem)) {
+            return false;
+        }
+    }
+    return true;
+}
+
+Set.prototype.union = function(setB) {
+    var union = new Set(this);
+    for (var elem of setB) {
+        union.add(elem);
+    }
+    return union;
+}
+
+Set.prototype.intersection = function(setB) {
+    var intersection = new Set();
+    for (var elem of setB) {
+        if (this.has(elem)) {
+            intersection.add(elem);
+        }
+    }
+    return intersection;
+}
+
+Set.prototype.difference = function(setB) {
+    var difference = new Set(this);
+    for (var elem of setB) {
+        difference.delete(elem);
+    }
+    return difference;
+}
+
+//Examples
+var setA = new Set([1, 2, 3, 4]),
+    setB = new Set([2, 3]),
+    setC = new Set([3, 4, 5, 6]);
+
+setA.isSuperset(setB); // => true
+setA.union(setC); // => Set [1, 2, 3, 4, 5, 6]
+setA.intersection(setC); // => Set [3, 4]
+setA.difference(setC); // => Set [1, 2]
+ +

Array 객체와의 관계

+ +
var myArray = ['value1', 'value2', 'value3'];
+
+// Array를 Set으로 변환하기 위해서는 정규 Set 생성자 사용
+var mySet = new Set(myArray);
+
+mySet.has('value1'); // true 반환
+
+// set을 Array로 변환하기 위해 전개 연산자 사용함.
+console.log([...mySet]); // myArray와 정확히 같은 배열을 보여줌
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES2015', '#sec-set-objects', 'Set')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Set")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/set/prototype/index.html b/files/ko/web/javascript/reference/global_objects/set/prototype/index.html new file mode 100644 index 0000000000..ca6e568bed --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/prototype/index.html @@ -0,0 +1,86 @@ +--- +title: Set.prototype +slug: Web/JavaScript/Reference/Global_Objects/Set/prototype +tags: + - ECMAScript 2015 + - JavaScript + - Property + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set +--- +
{{JSRef}}
+ +

Set.prototype 속성은 {{jsxref("Set")}} 생성자의 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0,0,0)}}
+ +

설명

+ +

{{jsxref("Set")}} 인스턴스는 {{jsxref("Set.prototype")}}에서 상속합니다. 모든 Set 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.

+ +

속성

+ +
+
Set.prototype.constructor
+
인스턴스의 프로토타입을 만든 함수를 반환합니다. 이는 기본으로 {{jsxref("Set")}} 함수입니다.
+
{{jsxref("Set.prototype.size")}}
+
Set 객체 내 값의 개수를 반환합니다.
+
+ +

메서드

+ +
+
{{jsxref("Set.add", "Set.prototype.add(value)")}}
+
Set 객체에 주어진 값을 갖는 새로운 요소를 추가합니다. Set 객체를 반환합니다.
+
{{jsxref("Set.prototype.clear()")}}
+
Set 객체에서 모든 요소를 제거합니다.
+
{{jsxref("Set.delete", "Set.prototype.delete(value)")}}
+
value와 관련된 요소를 제거하고 Set.prototype.has(value)가 이전에 반환했던 값을 반환합니다. Set.prototype.has(value)는 그 뒤에 false를 반환합니다.
+
{{jsxref("Set.prototype.entries()")}}
+
삽입 순으로 Set 객체 내 각 값에 대한 [value, value] 배열을 포함하는 새로운 Iterator 객체를 반환합니다. 이는 Map 객체와 비슷하게 유지되므로 여기서 각 항목은 그 keyvalue에 대해 같은 값을 갖습니다.
+
{{jsxref("Set.forEach", "Set.prototype.forEach(callbackFn[, thisArg])")}}
+
삽입 순으로 Set 객체 내에 있는 각 값에 대해 한 번 callbackFn을 호출합니다. thisArg 매개변수가 forEach에 제공된 경우, 이는 각 콜백에 대해 this 값으로 사용됩니다.
+
{{jsxref("Set.has", "Set.prototype.has(value)")}}
+
Set 객체 내 주어진 값을 갖는 요소가 있는지를 주장하는(asserting, 나타내는) boolean을 반환합니다.
+
{{jsxref("Set.prototype.keys()")}}
+
values() 함수와 같은 함수로 삽입 순으로 Set 객체 내 각 요소에 대한 값을 포함하는 새로운 Iterator 객체를 반환합니다.
+
{{jsxref("Set.prototype.values()")}}
+
삽입 순으로 Set 객체 내 각 요소에 대한 을 포함하는 새로운 Iterator 객체를 반환합니다.
+
{{jsxref("Set.prototype.@@iterator()", "Set.prototype[@@iterator]()")}}
+
삽입 순으로 Set 객체 내 각 요소에 대한 을 포함하는 새로운 Iterator 객체를 반환합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-set.prototype', 'Set.prototype')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-set.prototype', 'Set.prototype')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Set.prototype")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/set/size/index.html b/files/ko/web/javascript/reference/global_objects/set/size/index.html new file mode 100644 index 0000000000..2f437bed4a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/size/index.html @@ -0,0 +1,69 @@ +--- +title: Set.prototype.size +slug: Web/JavaScript/Reference/Global_Objects/Set/size +tags: + - ECMAScript 2015 + - JavaScript + - Property + - Prototype + - Reference + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set/size +--- +
{{JSRef}}
+ +

size 접근자 속성은 {{jsxref("Set")}} 객체의 원소 수를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-size.html")}}
+ + + +

설명

+ +

size의 값은 Set 객체가 가진 원소의 수를 나타내는 정수입니다. size 값의 설정자는 {{jsxref("undefined")}}입니다. 즉 값을 직접 바꿀 수는 없습니다.

+ +

예제

+ +

size 사용하기

+ +
var mySet = new Set();
+mySet.add(1);
+mySet.add(5);
+mySet.add('some text')
+
+mySet.size; // 3
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-get-set.prototype.size', 'Set.prototype.size')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-get-set.prototype.size', 'Set.prototype.size')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Set.size")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/set/values/index.html b/files/ko/web/javascript/reference/global_objects/set/values/index.html new file mode 100644 index 0000000000..37e019e3da --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/set/values/index.html @@ -0,0 +1,72 @@ +--- +title: Set.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Set/values +translation_of: Web/JavaScript/Reference/Global_Objects/Set/values +--- +
{{JSRef}}
+ +

values() method는 Set 객체에 요소가 삽입된 순서대로 각 요소의 값을 순환할 수 있는 Iterator 객체를 반환합니다.

+ +

The keys() method is an alias for this method (for similarity with {{jsxref("Map")}} objects); it behaves exactly the same and returns values of Set elements.

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-values.html")}}
+ + + +

Syntax

+ +
mySet.values();
+
+ +

Return value

+ +

A new Iterator object containing the values for each element in the given Set, in insertion order.

+ +

Examples

+ +

Using values()

+ +
var mySet = new Set();
+mySet.add('foo');
+mySet.add('bar');
+mySet.add('baz');
+
+var setIter = mySet.values();
+
+console.log(setIter.next().value); // "foo"
+console.log(setIter.next().value); // "bar"
+console.log(setIter.next().value); // "baz"
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-set.prototype.values', 'Set.prototype.values')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.values', 'Set.prototype.values')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Set.values")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/index.html b/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/index.html new file mode 100644 index 0000000000..9919adb447 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/index.html @@ -0,0 +1,137 @@ +--- +title: SharedArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer +tags: + - Constructor + - JavaScript + - Shared Memory + - SharedArrayBuffer + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer +--- +
{{JSRef}}
+ +

SharedArrayBuffer 객체는 제네릭, 고정된 길이의 원시 바이너리 데이터 버퍼를 표현하는데 사용됩니다. {{jsxref("ArrayBuffer")}} 객체와 유사하지만, 공유된 메모리상의 뷰를 생성하는데 사용될 수 있습니다. ArrayBuffer 와는 달리, SharedArrayBuffer 는 분리될 수 없습니다.

+ +
+

Spectre 에대한 응답으로 2018년 1월 5일에 SharedArrayBuffer 는 모든 주요 브라우저에서 기본적으로 비활성화되어있음을 참고하세요. Chrome 은 사이트 격리 기능을 사용하여 Spectre 스타일 취약점으로부터 보호될 수 있는 플랫폼상의 v67 에서 이를 다시 활성화하였습니다.

+
+ +

{{EmbedInteractiveExample("pages/js/sharedarraybuffer-constructor.html")}}

+ + + +

구문

+ +
new SharedArrayBuffer(length)
+
+ +

파라미터

+ +
+
length
+
생성할 array buffer 의 바이트 크기.
+
+ +

반환 값

+ +

크기가 지정된 새로운 SharedArrayBuffer 객체입니다. 컨텐츠는 0 으로 초기화됩니다.

+ +

설명

+ +

할당 및 메모리 공유

+ +

{{jsxref("SharedArrayBuffer")}} 객체를 사용해 메모리를 하나의 agent(agent 는 웹 페이지의 메인 프로그램 또는 웹 워커 중 하나입니다)와 다른 agent 에서 공유하기 위해, postMessagestructured cloning 이 사용됩니다.

+ +

Structured clone 알고리즘은 SharedArrayBuffer 와 SharedArrayBuffer 상에 맵핑된 TypedArray 를 받아들입니다. 이 두 경우에서, SharedArrayBuffer 객체는 수신자(receiver)에게 전달되어 수신 agent(예, {{jsxref("ArrayBuffer")}})의 새로운 비공개의 SharedArrayBuffer 객체를 생성합니다. 하지만, 두 SharedArrayBuffer 에 의해 참조되는 공유 데이터 블록은 같은 블록이며, 부수적인 효과로, 하나의 agent 가 다른 agent 에서 보이게 됩니다.

+ +
var sab = new SharedArrayBuffer(1024);
+worker.postMessage(sab);
+
+ +

Atomic operation 으로 공유 메모리 수정 및 동기화

+ +

공유 메모리는 워커나 메인 스레드에서 동시에 수정 및 생성할 수 있습니다. 시스템(CPU, OS, 브라우저)에따라 변경사항이 전체 컨텍스트로 전파될때까지 약간의 시간이 필요합니다. 동기화를 위해선, {{jsxref("Atomics", "atomic", "", 1)}} 연산이 필요합니다.

+ +

SharedArrayBuffer 객체를 사용할 수 있는 API

+ + + +

생성자는 new 연산자를 필요로 함

+ +

SharedArrayBuffer 생성자는 생성될 때, {{jsxref("Operators/new", "new")}} 연산자를 필요로 합니다. SharedArrayBuffer 생성자를 new 없이 함수로써 호출하면, {{jsxref("TypeError")}} 를 일으킬 것 입니다.

+ +
var sab = SharedArrayBuffer(1024);
+// TypeError: calling a builtin SharedArrayBuffer constructor
+// without new is forbidden
+ +
var sab = new SharedArrayBuffer(1024);
+ +

속성

+ +
+
SharedArrayBuffer.length
+
값이 1인 SharedArrayBuffer 생성자의 length 속성입니다.
+
{{jsxref("SharedArrayBuffer.prototype")}}
+
모든 SharedArrayBuffer 객체에 프로퍼티 추가를 가능하게 해줍니다.
+
+ +

SharedArrayBuffer prototype 객체

+ +

모든 SharedArrayBuffer 인스턴스는 {{jsxref("SharedArrayBuffer.prototype")}} 를 상속합니다.

+ +

속성

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/prototype','Properties')}}

+ +

메소드

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/prototype','Methods')}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('ESDraft', '#sec-sharedarraybuffer-objects', 'SharedArrayBuffer')}}{{Spec2('ESDraft')}}ES2017 에서 초기 정의.
{{SpecName('ES8', '#sec-sharedarraybuffer-objects', 'SharedArrayBuffer')}}{{Spec2('ES8')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.SharedArrayBuffer")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html b/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html new file mode 100644 index 0000000000..3499bc77ed --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/sharedarraybuffer/prototype/index.html @@ -0,0 +1,65 @@ +--- +title: SharedArrayBuffer.prototype +slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/prototype +tags: + - JavaScript + - SharedArrayBuffer + - TypedArrays + - 공유 메모리 + - 속성 +translation_of: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer +--- +
{{JSRef}}
+ +

SharedArrayBuffer.prototype 속성은 {{jsxref("SharedArrayBuffer")}} 객체를위한 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0,0,0)}}
+ +

설명

+ +

SharedArrayBuffer 인스턴스는 SharedArrayBuffer.prototype 을 상속합니다. 모든 생성자와 마찬가지로, 생성자의 프로토타입 객체를 변경하여 모든 SharedArrayBuffer 인스턴스에 변화를 줄 수 있습니다.

+ +

속성

+ +
+
SharedArrayBuffer.prototype.constructor
+
객체의 프로토타입을 생성하는 함수를 지정합니다. 초기 값은 SharedArrayBuffer 생성자에 내장된 표준입니다.
+
{{jsxref("SharedArrayBuffer.prototype.byteLength")}} {{readonlyInline}}
+
배열의 바이트 크기입니다. 배열이 생성되고 수정이 불가할 때 지정됩니다. 읽기 전용입니다.
+
+ +

메소드

+ +
+
{{jsxref("SharedArrayBuffer.slice", "SharedArrayBuffer.prototype.slice(begin, end)")}}
+
begin 부터 end 까지의 모든 것을 포함하는 SharedArrayBuffer 바이트의 복사본을 컨텐츠로 갖는 새로운 SharedArrayBuffer 를 반환합니다. begin 또는 end 가 음수인 경우, 인덱스는 배열의 끝에서부터이고 반대인 경우 시작부터입니다.
+
+ +

명세

+ + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('ESDraft', '#sec-sharedarraybuffer.prototype', 'SharedArrayBuffer.prototype')}}{{Spec2('ESDraft')}}ES2017 에서 초기 정의.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.SharedArrayBuffer.prototype")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/charat/index.html b/files/ko/web/javascript/reference/global_objects/string/charat/index.html new file mode 100644 index 0000000000..a5a68c03be --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/charat/index.html @@ -0,0 +1,260 @@ +--- +title: String.prototype.charAt() +slug: Web/JavaScript/Reference/Global_Objects/String/charAt +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/charAt +--- +
{{JSRef}}
+ +

charAt() 함수는 문자열에서 특정 인덱스에 위치하는  유니코드 단일문자를 반환합니다. 

+ +
{{EmbedInteractiveExample("pages/js/string-charat.html")}}
+ + + +

구문

+ +
str.charAt(index)
+ +

매개변수

+ + + +
+
index
+
+ +

반환 값

+ + + +

설명

+ +

문자열 내의 문자는 왼쪽에서 오른쪽으로 순번(인덱스)이 매겨집니다. 첫 번째 문자의 순번은 0, 그리고 stringName 이라는 이름을 가진 문자열의 마지막 문자 순번은 stringName.length - 1 입니다. index가 문자열 길이를 벗어나면 빈 문자열을 반환하게 됩니다.

+ +

index를 제공하지 않으면 기본값은 0입니다.

+ +

예제

+ +

문자열 내의 다른 위치에 있는 문자들을 출력하기

+ +

아래 예제는 문자열 "Brave new world"의 다른 위치에 있는 문자들을 출력합니다.

+ +
var anyString = 'Brave new world';
+console.log("The character at index 0   is '" + anyString.charAt()   + "'");
+// No index was provided, used 0 as default
+
+console.log("The character at index 0   is '" + anyString.charAt(0)   + "'");
+console.log("The character at index 1   is '" + anyString.charAt(1)   + "'");
+console.log("The character at index 2   is '" + anyString.charAt(2)   + "'");
+console.log("The character at index 3   is '" + anyString.charAt(3)   + "'");
+console.log("The character at index 4   is '" + anyString.charAt(4)   + "'");
+console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
+
+ +

프로그램의 실행 결과는 아래와 같습니다.

+ +
The character at index 0   is 'B'
+The character at index 1   is 'r'
+The character at index 2   is 'a'
+The character at index 3   is 'v'
+The character at index 4   is 'e'
+The character at index 999 is ''
+
+ +

문자열 내의 모든 문자 얻기

+ +

아래 예제는 문자열 전체를 순회하며 각 문자가 완전한지 확인하는 프로그램입니다. 심지어 기본 다국어 평면(Basic Multilingual Plane)에 포함되지 않은 문자들이 포함되어 있다고 하더라도 잘 동작합니다. 

+ +
var str = 'A \uD87E\uDC04 Z'; // 기본 다국어 평면에 포함되지 않는 문자를 사용합니다.
+for (var i = 0, chr; i < str.length; i++) {
+  if ((chr = getWholeChar(str, i)) === false) {
+    continue;
+  }
+  // Adapt this line at the top of each loop, passing in the whole string and
+  // the current iteration and returning a variable to represent the
+  // individual character
+
+  console.log(chr);
+}
+
+function getWholeChar(str, i) {
+  var code = str.charCodeAt(i);
+
+  if (Number.isNaN(code)) {
+    return ''; // Position not found
+  }
+  if (code < 0xD800 || code > 0xDFFF) {
+    return str.charAt(i);
+  }
+
+  // High surrogate (could change last hex to 0xDB7F to treat high private
+  // surrogates as single characters)
+  if (0xD800 <= code && code <= 0xDBFF) {
+    if (str.length <= (i + 1)) {
+      throw 'High surrogate without following low surrogate';
+    }
+    var next = str.charCodeAt(i + 1);
+      if (0xDC00 > next || next > 0xDFFF) {
+        throw 'High surrogate without following low surrogate';
+      }
+      return str.charAt(i) + str.charAt(i + 1);
+  }
+  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
+  if (i === 0) {
+    throw 'Low surrogate without preceding high surrogate';
+  }
+  var prev = str.charCodeAt(i - 1);
+
+  // (could change last hex to 0xDB7F to treat high private
+  // surrogates as single characters)
+  if (0xD800 > prev || prev > 0xDBFF) {
+    throw 'Low surrogate without preceding high surrogate';
+  }
+  // We can pass over low surrogates now as the second component
+  // in a pair which we have already processed
+  return false;
+}
+
+ +

비구조화 할당을 허용하는 ECMAScript 2016 환경에서는 아래 예제 코드가 더 간결하고, 문자가 서러게이트 페어가 되는 것을 허용할 때는 증가해야 하는 변수를 자동적으로 증가하기에 위의 코드보다 다소 더 유연합니다.

+ +
var str = 'A\uD87E\uDC04Z'; // We could also use a non-BMP character directly
+for (var i = 0, chr; i < str.length; i++) {
+  [chr, i] = getWholeCharAndI(str, i);
+  // Adapt this line at the top of each loop, passing in the whole string and
+  // the current iteration and returning an array with the individual character
+  // and 'i' value (only changed if a surrogate pair)
+
+  console.log(chr);
+}
+
+function getWholeCharAndI(str, i) {
+  var code = str.charCodeAt(i);
+
+  if (Number.isNaN(code)) {
+    return ''; // Position not found
+  }
+  if (code < 0xD800 || code > 0xDFFF) {
+    return [str.charAt(i), i]; // Normal character, keeping 'i' the same
+  }
+
+  // High surrogate (could change last hex to 0xDB7F to treat high private
+  // surrogates as single characters)
+  if (0xD800 <= code && code <= 0xDBFF) {
+    if (str.length <= (i + 1)) {
+      throw 'High surrogate without following low surrogate';
+    }
+    var next = str.charCodeAt(i + 1);
+      if (0xDC00 > next || next > 0xDFFF) {
+        throw 'High surrogate without following low surrogate';
+      }
+      return [str.charAt(i) + str.charAt(i + 1), i + 1];
+  }
+  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
+  if (i === 0) {
+    throw 'Low surrogate without preceding high surrogate';
+  }
+  var prev = str.charCodeAt(i - 1);
+
+  // (could change last hex to 0xDB7F to treat high private surrogates
+  // as single characters)
+  if (0xD800 > prev || prev > 0xDBFF) {
+    throw 'Low surrogate without preceding high surrogate';
+  }
+  // Return the next character instead (and increment)
+  return [str.charAt(i + 1), i + 1];
+}
+
+ +

기본다국어평면(Basic-Multilingual-Plane)이 아닌 문자들을 지원하도록 charAt() 수정하기

+ +

어떠한 non-BMP 문자들이 나타났는지 호출자가 알 필요가 없기 때문에 non-BMP 문자들을 지원하도록 하는데는 앞의 예제들이 더 자주 사용되지만, 인덱스로 문자를 선택하는데 있어서 문자열 내에 서로게이트 페어들이 하나의 문자들로 처리되길 원한다면, 아래 예제 코드를 사용하면 됩니다.

+ +
function fixedCharAt(str, idx) {
+  var ret = '';
+  str += '';
+  var end = str.length;
+
+  var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
+  while ((surrogatePairs.exec(str)) != null) {
+    var li = surrogatePairs.lastIndex;
+    if (li - 2 < idx) {
+      idx++;
+    } else {
+      break;
+    }
+  }
+
+  if (idx >= end || idx < 0) {
+    return '';
+  }
+
+  ret += str.charAt(idx);
+
+  if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) {
+    // Go one further, since one of the "characters" is part of a surrogate pair
+    ret += str.charAt(idx + 1);
+  }
+  return ret;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5.4.4', 'String.prototype.charAt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.charat', 'String.prototype.charAt')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.charat', 'String.prototype.charAt')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.String.charAt")}}

+ +

관련문서

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html b/files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html new file mode 100644 index 0000000000..9777130911 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/charcodeat/index.html @@ -0,0 +1,169 @@ +--- +title: String.prototype.charCodeAt() +slug: Web/JavaScript/Reference/Global_Objects/String/charCodeAt +tags: + - JavaScript + - Method + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/charCodeAt +--- +
{{JSRef}}
+ +

charCodeAt() 메서드는 주어진 인덱스에 대한 UTF-16 코드를 나타내는 0부터 65535 사이의 정수를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-charcodeat.html")}}
+ + + +

전체 코드 값을 원하신다면 {{jsxref("String.prototype.codePointAt()")}}을 사용하세요.

+ +

구문

+ +
str.charCodeAt(index)
+ +

매개변수

+ +
+
index
+
0 이상이고 문자열의 길이보다 작은 정수. 숫자가 아니라면 0을 기본값으로 사용함. 
+
+ +

반환 값

+ +

주어진 인덱스 대한 문자에 대한 UTF-16 코드를 나타내는 숫자
+ 범위 밖으로 넘어갔을 경우 {{jsxref("Global_Objects/NaN", "NaN")}}

+ +

설명

+ +

Unicode code points range from 0 to 1114111 (0x10FFFF). The first 128 Unicode code points are a direct match of the ASCII character encoding. For information on Unicode, see the JavaScript Guide.

+ +

Note that charCodeAt() will always return a value that is less than 65536. This is because the higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters which are used to comprise the real character. Because of this, in order to examine or reproduce the full character for individual characters of value 65536 and above, for such characters, it is necessary to retrieve not only charCodeAt(i), but also charCodeAt(i+1) (as if examining/reproducing a string with two letters), or to use codePointAt(i) instead. See example 2 and 3 below.

+ +

charCodeAt() returns {{jsxref("Global_Objects/NaN", "NaN")}} if the given index is less than 0 or is equal to or greater than the length of the string.

+ +

Backward compatibilty: In historic versions (like JavaScript 1.2) the charCodeAt() method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct match of the ASCII character set.

+ +

예제

+ +

Using charCodeAt()

+ +

The following example returns 65, the Unicode value for A.

+ +
'ABC'.charCodeAt(0); // returns 65
+
+ +

Fixing charCodeAt() to handle non-Basic-Multilingual-Plane characters if their presence earlier in the string is unknown

+ +

This version might be used in for loops and the like when it is unknown whether non-BMP characters exist before the specified index position.

+ +
function fixedCharCodeAt(str, idx) {
+  // ex. fixedCharCodeAt('\uD800\uDC00', 0); // 65536
+  // ex. fixedCharCodeAt('\uD800\uDC00', 1); // false
+  idx = idx || 0;
+  var code = str.charCodeAt(idx);
+  var hi, low;
+
+  // High surrogate (could change last hex to 0xDB7F to treat high
+  // private surrogates as single characters)
+  if (0xD800 <= code && code <= 0xDBFF) {
+    hi = code;
+    low = str.charCodeAt(idx + 1);
+    if (isNaN(low)) {
+      throw 'High surrogate not followed by low surrogate in fixedCharCodeAt()';
+    }
+    return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
+  }
+  if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
+    // We return false to allow loops to skip this iteration since should have
+    // already handled high surrogate above in the previous iteration
+    return false;
+    /*hi = str.charCodeAt(idx - 1);
+    low = code;
+    return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;*/
+  }
+  return code;
+}
+
+ +

Fixing charCodeAt() to handle non-Basic-Multilingual-Plane characters if their presence earlier in the string is known

+ +
function knownCharCodeAt(str, idx) {
+  str += '';
+  var code,
+      end = str.length;
+
+  var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
+  while ((surrogatePairs.exec(str)) != null) {
+    var li = surrogatePairs.lastIndex;
+    if (li - 2 < idx) {
+      idx++;
+    }
+    else {
+      break;
+    }
+  }
+
+  if (idx >= end || idx < 0) {
+    return NaN;
+  }
+
+  code = str.charCodeAt(idx);
+
+  var hi, low;
+  if (0xD800 <= code && code <= 0xDBFF) {
+    hi = code;
+    low = str.charCodeAt(idx + 1);
+    // Go one further, since one of the "characters" is part of a surrogate pair
+    return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
+  }
+  return code;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.5', 'String.prototype.charCodeAt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.charcodeat', 'String.prototype.charCodeAt')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.charcodeat', 'String.prototype.charCodeAt')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.charCodeAt")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/concat/index.html b/files/ko/web/javascript/reference/global_objects/string/concat/index.html new file mode 100644 index 0000000000..1d5b4f2cd6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/concat/index.html @@ -0,0 +1,105 @@ +--- +title: String.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/String/concat +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/concat +--- +
{{JSRef}}
+ +

concat() 메서드는 매개변수로 전달된 모든 문자열을 호출 문자열에 붙인 새로운 문자열을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/string-concat.html")}}

+ +

구문

+ +
str.concat(string2, string3[, ..., stringN])
+ +

매개변수

+ +
+
string2...stringN
+
합칠 문자열.
+
+ +

반환값

+ +

주어진 문자열을 모두 붙인 새로운 문자열.

+ +

설명

+ +

concat() 함수는 호출 문자열에 문자열 인수를 이어 붙인 결과를 반환합니다. 원본 문자열과 결과 문자열의 변형은 서로에게 영향을 미치지 않습니다. 인수가 문자열이 아니면 계산 전에 문자열로 변환합니다.

+ +

예제

+ +

concat() 사용하기

+ +

아래 예제에서는 문자열을 결합하여 새로운 문자열을 만듭니다.

+ +
var hello = 'Hello, ';
+console.log(hello.concat('Kevin', '. Have a nice day.'));
+/* Hello, Kevin. Have a nice day. */
+
+var greetList = ['Hello', ' ', 'Venkat', '!'];
+"".concat(...greetList); // "Hello Venkat!"
+
+"".concat({}); // [object Object]
+"".concat([]); // ""
+"".concat(null); // "null"
+"".concat(true); // "true"
+"".concat(4, 5); // "45"
+ +

성능

+ +

concat() 메서드보다 {{jsxref("Operators/Assignment_Operators", "할당 연산자", "", 1)}} (+, +=)를 사용하는게 더 좋습니다. 성능 테스트 결과에 따르면 할당 연산자의 속도가 몇 배 빠릅니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.6', 'String.prototype.concat')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.String.concat")}}

+ +
+ +
+ +

관련문서

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/endswith/index.html b/files/ko/web/javascript/reference/global_objects/string/endswith/index.html new file mode 100644 index 0000000000..d78645e9f3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/endswith/index.html @@ -0,0 +1,142 @@ +--- +title: String.prototype.endsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/endsWith +translation_of: Web/JavaScript/Reference/Global_Objects/String/endsWith +--- +
{{JSRef}}
+ +

The endsWith() 메서드를 사용하여 어떤 문자열에서 특정 문자열로 끝나는지를 확인할 수 있으며, 그 결과를 true 혹은 false로 반환한다. 

+ +

문법

+ +
str.endsWith(searchString[, length])
+ +

파라미터들

+ +
+
searchString
+
이 문자열의 끝이 특정 문자열로 끝나는지를 찾기 원하는 문자열입니다.
+
length
+
옵션입니다. 찾고자 하는 문자열의 길이값이며, 기본값은 문자열 전체 길이입니다. 문자열의 길이값은 문자열 전체 길이 안에서만 존재하여야 합니다.
+
+ +

반환 값

+ +

문자열의 끝이 주어진 문자열로 끝나면 true, 그렇지 않다면 false

+ +

설명

+ +

여러분은 이 메서드를 사용하여 어떤 문자열이 특정 문자열로 끝나는지를 확인할 수 있습니다.

+ +

예제

+ +

endsWith() 사용하기

+ +
var str = 'To be, or not to be, that is the question.';
+
+console.log(str.endsWith('question.')); // true
+console.log(str.endsWith('to be'));     // false
+console.log(str.endsWith('to be', 19)); // true
+
+ +

Polyfill

+ +

이 메서드는 ECMAScript 6 규격에 포함되었습니다만 아직까지는 모든 JavaScrpt가 이 기능을 지원하고 있지는 않습니다. 하지만 여러분은 String.prototype.endsWith() 메서드를 다음과 같이 쉽게 polyfill 할 수 있습니다:

+ +
if (!String.prototype.endsWith) {
+  String.prototype.endsWith = function(searchString, position) {
+      var subjectString = this.toString();
+      if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
+        position = subjectString.length;
+      }
+      position -= searchString.length;
+      var lastIndex = subjectString.indexOf(searchString, position);
+      return lastIndex !== -1 && lastIndex === position;
+  };
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.endswith', 'String.prototype.endsWith')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome("41")}}{{CompatGeckoDesktop("17")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatSafari("9")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("36")}}{{CompatGeckoMobile("17")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

관련문서

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html b/files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html new file mode 100644 index 0000000000..98b1627666 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/fromcharcode/index.html @@ -0,0 +1,101 @@ +--- +title: String.fromCharCode() +slug: Web/JavaScript/Reference/Global_Objects/String/fromCharCode +tags: + - JavaScript + - Method + - Reference + - String + - Unicode +translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCharCode +--- +
{{JSRef}}
+ +

String.fromCharCode() 메서드는 UTF-16 코드 유닛의 시퀀스로부터 문자열을 생성해 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-fromcharcode.html")}}
+ + + +

구문

+ +
String.fromCharCode(num1[, ...[, numN]])
+ +

매개변수

+ +
+
num1, ..., numN
+
UTF-16 코드 유닛인 숫자 뭉치. 가능한 값의 범위는 0부터 65535(0xFFFF)까지입니다. 0xFFFF를 초과하는 값은 잘립니다. 유효성 검사는 하지 않습니다.
+
+ +

반환 값

+ +

주어진 UTF-16 코드 유닛 N개로 이루어진 문자열.

+ +

설명

+ +

이 메서드는 {{jsxref("String")}} 객체가 아닌 문자열을 반환합니다.

+ +

fromCharCode()는 {{jsxref("String")}}의 정적 메서드이기 때문에 String.fromCharCode()로 사용해야 합니다.

+ +

예제

+ +

fromCharCode() 사용하기

+ +

다음 예제는 문자열 "ABC"를 반환합니다..

+ +
String.fromCharCode(65, 66, 67);  // "ABC"
+String.fromCharCode(0x2014)       // "—"
+String.fromCharCode(0x12014)      // 숫자 '1'은 무시해서 "—"
+
+ +

더 큰 값과 사용하기

+ +

초기 JavaScript 표준화 과정에서 예상했던 것처럼, 대부분의 흔한 유니코드 값을 16비트 숫자로 표현할 수 있고, fromCharCode()가 많은 흔한 값에서 하나의 문자를 반환할 수 있지만, 모든 유효한 유니코드 값(최대 21비트)을 처리하려면 fromCharCode()만으로는 부족합니다. 높은 코드 포인트의 문자는 써로게이트surrogate 값 두 개를 합쳐 하나의 문자를 표현하므로,{{jsxref("String.fromCodePoint()")}}(ES2015 표준) 메서드는 그러한 쌍을 높은 값의 문자로 변환할 수 있습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.3.2', 'StringfromCharCode')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.fromCharCode")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/includes/index.html b/files/ko/web/javascript/reference/global_objects/string/includes/index.html new file mode 100644 index 0000000000..a3eb79ad16 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/includes/index.html @@ -0,0 +1,125 @@ +--- +title: String.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/String/includes +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/includes +--- +
{{JSRef}}
+ +

includes() 메서드는 하나의 문자열이 다른 문자열에 포함되어 있는지를 판별하고, 결과를 true 또는 false 로 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/string-includes.html")}}

+ +

구문

+ +
str.includes(searchString[, position])
+ +

매개변수

+ +
+
searchString
+
이 문자열에서 찾을 다른 문자열.
+
position {{optional_inline}}
+
searchString을 찾기 시작할 위치. 기본값 0.
+
+ +

반환값

+ +

문자열을 찾아내면 true. 실패하면 false.

+ +

설명

+ +

includes() 메서드를 사용해 문자열 내에 찾고자 하는 다른 문자열이 있는지 확인할 수 있습니다.

+ +

대소문자 구분

+ +

includes() 메서드는 대소문자를 구별합니다. 예를 들어 아래 코드는 false를 반환합니다.

+ +
'Blue Whale'.includes('blue'); // returns false
+
+ +

예제

+ +

includes() 사용하기

+ +
var str = 'To be, or not to be, that is the question.';
+
+console.log(str.includes('To be'));       // true
+console.log(str.includes('question'));    // true
+console.log(str.includes('nonexistent')); // false
+console.log(str.includes('To be', 1));    // false
+console.log(str.includes('TO BE'));       // false
+
+ +

폴리필

+ +

이 메서드는 ECMAScript 6 규격에 포함되었습니다만 아직까지는 모든 JavaScrpt가 이 기능을 지원하고 있지는 않습니다. 하지만 여러분은 이 메서드를 다음과 같이 쉽게 polyfill 할 수 있습니다.

+ +
if (!String.prototype.includes) {
+  String.prototype.includes = function(search, start) {
+    'use strict';
+    if (typeof start !== 'number') {
+      start = 0;
+    }
+
+    if (start + search.length > this.length) {
+      return false;
+    } else {
+      return this.indexOf(search, start) !== -1;
+    }
+  };
+}
+
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.includes', 'String.prototype.includes')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.includes', 'String.prototype.includes')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.includes")}}
+ +

String.prototype.contains

+ +

Firefox 18 - 39에서, include() 메서드의 이름은 contains()이었습니다. contains() 함수는 아래와 같은 이유로 {{bug(1102219)}}에서 includes()로 변경되었습니다:

+ +

It's been reported that some websites using MooTools 1.2 broke on Firefox 17. This version of MooTools checks whether String.prototype.contains() exists and, if it doesn't,  MooTools adds its own function. With the introduction of this function in Firefox 17, the behavior of that check changed in a way that causes code based on MooTools' String.prototype.contains() implementation to break. As a result, the implementation was disabled in Firefox 17 and String.prototype.contains() was available one version later, in Firefox 18, when outreach to MooTools was leading to the release of MooTools version 1.2.6.

+ +

MooTools 1.3 forces its own version of String.prototype.contains(), so websites relying on it should not break. However, you should note that MooTools 1.3 signature and ECMAScript 6 signatures for this method differ (on the second argument). Later, MooTools 1.5+ changed the signature to match the ES6 standard.

+ +

Firefox 48에서, String.prototype.contains()은 제거되었습니다. 오직 String.prototype.includes()만 사용할 수 있습니다.

+ +

관련문서

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/index.html b/files/ko/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..68e9b021e5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,298 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

String 전역 객체는 문자열(문자의 나열)의 생성자입니다.

+ +

구문

+ +

문자열 리터럴은 다음과 같은 형식을 사용합니다.

+ +
'string text'
+"string text"
+"中文 español Deutsch English देवनागरी العربية português বাংলা русский 日本語 norsk bokmål ਪੰਜਾਬੀ 한국어 தமிழ் עברית"
+ +

문자열은 String 전역 객체를 직접 사용하여 생성할 수 있습니다.

+ +
String(thing)
+ +

매개변수

+ +
+
thing
+
문자열로 변환할 아무 값.
+
+

템플릿 리터럴

+
+
+ +

ECMAScript 2015 이후, 문자열 리터럴은 소위 템플릿 리터럴이 될 수 있습니다.

+ +
`hello world` `hello! world!` `hello ${who}` tag `<a>${who}</a>`
+ +

이스케이프 표현

+ +

일반적인 출력 문자 외의 특수 문자는 이스케이프 표현을 사용해 적을 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
코드출력
\XXX8진수 Latin-1 문자
\'작은따옴표
\"큰따옴표
\\역슬래시
\n개행
\r캐리지 리턴
\v세로 탭
\t
\b백 스페이스
\f폼 피드
\uXXXX유니코드 코드포인트
\u{X} ... \u{XXXXXX}유니코드 코드포인트 {{experimental_inline}}
\xXXLatin-1 문자
+ +
+

일부 다른 프로그래밍 언어와 달리, JavaScript는 작은따옴표와 큰따옴표 문자열을 구분하지 않습니다. 따라서 위의 이스케이프 문자는 작은따옴표나 큰따옴표에서 상관 없이 작동합니다.

+
+ +

긴 문자열 리터럴

+ +

작성한 코드가 매우 긴 문자열을 포함해야 하는 경우, 끝 없이 뻗어나가는 한 줄이나 편집기의 재량에 따라 자동으로 줄을 넘기는 대신 직접 여러 줄로 나누되 내용에는 영향을 주지 않고 싶을 때가 있을겁니다. 이런 상황에는 두 가지 방법을 사용할 수 있습니다.

+ +

우선 다음과 같이 + 연산자를 사용할 수 있습니다.

+ +
let longString = "여러 줄에 걸쳐 작성해야 할 정도로 " +
+                 "긴 문자열인데 왜 한 줄에 다 적으면 안되냐면 " +
+                 "코드를 읽기 힘들어지니까요.";
+ +

아니면 역슬래시 문자("\")를 각 줄의 맨 끝에 붙여 문자열이 이어진다는걸 표시할 수도 있습니다. 역슬래시 다음에 공백을 포함한 어떤 문자라도 붙으면 제대로 작동하지 않으므로 주의해야 합니다.

+ +
let longString = "여러 줄에 걸쳐 작성해야 할 정도로 \
+긴 문자열인데 왜 한 줄에 다 적으면 안되냐면 \
+코드를 읽기 힘들어지니까요.";
+ +

두 예시 모두 동일한 문자열을 생성합니다.

+ +

설명

+ +

문자열은 텍스트 형태로 표현될 수있는 데이터를 보관하는 데 유용합니다. 문자열에서 가장 많이 사용되는 작업들은 문자열의 길이를 확인하는 ({{jsxref("String.length", "length")}}), 문자열을 생성하고 연결하는 + 와 += 문자열 연산자, 서브문자열(substring)이 있는지 확인하고, 있으면 위치를 확인하는 {{jsxref("String.prototype.indexOf()", "indexOf()")}} 메서드, 서브문자열(substring)을 추출해내는 {{jsxref("String.prototype.substring()", "substring()")}} 메서드가 있습니다.

+ +

문자 접근

+ +

문자열에서 개개의 문자에 접근할 수 있는 방법은 두가지가 있습니다. 첫번째는 {{jsxref("String.prototype.charAt()", "charAt()")}} 메서드를 이용하는 것입니다:

+ +
return 'cat'.charAt(1); // returns "a"
+
+ +

다른 방법(ECMAScript 5에서 소개하고 있는)은 문자열을 배열과 같은 오브젝트로 취급하여, 문자에 해당하는 숫자 인덱스를 사용하는 방법입니다 :

+ +
return 'cat'[1]; // returns "a"
+
+ +

브라켓([ ]) 표기법을 사용하여 문자에 접근하는 경우 , 이러한 프로퍼티들에 새로운 값을 할당하거나 삭제할 수는 없습니다. 포함되어 있는 프로퍼티들은 작성할 수도, 수정할 수도 없습니다. (더 자세한 정보는 {{jsxref("Object.defineProperty()")}}를 참고 바랍니다 .)

+ +

문자열 비교

+ +

C 개발자는 문자열 비교를 위하여 strcmp() 함수를 사용합니다. JavaScript에서는 단지 less-than와 greater-than 연산자만을 사용하여 문자열을 비교할 수 있습니다 :

+ +
var a = "a";
+var b = "b";
+if (a < b) { // true
+  console.log(a + " is less than " + b);
+} else if (a > b) {
+  console.log(a + " is greater than " + b);
+} else {
+  console.log(a + " and " + b + " are equal.");
+}
+
+ +

비슷한 결과를 얻을 수 있는 방법으로 String 인스턴스에서 상속된 {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} 메서드를 사용할 수 있습니다.

+ +

문자열 원형과 String 객체의 차이

+ +
JavaScript는 String 오브젝트와 원형의 문자열을 다르게 취급한다는 것에 주의해야 합니다. ({{jsxref("Boolean")}}과 숫자의 true도 마찬가지입니다.)
+ +
 
+ +

문자열 리터럴(작은 따옴표 또는 큰 따옴표로 생성되는)과 생성자 없이(즉. {{jsxref("Operators/new", "new")}} 키워드를 사용하지 않고) String을 호출하여 반환된 문자열은 원형 문자열(primitive strings)입니다. JavaScript는 자동적으로 원형을 String 오브젝트로 변환하기 때문에, String 오브젝트 메서드를 사용하여 원형문자열을 생성할 수 있습니다. 문맥 안의 메서드에서 프로퍼티 조회 또는 원형의 문자열 호출이 발생하면, JavaScript는 자동으로 문자열 원형을 감싸고 프로퍼티 조회를 수행 하거나 메서드를 호출합니다.

+ +
var s_prim = "foo";
+var s_obj = new String(s_prim);
+
+console.log(typeof s_prim); // Logs "string"
+console.log(typeof s_obj);  // Logs "object"
+
+ +

문자열 원형과 String 오브젝트는 {{jsxref("Global_Objects/eval", "eval()")}}을 사용할 때 다른 결과를 제공합니다. eval에 전달되는 문자열 원형들은 소스 코드 취급을 받습니다; String 오브젝트들은 다른 모든 오브젝트들과 마찬가지로 취급하며, 오브젝트를 반환합니다. 예를 들면:

+ +
var s1 = '2 + 2';               // creates a string primitive
+var s2 = new String('2 + 2');   // creates a String object
+console.log(eval(s1));          // returns the number 4
+console.log(eval(s2));          // returns the string "2 + 2"
+
+ +

이러한 이유로, 비록 코드 상에서 원형 문자열을 사용하는 대신에 String 오브젝트를 사용하게 되면 코드가 손상될 수 있지만, 일반적인 개발자는 차이를 걱정할 필요는 없습니다.

+ +

String 오프젝트는 언제든지 {{jsxref("String.prototype.valueOf()", "valueOf()")}} 메서드로 원형에 대응하도록 전환할 수 있습니다.

+ +
console.log(eval(s2.valueOf())); // returns the number 4
+
+ +

속성

+ +
+
{{jsxref("String.prototype")}}
+
String 오브젝트는 프로퍼티의 추가가 가능합니다.
+
+ +

메서드

+ +
+
{{jsxref("String.fromCharCode()")}}
+
지정된 유니코 값의 순서를 이용하여 만든 문자열을 반환합니다.
+
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
+
지정된 코드 포인트 순서를 이용하여 만든 문자열을 반환합니다.
+
{{jsxref("String.raw()")}} {{experimental_inline}}
+
원형 템플릿 문자열(raw template string)에서 생성된 문자열을 반환합니다.
+
+ +

String generic 메서드

+ +
+

String generic들은 비표준으로, 가까운 미래에 사라질 것입니다. 아래에서 제공하고 있는 방식을 사용하지 않으면, 브라우저들간의 호환성은 기대하기 어렵습니다. 

+
+ +

String 인스턴스 메서드는 JavScript 1.6으로 Firefox에서(ECMAScript 표준에 속하지는 않지만) 어떤 오브젝트라도 String 메서드에 적용하여 String 오브젝트에서 사용가능합니다:

+ +
var num = 15;
+console.log(String.replace(num, /5/, '2'));
+
+ +

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}}은 {{jsxref("Global_Objects/Array", "Array")}} 메서드에도 사용 가능합니다.

+ +

String 인스턴스

+ +

속성

+ +

{{ page('ko/docs/JavaScript/Reference/Global_Objects/String/prototype', 'Properties') }}

+ +

메서드

+ +

HTML과 관계없는 메서드

+ +

{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}

+ +

HTML wrapper methods

+ +

{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}

+ +

예제

+ +

문자열 변환

+ +

비록 일반적으로 toString() 함수를 많이 사용하고 있지만, {{jsxref("String.prototype.toString()", "toString()")}}의 "안전한" 대안으로 String을 사용할 수 있습니다. String은 {{jsxref("Global_Objects/null", "null")}}과 {{jsxref("Global_Objects/undefined", "undefined")}}에 대해서도 잘 동작합니다. 예를 들면: 

+ +
var outputStrings = [];
+for (var i = 0, n = inputValues.length; i < n; ++i) {
+  outputStrings.push(String(inputValues[i]));
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string-objects', 'String')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String",2)}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/indexof/index.html b/files/ko/web/javascript/reference/global_objects/string/indexof/index.html new file mode 100644 index 0000000000..3e12f74d51 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/indexof/index.html @@ -0,0 +1,159 @@ +--- +title: String.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/indexOf +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf +--- +
{{JSRef}}
+ +

indexOf() 메서드는 호출한 {{jsxref("String")}} 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환합니다. 일치하는 값이 없으면 -1을 반환합니다. 

+ +
{{EmbedInteractiveExample("pages/js/string-indexof.html")}}
+ + + +
+

참고: {{jsxref("Array")}}에서는 {{jsxref("Array.prototype.indexOf()")}} 메서드가 같은 역할을 합니다.

+
+ +

구문

+ +
str.indexOf(searchValue[, fromIndex])
+ +

매개변수

+ +
+
searchValue
+
찾으려는 문자열. 아무 값도 주어지지 않으면 문자열 "undefined"를 찾으려는 문자열로 사용합니다.
+
fromIndex {{optional_inline}}
+
문자열에서 찾기 시작하는 위치를 나타내는 인덱스 값입니다. 어떤 정수값이라도 가능합니다. 기본값은 0이며, 문자열 전체를 대상으로 찾게 됩니다. 만약 fromIndex 값이 음의 정수이면 전체 문자열을 찾게 됩니다. 만약 fromIndex >= str.length 이면, 검색하지 않고 바로 -1을 반환합니다. searchValue가 공백 문자열이 아니라면, str.length를 반환합니다.
+
+ +

반환 값

+ +

searchValue의 첫 번째 등장 인덱스. 찾을 수 없으면 -1.

+ +

설명

+ +

문자열 내에 있는 문자들은 왼쪽에서 오른쪽 방향으로 순번이 매겨집니다. 제일 처음 문자는 0번째 순번(index)이며, stringName 문자열의 마지막 문자의 순번 stringName.length -1 입니다. 

+ +
'Blue Whale'.indexOf('Blue');     // returns  0
+'Blue Whale'.indexOf('Blute');    // returns -1
+'Blue Whale'.indexOf('Whale', 0); // returns  5
+'Blue Whale'.indexOf('Whale', 5); // returns  5
+'Blue Whale'.indexOf('Whale', 7); // returns -1
+'Blue Whale'.indexOf('');         // returns  0
+'Blue Whale'.indexOf('', 9);      // returns  9
+'Blue Whale'.indexOf('', 10);     // returns 10
+'Blue Whale'.indexOf('', 11);     // returns 10
+ +

indexOf() 메서드는 대소문자를 구분합니다. 예를 들면, 아래 예제는 일치하는 문자열이 없으므로 -1을 반환합니다.

+ +
'Blue Whale'.indexOf('blue'); // returns -1
+
+ +

존재 여부 확인

+ +

'0'을 평가했을 때 true가 아니고, -1을 평가했을 때 false가 아닌 것에 주의해야 합니다. 따라서, 임의의 문자열에 특정 문자열이 있는지를 확인하는 올바른 방법은 다음과 같습니다.

+ +
'Blue Whale'.indexOf('Blue') !== -1; // true
+'Blue Whale'.indexOf('Bloe') !== -1; // false
+
+ +

예제

+ +

indexOf() 사용하기

+ +

아래 예제는 "Brave new world" 문자열의 위치를 확인하기 위해 indexOf()와 {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} 를 사용하고 있습니다.

+ +
var anyString = 'Brave new world';
+
+console.log('The index of the first w from the beginning is ' + anyString.indexOf('w'));
+// 첫번째 w 문자 위치는 8
+console.log('The index of the first w from the end is ' + anyString.lastIndexOf('w'));
+// 마지막 w 문자 위치는 10
+
+console.log('The index of "new" from the beginning is ' + anyString.indexOf('new'));
+// 첫번째 new 문자열 위치는 6
+console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new'));
+// 마지막 new 문자열 위치는 6
+
+ +

indexOf()와 대소문자 구분

+ +

아래 예제에서는 2개의 문자열 변수를 정의하고 있습니다. 이 변수들 내에 있는 문자열들은 모두 같지만 두 번째 변수에 포함되어 있는 문자열은 대문자를 포함하고 있습니다. 첫 번째 {{domxref("console.log()")}} 메서드의 결과값은 19입니다. 하지만, 두 번째 console.log() 메서드의 결과값은 -1입니다. 왜냐하면, indexOf() 메서드는 대소문자를 구분하기 때문에 myCapString에서 "cheddar" 문자열을 찾을 수 없기 때문입니다. 

+ +
var myString    = 'brie, pepper jack, cheddar';
+var myCapString = 'Brie, Pepper Jack, Cheddar';
+
+console.log('myString.indexOf("cheddar") is ' + myString.indexOf('cheddar'));
+// 로그에 19를 출력합니다.
+console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar'));
+// 로그에 -1을 출력합니다.
+
+ +

indexOf()를 사용하여 문자열 내의 특정 문자 숫자 세기

+ +

아래 예제는 str 문자열에서 e 문자의 총 숫자를 확인하는 프로그램입니다:

+ +
var str = 'To be, or not to be, that is the question.';
+var count = 0;
+var pos = str.indexOf('e'); //pos는 4의 값을 가집니다.
+
+while (pos !== -1) {
+  count++;
+  pos = str.indexOf('e', pos + 1); // 첫 번째 e 이후의 인덱스부터 e를 찾습니다.
+}
+
+console.log(count); // 로그에 4를 출력합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.indexOf")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html b/files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html new file mode 100644 index 0000000000..d2244feee5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/lastindexof/index.html @@ -0,0 +1,105 @@ +--- +title: String.prototype.lastIndexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/lastIndexOf +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/lastIndexOf +--- +
{{JSRef}}
+ +

lastIndexOf() 메서드는 주어진 값과 일치하는 부분을 fromIndex로부터 역순으로 탐색하여, 최초로 마주치는 인덱스를 반환합니다. 일치하는 부분을 찾을 수 없으면 -1을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-lastindexof.html", "shorter")}}
+ + + +

구문

+ +
str.lastIndexOf(searchValue[, fromIndex])
+ +

매개변수

+ +
+
searchValue
+
탐색할 문자열. 빈 값을 제공할 경우 fromIndex를 반환합니다.
+
fromIndex {{optional_inline}}
+
탐색의 시작점으로 사용할 인덱스. 기본값은 +Infinity입니다. fromIndex >= str.length인 경우 모든 문자열을 탐색합니다. fromIndex < 0인 경우엔 0을 지정한 것과 동일합니다.
+
+ +

반환 값

+ +

문자열 내에서 searchValue가 마지막으로 등장하는 인덱스. 등장하지 않으면 -1.

+ +

설명

+ +

문자열의 문자는 왼쪽에서 오른쪽으로 인덱스를 매깁니다. 첫 번째 문자의 인덱스는 0이며, 마지막 문자의 인덱스는 str.length -1입니다.

+ +
'canal'.lastIndexOf('a');     //  3 반환
+'canal'.lastIndexOf('a', 2);  //  1 반환
+'canal'.lastIndexOf('a', 0);  // -1 반환
+'canal'.lastIndexOf('x');     // -1 반환
+'canal'.lastIndexOf('c', -5); //  0 반환
+'canal'.lastIndexOf('c', 0);  //  0 반환
+'canal'.lastIndexOf('');      //  5 반환
+'canal'.lastIndexOf('', 2);   //  2 반환
+
+ +
+

참고: 'abab'.lastIndexOf('ab', 2)는 0이 아니고 2를 반환합니다. fromIndex는 탐색의 시작점만 제한하기 때문입니다.

+
+ +

대소문자 구분

+ +

lastIndexOf() 메서드는 대소문자를 구분합니다. 예를 들어, 아래 예제는 -1을 반환합니다.

+ +
'Blue Whale, Killer Whale'.lastIndexOf('blue'); // -1 반환
+
+ +

예제

+ +

indexOf()와 lastIndexOf() 사용하기

+ +

아래 예제는 문자열 "Brave new world" 내에서 특정 값의 위치를 확인하기 위해 {{jsxref("String.prototype.indexOf()", "indexOf()")}}와 lastIndexOf()를 사용합니다.

+ +
let anyString = 'Brave new world';
+
+console.log('시작점으로부터 처음 만나는 w의 위치는 ' + anyString.indexOf('w'));
+// logs 8
+console.log('끝점으로부터 처음 만나는 w의 위치는 ' + anyString.lastIndexOf('w'));
+// logs 10
+console.log('시작점으로부터 처음 만나는 "new"의 위치는 ' + anyString.indexOf('new'));
+// logs 6
+console.log('끝점으로부터 처음 만나는 "new"의 위치는 ' + anyString.lastIndexOf('new'));
+// logs 6
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-string.prototype.lastindexof', 'String.prototype.lastIndexOf')}}
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.lastIndexOf")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/length/index.html b/files/ko/web/javascript/reference/global_objects/string/length/index.html new file mode 100644 index 0000000000..697957aaf9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/length/index.html @@ -0,0 +1,84 @@ +--- +title: String.length +slug: Web/JavaScript/Reference/Global_Objects/String/length +tags: + - JavaScript + - Property + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/length +--- +
{{JSRef}}
+ +

length 속성은 UTF-16 코드 유닛을 기준으로 문자열의 길이를 나타냅니다.

+ +
{{EmbedInteractiveExample("pages/js/string-length.html")}}
+ + + +

설명

+ +

length 속성은 문자열 안의 코드 유닛 수를 반환합니다. JavaScript가 사용하는 문자열 형식인 {{interwiki("wikipedia", "UTF-16")}}은 대부분의 일반적인 문자를 표현하기 위해 하나의 16비트 코드 유닛을 사용합니다. 반면, 덜 쓰이는 문자를 표현하기 위해 2개의 코드 유닛을 사용해야 할 때도 있으므로 문자열 내에 있는 문자들의 실제 총 숫자가 length 속성이 반환하는 숫자와 일치하지 않을 수 있습니다.

+ +

ECMAScript 2016 7판은 최대 길이를 2^53 - 1로 설정했습니다. 이전엔 명시된 최대 길이가 없었습니다.

+ +

빈 문자열은 length가 0입니다.

+ +

정적 속성 String.length는 1을 반환합니다. 

+ +

예제

+ +

일반적인 사용법

+ +
var x = 'Mozilla';
+var empty = '';
+
+console.log('Mozilla는 코드 유닛 ' + x.length + '개의 길이입니다.');
+/* "Mozilla는 코드 유닛 7개의 길이입니다." */
+
+console.log('빈 문자열은 ' + empty.length + '의 길이를 가집니다.');
+/* "빈 문자열은 0의 길이를 가집니다." */
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.length")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/localecompare/index.html b/files/ko/web/javascript/reference/global_objects/string/localecompare/index.html new file mode 100644 index 0000000000..9bd3b19236 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/localecompare/index.html @@ -0,0 +1,159 @@ +--- +title: String.prototype.localeCompare() +slug: Web/JavaScript/Reference/Global_Objects/String/localeCompare +translation_of: Web/JavaScript/Reference/Global_Objects/String/localeCompare +--- +
{{JSRef}}
+ +

The localeCompare() 메서드는 기준 문자열과 비교했을 때 비교 대상 문자열이 정렬상 전에 오는지, 후에 오는지 혹은 같은 순서에 배치되는지를 알려주는 숫자를 리턴합니다.

+ +

The new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation dependent.

+ +

Syntax

+ +
referenceStr.localeCompare(compareString[, locales[, options]])
+ +

Parameters

+ +

Check the Browser compatibility section to see which browsers support the locales and options arguments, and the Checking for support for locales and options arguments for feature detection.

+ +
+
compareString
+
The string against which the referring string is compared
+
+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator', 'Parameters')}}
+ +

Return value

+ +

A negative number if the reference string occurs before the compare string; positive if the reference string occurs after the compare string; 0 if they are equivalent.

+ +

Description

+ +

Returns an integer indicating whether the referenceStr comes before, after or is equivalent to the compareStr.

+ + + +

DO NOT rely on exact return values of -1 or 1. Negative and positive integer results vary between browsers (as well as between browser versions) because the W3C specification only mandates negative and positive values. Some browsers may return -2 or 2 or even some other negative or positive value.

+ +

Examples

+ +

Using localeCompare()

+ +
// The letter "a" is before "c" yielding a negative value
+'a'.localeCompare('c'); // -2 or -1 (or some other negative value)
+
+// Alphabetically the word "check" comes after "against" yielding a positive value
+'check'.localeCompare('against'); // 2 or 1 (or some other positive value)
+
+// "a" and "a" are equivalent yielding a neutral value of zero
+'a'.localeCompare('a'); // 0
+
+ +

Sort an array

+ +

localeCompare enables a case-insensitive sort of an array.

+ +
var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
+items.sort((a, b) => a.localeCompare(b)); // ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
+
+ +

Check browser support for extended arguments

+ +

The locales and options arguments are not supported in all browsers yet. To check whether an implementation supports them, use the "i" argument (a requirement that illegal language tags are rejected) and look for a {{jsxref("RangeError")}} exception:

+ +
function localeCompareSupportsLocales() {
+  try {
+    'foo'.localeCompare('bar', 'i');
+  } catch (e) {
+    return e.name === 'RangeError';
+  }
+  return false;
+}
+
+ +

Using locales

+ +

The results provided by localeCompare() vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument:

+ +
console.log('ä'.localeCompare('z', 'de')); // a negative value: in German, ä sorts before z
+console.log('ä'.localeCompare('z', 'sv')); // a positive value: in Swedish, ä sorts after z
+
+ +

Using options

+ +

The results provided by localeCompare() can be customized using the options argument:

+ +
// in German, ä has a as the base letter
+console.log('ä'.localeCompare('a', 'de', { sensitivity: 'base' })); // 0
+
+// in Swedish, ä and a are separate base letters
+console.log('ä'.localeCompare('a', 'sv', { sensitivity: 'base' })); // a positive value
+
+ +

Performance

+ +

When comparing large numbers of strings, such as in sorting large arrays, it is better to create an {{jsxref("Global_Objects/Collator", "Intl.Collator")}} object and use the function provided by its {{jsxref("Collator.prototype.compare", "compare")}} property.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.9', 'String.prototype.localeCompare')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.localecompare', 'String.prototype.localeCompare')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.localecompare', 'String.prototype.localeCompare')}}{{Spec2('ESDraft')}} 
{{SpecName('ES Int 1.0', '#sec-13.1.1', 'String.prototype.localeCompare')}}{{Spec2('ES Int 1.0')}}locale and option parameter definitions.
{{SpecName('ES Int 2.0', '#sec-13.1.1', 'String.prototype.localeCompare')}}{{Spec2('ES Int 2.0')}} 
{{SpecName('ES Int Draft', '#sec-String.prototype.localeCompare', 'String.prototype.localeCompare')}}{{Spec2('ES Int Draft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.localeCompare")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/match/index.html b/files/ko/web/javascript/reference/global_objects/string/match/index.html new file mode 100644 index 0000000000..e1031b8a0e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/match/index.html @@ -0,0 +1,156 @@ +--- +title: String.prototype.match() +slug: Web/JavaScript/Reference/Global_Objects/String/match +translation_of: Web/JavaScript/Reference/Global_Objects/String/match +--- +
{{JSRef}}
+ +
+ +

match() 메서드는 문자열이 정규식과 매치되는 부분을 검색합니다.

+ +

문법

+ +
str.match(regexp)
+ +

매개변수

+ +
+
regexp
+
정규식 개체입니다.  RegExp가 아닌 객체 obj가 전달되면, new RegExp(obj)를 사용하여 암묵적으로 {{jsxref("RegExp")}}로 변환됩니다. 매개변수를 전달하지 않고 match()를 사용하면, 빈 문자열:[""]이 있는 {{jsxref("Array")}}가 반환됩니다.
+
+ +

결과 값

+ +

문자열이 정규식과 일치하면, 일치하는 전체 문자열을 첫 번째 요소로 포함하는 {{jsxref("Array")}}를 반환한 다음 괄호 안에 캡처된 결과가 옵니다. 일치하는 것이 없으면 {{jsxref("null")}}이 반환됩니다.

+ +

설명

+ +

정규식에 g 플래그가 포함되어있지 않으면, str.match() 는 {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}와 같은 결과를 반환합니다. 반환된 {{jsxref("Array")}}는 원래 문자열의 값을 가지는 input 속성을 포함합니다. 그리고 문자열에서 제로 베이스의 인덱스를 나타내는 index 속성 또한 포함합니다.

+ +

정규식에 g 플래그가 포함되어 있으면, 일치는 객체가 아닌 일치하는 하위 문자열을 포함하는 {{jsxref("Array")}}를 반환합니다. 캡처된 그룹은 반환되지 않습니다. 일치하는 것이 없으면 null이 반환됩니다.

+ +

이것도 보세요: RegExp 메서드

+ + + +

예제

+ +

match() 사용하기

+ +

다음 예제에서는, match()를 사용하여 'Chapter' 라는 단어와 그에 이어지는 1 이상의 숫자, 그리고 그에 이어서 소숫점, 숫자 형태가 반복되는 문자열을 찾는다. 이 정규표현식은 i 플래그를 사용함으로써, 대소문자 구분 없이 찾고자 하는 문자열을 찾는다.

+ +
var str = 'For more information, see Chapter 3.4.5.1';
+var re = /see (chapter \d+(\.\d)*)/i;
+var found = str.match(re);
+
+console.log(found);
+
+// logs [ 'see Chapter 3.4.5.1',
+//        'Chapter 3.4.5.1',
+//        '.1',
+//        index: 22,
+//        input: 'For more information, see Chapter 3.4.5.1' ]
+
+// 'see Chapter 3.4.5.1'는 완전한 매치 상태임.
+// 'Chapter 3.4.5.1'는 '(chapter \d+(\.\d)*)' 부분에 의해 발견된 것임.
+// '.1' 는 '(\.\d)'를 통해 매치된 마지막 값임.
+// 'index' 요소가 (22)라는 것은 0에서부터 셀 때 22번째 위치부터 완전 매치된 문자열이 나타남을 의미함.
+// 'input' 요소는 입력된 원래 문자열을 나타냄.
+ +

match()와 함께 글로벌(g) 및 대/소문자 무시(i) 플래그 사용하기

+ +

다음 예제는 글로벌(g) 및 대/소문자 무시(i) 플래그를 사용하여  match()를 사용하는 방법을 보여준다. A부터 E 까지의 모든 문자와 a부터 e 까지의 모든 문자가 배열의 각 원소를 구성하는 형태로 반환된다.

+ +
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
+var regexp = /[A-E]/gi;
+var matches_array = str.match(regexp);
+
+console.log(matches_array);
+// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
+
+ +

매개변수 없이 match() 사용하기

+ +
var str = "Nothing will come of nothing.";
+
+str.match();   // returns [""]
+ +

정규표현식이 아닌 객체를 매개변수로 사용하기

+ +

매개변수가 문자열이나 숫자(Number)이면, 해당 매개변수는 내부적으로 new RegExp(obj)를 사용하여 {{jsxref("RegExp")}}로 변환된다. 만약 매개변수가 플러스 기호와 이어지는 숫자형이라면, RegExp() 매서드는 플러스 기호를 무시한다. 

+ +
var str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.",
+    str2 = "My grandfather is 65 years old and My grandmother is 63 years old.",
+    str3 = "The contract was declared null and void.";
+str1.match("number");   // "number"는 문자열임. ["number"]를 반환함.
+str1.match(NaN);        // NaN 타입은 숫자형임. ["NaN"]을 반환함.
+str1.match(Infinity);   // Infinity 타입은 숫자형임. ["Infinity"]를 반환함.
+str1.match(+Infinity);  // ["Infinity"]를 반환함.
+str1.match(-Infinity);  // ["-Infinity"]를 반환함.
+str2.match(65);         // ["65"]를 반환함
+str2.match(+65);        // 플러스 기호가 붙은 숫자형. ["65"]를 반환함.
+str3.match(null);       // ["null"]을 반환함.
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.10', 'String.prototype.match')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.match")}}

+ +

Firefox-specific notes

+ + + + + +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/normalize/index.html b/files/ko/web/javascript/reference/global_objects/string/normalize/index.html new file mode 100644 index 0000000000..d44f9bec99 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/normalize/index.html @@ -0,0 +1,163 @@ +--- +title: String.prototype.normalize() +slug: Web/JavaScript/Reference/Global_Objects/String/normalize +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - String + - Unicode +translation_of: Web/JavaScript/Reference/Global_Objects/String/normalize +--- +
{{JSRef}}
+ +

normalize() 메서드는 주어진 문자열을 유니코드 정규화 방식(Unicode Normalization Form)에 따라 정규화된 형태로 반환합니다. 만약 주어진 값이 문자열이 아닐 경우에는 우선 문자열로 변환 후 정규화합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-normalize.html")}}
+ + + +

구문

+ +
str.normalize([form])
+ +

매개변수

+ +
+
form
+
유니코드 정규화 방식을 지정합니다. "NFC", "NFD", "NFKC""NFKD" 중 하나이며, 생략되거나 {{jsxref("undefined")}} 일 경우 "NFC"가 사용됩니다. +
    +
  • NFC — 정규형 정준 결합(Normalization Form Canonical Composition).
  • +
  • NFD — 정규형 정준 분해(Normalization Form Canonical Decomposition).
  • +
  • NFKC — 정규형 호환성 결합(Normalization Form Compatibility Composition).
  • +
  • NFKD — 정규형 호환성 분해(Normalization Form Compatibility Decomposition).
  • +
+
+
+ +

반환 값

+ +

주어진 문자열을 유니코드 정규화 방식에 따라 정규화된 문자열로 반환합니다.

+ +

예외

+ +
+
{{jsxref("RangeError")}}
+
form이 위에서 명시된 값 중 하나가 아닐 경우 {{jsxref("RangeError")}} 에러가 발생합니다.
+
+ +

설명

+ +

normalize() 메서드는 문자열을 유니코드 정규화 방식에 따라 정규화된 형태로 반환합니다. 문자열의 값 자체에는 영향을 주지 않습니다.

+ +

예제

+ +

normalize() 사용하기

+ +
// 원본 문자열
+
+// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
+// U+0323: COMBINING DOT BELOW
+var str = '\u1E9B\u0323';
+
+
+// 정규형 정준 결합 (NFC)
+
+// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
+// U+0323: COMBINING DOT BELOW
+str.normalize('NFC'); // '\u1E9B\u0323'
+str.normalize();      // 위와 같은 결과
+
+
+// 정규형 정준 분해 (NFD)
+
+// U+017F: LATIN SMALL LETTER LONG S
+// U+0323: COMBINING DOT BELOW
+// U+0307: COMBINING DOT ABOVE
+str.normalize('NFD'); // '\u017F\u0323\u0307'
+
+
+// 정규형 호환성 결합 (NFKC)
+
+// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE
+str.normalize('NFKC'); // '\u1E69'
+
+
+// 정규형 호환성 분해 (NFKD)
+
+// U+0073: LATIN SMALL LETTER S
+// U+0323: COMBINING DOT BELOW
+// U+0307: COMBINING DOT ABOVE
+str.normalize('NFKD'); // '\u0073\u0323\u0307'
+
+ +

한글에 normalize() 사용하기

+ +
// 결합된 한글 문자열
+
+// U+D55C: 한(HANGUL SYLLABLE HAN)
+// U+AE00: 글(HANGUL SYLLABLE GEUL)
+var first = '\uD55C\uAE00';
+
+
+// 정규형 정준 분해 (NFD)
+// 정준 분해 결과 초성, 중성, 종성의 자소분리가 일어납니다.
+// 일부 브라우저에서는 결과값 '한글'이 자소분리된 상태로 보여질 수 있습니다.
+
+// U+1112: ᄒ(HANGUL CHOSEONG HIEUH)
+// U+1161: ᅡ(HANGUL JUNGSEONG A)
+// U+11AB: ᆫ(HANGUL JONGSEONG NIEUN)
+// U+1100: ᄀ(HANGUL CHOSEONG KIYEOK)
+// U+1173: ᅳ(HANGUL JUNGSEONG EU)
+// U+11AF: ᆯ(HANGUL JONGSEONG RIEUL)
+var second = first.normalize('NFD'); // '\u1112\u1161\u11AB\u1100\u1173\u11AF'
+
+
+// 정규형 정준 결합 (NFC)
+// 정준 결합 결과 자소분리 되었던 한글이 결합됩니다.
+
+// U+D55C: 한(HANGUL SYLLABLE HAN)
+// U+AE00: 글(HANGUL SYLLABLE GEUL)
+var third = second.normalize('NFC'); // '\uD55C\uAE00'
+
+
+console.log(second === third); // 같은 글자처럼 보이지만 false를 출력합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ES2015')}}초기 정의.
{{SpecName('ESDraft', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.normalize")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/padend/index.html b/files/ko/web/javascript/reference/global_objects/string/padend/index.html new file mode 100644 index 0000000000..1c027c1363 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/padend/index.html @@ -0,0 +1,99 @@ +--- +title: String.prototype.padEnd() +slug: Web/JavaScript/Reference/Global_Objects/String/padEnd +tags: + - JavaScript + - Method + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/padEnd +--- +
{{JSRef}}
+ +

padEnd() 메서드는 현재 문자열에 다른 문자열을 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 끝(우측)부터 적용됩니다.

+ +
{{EmbedInteractiveExample("pages/js/string-padend.html")}}
+ + + +

구문

+ +
str.padEnd(targetLength [, padString])
+ +

매개변수

+ +
+
targetLength
+
목표 문자열 길이. 현재 문자열의 길이보다 작다면 채워넣지 않고 그대로 반환.
+
padString {{optional_inline}}
+
현재 문자열에 채워넣을 다른 문자열. 문자열이 너무 길어 목표 문자열 길이를 초과한다면 좌측 일부를 잘라서 넣음. 기본값은 " ". (U+0020)
+
+ +

반환값

+ +

끝부터 주어진 문자열로 채워 목표 길이를 만족하는 {{jsxref("String")}}

+ +

예시

+ +
'abc'.padEnd(10);          // "abc       "
+'abc'.padEnd(10, "foo");   // "abcfoofoof"
+'abc'.padEnd(6, "123456"); // "abc123"
+'abc'.padEnd(1);           // "abc"
+ +

폴리필

+ +

다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 String.prototype.padStart() 메서드를 사용할 수 있습니다.

+ +
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
+if (!String.prototype.padEnd) {
+    String.prototype.padEnd = function padEnd(targetLength,padString) {
+        targetLength = targetLength>>0; //floor if number or convert non-number to 0;
+        padString = String((typeof padString !== 'undefined' ? padString : ' '));
+        if (this.length > targetLength) {
+            return String(this);
+        }
+        else {
+            targetLength = targetLength-this.length;
+            if (targetLength > padString.length) {
+                padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed
+            }
+            return String(this) + padString.slice(0,targetLength);
+        }
+    };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}{{Spec2('ESDraft')}}Initial definition in ECMAScript 2017.
{{SpecName('ES8', '#sec-string.prototype.padend', 'String.prototype.padEnd')}}{{Spec2('ES8')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.padEnd")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/padstart/index.html b/files/ko/web/javascript/reference/global_objects/string/padstart/index.html new file mode 100644 index 0000000000..eff03dd4ac --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/padstart/index.html @@ -0,0 +1,104 @@ +--- +title: String.prototype.padStart() +slug: Web/JavaScript/Reference/Global_Objects/String/padStart +tags: + - JavaScript + - Method + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/padStart +--- +
{{JSRef}}
+ +

padStart() 메서드는 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 시작(좌측)부터 적용됩니다.

+ +

 

+ +
{{EmbedInteractiveExample("pages/js/string-padstart.html")}}
+ + + +

 

+ +

구문

+ +
str.padStart(targetLength [, padString])
+ +

매개변수

+ +
+
targetLength
+
목표 문자열 길이. 현재 문자열의 길이보다 작다면 채워넣지 않고 그대로 반환.
+
padString {{optional_inline}}
+
현재 문자열에 채워넣을 다른 문자열. 문자열이 너무 길어 목표 문자열 길이를 초과한다면 좌측 일부를 잘라서 넣음. 기본값은 " ". (U+0020)
+
+ +

반환값

+ +

시작점부터 주어진 문자열로 채워 목표 길이를 만족하는 {{jsxref("String")}}.

+ +

예시

+ +
'abc'.padStart(10);         // "       abc"
+'abc'.padStart(10, "foo");  // "foofoofabc"
+'abc'.padStart(6,"123465"); // "123abc"
+'abc'.padStart(8, "0");     // "00000abc"
+'abc'.padStart(1);          // "abc"
+ +

폴리필

+ +

다른 모든 코드 이전에 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 String.prototype.padStart() 메서드를 사용할 수 있습니다.

+ +
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
+if (!String.prototype.padStart) {
+    String.prototype.padStart = function padStart(targetLength,padString) {
+        targetLength = targetLength>>0; //truncate if number or convert non-number to 0;
+        padString = String((typeof padString !== 'undefined' ? padString : ' '));
+        if (this.length > targetLength) {
+            return String(this);
+        }
+        else {
+            targetLength = targetLength-this.length;
+            if (targetLength > padString.length) {
+                padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed
+            }
+            return padString.slice(0,targetLength) + String(this);
+        }
+    };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}{{Spec2('ESDraft')}}Initial definition in ECMAScript 2017.
{{SpecName('ES8', '#sec-string.prototype.padstart', 'String.prototype.padStart')}}{{Spec2('ES8')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.padStart")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/prototype/index.html b/files/ko/web/javascript/reference/global_objects/string/prototype/index.html new file mode 100644 index 0000000000..707680d3c4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/prototype/index.html @@ -0,0 +1,218 @@ +--- +title: String.prototype +slug: Web/JavaScript/Reference/Global_Objects/String/prototype +tags: + - JavaScript + - Property + - Prototype + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef("Global_Objects", "String")}}
+ +

요약

+ +

String.prototype 프라퍼티는 {{jsxref("Global_Objects/String", "String")}} 프로토타입 오브젝트를 표현하고 있습니다.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

설명

+ +

모든 {{jsxref("Global_Objects/String", "String")}} 인스턴스들은 String.prototype를 상속합니다. String 프라퍼티 오브젝트를 변경하면, 그 변경은 모든 {{jsxref("Global_Objects/String", "String")}} 인스턴스들에 영향을 주게 됩니다.

+ +

Properties

+ +
+
String.prototype.constructor
+
오브젝트의 프로토타입을 생성하는 함수를 명세합니다.
+
{{jsxref("String.prototype.length")}}
+
문자열의 길이를 반영합니다.
+
N
+
N번째 위치에 있는 문자에 접근하기 위해 사용합니다.  N 은 0과 {{jsxref("String.length", "length")}}보다 작은 값 사이에 있는 양의 정수입니다. 이 퍼라퍼티들은 읽기 전용(read-only) 속성을 가지고 있습니다. 
+
+ +

메서드

+ +

HTML과 관련이 없는 메서드

+ +
+
{{jsxref("String.prototype.charAt()")}}
+
문자열 내 특정 위치(index)에 있는 문자를 반환합니다.
+
{{jsxref("String.prototype.charCodeAt()")}}
+
문자열 내 주어진 위치(index)에 있는 문자의 유니코드 값을 반환합니다.
+
{{jsxref("String.prototype.codePointAt()")}} {{experimental_inline}}
+
주어진 위치에 있는 UTF-16으로 인코딩된 코드 포인터값인 음수가 아닌 정수값을 반환합니다. 
+
{{jsxref("String.prototype.concat()")}}
+
두 문자열의 문자를 합쳐서 새로운 문자열로 만든 다음, 그 새로운 문자열을 반환합니다. 
+
{{jsxref("String.prototype.includes()")}} {{experimental_inline}}
+
문자열 내에 찾고자 하는 문자열이 있는지를 확인합니다. 
+
{{jsxref("String.prototype.endsWith()")}} {{experimental_inline}}
+
문자열에서 특정 문자열로 끝나는지를 확인할 수 있습니다.
+
{{jsxref("String.prototype.indexOf()")}}
+
{{jsxref("Global_Objects/String", "String")}} 오브젝트에 있는 특정 값이 일치하는 첫 번째 인덱스 값을 반환하며, 일치하는 값이 없을 경우에는 -1을 반환합니다.
+
{{jsxref("String.prototype.lastIndexOf()")}}
+
String 오브젝트에서 fromIndex로부터 반대방향으로 찾기 시작하여 특정 값이 일치하는 마지막 인덱스를 반환합니다. 문자열에서 일치하는 특정 값이 없으면 -1을 리턴합니다.
+
{{jsxref("String.prototype.localeCompare()")}}
+
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
+
{{jsxref("String.prototype.match()")}}
+
Used to match a regular expression against a string.
+
{{jsxref("String.prototype.normalize()")}} {{experimental_inline}}
+
Returns the Unicode Normalization Form of the calling string value.
+
{{jsxref("String.prototype.quote()")}} {{obsolete_inline}}
+
Wraps the string in double quotes (""").
+
{{jsxref("String.prototype.repeat()")}} {{experimental_inline}}
+
Returns a string consisting of the elements of the object repeated the given times.
+
{{jsxref("String.prototype.replace()")}}
+
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
+
{{jsxref("String.prototype.search()")}}
+
Executes the search for a match between a regular expression and a specified string.
+
{{jsxref("String.prototype.slice()")}}
+
Extracts a section of a string and returns a new string.
+
{{jsxref("String.prototype.split()")}}
+
Splits a {{jsxref("Global_Objects/String", "String")}} object into an array of strings by separating the string into substrings.
+
{{jsxref("String.prototype.startsWith()")}} {{experimental_inline}}
+
Determines whether a string begins with the characters of another string.
+
{{jsxref("String.prototype.substr()")}}
+
Returns the characters in a string beginning at the specified location through the specified number of characters.
+
{{jsxref("String.prototype.substring()")}}
+
Returns the characters in a string between two indexes into the string.
+
{{jsxref("String.prototype.toLocaleLowerCase()")}}
+
The characters within a string are converted to lower case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}.
+
{{jsxref("String.prototype.toLocaleUpperCase()")}}
+
The characters within a string are converted to upper case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}}.
+
{{jsxref("String.prototype.toLowerCase()")}}
+
Returns the calling string value converted to lower case.
+
{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}}
+
Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.
+
{{jsxref("String.prototype.toString()")}}
+
Returns a string representing the specified object. Overrides the {{jsxref("Object.prototype.toString()")}} method.
+
{{jsxref("String.prototype.toUpperCase()")}}
+
Returns the calling string value converted to uppercase.
+
{{jsxref("String.prototype.trim()")}}
+
Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.
+
{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}
+
Trims whitespace from the left side of the string.
+
{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}
+
Trims whitespace from the right side of the string.
+
{{jsxref("String.prototype.valueOf()")}}
+
Returns the primitive value of the specified object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.
+
{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}} {{experimental_inline}}
+
Returns a new Iterator object that iterates over the code points of a String value, returning each code point as a String value.
+
+ +

HTML wrapper methods

+ +

These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.

+ +
+
{{jsxref("String.prototype.big()")}} {{deprecated_inline}}
+
{{HTMLElement("big")}}
+
{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}
+
{{HTMLElement("blink")}}
+
{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}
+
{{HTMLElement("b")}}
+
{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}
+
{{HTMLElement("tt")}}
+
{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}
+
{{htmlattrxref("color", "font", "<font color=\"color\">")}}
+
{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}
+
{{htmlattrxref("size", "font", "<font size=\"size\">")}}
+
{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}
+
{{HTMLElement("i")}}
+
{{jsxref("String.prototype.link()")}}
+
{{htmlattrxref("href", "a", "<a href=\"rul\">")}} (link to URL)
+
{{jsxref("String.prototype.small()")}} {{deprecated_inline}}
+
{{HTMLElement("small")}}
+
{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}
+
{{HTMLElement("strike")}}
+
{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}
+
{{HTMLElement("sub")}}
+
{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}
+
{{HTMLElement("sup")}}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ES6')}}
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/repeat/index.html b/files/ko/web/javascript/reference/global_objects/string/repeat/index.html new file mode 100644 index 0000000000..8e1d67988b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/repeat/index.html @@ -0,0 +1,113 @@ +--- +title: String.prototype.repeat() +slug: Web/JavaScript/Reference/Global_Objects/String/repeat +translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat +--- +
{{JSRef}}
+ +

repeat() 메서드는 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환합니다.

+ +

구문

+ +
str.repeat(count);
+ +

매개변수

+ +
+
count
+
문자열을 반복할 횟수. 0과 양의 무한대 사이의 정수([0, +∞)).
+
+ +

반환값

+ +

현재 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열.

+ +

예외

+ + + +

예제

+ +
'abc'.repeat(-1);   // RangeError
+'abc'.repeat(0);    // ''
+'abc'.repeat(1);    // 'abc'
+'abc'.repeat(2);    // 'abcabc'
+'abc'.repeat(3.5);  // 'abcabcabc' (count will be converted to integer)
+'abc'.repeat(1/0);  // RangeError
+
+({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2);
+// 'abcabc' (repeat() is a generic method)
+
+ +

폴리필

+ +

repeat은 ECMAScript 2015 명세에 추가됐습니다. 따라서 어떤 표준 구현체에서는 사용할 수 없을 수도 있습니다. 그러나 아래 코드를 포함하면 지원하지 않는 플랫폼에서도 repeat을 사용할 수 있습니다.

+ +
if (!String.prototype.repeat) {
+  String.prototype.repeat = function(count) {
+    'use strict';
+    if (this == null) {
+      throw new TypeError('can\'t convert ' + this + ' to object');
+    }
+    var str = '' + this;
+    count = +count;
+    if (count != count) {
+      count = 0;
+    }
+    if (count < 0) {
+      throw new RangeError('repeat count must be non-negative');
+    }
+    if (count == Infinity) {
+      throw new RangeError('repeat count must be less than infinity');
+    }
+    count = Math.floor(count);
+    if (str.length == 0 || count == 0) {
+      return '';
+    }
+    // Ensuring count is a 31-bit integer allows us to heavily optimize the
+    // main part. But anyway, most current (August 2014) browsers can't handle
+    // strings 1 << 28 chars or longer, so:
+    if (str.length * count >= 1 << 28) {
+      throw new RangeError('repeat count must not overflow maximum string size');
+    }
+    var maxCount = str.length * count;
+    count = Math.floor(Math.log(count) / Math.log(2));
+    while (count) {
+       str += str;
+       count--;
+    }
+    str += str.substring(0, maxCount - str.length);
+    return str;
+  }
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.repeat")}}

diff --git a/files/ko/web/javascript/reference/global_objects/string/replace/index.html b/files/ko/web/javascript/reference/global_objects/string/replace/index.html new file mode 100644 index 0000000000..3b189bfbf5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/replace/index.html @@ -0,0 +1,299 @@ +--- +title: String.prototype.replace() +slug: Web/JavaScript/Reference/Global_Objects/String/replace +translation_of: Web/JavaScript/Reference/Global_Objects/String/replace +--- +
{{JSRef}}
+ +

replace() 메서드는 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환합니다. 그 패턴은 문자열이나 정규식({{jsxref("RegExp")}})이 될 수 있으며, 교체 문자열은 문자열이나 모든 매치에 대해서 호출된 함수일 수 있습니다.

+ +

 

+ +

pattern이 문자열 인 경우, 첫 번째 문자열만 치환이 되며 원래 문자열은 변경되지 않습니다.

+ +

{{EmbedInteractiveExample("pages/js/string-replace.html")}}

+ +

구문

+ +
var newStr = str.replace(regexp|substr, newSubstr|function)
+ +

매개변수

+ +
+
regexp (pattern)
+
정규식({{jsxref ( "RegExp")}}) 객체 또는 리터럴. 일치하는 항목은 newSubStr 또는 지정된 함수(function)가 반환 한 값으로 대체됩니다.
+
substr (pattern)
+
newSubStr로 대체 될 {{jsxref ( "String")}}. 정규식이 아닌 글자 그대로의 문자열로 처리됩니다. 오직 첫 번째 일치되는 문자열만이 교체됩니다.
+
newSubStr (replacement)
+
첫번째 파라미터를 대신할 문자열({{jsxref("String")}}). 여러가지 대체 패턴들이 지원됩니다. 아래의 "매개변수가 string으로 지정되었을 때" 섹션을 참고하세요.
+
function (replacement)
+
주어진 regexp 또는 substr에 일치하는 요소를 대체하는 데 사용될 새 하위 문자열을 생성하기 위해 호출되는 함수. 이 함수에 제공되는 인수는 아래 "매개변수가 function으로 지정되었을 때"단원에서 설명합니다.
+
+ +

반환값

+ +

어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열

+ +

설명

+ +

이 메서드는 호출된 {{jsxref("String")}} 객체를 바꾸지 않습니다. 단순히 새로운 문자열을 리턴합니다.

+ +

모든 문자열에 대해 검색하고 바꾸려면 정규표현식의 g플래그를 포함하세요.

+ +

매개변수가 string으로 지정되었을 때

+ +

replacement 문자열은 다음과 같은 특수 교체 패턴을 포함할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternInserts
$$ "$" 기호를 삽입합니다.
$&매치된 문자열을 삽입합니다.
$`매치된 문자열 앞쪽까지의 문자열을 삽입합니다.
$'매치된 문자열의 문자열을 삽입합니다.
$n +

n이 1이상 99이하의 정수라면, 첫번째 매개변수로 넘겨진 {{jsxref("RegExp")}}객체에서 소괄호로 묶인 n번째의 부분 표현식으로 매치된 문자열을 삽입합니다.

+
+ +

매개변수가 function으로 지정되었을 때

+ +

두번째 매개변수로 함수를 지정할 수 있습니다. 이 경우, 함수는 정규표현식 매치가 수행된 후 호출될 것입니다. 함수의 반환값은 교체될 문자열이 됩니다. (참고: 윗쪽에서 언급된 특수 교체 패턴은 반환값에 적용되지 않습니다.) 만약 정규표현식의 플래그로 글로벌(g)이 오는 경우, 함수는 매치될 때마다 계속 호출될 것입니다. 

+ +

함수의 매개변수들은 다음과 같습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Possible nameSupplied value
match매치된 문자열. (윗쪽의 $& 표현식으로 매치된 경우와 동일합니다.)
p1,
+ p2,
+ ...
윗쪽의 $n 표현식과 동일합니다. ($1p1, $2p2...) 예를 들어, 만약 정규표현식 /(\a+)(\b+)/ 이 주어진다면 p1\a+와 매치되고 p2\b+와 매치됩니다.
offset조사된 전체 문자열 중에서 매치된 문자열의 index.(예를 들어, 조사될 전체 문자열이 abcd이고, 매치된 문자열이 bc면 이 매개변수의 값은 1이 됩니다.)
string조사된 전체 문자열 (replace를 호출한 string)
+ +

인수의 정확한 수는 첫 번째 인수가 {{jsxref ( "RegExp")}} 객체인지 아닌지에 따라 다르며, 소괄호로 묶이는 부분표현식의 갯수에 따라 달라집니다.

+ +

 

+ +

다음 예제는 newString을 'abc - 12345 - #$*%'로 교체합니다:

+ +
function replacer(match, p1, p2, p3, offset, string) {
+  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
+  return [p1, p2, p3].join(' - ');
+}
+var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
+console.log(newString);  // abc - 12345 - #$*%
+ +

예제

+ +

replace()의 정규표현식 정의

+ +

다음 예제에서, 대소문자를 구분하지 않는 정규표현식을 replace()에 정의했습니다.

+ +
var str = 'Twas the night before Xmas...';
+var newstr = str.replace(/xmas/i, 'Christmas');
+console.log(newstr);  // Twas the night before Christmas...
+
+ +

'Twas the night before Christmas...'로 출력됩니다.

+ +

global과 ignore를 사용한 replace()

+ +

Global replace는 정규식으로만 수행 할 수 있습니다. 다음 예제에서 정규 표현식은 replace()가 'apples'를 'oranges'로 바꿀 수 있도록 global 및 ignore case 플래그를 포함합니다.

+ +
var re = /apples/gi;
+var str = 'Apples are round, and apples are juicy.';
+var newstr = str.replace(re, 'oranges');
+console.log(newstr);  // oranges are round, and oranges are juicy.
+
+ +

'오렌지는 둥글고 오렌지는 맛있습니다.' 가 출력됩니다.

+ +

 

+ +

문자열의 단어 치환

+ +

다음 스크립트는 문자열의 단어를 전환합니다. 대체 텍스트의 경우 스크립트는 $1$2 대체 패턴을 사용합니다.

+ +
var re = /(\w+)\s(\w+)/;
+var str = 'John Smith';
+var newstr = str.replace(re, '$2, $1');
+console.log(newstr);  // Smith, John
+
+ +

'Smith, John.'이 출력됩니다.

+ +

Using an inline function that modifies the matched characters

+ +

 

+ +

이 예제에서 문자열의 대문자가 모두 소문자로 변환되고 일치되는 위치 바로 앞에 하이픈이 삽입됩니다. 여기에서 중요한 점은 일치되는 항목이 대체 항목으로 다시 반환되기 전에 추가 작업이 필요하다는 것입니다.

+ +

바꾸기 기능은 일치하는 스니펫을 매개 변수로 받고 이를 사용하여 각 케이스별로 변환한후 반환하기 전에 하이픈을 연결합니다.

+ +

 

+ +
function styleHyphenFormat(propertyName) {
+  function upperToHyphenLower(match) {
+    return '-' + match.toLowerCase();
+  }
+  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
+}
+
+ +

Given styleHyphenFormat('borderTop'), this returns 'border-top'.

+ +

Because we want to further transform the result of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} method. If we had tried to do this using the match without a function, the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} would have no effect.

+ +
var newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase());  // won't work
+
+ +

This is because '$&'.toLowerCase() would be evaluated first as a string literal (resulting in the same '$&') before using the characters as a pattern.

+ +

Replacing a Fahrenheit degree with its Celsius equivalent

+ +

The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.

+ +

The regular expression test checks for any number that ends with F. The number of Fahrenheit degree is accessible to the function through its second parameter, p1. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the f2c() function. f2c() then returns the Celsius number. This function approximates Perl's s///e flag.

+ +
function f2c(x) {
+  function convert(str, p1, offset, s) {
+    return ((p1 - 32) * 5/9) + 'C';
+  }
+  var s = String(x);
+  var test = /(-?\d+(?:\.\d*)?)F\b/g;
+  return s.replace(test, convert);
+}
+
+ +

Use an inline function with a regular expression to avoid for loops

+ +

The following example takes a string pattern and converts it into an array of objects.

+ +

Input:

+ +

A string made out of the characters x, - and _

+ +
x-x_
+x---x---x---x---
+x-xxx-xx-x-
+x_x_x___x___x___
+
+ +

Output:

+ +

An array of objects. An 'x' denotes an 'on' state, a '-' (hyphen) denotes an 'off' state and an '_' (underscore) denotes the length of an 'on' state.

+ +
[
+  { on: true, length: 1 },
+  { on: false, length: 1 },
+  { on: true, length: 2 }
+  ...
+]
+
+ +

Snippet:

+ +
var str = 'x-x_';
+var retArr = [];
+str.replace(/(x_*)|(-)/g, function(match, p1, p2) {
+  if (p1) { retArr.push({ on: true, length: p1.length }); }
+  if (p2) { retArr.push({ on: false, length: 1 }); }
+});
+
+console.log(retArr);
+
+ +

This snippet generates an array of 3 objects in the desired format without using a for loop.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.11', 'String.prototype.replace')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.replace', 'String.prototype.replace')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
 
+ +
{{Compat("javascript.builtins.String.replace")}}
+ +

Firefox-specific notes

+ + + +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/search/index.html b/files/ko/web/javascript/reference/global_objects/string/search/index.html new file mode 100644 index 0000000000..3d27d812fc --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/search/index.html @@ -0,0 +1,100 @@ +--- +title: String.prototype.search() +slug: Web/JavaScript/Reference/Global_Objects/String/search +translation_of: Web/JavaScript/Reference/Global_Objects/String/search +--- +
{{JSRef}}
+ +

search() 메서드는 정규 표현식과  이 {{jsxref("String")}}  객체간에 같은 것을 찾기
+ 위한 검색을 실행한다.

+ +
{{EmbedInteractiveExample("pages/js/string-search.html")}}
+ + + +

구문

+ +
str.search(regexp)
+ +

매개변수

+ +
+
regexp
+
정규 표현식 객체.  non-RegExp 객체 obj 가 전달되면,  그것은  new RegExp(obj) 을 이용하여 {{jsxref("RegExp")}} 으로 암묵적으로 변환된다.
+
+ +

반환 값

+ +

정규표현식과 주어진 스트링간에 첫번째로 매치되는 것의 인덱스를 반환한다.
+ 찾지 못하면 -1 를 반환한다.

+ +

설명

+ +

When you want to know whether a pattern is found and also its index in a string use search() (if you only want to know if it exists, use the similar {{jsxref("RegExp.prototype.test()", "test()")}} method on the RegExp prototype, which returns a boolean); for more information (but slower execution) use {{jsxref("String.prototype.match()", "match()")}} (similar to the regular expression {{jsxref("RegExp.prototype.exec()", "exec()")}} method).

+ +

+ +

search()를 이용하기

+ +

The following example searches a string with 2 different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1)

+ +
var str = "hey JudE";
+var re = /[A-Z]/g;
+var re2 = /[.]/g;
+console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
+console.log(str.search(re2)); // returns -1 cannot find '.' dot punctuation
+ +

사양

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
사양상태주석
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.12', 'String.prototype.search')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.search', 'String.prototype.search')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.search', 'String.prototype.search')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.search")}}

+ +

Gecko-specific notes

+ + + +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/slice/index.html b/files/ko/web/javascript/reference/global_objects/string/slice/index.html new file mode 100644 index 0000000000..3bd23ace3b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/slice/index.html @@ -0,0 +1,129 @@ +--- +title: String.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/String/slice +tags: + - 메소드 + - 문자열 + - 자바스크립트 + - 프로토타입 +translation_of: Web/JavaScript/Reference/Global_Objects/String/slice +--- +
{{JSRef}}
+ +

slice() 메소드는 문자열의 일부를 추출하면서 새로운 문자열을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/string-slice.html")}}

+ +

문법

+ +
str.slice(beginIndex[, endIndex])
+ +

매개변수

+ +
+
beginIndex
+
추출 시작점인 0부터 시작하는 인덱스입니다. 만약 음수라면, beginIndex는  strLength(문자열 길이) + beginIndex로 취급됩니다. (예를 들어 beginIndex가 -3이면 시작점은 strLength - 3).
+
만약 beginIndex가 strLength 보다 크거나 같은 경우, slice()는 빈 문자열을 반환합니다.
+
endIndex{{optional_inline}}
+
0부터 시작하는 추출 종료점 인덱스로 그 직전까지 추출됩니다.  인덱스 위치의 문자는 추출에 포함되지 않습니다.
+
만약 endIndex가 생략된다면, silce()는 문자열 마지막까지 추출합니다. 만약 음수라면, endIndex는 strLength(문자열 길이) + endIndex 로 취급됩니다(예를 들어 endIndex가 -3이면 종료점은 strLength - 3).
+
+ +

반환 값

+ +

문자열의 추출된 부분을 담는 새로운 문자열이 반환됩니다.

+ +

설명

+ +

slice()는 문자열로부터 텍스트를 추출하고 새 문자열을 반환합니다. 문자열의 변경은 다른 문자열에 영향을 미치지 않습니다.

+ +

slice()endIndex를 포함하지 않고 추출합니다. str.slice(1, 4)는 두 번째 문자부터 네 번째 문자까지 추출합니다 (1, 2, 3 인덱스 문자).

+ +

str.slice(2, -1)는 세 번째 문자부터 문자열의 마지막에서 두 번째 문자까지 추출합니다.

+ +

예시

+ +

slice()를 사용하여 새 문자열 생성하기

+ +

아래 예시는 새 문자열을 생성하기 위해 slice()를 사용합니다.

+ +
var str1 = 'The morning is upon us.', // the length of str1 is 23.
+    str2 = str1.slice(1, 8),
+    str3 = str1.slice(4, -2),
+    str4 = str1.slice(12),
+    str5 = str1.slice(30);
+console.log(str2); // OUTPUT: he morn
+console.log(str3); // OUTPUT: morning is upon u
+console.log(str4); // OUTPUT: is upon us.
+console.log(str5); // OUTPUT: ""
+
+ +

음수 인덱스로 slice() 사용하기

+ +

아래 예시는 slice()에 음수 인덱스를 사용합니다.

+ +
var str = 'The morning is upon us.';
+str.slice(-3);     // returns 'us.'
+str.slice(-3, -1); // returns 'us'
+str.slice(0, -1);  // returns 'The morning is upon us'
+
+ +

아래의 예시는 시작 인덱스를 찾기 위해 문자열의 끝에서부터 역방향으로 11개를 세고 끝 인덱스를 찾기 위해 문자열의 시작에서부터 정방향으로 16개를 셉니다.

+ +
console.log(str.slice(-11, 16)) // => "is u";
+ +

아래에서는 시작 인덱스를 찾기 위해 문자열의 처음부터 정방향으로 11개를 세고 끝 인덱스를 찾기 위해 끝에서부터 7개를 셉니다.

+ +
console.log(str.slice(11, -7)) // => "is u";
+
+ +

이 인수는 끝에서부터 5로 역순으로 계산하여 시작 인덱스를 찾은 다음 끝에서부터 1을 거쳐 끝 인덱스를 찾습니다.

+ +
console.log(str.slice(-5, -1)) // => "n us";
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-string.prototype.slice', 'String.prototype.slice')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-string.prototype.slice', 'String.prototype.slice')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-15.5.4.13', 'String.prototype.slice')}}{{Spec2('ES5.1')}}
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
+ +

Browser compatibility

+ +

{{Compat("javascript.builtins.String.slice")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/split/index.html b/files/ko/web/javascript/reference/global_objects/string/split/index.html new file mode 100644 index 0000000000..7100e55a50 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/split/index.html @@ -0,0 +1,231 @@ +--- +title: String.prototype.split() +slug: Web/JavaScript/Reference/Global_Objects/String/split +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/split +--- +
{{JSRef}}
+ +

split() 메서드는 {{jsxref("String")}} 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.

+ +
{{EmbedInteractiveExample("pages/js/string-split.html")}}
+ + + +

구문

+ +
str.split([separator[, limit]])
+ +
+

주의: 구분자로 빈 문자열("")을 제공하면, 사용자가 인식하는 문자 하나(grapheme cluster) 또는 유니코드 문자(코드포인트) 하나씩으로 나누는 것이 아니라, UTF-16 코드유닛으로 나누게 되며 써로게이트 페어surrogate pair가 망가질 수 있습니다. 스택 오버플로우의 How do you get a string to a character array in JavaScript? 질문도 참고해 보세요.

+
+ +

매개변수

+ +
+
separator {{optional_inline}}
+
원본 문자열을 끊어야 할 부분을 나타내는 문자열을 나타냅니다. 실제 문자열이나 {{jsxref("Global_Objects/RegExp", "정규표현식", "", 1)}}을 받을 수 있습니다. 문자열 유형의 separator가 두 글자 이상일 경우 그 부분 문자열 전체가 일치해야 끊어집니다. separator가 생략되거나 str에 등장하지 않을 경우, 반환되는 배열은 원본 문자열을 유일한 원소로 가집니다. separator가 빈 문자열일 경우 str의 각각의 문자가 배열의 원소 하나씩으로 변환됩니다.
+
limit {{optional_inline}}
+
+

끊어진 문자열의 최대 개수를 나타내는 정수입니다. 이 매개변수를 전달하면 split() 메서드는 주어진 separator가 등장할 때마다 문자열을 끊지만 배열의 원소가 limit개가 되면 멈춥니다. 지정된 한계에 도달하기 전에 문자열의 끝까지 탐색했을 경우 limit개 미만의 원소가 있을 수도 있습니다. 남은 문자열은 새로운 배열에 포함되지 않습니다.

+
+
+ +

반환값

+ +

주어진 문자열을 separator마다 끊은 부분 문자열을 담은 {{jsxref("Array")}}.

+ +

설명

+ +

문자열에서 separator가 등장하면 해당 부분은 삭제되고 남은 문자열이 배열로 반환됩니다. separator가 등장하지 않거나 생략되었을 경우 배열은 원본 문자열을 유일한 원소로 가집니다. separator가 빈 문자열일 경우, str은 문자열의 모든 문자를 원소로 가지는 배열로 변환됩니다. separator가 원본 문자열의 처음이나 끝에 등장할 경우 반환되는 배열도 빈 문자열로 시작하거나 끝납니다. 그러므로 원본 문자열에 separator 하나만이 포함되어 있을 경우 빈 문자열 두 개를 원소로 가지는 배열이 반환됩니다.

+ +

separator가 포획 괄호capturing parentheses를 포함하는 정규표현식일 경우, separator가 일치할 때마다 포획 괄호의 (정의되지 않은 경우도 포함한) 결과가 배열의 해당 위치에 포함됩니다.

+ +

{{Note("separator가 배열일 경우 분할에 사용하기 전에 우선 문자열로 변환됩니다.")}}

+ +

예제

+ +

split() 사용하기

+ +

{{Note("빈 문자열이 주어졌을 경우 split()은 빈 배열이 아니라 빈 문자열을 포함한 배열을 반환합니다. 문자열과 separator가 모두 빈 문자열일 때는 빈 배열을 반환합니다.")}}

+ +
const myString = '';
+const splits = myString.split();
+
+console.log(splits);
+
+// ↪ [""]
+
+ +

다음 예제에서는 문자열을 주어진 구분자로 끊는 함수를 정의합니다. 문자열을 끊은 다음에는 (끊기 이전의) 원본 문자열과 사용한 구분자, 배열의 길이와 각 원소를 로그로 출력합니다.

+ +
function splitString(stringToSplit, separator) {
+  var arrayOfStrings = stringToSplit.split(separator);
+
+  console.log('The original string is: "' + stringToSplit + '"');
+  console.log('The separator is: "' + separator + '"');
+  console.log('The array has ' + arrayOfStrings.length + ' elements: ' + arrayOfStrings.join(' / '));
+}
+
+var tempestString = 'Oh brave new world that has such people in it.';
+var monthString = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec';
+
+var space = ' ';
+var comma = ',';
+
+splitString(tempestString, space);
+splitString(tempestString);
+splitString(monthString, comma);
+
+ +

위 예제의 출력은 다음과 같습니다.

+ +
The original string is: "Oh brave new world that has such people in it."
+The separator is: " "
+The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it.
+
+The original string is: "Oh brave new world that has such people in it."
+The separator is: "undefined"
+The array has 1 elements: Oh brave new world that has such people in it.
+
+The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
+The separator is: ","
+The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec
+
+ +

문자열에서 공백 제거하기

+ +

다음 예제에서 split()은 세미콜론 앞뒤에 각각 0개 이상의 공백이 있는 부분 문자열을 찾고, 있을 경우 문자열에서 세미콜론과 공백을 제거합니다. split()의 결과로 반환된 배열은  nameList에 저장됩니다.

+ +
var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ';
+
+console.log(names);
+
+var re = /\s*(?:;|$)\s*/;
+var nameList = names.split(re);
+
+console.log(nameList);
+
+ +

위 예제는 원본 문자열과 반환된 배열을 각각 한 줄씩 로그로 출력합니다.

+ +
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
+[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ]
+
+ +

끊는 횟수 제한하기

+ +

다음 예제에서 split()은 문자열을 공백으로 끊고 처음 3개의 문자열을 반환합니다.

+ +
var myString = 'Hello World. How are you doing?';
+var splits = myString.split(' ', 3);
+
+console.log(splits);
+
+ +

위 예제의 로그 출력은 다음과 같습니다.

+ +
["Hello", "World.", "How"]
+
+ +

RegExp를 사용해 구분자도 결과에 포함하기

+ +

separator가 포획 괄호 ()를 포함하는 정규표현식일 경우, 포획된 결과도 배열에 포함됩니다.

+ +
var myString = 'Hello 1 word. Sentence number 2.';
+var splits = myString.split(/(\d)/);
+
+console.log(splits);
+
+ +

위 예제의 로그 출력은 다음과 같습니다.

+ +
[ "Hello ", "1", " word. Sentence number ", "2", "." ]
+
+ +

배열을 구분자로 사용하기

+ +
var myString = 'this|is|a|Test';
+var splits = myString.split(['|']);
+
+console.log(splits); //["this", "is", "a", "Test"]
+
+var myString = 'ca,bc,a,bca,bca,bc';
+
+var splits = myString.split(['a','b']);
+// myString.split(['a','b'])myString.split(String(['a','b']))와 같다
+
+console.log(splits);  //["c", "c,", "c", "c", "c"]
+
+ +

split()으로 문자열 뒤집기

+ +
+

이 방법은 문자열 뒤집기에 효과적인 방법이 아닙니다.

+ +
var str = 'asdfghjkl';
+var strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
+// split()에서 반환한 배열에는 reverse()와 join()을 사용할 수 있다
+
+ +

문자열에 grapheme clusters가 있을 경우, 유니코드 플래그를 설정해도 오류를 일으킵니다(esrever 등의 라이브러리를 대신 사용하세요).

+ +
var str = 'résumé';
+var strReverse = str.split(/(?:)/u).reverse().join('');
+// => "́emuśer"
+
+ +

추가: {{jsxref("Operators/Comparison_Operators", "===", "#Identity_strict_equality_(===)")}} 연산자를 사용하면 원본 문자열이 팰린드롬인지 확인할 수 있습니다.

+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의. JavaScript 1.1에 구현되었음.
{{SpecName('ES5.1', '#sec-15.5.4.14', 'String.prototype.split')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.split")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/startswith/index.html b/files/ko/web/javascript/reference/global_objects/string/startswith/index.html new file mode 100644 index 0000000000..41eb064129 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/startswith/index.html @@ -0,0 +1,95 @@ +--- +title: String.prototype.startsWith() +slug: Web/JavaScript/Reference/Global_Objects/String/startsWith +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith +--- +
{{JSRef}}
+ +

startsWith() 메소드는 어떤 문자열이 특정 문자로 시작하는지 확인하여 결과를 true 혹은 false로 반환합니다.

+ +

구문

+ +
str.startsWith(searchString[, position])
+ +

매개변수

+ +
+
searchString
+
문자열의 시작 지점에서 탐색할 문자열
+
position {{optional_inline}}
+
searchString을 탐색할 위치. 기본값 0.
+
+ +

반환 값

+ +

문자열이 검색 문자열로 시작하면 true, 아니면 false.

+ +

  설명

+ +

startsWith 메소드로 어떤 문자열이 다른 문자열로 시작하는지 확인 할 수 있습니다. 대소문자를 구분합니다.

+ +

예시

+ +

startsWith() 사용하기

+ +
//startswith
+var str = 'To be, or not to be, that is the question.';
+
+console.log(str.startsWith('To be'));         // true
+console.log(str.startsWith('not to be'));     // false
+console.log(str.startsWith('not to be', 10)); // true
+
+ +

폴리필

+ +

startsWith 메소드는 ECMAScript 2015 명세에 포함됐으며, 아직까지 모든 JavaScrpt 구현체가 지원하지 않을 수 있습니다. 그러나 아래 코드 조각을 사용해 폴리필 할 수 있습니다.

+ +
if (!String.prototype.startsWith) {
+	String.prototype.startsWith = function(search, pos) {
+		return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
+	};
+}
+ +

ES2015 명세를 모두 만족하지만, 더 무거운 폴리필은 Mathias Bynens의 GitHub 에서 확인할 수 있습니다.

+ +

명세서

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.startsWith")}}
+ +

관련 문서

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/substr/index.html b/files/ko/web/javascript/reference/global_objects/string/substr/index.html new file mode 100644 index 0000000000..39fe5e126b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/substr/index.html @@ -0,0 +1,131 @@ +--- +title: String.prototype.substr() +slug: Web/JavaScript/Reference/Global_Objects/String/substr +tags: + - Deprecated + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/substr +--- +
{{JSRef}}
+ +
 
+ +
+

경고: 엄밀히 말해서 String.prototype.substr() 메서드가 더 이상 사용되지 않는, 즉 "웹 표준에서 제거된" 건 아닙니다. 그러나 substr()이 포함된 ECMA-262 표준의 부록 B는 다음과 같이 명시하고 있습니다.

+ +
… 본 부록이 포함한 모든 언어 기능과 행동은 하나 이상의 바람직하지 않은 특징을 갖고 있으며 사용처가 없어질 경우 명세에서 제거될 것입니다. …
+… 프로그래머는 새로운 ECMAScript 코드를 작성할 때 본 부록이 포함한 기능을 사용하거나 존재함을 가정해선 안됩니다. …
+
+ +

substr() 메서드는 문자열에서 특정 위치에서 시작하여 특정 문자 수 만큼의 문자들을 반환합니다.

+ +

{{EmbedInteractiveExample("pages/js/string-substr.html")}}

+ +

구문

+ +
str.substr(start[, length])
+ +

매개변수

+ +
+
start
+
추출하고자 하는 문자들의 시작위치입니다. 만약 음수가 주어진다면, 문자열총길이 + start의 값으로 취급합니다. 예를 들면, start에 -3을 설정하면, 자동적으로 문자열총길이 - 3으로 설정하게 됩니다. 
+
length
+
옵션값. 추출할 문자들의 총 숫자.
+
+ +

설명

+ +

start는 문자 인덱스입니다. 문자열에서 첫 번째 문자의 인덱스는 0이며, 마지막 문자의 인덱스는 문자열 전체 길이에서 1을 뺀 값입니다. substr() start에서 문자들을 추출을 시작하여 length만큼 문자들을 수집합니다.

+ +

만약 start 값이 양수이고 문자열 전체 길이보다 크거가 같을 경우, substr()은 빈 문자열을 반환합니다. 

+ +

만약 start가 음수이면, substr()은 문자열 끝에서 start 숫자만큼 뺀 곳에서 시작하게 됩니다. 만약 start가 음수이고 절대값이 문자열 전체보다 크다면, substr()은 문자열의 0 인덱스부터 시작하게 됩니다. (주의: start의 음수값은 Microsoft JScript에서는 위의 설명과 같이 동작하지 않습니다.)

+ +

만약 length가 0 혹은 음수이면, substr()은 빈 문자열을 반환합니다. 만약 length가 생략되면, substr()은 문자열의 끝까지 추출하여 반환합니다. 

+ +

예제

+ +

substr() 사용하기

+ +
var str = 'abcdefghij';
+
+console.log('(1, 2): '   + str.substr(1, 2));   // '(1, 2): bc'
+console.log('(-3, 2): '  + str.substr(-3, 2));  // '(-3, 2): hi'
+console.log('(-3): '     + str.substr(-3));     // '(-3): hij'
+console.log('(1): '      + str.substr(1));      // '(1): bcdefghij'
+console.log('(-20, 2): ' + str.substr(-20, 2)); // '(-20, 2): ab'
+console.log('(20, 2): '  + str.substr(20, 2));  // '(20, 2): '
+
+ +

폴리필

+ +

Microsoft의 JScript는 시작 인덱스에서 음수값을 지원하지 않습니다. 만약 여러분이 이렇게 동작하길 원한다면, 아래 코드를 사용하여 해결할 수 있습니다: 

+ +
// only run when the substr() function is broken
+if ('ab'.substr(-1) != 'b') {
+  /**
+   *  Get the substring of a string
+   *  @param  {integer}  start   where to start the substring
+   *  @param  {integer}  length  how many characters to return
+   *  @return {string}
+   */
+  String.prototype.substr = function(substr) {
+    return function(start, length) {
+      // call the original method
+      return substr.call(this,
+      	// did we get a negative start, calculate how much it is from the beginning of the string
+        // adjust the start parameter for negative value
+        start < 0 ? this.length + start : start,
+        length)
+    }
+  }(String.prototype.substr);
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Defined in the (informative) Compatibility Annex B. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-B.2.3', 'String.prototype.substr')}}{{Spec2('ES5.1')}}Defined in the (informative) Compatibility Annex B
{{SpecName('ES6', '#sec-string.prototype.substr', 'String.prototype.substr')}}{{Spec2('ES6')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers
{{SpecName('ESDraft', '#sec-string.prototype.substr', 'String.prototype.substr')}}{{Spec2('ESDraft')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.String.substr")}}
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/substring/index.html b/files/ko/web/javascript/reference/global_objects/string/substring/index.html new file mode 100644 index 0000000000..91d13974c9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/substring/index.html @@ -0,0 +1,190 @@ +--- +title: String.prototype.substring() +slug: Web/JavaScript/Reference/Global_Objects/String/substring +translation_of: Web/JavaScript/Reference/Global_Objects/String/substring +--- +
{{JSRef}}
+ +

substring()메소드는 string 객체의 시작 인덱스로 부터 종료 인덱스 전 까지 문자열의 부분 문자열을 반환합니다. 

+ +
{{EmbedInteractiveExample("pages/js/string-substring.html")}}
+ + + +

사용방법 

+ +
str.substring(indexStart[, indexEnd])
+ +

인자값

+ +
+
indexStart
+
반환문자열의 시작 인덱스 
+
 
+
indexEnd
+
옵션.  반환문자열의 마지막 인덱스 (포함하지 않음.)
+
+ +

반환값

+ +

기존문자열의  부분 문자열을 반환합니다. 

+ +

Description

+ +

substring() 메서드는 indexStart 부터 문자를 추출하지만 indexEnd 가 포함되지 않아도 괜찮습니다. 특징은 아래와 같습니다.

+ + + +

0보다 작은 인자 값을 가지는 경우에는 0으로, stringName.length 보다 큰 인자 값을 가지는 경우, stringName.length 로 처리됩니다. {{jsxref("NaN")}} 값은 0으로 처리됩니다.

+ +

Examples

+ +

Using substring()

+ +

The following example uses substring() to display characters from the string 'Mozilla':

+ +
var anyString = 'Mozilla';
+
+// Displays 'M'
+console.log(anyString.substring(0, 1));
+console.log(anyString.substring(1, 0));
+
+// Displays 'Mozill'
+console.log(anyString.substring(0, 6));
+
+// Displays 'lla'
+console.log(anyString.substring(4));
+console.log(anyString.substring(4, 7));
+console.log(anyString.substring(7, 4));
+
+// Displays 'Mozilla'
+console.log(anyString.substring(0, 7));
+console.log(anyString.substring(0, 10));
+
+ +

Using substring() with length property

+ +

The following example uses the substring() method and {{jsxref("String.length", "length")}} property to extract the last characters of a particular string. This method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples.

+ +
// Displays 'illa' the last 4 characters
+var anyString = 'Mozilla';
+var anyString4 = anyString.substring(anyString.length - 4);
+console.log(anyString4);
+
+// Displays 'zilla' the last 5 characters
+var anyString = 'Mozilla';
+var anyString5 = anyString.substring(anyString.length - 5);
+console.log(anyString5);
+
+ +

The difference between substring() and substr()

+ +

There's a subtle difference between the substring() and {{jsxref("String.substr", "substr()")}} methods, so you should be careful not to get them confused.

+ +

The arguments of substring() represent the starting and ending indexes, while the arguments of substr() represent the starting index and the number of characters to include in the returned string.

+ +
var text = 'Mozilla';
+console.log(text.substring(2,5)); // => "zil"
+console.log(text.substr(2,3));    // => "zil"
+ +

Differences between substring() and slice()

+ +

The substring() and {{jsxref("String.slice", "slice()")}} methods are almost identical, but there are a couple of subtle differences between the two, especially in the way negative arguments are dealt with.

+ +

The substring() method swaps its two arguments if indexStart is greater than indexEnd, meaning that a string is still returned. The {{jsxref("String.slice", "slice()")}} method returns an empty string if this is the case.

+ +
var text = 'Mozilla';
+console.log(text.substring(5, 2)); // => "zil"
+console.log(text.slice(5, 2));     // => ""
+
+ +

If either or both of the arguments are negative or NaN, the substring() method treats them as if they were 0.

+ +
console.log(text.substring(-5, 2)); // => "Mo"
+console.log(text.substring(-5, -2)); // => ""
+
+ +

slice() also treats NaN arguments as 0, but when it is given negative values it counts backwards from the end of the string to find the indexes.

+ +
console.log(text.slice(-5, 2)); // => ""
+console.log(text.slice(-5, -2)); // => "zil"
+
+ +

See the {{jsxref("String.slice", "slice()")}} page for more examples with negative numbers.

+ +

Replacing a substring within a string

+ +

The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string Brave New World to Brave New Web.

+ +
// Replaces oldS with newS in the string fullS
+function replaceString(oldS, newS, fullS) {
+  for (var i = 0; i < fullS.length; ++i) {
+    if (fullS.substring(i, i + oldS.length) == oldS) {
+      fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
+    }
+  }
+  return fullS;
+}
+
+replaceString('World', 'Web', 'Brave New World');
+
+ +

Note that this can result in an infinite loop if oldS is itself a substring of newS — for example, if you attempted to replace 'World' with 'OtherWorld' here. A better method for replacing strings is as follows:

+ +
function replaceString(oldS, newS, fullS) {
+  return fullS.split(oldS).join(newS);
+}
+
+ +

The code above serves as an example for substring operations. If you need to replace substrings, most of the time you will want to use {{jsxref("String.prototype.replace()")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Implemented in JavaScript 1.0.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.substring")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html new file mode 100644 index 0000000000..d91e48729f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/tolowercase/index.html @@ -0,0 +1,83 @@ +--- +title: String.prototype.toLowerCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +--- +
{{JSRef}}
+ +
toLowerCase() 메서드는 문자열을 소문자로 변환해 반환합니다.
+ +
 
+ +
{{EmbedInteractiveExample("pages/js/string-tolowercase.html")}}
+ +

구문

+ +
str.toLowerCase()
+ +

반환값

+ +

호출 문자열을 소문자로 변환한 새로운 문자열

+ +

설명

+ +

toLowerCase() 메서드는 호출 문자열을 소문자로 변환해 반환합니다.  toLowerCase() 는 원래의 str에 영향을 주지 않습니다.

+ +

예제

+ +

 toLowerCase()

+ +
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.toLowerCase")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/tosource/index.html b/files/ko/web/javascript/reference/global_objects/string/tosource/index.html new file mode 100644 index 0000000000..d08a2a816a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/tosource/index.html @@ -0,0 +1,49 @@ +--- +title: String.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/String/toSource +translation_of: Web/JavaScript/Reference/Global_Objects/String/toSource +--- +
{{JSRef}} {{non-standard_header}}
+ +

The toSource() method returns a string representing the source code of the object.

+ +

문법

+ +
String.toSource()
+str.toSource()
+
+ +

리턴 값

+ +

호출한 객체의 소스코드가 string으로 보여집니다.

+ +

설명

+ +

toSource() 메소드는 다음 값을 리턴:

+ +

For the built-in {{jsxref("String")}} object, toSource() returns the following string indicating that the source code is not available:

+ +
function String() {
+    [native code]
+}
+
+ +

For instances of {{jsxref("String")}} or string literals, toSource() returns a string representing the source code.

+ +

This method is usually called internally by JavaScript and not explicitly in code.

+ +

Specifications

+ +

Not part of any standard. Implemented in JavaScript 1.3.

+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.toSource")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/tostring/index.html b/files/ko/web/javascript/reference/global_objects/string/tostring/index.html new file mode 100644 index 0000000000..999d5c0c74 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/tostring/index.html @@ -0,0 +1,59 @@ +--- +title: String.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/String/toString +translation_of: Web/JavaScript/Reference/Global_Objects/String/toString +--- +
{{JSRef}}
+ +

toString()메소드는 지정된 객체를 나타내는 문자열을 반환합니다.

+ +
{{EmbedInteractiveExample ( "pages / js / string-tostring.html")}}
+ +

통사론

+ +
str.toString()
+ +

반환 값

+ +

호출 객체를 나타내는 문자열

+ +

기술

+ +

{{jsxref ( "String")}} 오브젝트 toString()는 {{jsxref ( "Object")}} 오브젝트 메소드를 대체 합니다. {{jsxref ( "Object.prototype.toString ()")}}을 상속하지 않습니다. {{jsxref ( "String")}} 오브젝트의 경우 toString()메소드는 오브젝트 의 문자열 표시를 리턴하며 {{jsxref ( "String.prototype.valueOf ()")}} 메소드와 동일합니다.

+ +

+ +

사용 toString()

+ +

다음 예제는 {{jsxref ( "String")}} 오브젝트의 문자열 값을 표시합니다.

+ +
var x = new String ( 'Hello world');
+
+console.log (x.toString ()); // 'Hello world'를 기록합니다.
+
+ +

명세서

+ + + + + + + + + + +
사양
{{SpecName ( 'ESDraft', '# sec-string.prototype.tostring', 'String.prototype.toString')}}}
+ +

브라우저 호환성

+ + + +

{{Compat ( "javascript.builtins.String.toString")}}

+ +

또한보십시오

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/touppercase/index.html b/files/ko/web/javascript/reference/global_objects/string/touppercase/index.html new file mode 100644 index 0000000000..f6a0c8f05c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/touppercase/index.html @@ -0,0 +1,105 @@ +--- +title: String.prototype.toUpperCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/toUpperCase +--- +
{{JSRef}}
+ +

toUpperCase() 메서드는 문자열을 대문자로 변환해 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-touppercase.html")}}
+ + + +

구문

+ +
str.toUpperCase()
+ +

반환 값

+ +

대문자로 변환한 새로운 문자열.

+ +

예외

+ +
+
{{jsxref("TypeError")}}
+
{{jsxref("Function.prototype.call()")}} 등을 사용해 {{jsxref("null")}}이나 {{jsxref("undefined")}}에서 호출 시.
+
+ +

설명

+ +

toUpperCase() 메서드는 문자열을 대문자로 변환한 값을 반환합니다. JavaScript의 문자열은 불변하므로 원본 문자열에는 영향을 주지 않습니다.

+ +

예제

+ +

기본 사용법

+ +
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
+ +

문자열이 아닌 this의 문자열 변환

+ +

toUpperCase()this가 문자열이 아니고, undefinednull도 아니면 자동으로 문자열로 변환합니다.

+ +
const a = String.prototype.toUpperCase.call({
+  toString: function toString() {
+    return 'abcdef';
+  }
+});
+
+const b = String.prototype.toUpperCase.call(true);
+
+// prints out 'ABCDEF TRUE'.
+console.log(a, b);
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.18', 'String.prototype.toUpperCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.toUpperCase")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/trim/index.html b/files/ko/web/javascript/reference/global_objects/string/trim/index.html new file mode 100644 index 0000000000..0f0b71f548 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/trim/index.html @@ -0,0 +1,97 @@ +--- +title: String.prototype.trim() +slug: Web/JavaScript/Reference/Global_Objects/String/Trim +tags: + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim +--- +
{{JSRef}}
+ +

trim() 메서드는 문자열 양 끝의 공백을 제거합니다. 공백이란 모든 공백문자(space, tab, NBSP 등)와 모든 개행문자(LF, CR 등)를 의미합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-trim.html")}}
+ + + +

구문

+ +
str.trim()
+ +

반환 값

+ +

양 끝에서 공백을 제거한 새로운 문자열.

+ +

설명

+ +

trim() 메서드는 양끝의 공백을 제거한 문자열을 반환합니다. trim()은 원본 문자열에는 영향을 주지 않습니다. 

+ +

예제

+ +

trim() 사용

+ +

아래의 예제는 소문자 문자열  'foo'를 표시합니다.

+ +
var orig = '   foo  ';
+console.log(orig.trim()); // 'foo'
+
+// 한 쪽의 공백만 제거하는 .trim() 예제
+
+var orig = 'foo    ';
+console.log(orig.trim()); // 'foo'
+
+ +

폴리필

+ +

다른 코드 전에 아래 코드를 실행하면 지원하지 않는 환경에서도  String.trim() 을 사용할 수 있습니다.

+ +
if (!String.prototype.trim) {
+  String.prototype.trim = function () {
+    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
+  };
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
표준상태비고
{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.1.
{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.trim")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/string/valueof/index.html b/files/ko/web/javascript/reference/global_objects/string/valueof/index.html new file mode 100644 index 0000000000..e8e217d615 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/string/valueof/index.html @@ -0,0 +1,83 @@ +--- +title: String.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/String/valueOf +tags: + - 메서드 + - 문자열 + - 자바스크립트 + - 참고 + - 프로토타입 +translation_of: Web/JavaScript/Reference/Global_Objects/String/valueOf +--- +
{{JSRef}}
+ +

valueOf() 메서드는 {{jsxref("String")}} 객체의 원시값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/string-valueof.html")}}
+ +

구문

+ +
str.valueOf()
+ +

반환 값

+ +

지정된 {{jsxref("String")}} 객체의 원시 값을 나타내는 문자열.

+ +

설명

+ +

{{jsxref("String")}} 의 valueOf() 메서드는 {{jsxref("String")}} 객체의 원시 값을 문자열 데이터 타입으로 반환 합니다. 이 값은 {{jsxref("String.prototype.toString()")}}.과 동일합니다.

+ +

이 메서드는 보통 자바스크립트에 의해 내부적으로 호출되며, 코드에서 명시적으로 사용하지는 않습니다.

+ +

예제

+ +

  valueOf() 사용

+ +
var x = new String('Hello world');
+console.log(x.valueOf()); // 'Hello world' 가 보여집니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.1 에서 구현.
{{SpecName('ES5.1', '#sec-15.5.4.3', 'String.prototype.valueOf')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.valueof', 'String.prototype.valueOf')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.valueof', 'String.prototype.valueOf')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.String.valueOf")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/symbol/for/index.html b/files/ko/web/javascript/reference/global_objects/symbol/for/index.html new file mode 100644 index 0000000000..e489deb27d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/symbol/for/index.html @@ -0,0 +1,150 @@ +--- +title: Symbol.for() +slug: Web/JavaScript/Reference/Global_Objects/Symbol/for +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/for +--- +
{{JSRef}}
+ +

Symbol.for(key) 메소드는  runtime-wide 심볼 레지스트리에서 해당 키로 존재하는 심볼을 찾는다. 없으면 전역 심볼 레지시트리에  해당 키로 새로운 심볼을 만들어 준다.  

+ +

문법

+ +
Symbol.for(key);
+ +

파라미터

+ +
+
key
+
String, 필수. 심볼의 키 (심볼의 설명을 위해서도 쓰인다).
+
+ +

반환 값

+ +

해당 키에 해당하는 심볼이 있다면 반환 없으면 새로운 심볼을 만들고 반환한다.

+ +

설명

+ +

Symbol()과는 다르게, the Symbol.for() 함수는 전역 심볼 레지스트리 리스트에 심볼을 만든다. Symbol.for()는 또한 매 호출마다 새로운 심볼을 만들지 않고 현재 레지스트리에 해당 키를 가진 심볼이 있는지 먼저 검사를 한다. 있다면 그 심볼을 반환한다. 만약 키에 해당하는 심볼이 없다면 Symbol.for()는 새로운 전역 심볼을 만들 것이다.

+ +

전역 심볼 레지스트리 

+ +

전역심볼 레지스트리는 다음 레코드 구조를 가진 리스트이고 초기 값은 비어 있다:

+ +

전역심볼 레지스트리의 레코드

+ + + + + + + + + + + + + + + + +
필드 명
[[key]]심볼을 구분하기 위해 사용되는 문자열 키
[[symbol]]전역으로 저장되는 심볼
+ +

예제

+ +
Symbol.for('foo'); // 새로운 전역심볼 생성
+Symbol.for('foo'); // 이미 만들어진 심볼을 검색
+
+// 전역심볼은 서로 같고, 지역심볼은 아니다.
+Symbol.for('bar') === Symbol.for('bar'); // true
+Symbol('bar') === Symbol('bar'); // false
+
+// 키는 설명하는데 쓰이기도 한다.
+var sym = Symbol.for('mario');
+sym.toString(); // "Symbol(mario)"
+
+ +

다른 라이브러리의 전역 심볼들과 당신의 전역 심볼간의 키 충돌을 피하기 위해서는 당신 심볼 앞에 prefix를 두는 것이 좋다:

+ +
Symbol.for('mdn.foo');
+Symbol.for('mdn.bar');
+
+ +

명세서

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-symbol.for', 'Symbol.for')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-symbol.for', 'Symbol.for')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(40) }}{{ CompatGeckoDesktop("36.0") }}{{CompatNo}}{{CompatNo}}10
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("36.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/symbol/index.html b/files/ko/web/javascript/reference/global_objects/symbol/index.html new file mode 100644 index 0000000000..05b1fdd25b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/symbol/index.html @@ -0,0 +1,233 @@ +--- +title: Symbol +slug: Web/JavaScript/Reference/Global_Objects/Symbol +tags: + - ECMAScript 2015 + - 심볼 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol +--- +
{{JSRef}}
+ +

Symbol() 함수는 심볼(symbol) 형식의 값을 반환하는데, 이 심볼은 내장 객체(built-in objects)의 여러 멤버를 가리키는 정적 프로퍼티와 전역 심볼 레지스트리(global symbol registry)를 가리키는 정적 메서드를 가지며, "new Symbol()" 문법을 지원하지 않아 생성자 측면에서는 불완전한 내장 객체 클래스(built-in object class)와 유사합니다.

+ +

Symbol()로부터 반환되는 모든 심볼 값은 고유합니다. 심볼 값은 객체 프로퍼티(object properties)에 대한 식별자로 사용될 수 있습니다; 이것이 심볼 데이터 형식의 유일한 목적입니다. 목적과 용례에 대한 더 자세한 설명은 용어집의 심볼 항목(glossary entry for Symbol)에서 볼 수 있습니다.

+ +

심볼(symbol) 데이터 형은 원시 데이터 형({{Glossary("Primitive", "primitive data type")}})의 일종입니다.

+ +
{{EmbedInteractiveExample("pages/js/symbol-constructor.html")}}
+ + + +

문법

+ +
Symbol([description])
+ +

매개변수

+ +
+
description {{optional_inline}}
+
선택적(optional) 문자열. 디버깅에 사용할 수 있는 심볼에 대한 설명(description)으로 심볼 자체에 접근하는 용도로는 사용할 수 없음.
+
+ +

설명(Description)

+ +

새 원시(primitive) 심볼을 생성하려면, 심볼을 설명하는 선택적(optional) 문자열과 함께 Symbol()을 쓰면됩니다.

+ +
var sym1 = Symbol();
+var sym2 = Symbol("foo");
+var sym3 = Symbol("foo");
+
+ +

위의 코드는 세 개의 새 심볼을 생성합니다. Symbol("foo")는 "foo"라는 문자열을 심볼로 강제로 변환시키지 않는다는 점에 유의하시기 바랍니다. 해당 코드는 매 번 새로운 심볼을 생성합니다:

+ +
Symbol("foo") === Symbol("foo"); // false
+ +

아래 {{jsxref("Operators/new", "new")}} 연산자를 이용한 문법은 {{jsxref("TypeError")}}를 발생시킬 것입니다:

+ +
var sym = new Symbol(); // TypeError
+ +

이는 작성자가 새로운 심볼 값 대신 명시적으로 심볼 래퍼 객체(Symbol wrapper object)를 생성할 수 없게 합니다. 일반적으로 원시 데이터 형에 대한 명시적인 래퍼 객체 생성(예를 들어, new Boolean, new String 또는 new Number와 같은)이 가능하다는 점에 비춰보면 의외일 수 있습니다.

+ +

꼭 심볼 래퍼 객체를 생성하고 싶다면, Object() 함수를 이용할 수 있습니다.

+ +
var sym = Symbol("foo");
+typeof sym;     // "symbol"
+var symObj = Object(sym);
+typeof symObj;  // "object"
+
+ +

전역 심볼 레지스트리 내 공유 심볼

+ +

Symbol() 함수를 사용한 위의 문법은 코드베이스(codebase) 전체에서 사용 가능한 전역 심볼을 생성하는 것은 아닙니다. 파일 간(across files), 또는 램(realms, 각각이 자체의 전역 범위(scope)를 가지는) 간에도 사용할 수 있는 심볼을 생성하기 위해서는, {{jsxref("Symbol.for()")}}와 {{jsxref("Symbol.keyFor()")}} 메서드를 이용해 전역 심볼 레지스트리에 심볼을 설정하거나 추출해야 합니다.

+ +

객체에서 심볼 속성(symbol properties) 찾기

+ +

{{jsxref("Object.getOwnPropertySymbols()")}} 메서드는 심볼의 배열을 반환하여 주어진 객체의 심볼 속성을 찾을 수 있게 해줍니다. 모든 객체는 스스로에 대한 심볼 속성이 없는 상태로 초기화되기 때문에 해당 객체에 심볼 속성을 설정하기 전까지는 빈 배열을 반환한다는 점에 유의하시기 바랍니다.

+ +

속성(properties)

+ +
+
Symbol.length
+
값이 0인 길이 속성
+
{{jsxref("Symbol.prototype")}}
+
Symbol 생성자의 프로토타입을 나타냄.
+
+ +

잘 알려진 심볼들

+ +

여러분이 정의하는 심볼 외에, 자바스크립트는 ECMAScript 5와 그 이전 버전에서는 개발자에게 제공되지 않았던 언어 내부의 동작을 나타내는 내장(built-in) 심볼을 몇 가지 가지고 있습니다. 다음 속성을 이용해 이들 심볼에 접근할 수 있습니다:

+ +

반복(iteration) 심볼

+ +
+
{{jsxref("Symbol.iterator")}}
+
객체의 기본 반복자(default iterator)를 반환하는 메서드.for...of에서 사용됨.
+
{{jsxref("Symbol.asyncIterator")}} {{experimental_inline}}
+
객체의 기본 비동기 반복자(default AsyncIterator)를 반환하는 메서드. for await of에서 사용됨.
+
+ +

정규표현식 심볼

+ +
+
{{jsxref("Symbol.match")}}
+
문자열과 일치하는(match) 메서드로 객체를 정규표현식으로 사용할 수 있는지 확인하는데도 사용. {{jsxref("String.prototype.match()")}}에서 사용됨.
+
{{jsxref("Symbol.replace")}}
+
문자열 중 일치하는 문자열 일부를 대체하는 메소드. {{jsxref("String.prototype.replace()")}}에서 사용됨.
+
{{jsxref("Symbol.search")}}
+
문자열에서 정규표현식과 일치하는 인덱스(index)를 반환하는 메서드. {{jsxref("String.prototype.search()")}}에서 사용됨.
+
{{jsxref("Symbol.split")}}
+
정규표현식과 일치하는 인덱스에서 문자열을 나누는 메서드. {{jsxref("String.prototype.split()")}}에서 사용됨.
+
+ +

그 외 심볼들

+ +
+
{{jsxref("Symbol.hasInstance")}}
+
생성자 객체(constructor object)가 어떤 객체를 자신의 인스턴스로 인식하는지를 확인하는데 사용하는 메소드. {{jsxref("Operators/instanceof", "instanceof")}}에서 사용됨.
+
{{jsxref("Symbol.isConcatSpreadable")}}
+
객체가 자신의 배열 요소를 직렬로(be flattened) 나타낼 수 있는지 여부를 나타내는 부울 값. {{jsxref("Array.prototype.concat()")}}에서 사용됨.
+
{{jsxref("Symbol.unscopables")}}
+
자신의 속성명 또는 상속된 속성명이 연관 객체(the associated objet)의 with 환경 바인딩(envorinment bindings)에서 제외된 객체의 값 (An object value of whose own and inherited property names are excluded from the with environment bindings of the associated object).
+
{{jsxref("Symbol.species")}}
+
파생(derived) 객체를 생성하는데 사용되는 생성자 함수.
+
{{jsxref("Symbol.toPrimitive")}}
+
객체를 원시형(primitive) 값으로 변환하는 메서드.
+
{{jsxref("Symbol.toStringTag")}}
+
객체에 대한 기본 설명(description)으로 사용되는 문자열 값. {{jsxref("Object.prototype.toString()")}}에서 사용됨.
+
+ +

메서드

+ +
+
{{jsxref("Symbol.for()", "Symbol.for(key)")}}
+
주어진 키(key)로 현재 존재하는 심볼을 검색하고 찾으면 반환합니다. 존재하지 않으면 주어진 키로 전역 심볼 레지스트리에 새로운 심볼을 생성하고 그 심볼을 반환합니다.
+
{{jsxref("Symbol.keyFor", "Symbol.keyFor(sym)")}}
+
전역 심볼 레지스트리로부터 주어진 심볼에 대한 공유 심볼 키(shared symbol key)를 추출합니다.
+
+ +

심볼(Symbol) 프로토타입

+ +

모든 심볼은 {{jsxref("Symbol.prototype")}}을 상속합니다.

+ +

속성(properties)

+ +

{{page('ko/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Properties')}}

+ +

메서드

+ +

{{page('ko/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Methods')}}

+ +

예제

+ +

심볼에 typeof 연산자 사용

+ +

{{jsxref("Operators/typeof", "typeof")}} 연산자를 이용해 심볼인지 알 수 있습니다.

+ +
typeof Symbol() === 'symbol'
+typeof Symbol('foo') === 'symbol'
+typeof Symbol.iterator === 'symbol'
+
+ +

심볼의 형 변환(type conversions)

+ +

심볼의 형 변환(type conversion)할 때 유의해야 할 사항

+ + + +

심볼과 for...in 반복문

+ +

심볼은 for...in 반복문 내에서 하나씩 열거할 수 없습니다. 더구나, {{jsxref("Object.getOwnPropertyNames()")}}는 심볼 객체 속성(symbol object properties)을 반환하지 않습니다. 하지만, {{jsxref("Object.getOwnPropertySymbols()")}}를 이용해 이것들을 가져올 수 있습니다.

+ +
var obj = {};
+
+obj[Symbol("a")] = "a";
+obj[Symbol.for("b")] = "b";
+obj["c"] = "c";
+obj.d = "d";
+
+for (var i in obj) {
+   console.log(i); // logs "c" and "d"
+}
+ +

심볼과 JSON.stringify()

+ +

심볼을 키로 사용한 속성(symbol-keyed properties)은 JSON.stringify()을 사용할 때 완전히 무시됩니다:

+ +
JSON.stringify({[Symbol("foo")]: "foo"});
+// '{}'
+ +

더 자세한 것은 {{jsxref("JSON.stringify()")}}를 참조하시기 바랍니다.

+ +

속성 키로서의 심볼 래퍼 객체(symbol wrapper object)

+ +

심볼 래퍼 객체를 속성 키로 사용하면, 이 객체는 래핑된 심볼로 강제 변환됩니다(When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped symbol):

+ +
var sym = Symbol("foo");
+var obj = {[sym]: 1};
+obj[sym];            // 1
+obj[Object(sym)];    // still 1
+
+ +

명세서

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-symbol-objects', 'Symbol')}}{{Spec2('ES2015')}}Initial definition
{{SpecName('ESDraft', '#sec-symbol-objects', 'Symbol')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.Symbol")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/symbol/iterator/index.html b/files/ko/web/javascript/reference/global_objects/symbol/iterator/index.html new file mode 100644 index 0000000000..820e63d1cb --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/symbol/iterator/index.html @@ -0,0 +1,95 @@ +--- +title: Symbol.iterator +slug: Web/JavaScript/Reference/Global_Objects/Symbol/iterator +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/iterator +--- +
{{JSRef}}
+ +

잘 알려진 Symbol.iterator 심볼은 객체에 대응하는 기본 이터레이터를 지정합니다. for...of와 같이 사용됩니다.

+ +
{{EmbedInteractiveExample("pages/js/symbol-iterator.html")}}
+ + + +
{{js_property_attributes(0,0,0)}}
+ +

설명

+ +

(for..of 루프의 시작부분과 같이) 객체가 반환될 필요가 있을때는 언제든지@@iterator 메서드는 인수 없이도 호출 할 수 있습니다. 반환된 iterator는 반복할 값을 취득하기 위해 사용됩니다.

+ +

{{jsxref("Object")}}와 같이 반복동작을 내장하고 있는 형태도 있지만 그렇지 않은 경우도 있습니다. @@iterator 메서드를 가지고 있는 내장형 타입은 아래와 같습니다.

+ + + +

상세한 내용은 반복처리 프로토콜도 확인 해 주시기 바랍니다.

+ +

예제

+ +

유저 정의 이터레이터

+ +

앞에서 기술한 바와 같이 독자적으로 이터레이터를 만드는 것이 가능합니다.

+ +
var myIterable = {}
+myIterable[Symbol.iterator] = function* () {
+    yield 1;
+    yield 2;
+    yield 3;
+};
+[...myIterable] // [1, 2, 3]
+
+ +

비정형 이터레이터

+ +

iterable의 @@iterator 메서드가 이터레이터 객체를 반환하지 않는 경우 비정형 이터레이터입니다. 이와 같이 사용하는 경우 실행시 예외 혹은 예상치 못한 버그를 발생할 가능성이 있습니다.

+ +
var nonWellFormedIterable = {}
+nonWellFormedIterable[Symbol.iterator] = () => 1
+[...nonWellFormedIterable] // TypeError: [] is not a function
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상황코멘트
{{SpecName('ES2015', '#sec-symbol.iterator', 'Symbol.iterator')}}{{Spec2('ES2015')}}초기 정의
{{SpecName('ESDraft', '#sec-symbol.iterator', 'Symbol.iterator')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Symbol.iterator")}}

+ +

관련 정보

+ + diff --git a/files/ko/web/javascript/reference/global_objects/syntaxerror/index.html b/files/ko/web/javascript/reference/global_objects/syntaxerror/index.html new file mode 100644 index 0000000000..84ccc26908 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/syntaxerror/index.html @@ -0,0 +1,123 @@ +--- +title: SyntaxError +slug: Web/JavaScript/Reference/Global_Objects/SyntaxError +translation_of: Web/JavaScript/Reference/Global_Objects/SyntaxError +--- +
{{JSRef}}
+ +

SyntaxError 객체는 문법적으로 유효하지 않은 코드를 해석하려고 시도할 때 발생하는 오류를 표현합니다.

+ +

설명

+ +

SyntaxError는 JavaScript 엔진이 코드를 분석할 때 문법을 준수하지 않은 코드를 만나면 발생합니다.

+ +

구문

+ +
new SyntaxError([message[, fileName[, lineNumber]]])
+ +

매개변수

+ +
+
message {{optional_inline}}
+
오류에 대한 설명.
+
fileName {{optional_inline}} {{non-standard_inline}}
+
예외가 발생한 코드를 담고 있는 파일의 이름.
+
lineNumber {{optional_inline}} {{non-standard_inline}}
+
예외가 발생한 코드의 라인 넘버.
+
+ +

속성

+ +
+
{{jsxref("SyntaxError.prototype")}}
+
SyntaxError 객체에 속성을 추가할 수 있도록 해주고 있습니다.
+
+ +

메서드

+ +

전역(global) SyntaxError 는 고유의 메소드를 가지고 있지 않지만, prototype chain을 통해 몇몇의 메소드를 상속 받습니다.

+ +

SyntaxError 인스턴스

+ +

속성

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError/prototype', 'Properties')}}
+ +

메소드

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError/prototype', 'Methods')}}
+ +

예제

+ +

SyntaxError 잡기

+ +
try {
+  eval('hoo bar');
+} catch (e) {
+  console.log(e instanceof SyntaxError); // true
+  console.log(e.message);                // "missing ; before statement"
+  console.log(e.name);                   // "SyntaxError"
+  console.log(e.fileName);               // "Scratchpad/1"
+  console.log(e.lineNumber);             // 1
+  console.log(e.columnNumber);           // 4
+  console.log(e.stack);                  // "@Scratchpad/1:2:3\n"
+}
+
+ +

SyntaxError 생성하기

+ +
try {
+  throw new SyntaxError('Hello', 'someFile.js', 10);
+} catch (e) {
+  console.log(e instanceof SyntaxError); // true
+  console.log(e.message);                // "Hello"
+  console.log(e.name);                   // "SyntaxError"
+  console.log(e.fileName);               // "someFile.js"
+  console.log(e.lineNumber);             // 10
+  console.log(e.columnNumber);           // 0
+  console.log(e.stack);                  // "@Scratchpad/2:11:9\n"
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의.
{{SpecName('ES5.1', '#sec-15.11.6.4', 'SyntaxError')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-syntaxerror', 'SyntaxError')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-syntaxerror', 'SyntaxError')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.SyntaxError")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html b/files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html new file mode 100644 index 0000000000..5fda6d61ad --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/syntaxerror/prototype/index.html @@ -0,0 +1,126 @@ +--- +title: SyntaxError.prototype +slug: Web/JavaScript/Reference/Global_Objects/SyntaxError/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/SyntaxError +--- +
{{JSRef}}
+ +

SyntaxError.prototype 속성은 {{jsxref("SyntaxError")}} 객체의 생성자 프로토타입을 표현합니다.

+ +

설명

+ +

모든 {{jsxref("SyntaxError")}} 인스턴스는 SyntaxError.prototype 객체로부터 상속 받습니다. 또한, 속성이나 메소드를 추가할 때 모든 인스턴스에 프로토타입을 사용 할 수 있습니다.

+ +

속성

+ +
+
SyntaxError.prototype.constructor
+
인스턴스의 프로토타입을 생성하는 함수를 명시합니다.
+
{{jsxref("Error.prototype.message", "SyntaxError.prototype.message")}}
+
에러 메시지. 비록 ECMA-262는  {{jsxref("SyntaxError")}} 가 고유의 message 속성을 제공해야 한다고 명시하고 있지만, SpiderMonkey 에서는, {{jsxref("Error.prototype.message")}}를 상속 받습니다. 
+
{{jsxref("Error.prototype.name", "SyntaxError.prototype.name")}}
+
에러명. {{jsxref("Error")}}로부터 상속 받습니다.
+
{{jsxref("Error.prototype.fileName", "SyntaxError.prototype.fileName")}}
+
에러를 발생시킨 파일의 경로. {{jsxref("Error")}}로부터 상속 받습니다.
+
{{jsxref("Error.prototype.lineNumber", "SyntaxError.prototype.lineNumber")}}
+
에러가 발생한 파일의 코드 라인 넘버. {{jsxref("Error")}}로부터 상속 받습니다.
+
{{jsxref("Error.prototype.columnNumber", "SyntaxError.prototype.columnNumber")}}
+
에러가 발생된 라인의 컬럼 넘버. {{jsxref("Error")}}로부터 상속 받습니다.
+
{{jsxref("Error.prototype.stack", "SyntaxError.prototype.stack")}}
+
스택 트레이스. {{jsxref("Error")}}로부터 상속 받습니다.
+
+ +

메소드

+ +

비록 {{jsxref("SyntaxError")}} 프로토타입 객체는 고유의 메소드를 가지고 있지는 않지만, {{jsxref("SyntaxError")}} 인스턴스는 몇 가지의 메소드를 프로토타입 체인을 통하여 상속 받습니다.

+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}초기 정의.
{{SpecName('ES5.1', '#sec-15.11.7.6', 'NativeError.prototype')}}{{Spec2('ES5.1')}}NativeError.prototype로 정의.
{{SpecName('ES6', '#sec-nativeerror.prototype', 'NativeError.prototype')}}{{Spec2('ES6')}}NativeError.prototype로 정의.
{{SpecName('ESDraft', '#sec-nativeerror.prototype', 'NativeError.prototype')}}{{Spec2('ESDraft')}}NativeError.prototype로 정의.
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/@@iterator/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/@@iterator/index.html new file mode 100644 index 0000000000..ded3d1c973 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/@@iterator/index.html @@ -0,0 +1,127 @@ +--- +title: 'TypedArray.prototype[@@iterator]()' +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator +tags: + - Iterator + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator +--- +
{{JSRef}}
+ +

@@iterator 속성의 초기값은 {{jsxref("TypedArray.prototype.values()", "values")}} 속성의 초기값과 같은 함수 객체입니다.

+ +

구문

+ +
arr[Symbol.iterator]()
+ +

+ +

for...of 루프를 사용하는 반복

+ +
var arr = new Uint8Array([10, 20, 30, 40, 50]);
+// 브라우저가 for..of 루프 및 for 루프에서
+// let 스코프인 변수를 지원해야 합니다
+for (let n of arr) {
+  console.log(n);
+}
+
+ +

대안 반복

+ +
var arr = new Uint8Array([10, 20, 30, 40, 50]);
+var eArr = arr[Symbol.iterator]();
+console.log(eArr.next().value); // 10
+console.log(eArr.next().value); // 20
+console.log(eArr.next().value); // 30
+console.log(eArr.next().value); // 40
+console.log(eArr.next().value); // 50
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-%typedarray%.prototype-@@iterator', '%TypedArray%.prototype[@@iterator]()')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype-@@iterator', '%TypedArray%.prototype[@@iterator]()')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown }}{{ CompatGeckoDesktop("36") }} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{ CompatVersionUnknown }}{{ CompatGeckoMobile("36") }} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Gecko 17 (Firefox 17 / Thunderbird 17 / SeaMonkey 2.14)에서 Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2)까지는 iterator 속성이 쓰였고(bug 907077), Gecko 27에서 Gecko 35까지는 "@@iterator" placeholder가 사용됐습니다. Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33)에서는, @@iterator symbol이 구현됐습니다 (bug 918828).

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/buffer/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/buffer/index.html new file mode 100644 index 0000000000..702fe13eb7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/buffer/index.html @@ -0,0 +1,111 @@ +--- +title: TypedArray.prototype.buffer +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/buffer +tags: + - JavaScript + - Property + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/buffer +--- +
{{JSRef}}
+ +

buffer 접근자(accessor) 속성(property)은 생성 시간에 TypedArray에 의해 참조되는 {{jsxref("ArrayBuffer")}}를 나타냅니다.

+ +

구문

+ +
typedArray.buffer
+ +

설명

+ +

buffer 속성은 set 접근자 함수가 undefined인 접근자 속성입니다, 이 속성을 읽을 수만 있음을 뜻하는. 그 값은 TypedArray가 만들어질 때 수립되어 변경될 수 없습니다. TypedArrayTypedArray 객체 유형 중 하나입니다.

+ +

+ +

buffer 속성 사용

+ +
var buffer = new ArrayBuffer(8);
+var uint16 = new Uint16Array(buffer);
+uint16.buffer; // ArrayBuffer { byteLength: 8 }
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-get-%typedarray%.prototype.buffer', 'TypedArray.prototype.buffer')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-get-%typedarray%.prototype.buffer', 'TypedArray.prototype.buffer')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7.0{{ CompatGeckoDesktop("2") }}1011.65.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.0{{CompatVersionUnknown}}{{ CompatGeckoMobile("2") }}1011.64.2
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/bytelength/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/bytelength/index.html new file mode 100644 index 0000000000..37a12d927a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/bytelength/index.html @@ -0,0 +1,73 @@ +--- +title: TypedArray.prototype.byteLength +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/byteLength +tags: + - JavaScript + - Property + - Prototype + - Reference + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/byteLength +--- +
{{JSRef}}
+ +

byteLength 접근자(accessor) 속성(property)은 형식화 배열의 길이(바이트 단위)를 나타냅니다.

+ +

구문

+ +
typedarray.byteLength
+ +

설명

+ +

byteLength 속성은 접근자 함수가 undefined인 접근자 속성입니다, 이 속성을 읽을 수만 있음을 뜻하는. 그 값은 TypedArray가 만들어질 때 수립되어 변경될 수 없습니다. TypedArraybyteOffset 또는 length를 지정하지 않은 경우, 참조되는 ArrayBufferlength가 반환됩니다. TypedArrayTypedArray 객체 유형 중 하나입니다.

+ +

예제

+ +

byteLength 속성 사용

+ +
var buffer = new ArrayBuffer(8);
+
+var uint8 = new Uint8Array(buffer);
+uint8.byteLength; // 8 (버퍼의 byteLength와 일치)
+
+var uint8 = new Uint8Array(buffer, 1, 5);
+uint8.byteLength; // 5 (Uint8Array를 만들 때 지정된 대로)
+
+var uint8 = new Uint8Array(buffer, 2);
+uint8.byteLength; // 6 (만든 Uint8Array의 오프셋으로 인해)
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-get-%typedarray%.prototype.bytelength', 'TypedArray.prototype.byteLength')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-get-%typedarray%.prototype.bytelength', 'TypedArray.prototype.byteLength')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.TypedArray.byteLength")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/byteoffset/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/byteoffset/index.html new file mode 100644 index 0000000000..3be7af84cd --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/byteoffset/index.html @@ -0,0 +1,69 @@ +--- +title: TypedArray.prototype.byteOffset +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/byteOffset +tags: + - JavaScript + - Property + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/byteOffset +--- +
{{JSRef}}
+ +

byteOffset 접근자(accessor) 속성(property)은 그 {{jsxref("ArrayBuffer")}}의 시작점에서 형식화 배열의 오프셋(단위 바이트)을 나타냅니다.

+ +

구문

+ +
typedarray.byteOffset
+ +

설명

+ +

byteOffset 속성은 set 접근자 함수가 undefined인 접근자 속성입니다, 이 속성을 읽을 수만 있음을 뜻하는. 그 값은 TypedArray가 만들어질 때 수립되어 변경될 수 없습니다. TypedArrayTypedArray 객체 유형 중 하나입니다.

+ +

+ +

byteOffset 속성 사용

+ +
var buffer = new ArrayBuffer(8);
+
+var uint8 = new Uint8Array(buffer);
+uint8.byteOffset; // 0 (지정된 오프셋이 없음)
+
+var uint8 = new Uint8Array(buffer, 3);
+uint8.byteOffset; // 3 (Uint8Array를 만들 때 지정된 대로)
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-get-%typedarray%.prototype.byteoffset', 'TypedArray.prototype.byteOffset')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-get-%typedarray%.prototype.byteoffset', 'TypedArray.prototype.byteOffset')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.TypedArray.byteOffset")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/bytes_per_element/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/bytes_per_element/index.html new file mode 100644 index 0000000000..563b7856cc --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/bytes_per_element/index.html @@ -0,0 +1,75 @@ +--- +title: TypedArray.BYTES_PER_ELEMENT +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT +tags: + - JavaScript + - Property + - Reference + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT +--- +
{{JSRef}}
+ +

TypedArray.BYTES_PER_ELEMENT 속성은 각 형식화 배열 요소의 크기를 바이트로 나타냅니다.

+ +
{{EmbedInteractiveExample("pages/js/typedarray-bytes-per-element.html")}}
+ + + +
{{js_property_attributes(0,0,0)}}
+ +

설명

+ +

TypedArray 객체는 요소 당 바이트 수 및 바이트가 해석되는 방법으로 서로 다릅니다. BYTES_PER_ELEMENT 상수는 주어진 TypedArray의 각 요소가 갖는 바이트 수를 포함합니다.

+ +

예제

+ +
Int8Array.BYTES_PER_ELEMENT;         // 1
+Uint8Array.BYTES_PER_ELEMENT;        // 1
+Uint8ClampedArray.BYTES_PER_ELEMENT; // 1
+Int16Array.BYTES_PER_ELEMENT;        // 2
+Uint16Array.BYTES_PER_ELEMENT;       // 2
+Int32Array.BYTES_PER_ELEMENT;        // 4
+Uint32Array.BYTES_PER_ELEMENT;       // 4
+Float32Array.BYTES_PER_ELEMENT;      // 4
+Float64Array.BYTES_PER_ELEMENT;      // 8
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}ECMAScript 6로 대체됨.
{{SpecName('ES6', '#sec-typedarray.bytes_per_element', 'TypedArray.BYTES_PER_ELEMENT')}}{{Spec2('ES6')}}ECMA 표준에서 초기 정의.
{{SpecName('ESDraft', '#sec-typedarray.bytes_per_element', 'TypedArray.BYTES_PER_ELEMENT')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.TypedArray.BYTES_PER_ELEMENT")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/fill/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/fill/index.html new file mode 100644 index 0000000000..8e315fc201 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/fill/index.html @@ -0,0 +1,75 @@ +--- +title: TypedArray.prototype.fill() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/fill +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/fill +--- +
{{JSRef}}
+ +

fill() 메서드는 배열의 모든 요소를 지정한 시작 인덱스부터 종료 인덱스까지 정적인 값으로 채웁니다. fill()은 {{jsxref("Array.prototype.fill()")}}과 동일한 알고리즘을 가지고 있습니다. TypedArray 는 typed array types 이곳에 있는 것 중 하나 입니다.

+ +

{{EmbedInteractiveExample("pages/js/typedarray-fill.html")}}

+ +

구문

+ +
typedarray.fill(value[, start = 0[, end = this.length]])
+ +

매개변수

+ +
+
value
+
배열에 채워넣을 값.
+
start
+
선택사항. 시작 위치. 기본값은 0.
+
end
+
선택사항. 종료 위치 (종료위치를 포함하지않습니다. 즉, end -1 까지만 해당됩니다.). 기본값 this.length(배열의 길이).
+
+ +

설명

+ +

start 와 end 사이에 요소들을 채웁니다.

+ +

fill 메소드는 value, start 그리고 and 3개의 매개변수를 요구합니다. start 와 end 매개변수는 선택사항이며 기본값은 0 과 지정한 배열객체의 길이값 입니다.

+ +

만약 start 매개변수가 음수이면, start 의 값은 배열의 길이값을 합한 결과가 시작지점이 되고, 만약 end 가 음수라면, end 매개변수와 배열의 길이값을 합한 결과가 종료지점이 됩니다.

+ +

예제

+ +
new Uint8Array([1, 2, 3]).fill(4);         // Uint8Array [4, 4, 4]
+new Uint8Array([1, 2, 3]).fill(4, 1);      // Uint8Array [1, 4, 4]
+new Uint8Array([1, 2, 3]).fill(4, 1, 2);   // Uint8Array [1, 4, 3]
+new Uint8Array([1, 2, 3]).fill(4, 1, 1);   // Uint8Array [1, 2, 3]
+new Uint8Array([1, 2, 3]).fill(4, -3, -2); // Uint8Array [4, 2, 3]
+
+ +

명세

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-%typedarray%.prototype.fill', 'TypedArray.prototype.fill')}}{{Spec2('ES6')}}Initial definition.
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.TypedArray.fill")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/index.html new file mode 100644 index 0000000000..3f4edc9970 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/index.html @@ -0,0 +1,342 @@ +--- +title: TypedArray +slug: Web/JavaScript/Reference/Global_Objects/TypedArray +tags: + - JavaScript + - TypedArray + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray +--- +
{{JSRef}}
+ +

TypedArray 객체는 밑에 깔린 이진 데이터 버퍼의 배열 같은 뷰를 기술합니다. TypedArray인 전역 속성도 눈에 직접 보이는 TypedArray 생성자도 없습니다. 대신 다양한 전역 속성이 있습니다, 그 값이 아래 나열된 특정 요소 유형에 대한 형식화 배열 생성자인. 다음 페이지에서 각 유형 요소를 포함하는 모든 형식화 배열에 쓰일 수 있는 공통 속성 및 메서드를 찾을 수 있습니다.

+ +

구문

+ +
new TypedArray(length);
+new TypedArray(typedArray);
+new TypedArray(object);
+new TypedArray(buffer [, byteOffset [, length]]);
+
+TypedArray()는 다음 중 하나입니다:
+
+Int8Array();
+Uint8Array();
+Uint8ClampedArray();
+Int16Array();
+Uint16Array();
+Int32Array();
+Uint32Array();
+Float32Array();
+Float64Array();
+
+ +

매개변수

+ +
+
length
+
length 인수와 함께 호출하면 메모리상에 길이에 BYTES_PER_ELEMENT bytes(바이트)를 곱한 크기만큼의, 0을 포함한 이진 데이터 버퍼를 생성합니다.
+
typedArray
+
typedArray 인수와 함께 호출하면, 모든 형식화 배열 객체 유형(가령 Int32Array)이 될 수 있는, typedArray는 새로운 형식화 배열로 복사됩니다. typedArray 내 각 값은 새로운 배열로 복사되기 전에 해당 유형의 생성자로 변환됩니다.
+
object
+
object 인수와 함께 호출하면, 새로운 형식화 배열이 마치 TypedArray.from() 메서드에 의해서처럼 생성됩니다.
+
buffer, byteOffset, length
+
buffer와 선택 사항으로 byteOffsetlength 인수와 함께 호출하면, 새로운 형식화 배열 뷰는 지정된 {{jsxref("ArrayBuffer")}} 뷰로 생성됩니다. byteOffsetlength 매개변수는 형식화 배열 뷰에 의해 노출되는 메모리 범위를 지정합니다. 둘 다 생략된 경우, buffer가 모두 보입니다; length만 생략된 경우, buffer의 나머지가 보입니다.
+
+ +

설명

+ +

ECMAScript 6는 모든 TypedArray 생성자의 [[Prototype]] 역할을 하는 TypedArray 생성자를 정의합니다. 이 생성자는 직접 노출되지 않습니다: 전역 %TypedArray% 또는 TypedArray 속성은 없습니다. Object.getPrototypeOf(Int8Array.prototype) 및 비슷한 방식을 통해서만 직접 접근할 수 있습니다. 모든 TypedArray 생성자는 %TypedArray% 생성자 함수로부터 공통 속성을 상속합니다. 게다가, 모든 형식화 배열 프로토타입(TypedArray.prototype)은 자기 [[Prototype]]으로서 %TypedArray%.prototype이 있습니다.

+ +

%TypedArray% 생성자 자체로는 특별히 유용한 것은 아닙니다. 호출하거나 new 식으로 사용하면 TypeError가 발생합니다, 서브클래싱을 지원하는 JS 엔진에서 객체 생성 도중 사용될 때 빼고는. 현재로서는 그러한 엔진이 없기에 %TypedArray%는 모든 TypedArray 생성자에 함수 또는 속성을 폴리필할 때만 유용합니다.

+ +

속성 접근

+ +

표준 배열 인덱스 구문(즉, 각괄호 표기법)을 써서 배열의 요소를 참조할 수 있습니다. 그러나, 형식화 배열에 인덱스 있는 속성의 읽기(getting) 또는 쓰기(setting)는 이 속성에 대한 프로토타입 체인에서 찾을 수 없습니다, 심지어 인덱스가 범위 밖인 경우라도. 인덱스 있는 속성은 {{jsxref("ArrayBuffer")}}를 조사하고 객체 속성을 조사하지는 않습니다. 여전히 유명 속성을 사용할 수 있습니다, 모든 객체와 마찬가지로.

+ +
// 표준 배열 구문을 사용해 쓰기 및 읽기
+var int16 = new Int16Array(2);
+int16[0] = 42;
+console.log(int16[0]); // 42
+
+// 프로토타입의 인덱스 있는 속성은 조사되지 않음 (Fx 25)
+Int8Array.prototype[20] = "foo";
+(new Int8Array(32))[20]; // 0
+// 비록 범위 밖 또는
+Int8Array.prototype[20] = "foo";
+(new Int8Array(8))[20]; // undefined
+// 음의 정수인 경우에도
+Int8Array.prototype[-1] = "foo";
+(new Int8Array(8))[-1]; // undefined
+
+// 유명(named) 속성은 허용됨, 다만 (Fx 30) 에서지만
+Int8Array.prototype.foo = "bar";
+(new Int8Array(32)).foo; // "bar"
+ +

TypedArray 객체

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
유형크기 (바이트)설명Web IDL 형해당 C 형
{{jsxref("Int8Array")}}18비트 2의 보수 형식 부호 있는 정수byteint8_t
{{jsxref("Uint8Array")}}18비트 부호 없는 정수octetuint8_t
{{jsxref("Uint8ClampedArray")}}18비트 부호 없는 정수 (단속됨)octetuint8_t
{{jsxref("Int16Array")}}216비트 2의 보수 형식 부호 있는 정수shortint16_t
{{jsxref("Uint16Array")}}216비트 부호 없는 정수unsigned shortuint16_t
{{jsxref("Int32Array")}}432비트 2의 보수 형식 부호 있는 정수longint32_t
{{jsxref("Uint32Array")}}432비트 부호 없는 정수unsigned longuint32_t
{{jsxref("Float32Array")}}432비트 IEEE 부동 소수점 수unrestricted floatfloat
{{jsxref("Float64Array")}}864비트 IEEE 부동 소수점 수unrestricted doubledouble
+ +

속성

+ +
+
{{jsxref("TypedArray.BYTES_PER_ELEMENT")}}
+
서로 다른 형식화 배열 객체에 대해 요소 크기의 숫자값을 반환합니다.
+
TypedArray.length
+
값이 3인 길이 속성.
+
{{jsxref("TypedArray.name")}}
+
생성자 이름의 문자열 값을 반환합니다. 가령 "Int8Array".
+
{{jsxref("TypedArray.@@species", "get TypedArray[@@species]")}}
+
파생된 객체를 생성하는데 쓰이는 생성자 함수.
+
{{jsxref("TypedArray.prototype")}}
+
TypedArray 객체에 대한 프로토타입.
+
+ +

메서드

+ +
+
{{jsxref("TypedArray.from()")}}
+
배열 같은 또는 반복가능(iterable) 객체로부터 새로운 형식화 배열을 생성합니다. {{jsxref("Array.from()")}}도 참조.
+
{{jsxref("TypedArray.of()")}}
+
가변(variable) 인수로 새로운 형식화 배열을 생성합니다. {{jsxref("Array.of()")}}도 참조.
+
+ +

TypedArray 프로토타입

+ +

모든 TypedArray는 {{jsxref("TypedArray.prototype")}}을 상속합니다.

+ +

속성

+ +

{{page('ko/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','속성')}}

+ +

메서드

+ +

{{page('ko/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','메서드')}}

+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}형식화 배열 뷰 유형이 있는 TypedArrayArrayBufferView 인터페이스로 정의됨. ECMAScript 6로 대체됨.
{{SpecName('ES6', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ES6')}}ECMA 표준에서 초기 정의. 인덱스 있고 유명 속성에 대한 행동이 지정됨. new가 필요함이 지정됨.
{{SpecName('ESDraft', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(7.0)}}{{CompatGeckoDesktop("2")}}1011.65.1
Indexed properties not consulting prototype{{CompatVersionUnknown}} [1]{{CompatGeckoDesktop("25")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Named properties{{CompatVersionUnknown}}{{CompatGeckoDesktop("30")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
new is required{{CompatUnknown}}{{CompatGeckoDesktop("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support4.0{{CompatVersionUnknown}}{{ CompatGeckoMobile("2") }}1011.64.2{{CompatVersionUnknown}}
Indexed properties not consulting prototype{{CompatUnknown}}{{CompatVersionUnknown}} [1]{{ CompatGeckoMobile("25") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} [1]
Named properties{{CompatUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("30") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
new is required{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile("44") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] -1과 비슷한 값은 인덱스 있는 속성으로 여겨지지 않기에 그 프로토타입 속성값을 반환합니다.

+ +

호환성 주의사항

+ +

ECMAScript 2015 (ES6)를 시작으로, TypedArray 생성자는 {{jsxref("Operators/new", "new")}} 연산자로 생성되어야 합니다. new 없는 함수로서 TypedArray 생성자를 호출하면, 이제부터 {{jsxref("TypeError")}}가 발생합니다.

+ +
var dv = Int8Array([1, 2, 3]);
+// TypeError: new 없은 내장 Int8Array 생성자
+// 호출은 금지됩니다
+ +
var dv = new Int8Array([1, 2, 3]);
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/indexof/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/indexof/index.html new file mode 100644 index 0000000000..1ccd923d93 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/indexof/index.html @@ -0,0 +1,80 @@ +--- +title: TypedArray.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/indexOf +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/indexOf +--- +
{{JSRef}}
+ +

indexOf() 메소드는 형식화 배열(typed array)에서 주어진 값과 일치하는 첫 번째 인덱스를 반환한다. 일치하는 값이 없으면 -1을 반환한다. 이 메소드는 {{jsxref("Array.prototype.indexOf()")}} 와 동일한 알고리즘을 가지고 있다. TypedArrayTypedArray 객체 유형 중 하나이다.

+ +
{{EmbedInteractiveExample("pages/js/typedarray-indexof.html")}}
+ + + +

구문

+ +
typedarray.indexOf(searchElement[, fromIndex = 0])
+ +

매개변수

+ +
+
searchElement
+
배열에서 검색할 요소.
+
fromIndex
+
문자열에서 찾기 시작하는 위치를 나타내는 인덱스 값. 만약 인덱스 번호가 배열의 길이와 동일하거나 더 크다면, 해당 요소를 찾을 수 없기 때문에 결과값으로 -1이 반환된다. 만약 인덱스 번호가 음수라면, 배열의 끝에서부터 하나씩 상쇄하며 계산한다. (예.  fromIndex로 -1을 준 경우 가장 마지막 배열 요소의 값부터 검색을 시작. -2를 준 경우, 가장 마지막 배열 요소에서 하나 앞 요소부터 검색을 시작). 주의: 주어진 인덱스가 음수인 경우에도 배열은 여전히 앞에서부터 뒤로(왼쪽에서 오른쪽 순서로) 검색 된다. 만약 결과값으로 나온 인덱스가 0보다 작다면, 배열 전체가 찾아진 것이다. 디폴트 값 : 0 (전체 배열이 검색된다).
+
+ +

반환 결과

+ +

해당 배열에서 찾으려는 요소가 위치한 첫 번째 인덱스 값. 만약 찾으려는 요소가 없을 경우에는 -1을 반환. 

+ +

설명

+ +

indexOf 메소드는 배열의 요소를 searchElement 와 비교할 때, strict equality(===, 트리플 equals) 를 사용하여 자료형의 일치 여부까지 비교한다. 

+ +

예시

+ +
var uint8 = new Uint8Array([2, 5, 9]);
+uint8.indexOf(2);     // 0
+uint8.indexOf(7);     // -1
+uint8.indexOf(9, 2);  // 2
+uint8.indexOf(2, -1); // -1
+uint8.indexOf(2, -3); // 0
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-%typedarray%.prototype.indexof', 'TypedArray.prototype.indexOf')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype.indexof', 'TypedArray.prototype.indexOf')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.TypedArray.indexOf")}}

+
+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/length/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/length/index.html new file mode 100644 index 0000000000..0d5091aeb6 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/length/index.html @@ -0,0 +1,68 @@ +--- +title: TypedArray.prototype.length +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/length +tags: + - JavaScript + - Property + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/length +--- +
{{JSRef}}
+ +

length 접근자(accessor) 속성(property)은 형식화 배열의 (요소) 길이를 나타냅니다.

+ +

설명

+ +

length 속성은 set 접근자 함수가 undefined인 접근자 속성입니다, 이 속성을 읽을 수만 있음을 뜻하는. 값은 TypedArray가 만들어질 때 수립되어 변경될 수 없습니다. TypedArraybyteOffset 또는 length를 지정하지 않은 경우, 참조되는 {{jsxref("ArrayBuffer")}}의 길이가 반환됩니다. TypedArrayTypedArray 객체 유형 중 하나입니다.

+ +

예제

+ +

length 속성 사용

+ +
var buffer = new ArrayBuffer(8);
+
+var uint8 = new Uint8Array(buffer);
+uint8.length; // 8 (버퍼의 길이와 일치)
+
+var uint8 = new Uint8Array(buffer, 1, 5);
+uint8.length; // 5 (Uint8Array를 만들 때 지정된 대로)
+
+var uint8 = new Uint8Array(buffer, 2);
+uint8.length; // 6 (만든 Uint8Array의 오프셋으로 인해)
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-get-%typedarray%.prototype.length', 'TypedArray.prototype.length')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-get-%typedarray%.prototype.length', 'TypedArray.prototype.length')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.TypedArray.length")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/name/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/name/index.html new file mode 100644 index 0000000000..83b7f47ab1 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/name/index.html @@ -0,0 +1,70 @@ +--- +title: TypedArray.name +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/name +tags: + - JavaScript + - Property + - Reference + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/name +--- +
{{JSRef}}
+ +

TypedArray.name 속성은 형식화 배열 생성자 이름의 문자열 값을 나타냅니다.

+ +
{{EmbedInteractiveExample("pages/js/typedarray-name.html")}}
+ + + +
{{js_property_attributes(0,0,0)}}
+ +

설명

+ +

TypedArray 객체는 요소 당 바이트 수 및 바이트가 해석되는 방법으로 서로 다릅니다. name 속성은 어떤 데이터 형이 배열을 구성하는 지를 기술합니다. 첫 번째 부분은 "정수"용 Int 또는 "부호 없는 정수"용 Uint일 수 있습니다, "부동 소수점"용 Float도 쓰입니다 . 두 번째 부분은 배열의 비트 크기를 기술하는 숫자입니다. 끝으로, 객체 형은 Array입니다, 특수한 경우로 ClampedArray가 있는. 자세한 사항은 {{jsxref("Uint8ClampedArray")}}를 참조해 주세요.

+ +

예제

+ +
Int8Array.name;         // "Int8Array"
+Uint8Array.name;        // "Uint8Array"
+Uint8ClampedArray.name; // "Uint8ClampedArray"
+Int16Array.name;        // "Int16Array"
+Uint16Array.name;       // "Uint16Array"
+Int32Array.name;        // "Int32Array"
+Uint32Array.name;       // "Uint32Array"
+Float32Array.name;      // "Float32Array"
+Float64Array.name;      // "Float64Array"
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-properties-of-the-typedarray-constructors', 'TypedArray.name')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-properties-of-the-typedarray-constructors', 'TypedArray.name')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.TypedArray.name")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/of/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/of/index.html new file mode 100644 index 0000000000..854c53cedf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/of/index.html @@ -0,0 +1,92 @@ +--- +title: TypedArray.of() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/of +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/of +--- +
{{JSRef}}
+ +
TypedArray.of()는 가변적으로 인수를 전달 할수 있는 새로운 형식화 배열(typed array)를 만들어내는 메소드입니다.
+ +

이 메소드는 {{jsxref("Array.of()")}}와 거의 같습니다.

+ +

문법

+ +
TypedArray.of(element0[, element1[, ...[, elementN]]])
+
+where TypedArray is one of:
+
+Int8Array
+Uint8Array
+Uint8ClampedArray
+Int16Array
+Uint16Array
+Int32Array
+Uint32Array
+Float32Array
+Float64Array
+ +

매개변수

+ +
+
elementN
+
형식화 된 배열을 만들 요소입니다.
+
+ +

반환 값

+ +

생성된 {{jsxref("TypedArray")}} 인스턴스

+ +

설명

+ +

{{jsxref("Array.of()")}}와 TypedArray.of() 사이의 약간의 차이점은 다음과 같습니다. 

+ + + +

예제

+ +
Uint8Array.of(1);            // Uint8Array [ 1 ]
+Int8Array.of('1', '2', '3'); // Int8Array [ 1, 2, 3 ]
+Float32Array.of(1, 2, 3);    // Float32Array [ 1, 2, 3 ]
+Int16Array.of(undefined);    // IntArray [ 0 ]
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-%typedarray%.of', '%TypedArray%.of')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-%typedarray%.of', '%TypedArray%.of')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.TypedArray.of")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html new file mode 100644 index 0000000000..9a1b624b3b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/prototype/index.html @@ -0,0 +1,175 @@ +--- +title: TypedArray.prototype +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/prototype +tags: + - JavaScript + - Property + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray +--- +
{{JSRef}}
+ +

TypedArray.prototype 속성(property)은 {{jsxref("TypedArray")}} 생성자에 대한 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0,0,0)}}
+ +

설명

+ +

{{jsxref("TypedArray")}} 인스턴스는 {{jsxref("TypedArray.prototype")}}을 상속합니다. 모든 TypedArray 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있으며, TypedArrayTypedArray 객체 유형 중 하나입니다.

+ +

상속에 관한 자세한 정보를 위해 TypedArray에 대한 설명도 참조하세요.

+ +

속성

+ +
+
TypedArray.prototype.constructor
+
인스턴스의 프로토타입을 만든 함수를 반환합니다. 이는 기본으로 해당 TypedArray 객체 유형 함수 중 하나입니다.
+
{{jsxref("TypedArray.prototype.buffer")}} {{readonlyInline}}
+
형식화 배열에 의해 참조되는 {{jsxref("ArrayBuffer")}}를 반환합니다. 생성 시에 고정되기에 읽기 전용.
+
{{jsxref("TypedArray.prototype.byteLength")}} {{readonlyInline}}
+
{{jsxref("ArrayBuffer")}}의 시작점부터 형식화 배열의 길이(단위 바이트)를 반환합니다. 생성 시에 고정되기에 읽기 전용.
+
{{jsxref("TypedArray.prototype.byteOffset")}} {{readonlyInline}}
+
{{jsxref("ArrayBuffer")}}의 시작점부터 형식화 배열의 오프셋(단위 바이트)을 반환합니다. 생성 시에 고정되기에 읽기 전용.
+
{{jsxref("TypedArray.prototype.length")}} {{readonlyInline}}
+
형식화 배열 내 보유한 요소의 수를 반환합니다. 생성 시에 고정되기에 읽기 전용.
+
+ +

메서드

+ +
+
{{jsxref("TypedArray.prototype.copyWithin()")}}
+
배열 내부 일련의 배열 요소를 복사합니다. {{jsxref("Array.prototype.copyWithin()")}}도 참조.
+
{{jsxref("TypedArray.prototype.entries()")}}
+
배열 내 각 인덱스에 대한 키/값 쌍을 포함하는 새로운 Array Iterator 객체를 반환합니다. {{jsxref("Array.prototype.entries()")}}도 참조.
+
{{jsxref("TypedArray.prototype.every()")}}
+
배열의 모든 요소가 함수로 제공되는 테스트를 통과하는지를 테스트합니다. {{jsxref("Array.prototype.every()")}}도 참조.
+
{{jsxref("TypedArray.prototype.fill()")}}
+
시작 인덱스부터 끝 인덱스까지 배열의 모든 요소를 고정값으로 채웁니다. {{jsxref("Array.prototype.fill()")}}도 참조.
+
{{jsxref("TypedArray.prototype.filter()")}}
+
제공되는 필터링 함수가 true를 반환하는 이 배열의 모든 요소를 갖는 새로운 배열을 생성합니다. {{jsxref("Array.prototype.filter()")}}도 참조.
+
{{jsxref("TypedArray.prototype.find()")}}
+
배열 내 요소가 제공되는 테스트 함수를 만족하는 경우 배열 내 찾은 값 또는 못 찾은 경우 undefined를 반환합니다. {{jsxref("Array.prototype.find()")}}도 참조.
+
{{jsxref("TypedArray.prototype.findIndex()")}}
+
배열 내 요소가 제공되는 테스트 함수를 만족하는 경우 배열 내 찾은 인덱스 또는 못 찾은 경우 -1을 반환합니다. {{jsxref("Array.prototype.findIndex()")}}도 참조.
+
{{jsxref("TypedArray.prototype.forEach()")}}
+
배열 내 각 요소에 대해 함수를 호출합니다. {{jsxref("Array.prototype.forEach()")}}도 참조.
+
{{jsxref("TypedArray.prototype.includes()")}} {{experimental_inline}}
+
형식화 배열이 특정 요소를 포함하는지를 판단해, 적절히 true 또는 false를 반환합니다. {{jsxref("Array.prototype.includes()")}}도 참조.
+
{{jsxref("TypedArray.prototype.indexOf()")}}
+
지정된 값과 같은 배열 내부 요소의 첫(최소) 인덱스 또는 못 찾은 경우 -1을 반환합니다. {{jsxref("Array.prototype.indexOf()")}}도 참조.
+
{{jsxref("TypedArray.prototype.join()")}}
+
배열의 모든 요소를 문자열로 합칩니다. {{jsxref("Array.prototype.join()")}}도 참조.
+
{{jsxref("TypedArray.prototype.keys()")}}
+
배열의 각 인덱스에 대한 키를 포함하는 새로운 Array Iterator를 반환합니다. {{jsxref("Array.prototype.keys()")}}도 참조.
+
{{jsxref("TypedArray.prototype.lastIndexOf()")}}
+
지정된 값과 같은 배열 내부 요소의 끝(최대) 인덱스 또는 못 찾은 경우 -1을 반환합니다. {{jsxref("Array.prototype.lastIndexOf()")}}도 참조.
+
{{jsxref("TypedArray.prototype.map()")}}
+
이 배열의 모든 요소에 제공된 함수를 호출한 결과를 갖는 새로운 배열을 생성합니다. {{jsxref("Array.prototype.map()")}}도 참조.
+
{{jsxref("TypedArray.prototype.move()")}} {{non-standard_inline}} {{unimplemented_inline}}
+
{{jsxref("TypedArray.prototype.copyWithin()")}}의 이전 비표준 버전.
+
{{jsxref("TypedArray.prototype.reduce()")}}
+
누산기(accumulator) 및 배열의 각 값(좌에서 우로)에 대해 한 값으로 줄도록 함수를 적용합니다. {{jsxref("Array.prototype.reduce()")}}도 참조.
+
{{jsxref("TypedArray.prototype.reduceRight()")}}
+
누산기 및 배열의 각 값(우에서 좌로)에 대해 한 값으로 줄도록 함수를 적용합니다. {{jsxref("Array.prototype.reduceRight()")}}도 참조.
+
{{jsxref("TypedArray.prototype.reverse()")}}
+
배열 요소의 순서를 뒤집습니다 — 처음이 마지막이 되고 마지막이 처음이 됩니다. {{jsxref("Array.prototype.reverse()")}}도 참조.
+
{{jsxref("TypedArray.prototype.set()")}}
+
형식화 배열에 여러 값을 저장합니다, 지정된 배열에서 입력 값을 읽어.
+
{{jsxref("TypedArray.prototype.slice()")}}
+
배열의 한 부분을 추출하여 새로운 배열을 반환합니다. {{jsxref("Array.prototype.slice()")}}도 참조.
+
{{jsxref("TypedArray.prototype.some()")}}
+
이 배열의 적어도 한 요소가 제공된 테스트 함수를 만족하는 경우 true를 반환합니다. {{jsxref("Array.prototype.some()")}}도 참조.
+
{{jsxref("TypedArray.prototype.sort()")}}
+
배열의 요소를 적소에 정렬해 그 배열을 반환합니다. {{jsxref("Array.prototype.sort()")}}도 참조.
+
{{jsxref("TypedArray.prototype.subarray()")}}
+
주어진 시작 및 끝 요소 인덱스로부터 새로운 TypedArray를 반환합니다.
+
{{jsxref("TypedArray.prototype.values()")}}
+
배열의 각 인덱스에 대한 값을 포함하는 새로운 Array Iterator 객체를 반환합니다. {{jsxref("Array.prototype.values()")}}도 참조.
+
{{jsxref("TypedArray.prototype.toLocaleString()")}}
+
배열 및 그 요소를 나타내는 지역화된 문자열을 반환합니다. {{jsxref("Array.prototype.toLocaleString()")}}도 참조.
+
{{jsxref("TypedArray.prototype.toString()")}}
+
배열 및 그 요소를 나타내는 문자열을 반환합니다. {{jsxref("Array.prototype.toString()")}}도 참조.
+
{{jsxref("TypedArray.prototype.@@iterator()", "TypedArray.prototype[@@iterator]()")}}
+
배열의 각 인덱스에 대한 값을 포함하는 새로운 Array Iterator 객체를 반환합니다.
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-properties-of-the-%typedarrayprototype%-object', 'TypedArray prototype')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-properties-of-the-%typedarrayprototype%-object', 'TypedArray prototype')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7.0{{ CompatGeckoDesktop("2") }}1011.65.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.0{{CompatVersionUnknown}}{{ CompatGeckoMobile("2") }}1011.64.2
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/reverse/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/reverse/index.html new file mode 100644 index 0000000000..0d7ff7f5e2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/reverse/index.html @@ -0,0 +1,69 @@ +--- +title: TypedArray.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/reverse +tags: + - ECMAScript6 + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/reverse +--- +
{{JSRef}}
+ +

reverse() 메서드는 제자리에서 형식화 배열을 뒤집습니다. 형식화 배열 첫 요소는 마지막이 되고 마지막은 첫 요소가 됩니다. 이 메서드는 {{jsxref("Array.prototype.reverse()")}}와 같은 알고리즘입니다. TypedArray는 여기 TypedArray 객체 유형 중 하나입니다.

+ +
{{EmbedInteractiveExample("pages/js/typedarray-reverse.html")}}
+ + + +

구문

+ +
typedarray.reverse();
+
+ +

반환 값

+ +

뒤집힌 배열.

+ +

예제

+ +
var uint8 = new Uint8Array([1, 2, 3]);
+uint8.reverse();
+
+console.log(uint8); // Uint8Array [3, 2, 1]
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-%typedarray%.prototype.reverse', 'TypedArray.prototype.reverse')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype.reverse', 'TypedArray.prototype.reverse')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.TypedArray.reverse")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/set/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/set/index.html new file mode 100644 index 0000000000..3ce518f8cc --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/set/index.html @@ -0,0 +1,95 @@ +--- +title: TypedArray.prototype.set() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/set +tags: + - JavaScript + - Method + - Prototype + - Reference + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/set +--- +
{{JSRef}}
+ +

set() 메서드는 지정된 배열로부터 입력 값을 읽어 형식화 배열 내에 여러 값을 저장합니다.

+ +
{{EmbedInteractiveExample("pages/js/typedarray-set.html")}}
+ + + +

구문

+ +
typedarr.set(array[, offset])
+typedarr.set(typedarray[, offset])
+
+ +

매개변수

+ +
+
array
+
값을 복사할 배열. 소스 배열로부터 모든 값이 대상 배열로 복사됩니다, 소스 배열의 길이 + 오프셋이 대상 배열의 길이를 초과하지 않는 한, 그 경우에는 예외가 발생됩니다.
+
typedarray
+
소스 배열이 형식화 배열인 경우, 두 배열은 기본 {{jsxref("ArrayBuffer")}}를 같이 공유할 수 있습니다; 브라우저는 버퍼의 소스 범위를 대상(destination) 범위로 똑똑하게 복사합니다.
+
offset {{optional_inline}}
+
소스 array에서 값을 쓰기 시작하는 대상 배열의 오프셋. 이 값이 생략된 경우, 0으로 간주됩니다 (즉, 소스 array는 인덱스 0에서 시작하는 대상 배열 내 값을 덮어씁니다).
+
+ +

예외

+ +
+
{{jsxref("RangeError")}}
+
offset이 가령 형식화 배열의 끝을 넘어서 저장하려고 설정된 경우 발생.
+
+ +

예제

+ +

set() 사용하기

+ +
var buffer = new ArrayBuffer(8);
+var uint8 = new Uint8Array(buffer);
+
+uint8.set([1,2,3], 3);
+
+console.log(uint8); // Uint8Array [ 0, 0, 0, 1, 2, 3, 0, 0 ]
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}ECMAScript 6에 의해 대체됨.
{{SpecName('ES6', '#sec-%typedarray%.prototype.set-array-offset', 'TypedArray.prototype.set')}}{{Spec2('ES6')}}ECMA 표준에서 초기 정의.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype.set-array-offset', 'TypedArray.prototype.set')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.TypedArray.set")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/slice/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/slice/index.html new file mode 100644 index 0000000000..adef23132b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/slice/index.html @@ -0,0 +1,129 @@ +--- +title: TypedArray.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/slice +tags: + - ECMAScript6 + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/slice +--- +
{{JSRef}}
+ +

slice() 메서드는 형식화 배열의 일부를 얕게 복사(shallow copy)한 새로운 형식화 배열 객체를 반환합니다. 이 메서드는 {{jsxref("Array.prototype.slice()")}}와 같은 알고리즘입니다. TypedArray는 여기 TypedArray 객체 유형 중 하나입니다.

+ +

구문

+ +
typedarray.slice([begin[, end]])
+ +

매개변수

+ +
+
begin {{optional_inline}}
+
추출을 시작하는 인덱스(0부터 셈).
+
음수 인덱스일 때, begin은 열 끝으로부터 오프셋을 나타냅니다. slice(-2)는 열에서 마지막 두 요소를 추출합니다.
+
begin이 생략된 경우, slice는 인덱스 0에서 시작합니다.
+
end {{optional_inline}}
+
추출을 끝내는 인덱스(0부터 셈). sliceend(를 포함하지 않음)까지만 추출합니다.
+
slice(1,4)는 2번째부터 4번째 요소까지 추출합니다 (인덱스가 1, 2 및 3인 요소).
+
음수 인덱스일 때, end는 열 끝으로부터 오프셋을 나타냅니다. slice(2,-1)은 열의 3번째부터 끝에서 2번째 요소까지 추출합니다.
+
end가 생략된 경우, slice는 열의 끝까지 추출합니다 (arr.length).
+
+ +

설명

+ +

slice 메서드는 바꾸지 않습니다. 원래 형식화 배열에서 얕게 복사된 요소를 반환합니다.

+ +

새 요소가 어느 형식화 배열에든 추가된 경우, 다른 형식화 배열은 영향을 받지 않습니다.

+ +

+ +

기존 형식화 배열의 일부를 반환

+ +
var uint8 = new Uint8Array([1,2,3]);
+uint8.slice(1);   // Uint8Array [ 2, 3 ]
+uint8.slice(2);   // Uint8Array [ 3 ]
+uint8.slice(-2);  // Uint8Array [ 2, 3 ]
+uint8.slice(0,1); // Uint8Array [ 1 ]
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-%typedarray%.prototype.slice', '%TypedArray%.prototype.slice')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype.slice', '%TypedArray%.prototype.slice')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support45{{CompatGeckoDesktop("38")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("38")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/some/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/some/index.html new file mode 100644 index 0000000000..94ce55b40a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/some/index.html @@ -0,0 +1,106 @@ +--- +title: TypedArray.prototype.some() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/some +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/some +--- +
{{JSRef}}
+ +

some() 메서드는 형식화 배열 내 일부 요소가 제공되는 함수에 의해 구현되는 테스트를 통과하는지 여부를 테스트합니다. 이 메서드는 {{jsxref("Array.prototype.some()")}}과 같은 알고리즘입니다. TypedArray는 여기 TypedArray 객체 유형 중 하나입니다.

+ +
{{EmbedInteractiveExample("pages/js/typedarray-some.html")}}
+ + + +

구문

+ +
typedarray.some(callback[, thisArg])
+ +

매개변수

+ +
+
callback
+
각 요소에 대해 테스트하는 함수, 다음 인수 셋을 취하는: +
+
currentValue
+
형식화 배열에서 현재 처리 중인 요소.
+
index
+
형식화 배열에서 현재 처리 중인 요소의 인덱스.
+
array
+
some이 호출한 형식화 배열.
+
+
+
thisArg
+
선택 사항. callback을 실행할 때 this로서 사용하는 값.
+
+ +

설명

+ +

some 메서드는 callback이 true 값을 반환하는 요소를 찾을 때까지 형식화 배열에 있는 각 요소에 대해 한 번 callback 함수를 실행합니다. 그런 요소가 발견된 경우, some은 즉시 true를 반환합니다. 그렇지 않으면, somefalse를 반환합니다.

+ +

callback은 세 인수와 함께 호출됩니다: 요소값, 요소 인덱스 및 순회(traverse)되는 배열 객체.

+ +

thisArg 매개변수가 some에 제공되는 경우, 호출될 때 callback에 전달됩니다, 그 this 값으로 사용하기 위해. 그렇지 않으면, undefined 값이 그 this 값으로 사용하기 위해 전달됩니다. callback에 의해 결국 관찰할 수 있는 this 값은 함수에 의해 보이는 this를 결정하는 평소 규칙에 따라 결정됩니다.

+ +

some은 호출된 형식화 배열을 변화시키지(mutate) 않습니다.

+ +

예제

+ +

모든 형식화 배열 요소의 크기 테스트

+ +

다음 예는 형식화 배열의 모든 요소가 10보다 더 큰지 테스트합니다.

+ +
function isBiggerThan10(element, index, array) {
+  return element > 10;
+}
+new Uint8Array([2, 5, 8, 1, 4]).some(isBiggerThan10); // false
+new Uint8Array([12, 5, 8, 1, 4]).some(isBiggerThan10); // true
+
+ +

화살표 함수를 사용하여 형식화 배열 요소 테스트

+ +

화살표 함수는 같은 테스트에 대해 더 짧은 구문을 제공합니다.

+ +
new Uint8Array([2, 5, 8, 1, 4]).some(elem => elem > 10); // false
+new Uint8Array([12, 5, 8, 1, 4]).some(elem => elem > 10); // true
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-%typedarray%.prototype.some', 'TypedArray.prototype.some')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype.some', 'TypedArray.prototype.some')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.TypedArray.some")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/sort/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/sort/index.html new file mode 100644 index 0000000000..ef94943b23 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/sort/index.html @@ -0,0 +1,119 @@ +--- +title: TypedArray.prototype.sort() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/sort +tags: + - ECMAScript6 + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/sort +--- +
{{JSRef}}
+ +

sort() 메서드는 적소에 형식화 배열의 요소를 정렬하여 그 형식화 배열을 반환합니다. 이 메서드는 {{jsxref("Array.prototype.sort()")}}와 같은 알고리즘입니다. TypedArray는 여기 형식화 배열 유형 중 하나입니다.

+ +

구문

+ +
typedarray.sort([compareFunction])
+ +

매개변수

+ +
+
compareFunction {{optional_inline}}
+
정렬 순서를 정의하는 함수를 지정합니다.
+
+ +

+ +

더 많은 예는, {{jsxref("Array.prototype.sort()")}} 메서드도 참조하세요.

+ +
var number = new Uint8Array([40, 1, 5, 200]);
+
+function compareNumbers(a, b) {
+  return a - b;
+}
+
+numbers.sort(compareNumbers);
+// Uint8Array [ 1, 5, 40, 200 ]
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-%typedarray%.prototype.sort', 'TypedArray.prototype.sort')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype.sort', 'TypedArray.prototype.sort')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(46)}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(46)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typedarray/values/index.html b/files/ko/web/javascript/reference/global_objects/typedarray/values/index.html new file mode 100644 index 0000000000..863d3c3cbb --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typedarray/values/index.html @@ -0,0 +1,127 @@ +--- +title: TypedArray.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/TypedArray/values +tags: + - ECMAScript6 + - Iterator + - JavaScript + - Method + - Prototype + - TypedArray +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/values +--- +
{{JSRef}}
+ +

values() 메서드는 배열 내 각 인덱스에 대한 값을 포함하는 새로운 Array Iterator 객체를 반환합니다.

+ +

구문

+ +
arr.values()
+ +

+ +

for...of 루프를 사용한 반복

+ +
var arr = new Uint8Array([10, 20, 30, 40, 50]);
+var eArray = arr.values();
+// 브라우저가 for..of 루프 및 for 루프에서
+// let 스코프인 변수를 지원해야 합니다
+for (let n of eArray) {
+  console.log(n);
+}
+
+ +

대안 반복

+ +
var arr = new Uint8Array([10, 20, 30, 40, 50]);
+var eArr = arr.values();
+console.log(eArr.next().value); // 10
+console.log(eArr.next().value); // 20
+console.log(eArr.next().value); // 30
+console.log(eArr.next().value); // 40
+console.log(eArr.next().value); // 50
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-%typedarray%.prototype.values', '%TypedArray%.prototype.values()')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype.values', '%TypedArray%.prototype.values()')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown }}{{CompatGeckoDesktop(37)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{ CompatVersionUnknown }}{{CompatGeckoMobile(37)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/typeerror/index.html b/files/ko/web/javascript/reference/global_objects/typeerror/index.html new file mode 100644 index 0000000000..2a95fc358d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/typeerror/index.html @@ -0,0 +1,123 @@ +--- +title: TypeError +slug: Web/JavaScript/Reference/Global_Objects/TypeError +tags: + - Error + - JavaScript + - Reference + - TypeError +translation_of: Web/JavaScript/Reference/Global_Objects/TypeError +--- +
{{JSRef}}
+ +

TypeError 객체는 보통 값이 기대하던 자료형이 아니라서 연산을 할 수 없을 때 발생하는 오류입니다.

+ +

구문

+ +
new TypeError([message[, fileName[, lineNumber]]])
+ +

매개변수

+ +
+
message {{optional_inline}}
+
사람이 읽을 수 있는 오류에 대한 설명.
+
fileName {{optional_inline}} {{non-standard_inline}}
+
오류가 발생한 코드를 포함한 파일 이름.
+
lineNumber {{optional_inline}} {{non-standard_inline}}
+
오류가 발생한 코드의 줄 위치.
+
+ +

설명

+ +

함수나 연산자의 인자가, 그 함수나 연산자가 예상하던 타입과 호환되지 않을 때 TypeError 오류가 던져집니다.

+ +

속성

+ +
+
{{jsxref("TypeError.prototype")}}
+
TypeError 객체에 속성을 추가할 수 있습니다.
+
+ +

메서드

+ +

전역 TypeError는 메서드는 자신만의 메서드를 갖지 않지만, 프로토타입 체인을 통해 몇몇 메서드를 상속합니다.

+ +

TypeError 인스턴스

+ +

속성

+ +
+
+
TypeError.prototype.constructor
+
인스턴스의 프로토타입을 생성한 함수를 나타냅니다.
+
{{jsxref("Error.prototype.message", "TypeError.prototype.message")}}
+
오류의 메시지.
+
{{jsxref("Error.prototype.name", "TypeError.prototype.name")}}
+
오류 이름. {{jsxref("Error")}}에서 상속합니다.
+
{{jsxref("Error.prototype.fileName", "TypeError.prototype.fileName")}}
+
오류가 발생한 파일로의 경로. {{jsxref("Error")}}에서 상속합니다.
+
{{jsxref("Error.prototype.lineNumber", "TypeError.prototype.lineNumber")}}
+
오류가 발생한 곳의 줄 위치. {{jsxref("Error")}}에서 상속합니다.
+
{{jsxref("Error.prototype.columnNumber", "TypeError.prototype.columnNumber")}}
+
오류가 발생한 곳의 행 위치. {{jsxref("Error")}}에서 상속합니다.
+
{{jsxref("Error.prototype.stack", "TypeError.prototype.stack")}}
+
스택 추적. {{jsxref("Error")}}에서 상속합니다.
+
+
+ +

예제

+ +

TypeError 오류를 잡아내기

+ +
try {
+  null.f();
+} catch (e) {
+  console.log(e instanceof TypeError); // true
+  console.log(e.message);              // "null has no properties"
+  console.log(e.name);                 // "TypeError"
+  console.log(e.fileName);             // "Scratchpad/1"
+  console.log(e.lineNumber);           // 2
+  console.log(e.columnNumber);         // 2
+  console.log(e.stack);                // "@Scratchpad/2:2:3\n"
+}
+
+ +

TypeError 오류를 생성하기

+ +
try {
+  throw new TypeError('Hello', "someFile.js", 10);
+} catch (e) {
+  console.log(e instanceof TypeError); // true
+  console.log(e.message);              // "Hello"
+  console.log(e.name);                 // "TypeError"
+  console.log(e.fileName);             // "someFile.js"
+  console.log(e.lineNumber);           // 10
+  console.log(e.columnNumber);         // 0
+  console.log(e.stack);                // "@Scratchpad/2:2:9\n"
+}
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-typeerror', 'TypeError')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.TypeError")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/undefined/index.html b/files/ko/web/javascript/reference/global_objects/undefined/index.html new file mode 100644 index 0000000000..8ff8f09360 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/undefined/index.html @@ -0,0 +1,138 @@ +--- +title: undefined +slug: Web/JavaScript/Reference/Global_Objects/undefined +tags: + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/undefined +--- +
{{jsSidebar("Objects")}}
+ +

전역 undefined 속성은 {{Glossary("Undefined", "undefined")}} 원시 값을 나타내며, JavaScript의 {{Glossary("Primitive", "원시 자료형")}} 중 하나입니다.

+ +

{{js_property_attributes(0,0,0)}}

+ +
{{EmbedInteractiveExample("pages/js/globalprops-undefined.html")}}
+ + + +

구문

+ +
undefined
+ +

설명

+ +

undefined는 전역 객체의 속성입니다. 즉, 전역 스코프에서의 변수입니다. undefined의 초기 값은 {{Glossary("Undefined", "undefined")}} 원시 값입니다.

+ +

최신 브라우저에서 undefined는 ECMAScript 5 명세에 따라 설정 불가, 쓰기 불가한 속성입니다. 그렇지 않더라도 덮어쓰는건 피하는게 좋습니다.

+ +

값을 할당하지 않은 변수는 undefined 자료형입니다. 또한 메서드와 선언도 평가할 변수가 값을 할당받지 않은 경우에 undefined를 반환합니다. 함수는 값을 명시적으로 {{jsxref("Statements/return", "반환", "", 1)}}하지 않으면 undefined를 반환합니다.

+ +
+

undefined예약어가 아니기 때문에 전역 범위 외에서 {{Glossary("Identifier", "식별자")}}(변수 이름)로 사용할 수 있습니다. 그러나 유지보수와 디버깅 시 어려움을 낳을 수 있으므로 반드시 피해야 합니다.

+ +
//  DON'T DO THIS
+
+//  logs "foo string"
+(function() {
+  var undefined = 'foo';
+  console.log(undefined, typeof undefined);
+})();
+
+//  logs "foo string"
+(function(undefined) {
+  console.log(undefined, typeof undefined);
+})('foo');
+
+ +

예제

+ +

일치 연산과 undefined

+ +

undefined와 일치, 불일치 연산자를 사용해 변수에 값이 할당됐는지 판별할 수 있습니다. 다음 예제에서 변수 x는 초기화되지 않았으므로 if문은 true로 평가됩니다.

+ +
var x;
+if (x === undefined) {
+   // 이 문이 실행됨
+}
+else {
+   // 이 문이 실행되지 않음
+}
+
+ +
+

참고: 동등 연산자가 아니라 일치 연산자를 사용해야 합니다. 동등 연산자일 때 x == undefinedx가 {{jsxref("null")}}일 때도 참이기 때문입니다. 즉 nullundefined와 동등하지만, 일치하지는 않습니다.

+ +

자세한 내용은 {{jsxref("Operators/Comparison_Operators", "비교 연산자", "", 1)}} 문서를 확인하세요.

+
+ +

typeof 연산자와 undefined

+ +

위의 예제 대신 {{jsxref("Operators/typeof", "typeof")}}를 사용할 수도 있습니다.

+ +
var x;
+if (typeof x === 'undefined') {
+   // 이 문이 실행됨
+}
+
+ +

typeof를 사용하는 이유 중 하나는 선언하지 않은 변수를 사용해도 오류를 던지지 않기 때문입니다.

+ +
// x를 선언한 적 없음
+if (typeof x === 'undefined') { // 오류 없이 true로 평가
+   // 이 문이 실행됨
+}
+
+if(x === undefined) { // ReferenceError
+
+}
+
+ +

그러나 다른 방법도 있습니다. JavaScript는 정적 범위를 가지는 언어이므로, 변수의 선언 여부는 현재 맥락의 코드를 읽어 알 수 있습니다.

+ +

전역 범위는 {{jsxref("globalThis", "전역 객체", "", 1)}}에 묶여 있으므로, 전역 맥락에서 변수의 존재 유무는 {{jsxref("Operators/in", "in")}} 연산자를 전역 객체 대상으로 실행해 알 수 있습니다. 즉,

+ +
if ('x' in window) {
+  //  x가 전역으로 정의된 경우 이 문이 실행됨
+}
+ +

void 연산자와 undefined

+ +

{{jsxref("Operators/void", "void")}} 연산자를 제 3의 대안으로 사용할 수 있습니다.

+ +
var x;
+if (x === void 0) {
+   // 이 문이 실행됨
+}
+
+// y를 선언한 적 없음
+if (y === void 0) {
+   // Uncaught Reference Error: y is not defined
+}
+
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-undefined', 'undefined')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.undefined")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/uneval/index.html b/files/ko/web/javascript/reference/global_objects/uneval/index.html new file mode 100644 index 0000000000..54713864f3 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/uneval/index.html @@ -0,0 +1,67 @@ +--- +title: uneval() +slug: Web/JavaScript/Reference/Global_Objects/uneval +tags: + - Function + - JavaScript + - Non-standard + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/uneval +--- +
{{jsSidebar("Objects")}}{{Non-standard_header}}
+ +

uneval()는 개체의 소스코드에 대한 문자열 표현을 만드는 함수이다.

+ +

구문

+ +
uneval(object)
+ +

매개변수

+ +
+
object
+
JavaScript 표현식 혹은 구문.
+
+ +

반환 값

+ +

주어진 개체의 소스코드에 대한 문자열 표현

+ +
주의: 인자로 넘긴 개체의 유효한 JSON 표현이 아닐 수 있습니다.
+ +

설명

+ +

uneval()은 최상위 수준의 함수이며 어떠한 개체와도 연관 되어있지 않습니다.

+ +

예제

+ +
var a = 1;
+uneval(a); // 1을 포함한 문자열을 반환한다
+
+var b = '1';
+uneval(b); // "1"을 포함한 문자열을 반환한다
+
+uneval(function foo() {}); // "(function foo(){})"를 반환
+
+
+var a = uneval(function foo() { return 'hi'; });
+var foo = eval(a);
+foo(); // "hi"를 반환
+
+ +

명세

+ +

어떤 명세에도 속하지 않습니다.

+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.uneval")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/weakmap/delete/index.html b/files/ko/web/javascript/reference/global_objects/weakmap/delete/index.html new file mode 100644 index 0000000000..0c82351679 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/weakmap/delete/index.html @@ -0,0 +1,80 @@ +--- +title: WeakMap.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/WeakMap/delete +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - WeakMap +translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap/delete +--- +
{{JSRef}}
+ +

delete() 메소드는 WeakMap 객체의 특정 요소를 제거합니다.

+ +
{{EmbedInteractiveExample("pages/js/weakmap-prototype-delete.html")}}
+ + + +

구문

+ +
wm.delete(key);
+ +

매개변수

+ +
+
key
+
WeakMap 객체에서 제거할 요소의 키.
+
+ +

반환 값

+ +

WeakMap 객체의 요소가 성공적으로 제거되면 true, 키를 찾을 수 없거나 키가 객체가 아닌 경우 false.

+ +

예제

+ +

delete 메서드 사용하기

+ +
var wm = new WeakMap();
+wm.set(window, 'foo');
+
+wm.delete(window); // Returns true. Successfully removed.
+
+wm.has(window);    // Returns false. The window object is no longer in the WeakMap.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-weakmap.prototype.delete', 'WeakMap.prototype.delete')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-weakmap.prototype.delete', 'WeakMap.prototype.delete')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.builtins.WeakMap.delete")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/weakmap/index.html b/files/ko/web/javascript/reference/global_objects/weakmap/index.html new file mode 100644 index 0000000000..392759f523 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/weakmap/index.html @@ -0,0 +1,283 @@ +--- +title: WeakMap +slug: Web/JavaScript/Reference/Global_Objects/WeakMap +tags: + - ECMAScript6 + - JavaScript + - WeakMap +translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap +--- +
{{JSRef}}
+ +

WeakMap 객체는 키가 약하게 참조되는 키/값 쌍의 컬렉션입니다. 키는 객체여야만 하나 값은 임의 값이 될 수 있습니다.

+ +

구문

+ +
new WeakMap([iterable])
+
+ +

매개변수

+ +
+
iterable
+
iterable은 배열 또는 요소가 키-값 쌍(2-요소 배열)인 다른 iterable 객체입니다. 각 키-값 쌍은 새로운 WeakMap에 추가됩니다. null은 undefined로 취급됩니다.
+
+ +

설명

+ +

WeakMap의 키는 오직 Object형뿐입니다. 키로 {{Glossary("Primitive", "원시 데이터형")}}은 허용되지 않습니다(가령 {{jsxref("Symbol")}}은 WeakMap 키가 될 수 없습니다).

+ +

WeakMap 내 키는 약하게 유지됩니다. 이게 뜻하는 바는, 다른 강한 키 참조가 없는 경우, 그러면 모든 항목은 가비지 컬렉터에 의해 WeakMap에서 제거됩니다.

+ +

WeakMap인가요?

+ +

숙련된 JavaScript 프로그래머는 이 API는 네 API 메서드에 의해 공유되는 두 배열(키에 하나, 값에 하나)로 JavaScript에서 구현될 수 있음을 알 수 있습니다. 이러한 구현은 주로 두 가지가 불편했을 겁니다. 첫 번째는 O(n) 검색(n은 map 내 키 개수)입니다. 두 번째는 메모리 누수 문제입니다. 수동으로 작성된 map이면, 키 배열은 키 객체 참조를 유지하려고 합니다, 가비지 컬렉트되는 것을 방지하는. 원래 WeakMap에서는, 키 객체 참조는 "약하게" 유지되고, 이는 다른 객체 참조가 없는 경우 가비지 컬렉션을 막지 않음을 뜻합니다.

+ +

약한 참조로 인해, WeakMap 키는 열거불가입니다(즉 키 목록을 제공하는 메서드가 없습니다). 키가 있다면, 그 목록은 가비지 콜렉션 상태에 달려있습니다, 비결정성(non-determinism, 크기를 결정할 수 없는)을 도입하는. 키 목록을 원하는 경우, {{jsxref("Map")}}을 사용해야 합니다.

+ +

속성

+ +
+
WeakMap.length
+
length 속성값은 0.
+
{{jsxref("WeakMap.prototype")}}
+
WeakMap 생성자에 대한 프로토타입을 나타냅니다. 모든 WeakMap 객체에 속성을 추가할 수 있습니다.
+
+ +

WeakMap 인스턴스

+ +

모든 WeakMap 인스턴스는 {{jsxref("WeakMap.prototype")}}에서 상속합니다.

+ +

속성

+ +

{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/prototype','속성')}}

+ +

메서드

+ +

{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/prototype','메서드')}}

+ +

+ +

WeakMap 사용

+ +
var wm1 = new WeakMap(),
+    wm2 = new WeakMap(),
+    wm3 = new WeakMap();
+var o1 = {},
+    o2 = function(){},
+    o3 = window;
+
+wm1.set(o1, 37);
+wm1.set(o2, "azerty");
+wm2.set(o1, o2); // 값은 무엇이든 될 수 있음, 객체 또는 함수 포함
+wm2.set(o3, undefined);
+wm2.set(wm1, wm2); // 키와 값은 어떤 객체든 될 수 있음. 심지어 WeakMap도!
+
+wm1.get(o2); // "azerty"
+wm2.get(o2); // undefined, wm2에 o2에 대한 키가 없기에
+wm2.get(o3); // undefined, 이게 설정값이기에
+
+wm1.has(o2); // true
+wm2.has(o2); // false
+wm2.has(o3); // true (값 자체가 'undefined'이더라도)
+
+wm3.set(o1, 37);
+wm3.get(o1); // 37
+
+wm1.has(o1); // true
+wm1.delete(o1);
+wm1.has(o1); // false
+
+ +

.clear() 메서드로 WeakMap 같은 클래스 구현

+ +

설명을 위해, 다음 예는 새로운 ECMAScript 6 class 구조를 사용합니다, 현재 널리 구현되지 않은.

+ +
class ClearableWeakMap {
+  constructor(init) {
+    this._wm = new WeakMap(init)
+  }
+  clear() {
+    this._wm = new WeakMap()
+  }
+  delete(k) {
+    return this._wm.delete(k)
+  }
+  get(k) {
+    return this._wm.get(k)
+  }
+  has(k) {
+    return this._wm.has(k)
+  }
+  set(k, v) {
+    this._wm.set(k, v)
+    return this
+  }
+}
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-weakmap-objects', 'WeakMap')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-weakmap-objects', 'WeakMap')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support36{{CompatGeckoDesktop("6.0")}}11{{ CompatOpera(23) }}7.1
new WeakMap(iterable)38{{CompatGeckoDesktop("36")}}{{CompatNo}}{{ CompatOpera(25) }}{{CompatNo}}
clear()36{{CompatNo}} [1]11{{ CompatOpera(23) }}7.1
Constructor argument: new WeakMap(null){{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}11{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in constructor{{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WeakMap() without new throws{{CompatVersionUnknown}}{{CompatGeckoDesktop("42")}}11{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support35{{CompatGeckoMobile("6.0")}}{{CompatNo}}{{CompatNo}}8
new WeakMap(iterable)38{{CompatGeckoMobile("36")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
clear()35{{CompatNo}} [1]{{CompatNo}}{{CompatNo}}8
Constructor argument: new WeakMap(null){{CompatUnknown}}{{CompatGeckoMobile("37")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in constructor{{CompatUnknown}}{{CompatGeckoMobile("37")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
WeakMap() without new throws{{CompatUnknown}}{{CompatGeckoMobile("42")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] clear() 메서드는 버전 20부터 45(포함)까지 지원됐습니다.

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html b/files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html new file mode 100644 index 0000000000..48b4586b6e --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/weakmap/prototype/index.html @@ -0,0 +1,142 @@ +--- +title: WeakMap.prototype +slug: Web/JavaScript/Reference/Global_Objects/WeakMap/prototype +tags: + - ECMAScript6 + - JavaScript + - Property + - WeakMap +translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap +--- +
{{JSRef}}
+ +

WeakMap.prototype 속성(property)은 {{jsxref("WeakMap")}} 생성자에 대한 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0,0,0)}}
+ +

설명

+ +

{{jsxref("WeakMap")}} 인스턴스는 {{jsxref("WeakMap.prototype")}}에서 상속합니다. 모든 WeakMap 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.

+ +

WeakMap.prototype은 그 자체로 그냥 평범한 객체입니다:

+ +
Object.prototype.toString.call(WeakMap.prototype); // "[object Object]"
+ +

속성

+ +
+
WeakMap.prototype.constructor
+
인스턴스의 프로토타입을 생성한 함수를 반환합니다. 이는 기본으로 {{jsxref("WeakMap")}} 함수입니다.
+
+ +

메서드

+ +
+
{{jsxref("WeakMap.delete", "WeakMap.prototype.delete(key)")}}
+
key와 관련된 모든 값을 제거합니다. WeakMap.prototype.has(key)는 그 뒤에 false를 반환합니다.
+
{{jsxref("WeakMap.get", "WeakMap.prototype.get(key)")}}
+
key와 관련된 값 또는 관련 값이 없는 경우 undefined를 반환합니다.
+
{{jsxref("WeakMap.has", "WeakMap.prototype.has(key)")}}
+
WeakMap 객체 내 key와 관련된 값이 있는지 여부를 주장하는(asserting, 나타내는) boolean을 반환합니다.
+
{{jsxref("WeakMap.set", "WeakMap.prototype.set(key, value)")}}
+
WeakMap 객체 내 key에 대해 값을 설정합니다. WeakMap 객체를 반환합니다.
+
{{jsxref("WeakMap.prototype.clear()")}} {{obsolete_inline}}
+
WeakMap 객체에서 모든 키/값 쌍을 제거합니다. 메서드가 없는 WeakMap 객체를 캡슐화하여 .clear() 메서드가 있는 WeakMap 같은 객체 구현이 가능함을 주의하세요 ({{jsxref("WeakMap")}} 페이지 예 참조)
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-weakmap.prototype', 'WeakMap.prototype')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-weakmap.prototype', 'WeakMap.prototype')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support36{{CompatGeckoDesktop("6.0")}}11237.1
Ordinary object{{CompatUnknown}}{{CompatGeckoDesktop("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("6.0")}}{{CompatNo}}{{CompatNo}}8
Ordinary object{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/weakset/index.html b/files/ko/web/javascript/reference/global_objects/weakset/index.html new file mode 100644 index 0000000000..17f818659d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/weakset/index.html @@ -0,0 +1,108 @@ +--- +title: WeakSet +slug: Web/JavaScript/Reference/Global_Objects/WeakSet +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - WeakSet +translation_of: Web/JavaScript/Reference/Global_Objects/WeakSet +--- +
{{JSRef}}
+ +

WeakSet 객체는 약하게 유지되는(held, 잡아두는) 객체를 컬렉션에 저장할 수 있습니다.

+ +

구문

+ +
new WeakSet([iterable]);
+ +

매개변수

+ +
+
iterable
+
iterable 객체가 전달된 경우, 모든 객체 요소는 새로운 WeakSet에 추가됩니다. null은 undefined로 취급됩니다.
+
+ +

설명

+ +

WeakSet 객체는 객체 컬렉션입니다. WeakSet 내 객체는 오직 한 번만 발생할 수 있습니다. 즉, WeakSet 컬렉션 내에서 유일합니다.

+ +

{{jsxref("Set")}} 객체와 주된 차이는 다음과 같습니다:

+ + + +

속성

+ +
+
WeakSet.length
+
length 속성값은 0.
+
{{jsxref("WeakSet.prototype")}}
+
Set 생성자에 대한 프로토타입을 나타냅니다. 모든 WeakSet 객체에 속성을 추가할 수 있습니다.
+
+ +

WeakSet 인스턴스

+ +

모든 WeakSet 인스턴스는 {{jsxref("WeakSet.prototype")}}에서 상속합니다.

+ +

속성

+ +

{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/WeakSet/prototype','속성')}}

+ +

메서드

+ +

{{page('ko/docs/Web/JavaScript/Reference/Global_Objects/WeakSet/prototype','메서드')}}

+ +

예제

+ +

WeakSet 객체 사용

+ +
var ws = new WeakSet();
+var obj = {};
+var foo = {};
+
+ws.add(window);
+ws.add(obj);
+
+ws.has(window); // true
+ws.has(foo);    // false, foo가 집합에 추가되지 않았음
+
+ws.delete(window); // 집합에서 window 제거함
+ws.has(window);    // false, window가 제거되었음
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES2015', '#sec-weakset-objects', 'WeakSet')}}{{Spec2('ES2015')}}초기 정의.
{{SpecName('ESDraft', '#sec-weakset-objects', 'WeakSet')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.builtins.WeakSet")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html b/files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html new file mode 100644 index 0000000000..ee3f439ae9 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/weakset/prototype/index.html @@ -0,0 +1,141 @@ +--- +title: WeakSet.prototype +slug: Web/JavaScript/Reference/Global_Objects/WeakSet/prototype +tags: + - ECMAScript6 + - JavaScript + - Property + - WeakSet +translation_of: Web/JavaScript/Reference/Global_Objects/WeakSet +--- +
{{JSRef}}
+ +

WeakSet.prototype 속성(property)은 {{jsxref("WeakSet")}} 생성자에 대한 프로토타입을 나타냅니다.

+ +
{{js_property_attributes(0,0,0)}}
+ +

설명

+ +

{{jsxref("WeakSet")}} 인스턴스는 {{jsxref("WeakSet.prototype")}}에서 상속합니다. 모든 WeakSet 인스턴스에 속성 또는 메서드를 추가하기 위해 생성자의 프로토타입 객체를 사용할 수 있습니다.

+ +

WeakSet.prototype은 그 자체로 그냥 평범한 객체입니다:

+ +
Object.prototype.toString.call(WeakSet.prototype); // "[object Object]"
+ +

속성

+ +
+
WeakSet.prototype.constructor
+
인스턴스의 프로토타입을 생성한 함수를 반환합니다. 이는 기본으로 {{jsxref("WeakSet")}} 함수입니다.
+
+ +

메서드

+ +
+
{{jsxref("WeakSet.add", "WeakSet.prototype.add(value)")}}
+
WeakSet 객체에 주어진 값을 갖는 새로운 객체를 추가합니다.
+
{{jsxref("WeakSet.delete", "WeakSet.prototype.delete(value)")}}
+
value와 관련된 요소를 제거합니다. WeakSet.prototype.has(value)는 그 뒤에 false를 반환합니다.
+
{{jsxref("WeakSet.has", "WeakSet.prototype.has(value)")}}
+
WeakSet 객체 내 주어진 값을 갖는 요소가 존재하는 지 여부를 주장하는(asserting, 나타내는) boolean을 반환합니다.
+
{{jsxref("WeakSet.prototype.clear()")}} {{obsolete_inline}}
+
WeakSet 객체에서 모든 요소를 제거합니다.
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ES6', '#sec-weakset.prototype', 'WeakSet.prototype')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-weakset.prototype', 'WeakSet.prototype')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support36{{ CompatGeckoDesktop(34) }}{{CompatNo}}23{{CompatNo}}
Ordinary object{{CompatUnknown}}{{CompatGeckoDesktop("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChrome for AndroidAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile(34) }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Ordinary object{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/compile/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/compile/index.html new file mode 100644 index 0000000000..eb7dd71f5f --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/compile/index.html @@ -0,0 +1,83 @@ +--- +title: WebAssembly.compile() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/compile +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/compile +--- +
{{JSRef}}
+ +

WebAssembly.compile()함수는 WebAssembly 바이너리 코드에서 {{jsxref ( "WebAssembly.Module")}}을 컴파일합니다. 이 함수는 모듈을 인스턴스화하기 전에 컴파일해야하는 경우에 유용합니다. 그렇지 않으면 {{jsxref ( "WebAssembly.instantiate ()")}} 함수를 사용해야합니다.

+ +

Syntax

+ +
Promise<WebAssembly.Module> WebAssembly.compile(bufferSource);
+ +

Parameters

+ +
+
bufferSource
+
컴파일 할 .wasm 모듈의 이진 코드가 들어있는 typed array 또는 ArrayBuffer입니다.
+
+ +

Return value

+ +

Promise는 컴파일 된 모듈로 표현된 {{jsxref ( "WebAssembly.Module")}} 객체로 반환됩니다.

+ +

Exceptions

+ + + +

Examples

+ +

다음은 compile() 함수를 사용하여 simple.wasm 바이트 코드를 컴파일 하고 postMessage()를 사용하여 worker에 보내는 예제입니다.

+ +
var worker = new Worker("wasm_worker.js");
+
+fetch('simple.wasm').then(response =>
+  response.arrayBuffer()
+).then(bytes =>
+  WebAssembly.compile(bytes)
+).then(mod =>
+  worker.postMessage(mod)
+);
+ +
+

Note: 대부분의 경우에 {{jsxref("WebAssembly.compileStreaming()")}}를 사용하는 것이 좋습니다. 이는 compile()보다 효율적이기 때문입니다.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#webassemblycompile', 'compile()')}}{{Spec2('WebAssembly JS')}}Initial draft definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.compile")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/compileerror/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/compileerror/index.html new file mode 100644 index 0000000000..40ba328985 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/compileerror/index.html @@ -0,0 +1,114 @@ +--- +title: WebAssembly.CompileError() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/CompileError +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/CompileError +--- +
{{JSRef}}
+ +

WebAssembly.CompileError()생성자는 WebAssembly 디코딩 또는 유효성 검사 중에 발생한 오류를 나타내는 WebAssembly CompileError 객체를 새로 만듭니다.

+ +

Syntax

+ +
new WebAssembly.CompileError(message, fileName, lineNumber)
+ +

Parameters

+ +
+
message {{optional_inline}}
+
사람이 읽을수 있는 형태의 에러에 대한 설명.
+
fileName {{optional_inline}}{{non-standard_inline}}
+
예외의 원인이 된 코드가 들어있는 파일의 이름입니다.
+
lineNumber {{optional_inline}}{{non-standard_inline}}
+
예외의 원인이 된 코드의 행 번호입니다.
+
+ +

Properties

+ +

CompileError 생성자에는 고유 한 고유 속성이 없지만 프로토 타입 체인을 통해 일부 속성을 상속합니다.

+ +
+
WebAssembly.CompileError.prototype.constructor
+
인스턴스의 프로토 타입을 작성한 함수를 지정합니다.
+
{{jsxref("Error.prototype.message", "WebAssembly.CompileError.prototype.message")}}
+
에러 메시지. ECMA-262는 {{jsxref ( "URIError")}}가 SpiderMonkey에서 자체 message 속성을 제공하도록 지정했지만 {{jsxref ( "Error.prototype.message")}}를 상속받습니다.
+
{{jsxref("Error.prototype.name", "WebAssembly.CompileError.prototype.name")}}
+
에러 명칭. {{jsxref("Error")}}에서 상속합니다.
+
{{jsxref("Error.prototype.fileName", "WebAssembly.CompileError.prototype.fileName")}}
+
에러가 발생한 파일의 경로. {{jsxref("Error")}}에서 상속합니다.
+
{{jsxref("Error.prototype.lineNumber", "WebAssembly.CompileError.prototype.lineNumber")}}
+
에러가 발생한 파일의 코드 줄번호. {{jsxref("Error")}}에서 상속합니다.
+
{{jsxref("Error.prototype.columnNumber", "WebAssembly.CompileError.prototype.columnNumber")}}
+
에러가 발생한 줄의 열 번호. {{jsxref("Error")}}에서 상속합니다.
+
{{jsxref("Error.prototype.stack", "WebAssembly.CompileError.prototype.stack")}}
+
스텍 추적. {{jsxref("Error")}}에서 상속합니다.
+
+ +

Methods

+ +

CompileError 생성자에는 자체 메서드가 없지만 프로토 타입 체인을 통해 일부 메서드를 상속합니다.

+ +
+
{{jsxref("Error.prototype.toSource", "WebAssembly.CompileError.prototype.toSource()")}}
+
동일한 오류로 판단할 수 있는 코드를 반환합니다. {{jsxref("Error")}}에서 상속합니다.
+
{{jsxref("Error.prototype.toString", "WebAssembly.CompileError.prototype.toString()")}}
+
지정된 Error 객체를 나타내는 문자열을 반환합니다. {{jsxref("Error")}}에서 상속합니다.
+
+ +

Examples

+ +

다음 스 니펫은 새 CompileError 인스턴스를 만들고 콘솔에 세부 정보를 기록합니다.

+ +
try {
+  throw new WebAssembly.CompileError('Hello', 'someFile', 10);
+} catch (e) {
+  console.log(e instanceof CompileError); // true
+  console.log(e.message);                 // "Hello"
+  console.log(e.name);                    // "CompileError"
+  console.log(e.fileName);                // "someFile"
+  console.log(e.lineNumber);              // 10
+  console.log(e.columnNumber);            // 0
+  console.log(e.stack);                   // returns the location where the code was run
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#constructor-properties-of-the-webassembly-object', 'WebAssembly constructors')}}{{Spec2('WebAssembly JS')}}Initial WebAssembly draft definition.
{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard', 'NativeError')}}{{Spec2('ESDraft')}}Definition of standard NativeError types.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.CompileError")}}

+
+ +

See also

+ + + +
+
diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/compilestreaming/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/compilestreaming/index.html new file mode 100644 index 0000000000..a713ca1c0d --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/compilestreaming/index.html @@ -0,0 +1,79 @@ +--- +title: WebAssembly.compileStreaming() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/compileStreaming +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/compileStreaming +--- +
{{JSRef}}
+ +

WebAssembly.compileStreaming()함수는 스트림 된 원본 소스에서 직접 {{jsxref ( "WebAssembly.Module")}}을 컴파일합니다. 이 함수는 모듈을 인스턴스화하기 전에 컴파일해야하는 경우 유용합니다 (그렇지 않으면 {{jsxref ( "WebAssembly.instantiateStreaming ()")}} 함수를 사용해야합니다).

+ +

 

+ +

Syntax

+ +
Promise<WebAssembly.Module> WebAssembly.compileStreaming(source);
+ +

Parameters

+ +
+
source
+
스트리밍 및 컴파일하려는 .wasm 모듈의 기본 소스를 나타내는 {{domxref ( "Response")}} 객체 또는 약속을 수행합니다.
+
+ +

Return value

+ +

Promise는 컴파일 된 모듈로 표현된 WebAssembly.Module 객체로 반환됩니다.

+ +

Exceptions

+ + + +

Examples

+ +

다음 예제 (GitHub의 compile-streaming.html 데모 및 라이브보기)에서 기본 소스의 .wasm 모듈을 직접 스트리밍 한 다음 {{jsxref ( "WebAssembly.Module")}} 객체로 컴파일합니다. compileStreaming() 함수는 {{domxref ( "Response")}} 객체에 대한 promise를 받으므로 직접 {{domxref ( "WindowOrWorkerGlobalScope.fetch ()")}} 호출을 전달할 수 있습니다.

+ +
var importObject = { imports: { imported_func: arg => console.log(arg) } };
+
+WebAssembly.compileStreaming(fetch('simple.wasm'))
+.then(module => WebAssembly.instantiate(module, importObject))
+.then(instance => instance.exports.exported_func());
+ +

결과 모듈 인스턴스는 {{jsxref ( "WebAssembly.instantiate ()")}}를 사용하여 인스턴스화되고 내 보낸 함수가 호출됩니다.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly Embedding', '#webassemblycompilestreaming', 'compileStreaming()')}}{{Spec2('WebAssembly Embedding')}}Initial draft definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.compileStreaming")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/global/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/global/index.html new file mode 100644 index 0000000000..c85d74b53c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/global/index.html @@ -0,0 +1,116 @@ +--- +title: WebAssembly.Global +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global +--- +
{{JSRef}}
+ +
 
+ +
WebAssembly.Global 객체는 전역 변수 인스턴스를 나타내며 JavaScript 및 하나 이상의 {{jsxref("WebAssembly.Module")}} 인스턴스에서 가져 오거나 내보낼 수 있습니다. 이렇게하면 여러 모듈을 동적으로 연결할 수 있습니다.
+ +

Constructor Syntax

+ +
var myGlobal = new WebAssembly.Global(descriptor, value);
+ +

Parameters

+ +
+
descriptor
+
A GlobalDescriptor dictionary object, 두 개의 속성이 포함되어 있습니다. +
    +
  • value: {{domxref("USVString")}}는 전역의 데이터 유형을 나타냅니다. i32, i64, f32 및 f64 중 하나입니다.
  • +
  • mutable: 전역 변수를 변경할 수 있는지 여부를 결정하는 부울 값입니다. 기본적으로 false입니다.
  • +
+
+
value
+
변수에 포함 된 값입니다. 변수의 데이터 타입과 일치하는 한 모든 값을 사용할 수 있습니다.
+ 변수에 포함 된 값입니다. 변수의 데이터 타입과 일치하는 모든 값을 사용할 수 있습니다. 값을 지정하지 않으면 DefaultValue 알고리즘에 지정된대로 입력 된 0 값이 사용됩니다.
+
+ +

Function properties of the Module constructor

+ +

None.

+ +

Global instances

+ +

모든 Global 인스턴스는 Global() 생성자의 prototype object에서 상속받습니다.이 인스턴스는 모든 Global 인스턴스에 영향을 미치도록 수정할 수 있습니다.

+ +

Instance properties

+ +

{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/prototype', 'Properties')}}

+ +

Instance methods

+ +

{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/prototype', 'Methods')}}

+ +

Examples

+ +

다음 예제에서는 WebAssembly.Global() 생성자를 사용하여 만드는 새 전역 인스턴스를 보여줍니다. 값이 0 인 변경 가능한 i32 유형으로 정의됩니다.

+ +

The value of the global is then changed, first to 42 using the Global.value property, and then to 43 using the incGlobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value). 

+ +

그런 다음 global.value 속성을 사용하여 42까지 전역 값을 변경 한 다음 global.wasm 모듈에서 내 보낸 incGlobal() 함수를 사용하여 43으로 변경합니다.(이것은 값이 주어진 값에 1을 더한 다음 새 값을 반환합니다.)

+ +
const output = document.getElementById('output');
+
+function assertEq(msg, got, expected) {
+    output.innerHTML += `Testing ${msg}: `;
+    if (got !== expected)
+        output.innerHTML += `FAIL!<br>Got: ${got}<br>Expected: ${expected}<br>`;
+    else
+        output.innerHTML += `SUCCESS! Got: ${got}<br>`;
+}
+
+assertEq("WebAssembly.Global exists", typeof WebAssembly.Global, "function");
+
+const global = new WebAssembly.Global({value:'i32', mutable:true}, 0);
+
+WebAssembly.instantiateStreaming(fetch('global.wasm'), { js: { global } })
+.then(({instance}) => {
+    assertEq("getting initial value from wasm", instance.exports.getGlobal(), 0);
+    global.value = 42;
+    assertEq("getting JS-updated value from wasm", instance.exports.getGlobal(), 42);
+    instance.exports.incGlobal();
+    assertEq("getting wasm-updated value from JS", global.value, 43);
+});
+ +
+

Note: GitHub에서 실행중인 예제(running live on GitHub)를 볼 수 있습니다. source code도 참조하십시오.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#globals', 'WebAssembly.Global()')}}{{Spec2('WebAssembly JS')}}Initial draft definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.Global")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html new file mode 100644 index 0000000000..3b7e8a9e2b --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/global/prototype/index.html @@ -0,0 +1,69 @@ +--- +title: WebAssembly.Global.prototype +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global +--- +
{{JSRef}}
+ +

WebAssembly.Global.prototype 속성은 {{jsxref("WebAssembly.Global()")}} 생성자의 프로토 타입을 나타냅니다.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Description

+ +

모든 {{jsxref("WebAssembly.Global")}} 인스턴스는 Global.prototype에서 상속받습니다. {{jsxref("WebAssembly.Global()")}} 생성자의 프로토 타입 객체는 모든 {{jsxref( "WebAssembly.Global")}} 인스턴스에 영향을 미치도록 수정할 수 있습니다.

+ +

Properties

+ +
+
Global.prototype.constructor
+
이 객체의 인스턴스를 생성 한 함수를 돌려줍니다. 기본적으로 이것은 {{jsxref("WebAssembly.Global()")}} 생성자입니다.
+
Global.prototype[@@toStringTag]
+
@@toStringTag 속성의 초기 값은 String 값인 "WebAssembly.Global"입니다.
+
Global.prototype.value
+
전역 변수에 포함 된 값 - 전역 값을 직접 설정하고 가져 오는 데 사용할 수 있습니다.
+
+ +

Methods

+ +
+
Global.prototype.valueOf()
+
전역 변수에 포함 된 값을 반환하는 Old-style 메서드입니다.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#globals', 'WebAssembly.Global()')}}{{Spec2('WebAssembly JS')}}Initial draft definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.Global.prototype")}}

+
+ +
+ +
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/index.html new file mode 100644 index 0000000000..8412c9f0e4 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/index.html @@ -0,0 +1,100 @@ +--- +title: WebAssembly +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly +--- +
{{JSRef}}
+ +

WebAssembly 자바스크립트 객체는 모든 WebAssembly에 관계된 기능의 네임스페이스로서 역할합니다.

+ +

대부분의 전역객체와 다르게, WebAssembly는 생성자가 아닙니다 (함수 객체가 아닙니다). 비슷한 예로 수학적인 상수나 함수들을 담고있는 {{jsxref("Math")}} 객체나, 국제화 관련 생성자나 언어에 민감한 다른 함수들을 담고있는 {{jsxref("Intl")}} 등이 있습니다.

+ +

설명

+ +

WebAssembly 객체의 기본적인 사용례는 다음과 같습니다:

+ + + +

메서드

+ +
+
{{jsxref("WebAssembly.instantiate()")}}
+
WebAssembly 코드를 컴파일하고 인스턴스화하여 Module과 첫 번째 Instance를 반환하는 기본 API입니다.
+
{{jsxref("WebAssembly.instantiateStreaming()")}}
+
스트리밍 된 원본 소스에서 직접 WebAssembly 모듈을 컴파일하고 인스턴스화하여 Module과 첫 번째 Instance를 반환합니다.
+
{{jsxref("WebAssembly.compile()")}}
+
WebAssembly 바이너리 코드에서 {{jsxref("WebAssembly.Module")}}을 컴파일하여 인스턴스화를 별도의 단계로 남겨 둡니다.
+
{{jsxref("WebAssembly.compileStreaming()")}}
+
{{jsxref("WebAssembly.Module")}}을 스트림 된 원본 소스에서 직접 컴파일하여 인스턴스화를 별도의 단계로 남겨 둡니다.
+
{{jsxref("WebAssembly.validate()")}}
+
바이트가 유효한 WebAssembly 코드 (true)인지 아닌지 (false)를 반환하여 WebAssembly 바이너리 코드의 지정된 입력 된 배열을 확인합니다.
+
+ +

생성자

+ +
+
{{jsxref("WebAssembly.Global()")}}
+
Creates a new WebAssembly Global object.
+
{{jsxref("WebAssembly.Module()")}}
+
Creates a new WebAssembly Module object.
+
{{jsxref("WebAssembly.Instance()")}}
+
Creates a new WebAssembly Instance object.
+
{{jsxref("WebAssembly.Memory()")}}
+
Creates a new WebAssembly Memory object.
+
{{jsxref("WebAssembly.Table()")}}
+
Creates a new WebAssembly Table object.
+
{{jsxref("WebAssembly.CompileError()")}}
+
Creates a new WebAssembly CompileError object.
+
{{jsxref("WebAssembly.LinkError()")}}
+
Creates a new WebAssembly LinkError object.
+
{{jsxref("WebAssembly.RuntimeError()")}}
+
Creates a new WebAssembly RuntimeError object.
+
+ +

예제

+ +

다음 예제 (GitHub의 instantiate-streaming.html 데모보기 및 라이브보기)에서는 기본 소스에서 .wasm 모듈을 직접 스트리밍 한 다음 컴파일하고 인스턴스화합니다. 프로미스는 ResultObject로 충족됩니다. instantiateStreaming() 함수는 {{domxref ( "Response")}} 객체에 대한 promise를 받아들이므로 직접 {{domxref ( "WindowOrWorkerGlobalScope.fetch()")}} 호출에 전달할 수 있습니다.

+ +
var importObject = { imports: { imported_func: arg => console.log(arg) } };
+
+WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject)
+.then(obj => obj.instance.exports.exported_func());
+ +

그런 다음 ResultObject의 인스턴스 구성에 액세스하고 그 안에 있는 exported_func을 호출합니다.

+ +

스펙

+ + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('WebAssembly JS', '#the-webassembly-object', 'WebAssembly')}}{{Spec2('WebAssembly JS')}}초안 정의
+ +

브라우저 호환성

+ +
{{Compat("javascript.builtins.WebAssembly")}}
+ + + +

바깥 고리

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/instance/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/instance/index.html new file mode 100644 index 0000000000..3141c6809a --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/instance/index.html @@ -0,0 +1,74 @@ +--- +title: WebAssembly.Instance +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance +--- +
{{JSRef}}
+ +

WebAssembly.Instance 개체는 WebAssembly.Module의 상태 저장되고 실행 가능한 인스턴스입니다. Instance 객체에는 JavaScript에서 WebAssembly 코드로 호출 할 수있는 모든 Exported WebAssembly functions가 포함되어 있습니다.

+ +

주어진 {{jsxref ( "WebAssembly.Module")}} 객체를 동기적으로 인스턴스화하기 위해 WebAssembly.Instance() 생성자 함수를 호출 할 수 있습니다. 하지만 Instance를 가져 오는 주요 방법은 비동기 {{jsxref ( "WebAssembly.instantiateStreaming ()")}} 함수를 사용하는 것입니다.

+ +

생성자 구문

+ +
+

중요: 대형 모듈의 인스턴스화는 비용이 많이들 수 있으므로 개발자는 동기 인스턴스 생성이 절대적으로 필요한 경우에만 Instance () 생성자를 사용해야합니다. 비동기 {{jsxref ( "WebAssembly.instantiateStreaming ()")}} 메서드를 사용하세요.

+
+ +
var myInstance = new WebAssembly.Instance(module, importObject);
+ +

매개변수

+ +
+
module
+
인스턴스화 할 WebAssembly.Module 객체입니다.
+
importObject {{optional_inline}}
+
함수 또는 WebAssembly.Memory객체와 같이 새로 생성 된 인스턴스로 가져올 값을 포함하는 객체입니다. 선언 된 각 module 가져오기에 대해 일치하는 속성이 하나 있어야합니다. 그렇지 않으면 WebAssembly.LinkError가 발생합니다.
+
+ +

Instance 인스턴스

+ +

모든 Instance 인스턴스는 Instance() 생성자의 prototype object에서 상속받습니다.이 인스턴스를 수정하면 모든 Instance 인스턴스에 영향을 줍니다.

+ +

인스턴스 속성

+ +

{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/prototype', 'Properties')}}

+ +

인스턴스 메서드

+ +

{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance/prototype', 'Methods')}}

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#webassemblyinstance-objects', 'Instance')}}{{Spec2('WebAssembly JS')}}Initial draft definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.Instance")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/instantiate/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/instantiate/index.html new file mode 100644 index 0000000000..c7b250c090 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/instantiate/index.html @@ -0,0 +1,168 @@ +--- +title: WebAssembly.instantiate() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate +--- +
{{JSRef}}
+ +

WebAssembly.instantiate() 함수를 사용하면 WebAssembly 코드를 컴파일하고 인스턴스화 할 수 있습니다. 이 함수에는 두개의 overloads가 있습니다.

+ + + +
+

중요 : 이 방법은 wasm 모듈을 가져와 인스턴스화하는 가장 효율적인 방법은 아닙니다. 가능하다면 원시 바이트 코드에서 모듈을 모두 한 단계로 가져오고, 컴파일하고 인스턴스화하는 대신 최신 {{jsxref ( "WebAssembly.instantiateStreaming ()")}} 메서드를 사용해야합니다. {{jsxref ( "ArrayBuffer")}} 로의 변환이 필요합니다.

+
+ +

Syntax

+ +

Primary overload — taking wasm binary code

+ +
Promise<ResultObject> WebAssembly.instantiate(bufferSource, importObject);
+
+ +

Parameters

+ +
+
bufferSource
+
컴파일 할 .wasm 모듈의 이진 코드가 들어있는 typed array 또는 {{jsxref("ArrayBuffer")}}입니다.
+
importObject {{optional_inline}}
+
함수 또는 {{jsxref ( "WebAssembly.Memory")}} 객체와 같이 새로 생성 된 인스턴스로 가져올 값을 포함하는 객체입니다. 컴파일 된 모듈의 각 선언 된 가져 오기에 대해 하나의 일치하는 속성이 있어야합니다. 그렇지 않으면 {{jsxref("WebAssembly.LinkError")}}가 발생합니다.
+
+ +

Return value

+ +

두개의 필드를 포함하는 ResultObject를 가진 Promise를 반환:

+ + + +

Exceptions

+ + + +

Secondary overload — taking a module object instance

+ +
Promise<WebAssembly.Instance> WebAssembly.instantiate(module, importObject);
+
+ +

Parameters

+ +
+
module
+
{{jsxref ( "WebAssembly.Module")}} 객체가 인스턴스화됩니다.
+
importObject {{optional_inline}}
+
함수 또는 {{jsxref ( "WebAssembly.Memory")}} 객체와 같이 새로 생성 된 인스턴스로 가져올 값을 포함하는 객체입니다. 선언 된 각 module 가져 오기에 대해 일치하는 속성이 하나 있어야합니다. 그렇지 않으면 {{jsxref("WebAssembly.LinkError")}} 가 발생합니다.
+
+ +

Return value

+ +

A Promise that resolves to an {{jsxref("WebAssembly.Instance")}} object.

+ +

Exceptions

+ + + +

Examples

+ +

Note: 대부분의 경우 instantiate()보다 더 효율적이므로 {{jsxref ( "WebAssembly.instantiateStreaming ()")}}을 사용하는 것이 좋습니다.

+ +

First overload example

+ +

fetch를 사용하여 일부 WebAssembly 바이트 코드를 가져온 후 우리는 {{jsxref ( "WebAssembly.instantiate ()")}} 함수를 사용하여 모듈을 컴파일하고 인스턴스화하여 해당 프로세스에서 JavaScript 함수를 WebAssembly 모듈로 가져옵니다. 그런 다음 Instance에서 Exported WebAssembly function를 호출합니다.

+ +
var importObject = {
+  imports: {
+    imported_func: function(arg) {
+      console.log(arg);
+    }
+  }
+};
+
+fetch('simple.wasm').then(response =>
+  response.arrayBuffer()
+).then(bytes =>
+  WebAssembly.instantiate(bytes, importObject)
+).then(result =>
+  result.instance.exports.exported_func()
+);
+ +
+

Note: 이 예제는 GitHub의 index.html에서도 찾을 수 있습니다 (라이브보기도 있음).

+
+ +

Second overload example

+ +

다음 예제는 (GitHub의 index-compile.html 데모 혹은 라이브로 보기). {{jsxref ( "WebAssembly.compileStreaming ()")}} 메서드를 사용하여 로드된 simple.wasm 바이트 코드를 컴파일 한 다음 {{domxref("Worker.postMessage", "postMessage()")}}를 사용하여 worker에게 전달합니다.

+ +
var worker = new Worker("wasm_worker.js");
+
+WebAssembly.compileStreaming(fetch('simple.wasm'))
+.then(mod =>
+  worker.postMessage(mod)
+);
+ +

작업자 (wasm_worker.js 참조)에서 모듈이 사용할 가져 오기 객체를 정의한 다음 주 스레드에서 모듈을 수신 할 이벤트 핸들러를 설정합니다. 모듈을 받으면 {{jsxref ( "WebAssembly.instantiate ()")}} 메소드를 사용하여 인스턴스를 만들고 내부에서 내 보낸 함수를 호출합니다.

+ +
var importObject = {
+  imports: {
+    imported_func: function(arg) {
+      console.log(arg);
+    }
+  }
+};
+
+onmessage = function(e) {
+  console.log('module received from main thread');
+  var mod = e.data;
+
+  WebAssembly.instantiate(mod, importObject).then(function(instance) {
+    instance.exports.exported_func();
+  });
+};
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#webassemblyinstantiate', 'instantiate()')}}{{Spec2('WebAssembly JS')}}Initial draft definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.instantiate")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/instantiatestreaming/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/instantiatestreaming/index.html new file mode 100644 index 0000000000..e1b2fde3b7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/instantiatestreaming/index.html @@ -0,0 +1,83 @@ +--- +title: WebAssembly.instantiateStreaming() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiateStreaming +--- +
{{JSRef}}
+ +

WebAssembly.instantiateStreaming() 함수는 스트림 된 원본 소스에서 직접 WebAssembly 모듈을 컴파일하고 인스턴스화합니다. Wasm 코드를로드하는 가장 효율적이고 최적화 된 방법입니다.

+ +

Syntax

+ +
Promise<ResultObject> WebAssembly.instantiateStreaming(source, importObject);
+ +

Parameters

+ +
+
source
+
스트리밍, 컴파일 및 인스턴스화하려는 .wasm 모듈의 기본 소스를 나타내는 {{domxref ( "Response")}} 객체 또는 promise.
+
importObject {{optional_inline}}
+
함수 또는 {{jsxref("WebAssembly.Memory")}} 객체와 같이 새로 생성 된 Instance로 가져올 값을 포함하는 객체입니다. 컴파일 된 모듈의 각 선언 된 가져 오기에 대해 하나의 일치하는 속성이 있어야합니다. 그렇지 않으면 WebAssembly.LinkError가 발생합니다.
+
+ +

Return value

+ +

두 개의 필드를 포함하는 ResultObject로 해석되는 Promise :

+ + + +

Exceptions

+ + + +

Examples

+ +

다음 예제 (GitHub의 instantiate-streaming.html 데모보기 및 view it live)에서는 원본 소스에서 .wasm 모듈을 직접 스트리밍 한 다음 컴파일하고 인스턴스화합니다. 약속은 ResultObject로 충족됩니다.instantiateStreaming() 함수는 {{domxref("Response")}} 객체에 대한 promise를 받아들이므로 직접 {{domxref("WindowOrWorkerGlobalScope.fetch()")}} 호출을 전달할 수 있으며 응답을 수행하면 함수에 응답을 전달합니다.

+ +
var importObject = { imports: { imported_func: arg => console.log(arg) } };
+
+WebAssembly.instantiateStreaming(fetch('simple.wasm'), importObject)
+.then(obj => obj.instance.exports.exported_func());
+ +

그런 다음 ResultObject의 인스턴스 구성원에 액세스하고 포함 된 내 보낸 함수를 호출합니다.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly Embedding', '#webassemblyinstantiatestreaming', 'instantiateStreaming()')}}{{Spec2('WebAssembly Embedding')}}Initial draft definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.instantiateStreaming")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/linkerror/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/linkerror/index.html new file mode 100644 index 0000000000..b9b5c3264c --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/linkerror/index.html @@ -0,0 +1,113 @@ +--- +title: WebAssembly.LinkError() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/LinkError +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/LinkError +--- +
{{JSRef}}
+ +

The WebAssembly.LinkError() constructor creates a new WebAssembly LinkError object, which indicates an error during module instantiation (besides traps from the start function). 

+ +

WebAssembly.LinkError() 생성자는 새 WebAssembly LinkError 객체를 만듭니다. 이 객체는 모듈 인스턴스화 중의 오류를 나타냅니다 (시작 함수의 traps와 함께).

+ +

Syntax

+ +
new WebAssembly.LinkError(message, fileName, lineNumber)
+ +

Parameters

+ +
+
message {{optional_inline}}
+
사람이 읽을 수 있는 오류 설명.
+
fileName {{optional_inline}}{{non-standard_inline}}
+
예외의 원인이 된 코드가 들어있는 파일의 이름입니다.
+
lineNumber {{optional_inline}}{{non-standard_inline}}
+
예외의 원인이 된 코드의 행 번호입니다.
+
+ +

Properties

+ +

LinkError 생성자에는 고유 한 고유 속성이 없지만 프로토 타입 체인을 통해 일부 속성을 상속합니다.

+ +
+
WebAssembly.LinkError.prototype.constructor
+
인스턴스의 프로토 타입을 작성한 함수를 지정합니다.
+
{{jsxref("Error.prototype.message", "WebAssembly.LinkError.prototype.message")}}
+
에러 메시지. ECMA-262는 {{jsxref ( "URIError")}}가 SpiderMonkey에서 자체 message 속성을 제공하도록 지정했지만 {{jsxref ( "Error.prototype.message")}}를 상속받습니다.
+
{{jsxref("Error.prototype.name", "WebAssembly.LinkError.prototype.name")}}
+
에러 이름. {{jsxref("Error")}}를 상속받습니다.
+
{{jsxref("Error.prototype.fileName", "WebAssembly.LinkError.prototype.fileName")}}
+
해당 에러가 발생한 파일의 경로. {{jsxref("Error")}}를 상속받습니다.
+
{{jsxref("Error.prototype.lineNumber", "WebAssembly.LinkError.prototype.lineNumber")}}
+
에러가 발생한 파일의 행 번호. {{jsxref("Error")}}를 상속받습니다.
+
{{jsxref("Error.prototype.columnNumber", "WebAssembly.LinkError.prototype.columnNumber")}}
+
이 오류가 발생한 행의 열 번호입니다.. {{jsxref("Error")}}를 상속받습니다.
+
{{jsxref("Error.prototype.stack", "WebAssembly.LinkError.prototype.stack")}}
+
스텍 추적. {{jsxref("Error")}}를 상속받습니다.
+
+ +

Methods

+ +

LinkError 생성자에는 자체 메서드가 없지만 프로토 타입 체인을 통해 일부 메서드를 상속합니다.

+ +
+
{{jsxref("Error.prototype.toSource", "WebAssembly.LinkError.prototype.toSource()")}}
+
동일한 오류로 평가 될 수있는 코드를 반환합니다. {{jsxref("Error")}}를 상속받습니다.
+
{{jsxref("Error.prototype.toString", "WebAssembly.LinkError.prototype.toString()")}}
+
지정된 Error 객체를 나타내는 문자열을 반환합니다. {{jsxref("Error")}}를 상속받습니다.
+
+ +

Examples

+ +

다음 snippet은 새 LinkError 인스턴스를 만들고 콘솔에 세부 정보를 기록합니다.

+ +
try {
+  throw new WebAssembly.LinkError('Hello', 'someFile', 10);
+} catch (e) {
+  console.log(e instanceof LinkError); // true
+  console.log(e.message);                 // "Hello"
+  console.log(e.name);                    // "LinkError"
+  console.log(e.fileName);                // "someFile"
+  console.log(e.lineNumber);              // 10
+  console.log(e.columnNumber);            // 0
+  console.log(e.stack);                   // returns the location where the code was run
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#constructor-properties-of-the-webassembly-object', 'WebAssembly constructors')}}{{Spec2('WebAssembly JS')}}Initial WebAssembly draft definition.
{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard', 'NativeError')}}{{Spec2('ESDraft')}}Definition of standard NativeError types.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.LinkError")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/memory/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/memory/index.html new file mode 100644 index 0000000000..96b1614fff --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/memory/index.html @@ -0,0 +1,112 @@ +--- +title: WebAssembly.Memory() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory +--- +
{{JSRef}}
+ +

WebAssembly.Memory() 생성자는 WebAssembly Instance가 액세스하는 메모리의 원시 바이트를 가진 ArrayBuffer(크기조정이 가능)인 새 Memory 객체를 만듭니다.

+ +

메모리는 자바스크립트 혹은 WebAssembly 코드 안에서 만들어지며 자바스크립트 그리고 WebAssembly에서 접근하거나 변경이 가능합니다.

+ +

Syntax

+ +
var myMemory = new WebAssembly.Memory(memoryDescriptor);
+ +

Parameters

+ +
+
memoryDescriptor
+
다음의 멤버를 가질수 있는 객체입니다. +
+
initial
+
WebAssembly Page의 단위별 WebAssembly 메모리의 초기 크기입니다.
+
maximum {{optional_inline}}
+
WebAssembly 메모리의 최대 크기는 WebAssembly 페이지 단위로 증가 할 수 있습니다. 이 매개 변수가 있으면 maximum 매개 변수는 엔진에 대해 메모리를 전면에 예약하도록 합니다. 그러나 엔진은 이 예약 요청을 무시하거나 클램핑 할 수 있습니다. 일반적으로 대부분의 WebAssembly 모듈은 maximum 값을 설정할 필요가 없습니다.
+
+
+
+ +
+

Note: WebAssembly 페이지의 크기는 65,536 바이트로 64KiB로 고정되어 있습니다.

+
+ +

Exceptions

+ + + +

Memory instances

+ +

모든 Memory 인스턴스는 Memory()생성자의 prototype object를 상속합니다.이 인스턴스는 모든 Memory 인스턴스에 적용되도록 수정할 수 있습니다.

+ +

Instance properties

+ +
+
Memory.prototype.constructor
+
이 객체의 인스턴스를 생성 한 함수를 돌려줍니다. 기본적으로 이것은 {{jsxref("WebAssembly.Memory()")}} 생성자입니다.
+
{{jsxref("WebAssembly/Memory/buffer","Memory.prototype.buffer")}}
+
메모리에 포함 된 버퍼를 반환하는 접근 자 속성입니다.
+
+ +

Instance methods

+ +
+
{{jsxref("WebAssembly/Memory/grow","Memory.prototype.grow()")}}
+
지정된 수의 WebAssembly 페이지 (각각 64KB 크기)만큼 메모리 인스턴스의 크기를 늘립니다.
+
+ +

Examples

+ +

WebAssembly.Memory 객체를 가져 오는 두 가지 방법이 있습니다. 첫 번째 방법은 JavaScript에서 생성하는 것입니다. 다음 예제에서는 초기 크기가 10 페이지 (640KiB)이고 최대 크기가 100 페이지 (6.4MiB) 인 새 WebAssembly 메모리 인스턴스를 만듭니다.

+ +
var memory = new WebAssembly.Memory({initial:10, maximum:100});
+ +

WebAssembly.Memory 객체를 가져 오는 두 번째 방법은 WebAssembly 모듈에서 내보냅니다. 다음 예제는 (GitHub의 memory.html을 보세요. 라이브로 보기) 생성된 메모리를 가져 오는 동안 {{jsxref("WebAssembly.instantiateStreaming()")}} 메소드를 사용하여로드 된 memory.wasm 바이트 코드를 가져 와서 인스턴스화합니다. 위의 줄에. 그런 다음 메모리에 일부 값을 저장 한 다음 함수를 내 보낸 다음 일부 값의 합계에 사용합니다.

+ +
WebAssembly.instantiateStreaming(fetch('memory.wasm'), { js: { mem: memory } })
+.then(obj => {
+  var i32 = new Uint32Array(memory.buffer);
+  for (var i = 0; i < 10; i++) {
+    i32[i] = i;
+  }
+  var sum = obj.instance.exports.accumulate(0, 10);
+  console.log(sum);
+});
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#webassemblymemory-objects', 'Memory')}}{{Spec2('WebAssembly JS')}}Initial draft definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.Memory")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/module/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/module/index.html new file mode 100644 index 0000000000..814835fd00 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/module/index.html @@ -0,0 +1,83 @@ +--- +title: WebAssembly.Module +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Module +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Module +--- +
{{JSRef}}
+ +

WebAssembly.Module 객체는 브라우저에서 이미 컴파일 된 stateless WebAssembly 코드를 포함하며 효율적으로 Workers와 공유하고 여러 번 인스턴스화 할 수 있습니다. 모듈을 인스턴스화하려면 WebAssembly.instantiate() 2차 오버로드를 호출하세요.

+ +

WebAssembly.Module() 생성자 함수를 호출하여 지정된 WebAssembly 바이너리 코드를 동기식으로 컴파일 할 수 있습니다. 그러나 Module을 쓰는 주된 방법은 {{jsxref ( "WebAssembly.compile ()")}}과 같은 비동기 컴파일 함수를 사용하는 것입니다.

+ +

생성자 구문

+ +
+

Important: 대형 모듈의 컴파일은 비용이 많이들 수 있으므로 개발자는 동기 컴파일이 절대적으로 필요한 경우에만 Module () 생성자를 사용해야합니다. 비동기 {{jsxref ( "WebAssembly.compileStreaming ()")}} 메서드를 사용하세요.

+
+ +
var myModule = new WebAssembly.Module(bufferSource);
+ +

매개변수

+ +
+
bufferSource
+
컴파일 할 .wasm 모듈의 이진 코드가 들어있는 typed array또는 ArrayBuffer입니다.
+
+ +

Function Properties of the Module Constructor

+ +
+
{{jsxref("Global_Objects/WebAssembly/Module/customSections", "WebAssembly.Module.customSections()")}}
+
모듈(Module)과 문자열이 주어지면 모듈의 모든 사용자 정의 섹션 내용의 사본을 주어진 문자열 이름으로 반환합니다.
+
{{jsxref("Global_Objects/WebAssembly/Module/exports", "WebAssembly.Module.exports()")}}
+
모듈(Module)이 주어지면 선언 된 모든 내보내기에 대한 설명이 들어있는 배열을 반환합니다.
+
{{jsxref("Global_Objects/WebAssembly/Module/imports", "WebAssembly.Module.imports()")}}
+
모듈(Module)이 주어지면 선언 된 모든 가져오기에 대한 설명이 들어있는 배열을 반환합니다.
+
+ +

Module instances

+ +

모든 Module 인스턴스는 Module() 생성자의 prototype object에서 상속받습니다.이 인스턴스는 모든 Module 인스턴스에 적용되도록 수정할 수 있습니다.

+ +

Instance properties

+ +

{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module/prototype', 'Properties')}}

+ +

Instance methods

+ +

모듈 인스턴스에는 기본 메서드가 없습니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#webassemblymodule-objects', 'WebAssembly.Module()')}}{{Spec2('WebAssembly JS')}}Initial draft definition.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.Module")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/runtimeerror/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/runtimeerror/index.html new file mode 100644 index 0000000000..ebd8da6f46 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/runtimeerror/index.html @@ -0,0 +1,111 @@ +--- +title: WebAssembly.RuntimeError() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/RuntimeError +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/RuntimeError +--- +
{{JSRef}}
+ +

WebAssembly.RuntimeError() 생성자는 WebAssembly에서 trap을 지정할 때마다 throw되는 새 WebAssembly RuntimeError 객체를 만듭니다.

+ +

Syntax

+ +
new WebAssembly.RuntimeError(message, fileName, lineNumber)
+ +

Parameters

+ +
+
message {{optional_inline}}
+
인간이 읽을 수있는 오류 설명.
+
fileName {{optional_inline}}{{non-standard_inline}}
+
예외의 원인이 된 코드가 들어있는 파일의 이름입니다.
+
lineNumber {{optional_inline}}{{non-standard_inline}}
+
예외의 원인이 된 코드의 행 번호입니다.
+
+ +

Properties

+ +

RuntimeError 생성자에는 고유 한 고유 속성이 없지만 프로토 타입 체인을 통해 일부 속성을 상속합니다.

+ +
+
WebAssembly.RuntimeError.prototype.constructor
+
인스턴스의 프로토 타입을 작성한 함수를 지정합니다.
+
{{jsxref("Error.prototype.message", "WebAssembly.RuntimeError.prototype.message")}}
+
에러 메시지. ECMA-262는 {{jsxref ( "URIError")}}가 SpiderMonkey에서 자체 message 속성을 제공하도록 지정했지만 {{jsxref ( "Error.prototype.message")}}를 상속받습니다.
+
{{jsxref("Error.prototype.name", "WebAssembly.RuntimeError.prototype.name")}}
+
오류 이름. {{jsxref ( "Error")}}에서 상속됩니다.
+
{{jsxref("Error.prototype.fileName", "WebAssembly.RuntimeError.prototype.fileName")}}
+
이 오류를 발생시킨 파일의 경로입니다. {{jsxref ( "Error")}}에서 상속됩니다.
+
{{jsxref("Error.prototype.lineNumber", "WebAssembly.RuntimeError.prototype.lineNumber")}}
+
이 오류가 발생한 파일의 행 번호입니다. {{jsxref ( "Error")}}에서 상속됩니다.
+
{{jsxref("Error.prototype.columnNumber", "WebAssembly.RuntimeError.prototype.columnNumber")}}
+
이 오류가 발생한 행의 열 번호입니다. {{jsxref ( "Error")}}에서 상속됩니다.
+
{{jsxref("Error.prototype.stack", "WebAssembly.RuntimeError.prototype.stack")}}
+
스택 추적. {{jsxref ( "Error")}}에서 상속됩니다.
+
+ +

Methods

+ +

RuntimeError 생성자에는 자체 메서드가 없지만 프로토 타입 체인을 통해 일부 메서드를 상속합니다.

+ +
+
{{jsxref("Error.prototype.toSource", "WebAssembly.RuntimeError.prototype.toSource()")}}
+
동일한 오류로 평가 될 수있는 코드를 반환합니다. {{jsxref ( "Error")}}에서 상속됩니다.
+
{{jsxref("Error.prototype.toString", "WebAssembly.RuntimeError.prototype.toString()")}}
+
지정된 Error 객체를 나타내는 문자열을 반환합니다. {{jsxref ( "Error")}}에서 상속됩니다.
+
+ +

Examples

+ +

다음의 스니펫은, 새로운 RuntimeError 인스턴스를 작성해, 그 상세를 콘솔에 기록합니다.

+ +
try {
+  throw new WebAssembly.RuntimeError('Hello', 'someFile', 10);
+} catch (e) {
+  console.log(e instanceof RuntimeError); // true
+  console.log(e.message);                 // "Hello"
+  console.log(e.name);                    // "RuntimeError"
+  console.log(e.fileName);                // "someFile"
+  console.log(e.lineNumber);              // 10
+  console.log(e.columnNumber);            // 0
+  console.log(e.stack);                   // returns the location where the code was run
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#constructor-properties-of-the-webassembly-object', 'WebAssembly constructors')}}{{Spec2('WebAssembly JS')}}Initial WebAssembly draft definition.
{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard', 'NativeError')}}{{Spec2('ESDraft')}}Definition of standard NativeError types.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.RuntimeError")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/table/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/table/index.html new file mode 100644 index 0000000000..9d86fe40c7 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/table/index.html @@ -0,0 +1,130 @@ +--- +title: WebAssembly.Table() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/Table +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Table +--- +
{{JSRef}}
+ +

WebAssembly.Table() 생성자는 지정된 크기 및 요소 유형의 새 Table 객체를 만듭니다.

+ +

이것은 자바 스크립트 래퍼 객체로, 함수 참조를 저장하는 WebAssembly 테이블을 나타내는 배열과 같은 구조입니다. JavaScript 또는 WebAssembly 코드로 작성된 테이블은 JavaScript 및 WebAssembly에서 액세스 및 변경할 수 있습니다.

+ +
+

Note: 테이블은 현재 function references만 저장할 수 있지만 나중에 확장 될 수 있습니다.

+
+ +

Syntax

+ +
var myTable = new WebAssembly.Table(tableDescriptor);
+ +

Parameters

+ +
+
tableDescriptor
+
다음 멤버를 포함 할 수있는 객체입니다: +
+
element
+
테이블에 저장 될 값 유형을 나타내는 문자열. 현재로서는 "anyfunc"(함수) 값만있을 수 있습니다.
+
initial
+
WebAssembly 테이블의 초기 요소 수입니다.
+
maximum {{optional_inline}}
+
WebAssembly 테이블의 최대 증가 요소 수입니다.
+
+
+
+ +

Exceptions

+ + + +

Table instances

+ +

모든 Table 인스턴스는 Table()생성자의 prototype object에서 상속받습니다.이 인스턴스는 모든 Table 인스턴스에 적용되도록 수정할 수 있습니다.

+ +

Instance properties

+ +
+
Table.prototype.constructor
+
이 객체의 인스턴스를 생성 한 함수를 돌려줍니다. 기본적으로 이것은 {{jsxref("WebAssembly.Table()")}} 생성자입니다.
+
{{jsxref("WebAssembly/Table/length","Table.prototype.length")}}
+
테이블의 길이, 즉 요소의 수를 돌려줍니다.
+
+ +

Instance methods

+ +
+
{{jsxref("WebAssembly/Table/get","Table.prototype.get()")}}
+
접근 자 함수 - 주어진 색인에 저장된 요소를 가져옵니다.
+
{{jsxref("WebAssembly/Table/grow","Table.prototype.grow()")}}
+
지정된 요소 수만큼 Table 인스턴스의 크기를 늘립니다.
+
{{jsxref("WebAssembly/Table/set","Table.prototype.set()")}}
+
지정된 인덱스에 격납되어있는 요소를, 지정된 값으로 설정합니다.
+
+ +

Examples

+ +

다음 예제 (table2.html source codelive version 참조)는 초기 크기가 2인 새 WebAssembly Table 인스턴스를 만듭니다. 그런 다음 두 개의 인덱스 (표 {{jsxref ( "WebAssembly / Table / get", "Table.prototype.get ()")}}를 통해 검색하여 테이블의 길이와 내용을 인쇄합니다. 길이가 2이고 {{jsxref ( "null")}}이 두개라고 출력됩니다.

+ +
var tbl = new WebAssembly.Table({initial:2, element:"anyfunc"});
+console.log(tbl.length);  // "2"
+console.log(tbl.get(0));  // "null"
+console.log(tbl.get(1));  // "null"
+ +

그런 다음 테이블을 포함한 importObj를 만듭니다.

+ +
var importObj = {
+  js: {
+    tbl:tbl
+  }
+};
+ +

마지막으로 {{jsxref ( "WebAssembly.instantiateStreaming ()")}} 메소드를 사용하여 wasm 모듈 (table2.wasm)을 로드하고 인스턴스화합니다. table2.wasm 모듈에는 두 개의 함수 (하나는 42를 반환하고 다른 하나는 83을 반환하는 함수)가 들어 있고 가져온 테이블의 요소 0과 1에 둘 다 저장합니다 (text representation 참조). 인스턴스화 후에도 테이블의 길이는 여전히 2이지만 JS에 호출 할 수있는 호출 가능한 Exported WebAssembly Functions가 요소에 포함됩니다.

+ +
WebAssembly.instantiateStreaming(fetch('table2.wasm'), importObject)
+.then(function(obj) {
+  console.log(tbl.length);
+  console.log(tbl.get(0)());
+  console.log(tbl.get(1)());
+});
+ +

액세서의 끝 부분에 두 번째 함수 호출 연산자를 포함시켜 실제로 참조 된 함수를 호출하고 그 안에 저장된 값을 기록해야합니다 (예 : get(0) 대신 get(0)()).

+ +

이 예제는 자바 스크립트에서 테이블을 만들고 액세스하고 있지만 wasm 인스턴스 내부에서도 같은 테이블을 볼 수 있고 호출 할 수 있음을 보여줍니다.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#webassemblytable-objects', 'Table')}}{{Spec2('WebAssembly JS')}}Initial draft definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.Table")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/global_objects/webassembly/validate/index.html b/files/ko/web/javascript/reference/global_objects/webassembly/validate/index.html new file mode 100644 index 0000000000..a5ea4850e5 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/webassembly/validate/index.html @@ -0,0 +1,75 @@ +--- +title: WebAssembly.validate() +slug: Web/JavaScript/Reference/Global_Objects/WebAssembly/validate +translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/validate +--- +
{{JSRef}}
+ +

WebAssembly.validate() 함수는 바이트가 유효한 wasm 모듈을 형성하는지 (true) 또는 생성하지 않는지 (false)를 반환하여 WebAssembly 바이너리 코드의 지정된 typed array의 유효성을 검사합니다.

+ +

Syntax

+ +
WebAssembly.validate(bufferSource);
+ +

Parameters

+ +
+
bufferSource
+
유효성을 검사 할 WebAssembly 바이너리 코드가 들어있는 typed array 또는 ArrayBuffer입니다.
+
+ +

Return value

+ +

bufferSource가 유효한 wasm 코드 (true)인지 아닌지 (false)를 지정하는 부울입니다.

+ +

Exceptions

+ +

bufferSourcetyped array이나 ArrayBuffer가 아닌 경우 {{jsxref ( "TypeError")}}가 발생합니다.

+ +

Examples

+ +

다음 예제 (validate.html source code 참조 및 see it live)는 .wasm 모듈을 가져 와서 형식화 된 배열로 변환합니다. 그런 다음 validate() 메서드를 사용하여 모듈이 유효한지 확인합니다.

+ +
fetch('simple.wasm').then(response =>
+  response.arrayBuffer()
+).then(function(bytes) {
+  var valid = WebAssembly.validate(bytes);
+  console.log("The given bytes are "
+    + (valid ? "" : "not ") + "a valid wasm module");
+});
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebAssembly JS', '#webassemblyvalidate', 'validate()')}}{{Spec2('WebAssembly JS')}}Initial draft definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.WebAssembly.validate")}}

+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/index.html b/files/ko/web/javascript/reference/index.html new file mode 100644 index 0000000000..c7d883f2b1 --- /dev/null +++ b/files/ko/web/javascript/reference/index.html @@ -0,0 +1,48 @@ +--- +title: JavaScript 참고자료 +slug: Web/JavaScript/Reference +tags: + - JavaScript +translation_of: Web/JavaScript/Reference +--- +
{{JsSidebar}}
+ +

MDN 내 JavaScript 절의 이 부분은 JavaScript 언어에 관한 정보 저장소(facts repository)로 쓸 수 있습니다. 이 참고서에 관하여를 더 읽어보세요.

+ +

전역 객체들

+ +

이 장은 모든 JavaScript 표준 내장 객체를, 메서드 및 속성(property)을 위주로 문서화합니다.

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Global_Objects', '항목별_표준_객체')}}
+ +

+ +

이 장은 모든 JavaScript 문 및 선언을 문서화합니다.

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Statements', '항목별_문_및_선언')}}
+ +

표현식 및 연산자

+ +

이 장은 모든 JavaScript 표현식 및 연산자를 문서화합니다.

+ +
{{page('/ko/docs/Web/JavaScript/Reference/Operators', '항목별_식_및_연산자')}}
+ +

함수

+ +

이 장은 응용 프로그램을 개발하기 위해 JavaScript 함수로 작업하는 법을 문서화합니다.

+ + + +

추가 참고 페이지

+ + diff --git a/files/ko/web/javascript/reference/iteration_protocols/index.html b/files/ko/web/javascript/reference/iteration_protocols/index.html new file mode 100644 index 0000000000..bddc56a50f --- /dev/null +++ b/files/ko/web/javascript/reference/iteration_protocols/index.html @@ -0,0 +1,394 @@ +--- +title: Iteration protocols +slug: Web/JavaScript/Reference/Iteration_protocols +translation_of: Web/JavaScript/Reference/Iteration_protocols +--- +
{{jsSidebar("More")}}
+ +

ECMAScript 2015 (ES6)에는 새로운 문법이나 built-in 뿐만이 아니라, protocols(표현법들)도 추가되었습니다. 이 protocol 은 일정 규칙만 충족한다면 어떠한 객체에 의해서도 구현될 수 있습니다.

+ +

2개의 protocol이 있습니다 : iterable protocol 과 iterator protocol.

+ +

The iterable protocol

+ +

iterable protocol 은 JavaScript 객체들이, 예를 들어 {{jsxref("Statements/for...of", "for..of")}} 구조에서 어떠한 value 들이 loop 되는 것과 같은 iteration 동작을 정의하거나 사용자 정의하는 것을 허용합니다. 다른 type 들({{jsxref("Object")}} 와 같은)이 그렇지 않은 반면에, 어떤 built-in type 들은 {{jsxref("Array")}} 또는 {{jsxref("Map")}} 과 같은 default iteration 동작으로 built-in iterables 입니다.

+ +

iterable 하기 위해서 object는 @@iterator 메소드를 구현해야 합니다. 이것은 object (또는 prototype chain 의 오브젝트 중 하나) 가 {{jsxref("Symbol.iterator")}} key 의 속성을 가져야 한다는 것을 의미합니다 :

+ + + + + + + + + + + + + + +
PropertyValue
[Symbol.iterator]object를 반환하는, arguments 없는 function. iterator protocol 을 따른다.
+ +

어떠한 객체가 반복(Iterate)되어야 한다면 이 객체의 @@iterator 메소드가 인수없이 호출되고, 반환된 iterator는 반복을 통해서 획득할 값들을 얻을 때 사용됩니다.

+ +

The iterator protocol

+ +

iterator protocol 은 value( finite 또는 infinite) 들의 sequence 를 만드는 표준 방법을 정의합니다. 

+ +

객체가 next() 메소드를 가지고 있고, 아래의 규칙에 따라 구현되었다면 그 객체는 iterator이다:

+ + + + + + + + + + + + +
PropertyValue
next +

아래 2개의 속성들을 가진 object 를 반환하는 arguments 없는 함수 :

+ +
    +
  • done (boolean) + +
      +
    • Iterator(반복자)가 마지막 반복 작업을 마쳤을 경우 true. 만약 iterator(반복자)에 return 값이 있다면 value의 값으로 지정된다. 반환 값에 대한 설명은 여기.
    • +
    • Iterator(반복자)의 작업이 남아있을 경우 false. Iterator(반복자)에 done 프로퍼티 자체를 특정짓지 않은 것과 동일하다.
    • +
    +
  • +
  • value - Iterator(반복자)으로부터 반환되는 모든 자바스크립트 값이며 done이 true일 경우 생략될 수 있다.
  • +
+
+ +

몇몇 iterator들은 iterable(반복 가능)이다:

+ +
var someArray = [1, 5, 7];
+var someArrayEntries = someArray.entries();
+
+someArrayEntries.toString();           // "[object Array Iterator]"
+someArrayEntries === someArrayEntries[Symbol.iterator]();    // true
+
+ +

 Iteration protocols 사용 예시

+ +

{{jsxref("String")}} 은 built-in iterable 객체의 한 예시입니다.

+ +
var someString = "hi";
+typeof someString[Symbol.iterator];          // "function"
+
+ +

String 의 기본 iterator 는 string 의 문자를 하나씩 반환합니다.

+ +
var iterator = someString[Symbol.iterator]();
+iterator + "";                               // "[object String Iterator]"
+
+iterator.next();                             // { value: "h", done: false }
+iterator.next();                             // { value: "i", done: false }
+iterator.next();                             // { value: undefined, done: true }
+ +

spread operator와 같은 특정 내장 구조(built-in constructs)들은 실제로는 동일한 iteration protocol을 사용한다:

+ +
[...someString]                              // ["h", "i"]
+ +

사용자만의 @@iterator를 특정함으로써 원하는 반복 행위(iteration behavior)를 설정할 수 있다:

+ +
var someString = new String("hi");          // need to construct a String object explicitly to avoid auto-boxing
+
+someString[Symbol.iterator] = function() {
+  return { // this is the iterator object, returning a single element, the string "bye"
+    next: function() {
+      if (this._first) {
+        this._first = false;
+        return { value: "bye", done: false };
+      } else {
+        return { done: true };
+      }
+    },
+    _first: true
+  };
+};
+
+ +

재설정된 @@iterator가 어떻게 내장 구조(built-in constructs)의 반복 행위에 영향을 주는지 참고:

+ +
[...someString];                              // ["bye"]
+someString + "";                              // "hi"
+
+ +

Iterable 예시

+ +

내장 iterables

+ +

{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}} and {{jsxref("Set")}} 는 모두 내장 iterable이다. 이 객체들의 프로토타입 객체들은 모두 @@iterator 메소드를 가지고 있기 때문이다.

+ +

사용자 정의된 iterables

+ +

이렇게 고유한 iterables 를 만들 수 있다.

+ +
var myIterable = {};
+myIterable[Symbol.iterator] = function* () {
+    yield 1;
+    yield 2;
+    yield 3;
+};
+[...myIterable]; // [1, 2, 3]
+
+ +

Iterable을 허용하는 내장 API들

+ +

Iterable을 허용하는 많은 내장 API들이 있다. 예를 들어: {{jsxref("Map", "Map([iterable])")}}, {{jsxref("WeakMap", "WeakMap([iterable])")}}, {{jsxref("Set", "Set([iterable])")}} and {{jsxref("WeakSet", "WeakSet([iterable])")}}이 그것이다:

+ +
var myObj = {};
+new Map([[1,"a"],[2,"b"],[3,"c"]]).get(2);               // "b"
+new WeakMap([[{},"a"],[myObj,"b"],[{},"c"]]).get(myObj); // "b"
+new Set([1, 2, 3]).has(3);                               // true
+new Set("123").has("2");                                 // true
+new WeakSet(function*() {
+    yield {};
+    yield myObj;
+    yield {};
+}()).has(myObj);                                         // true
+
+ +

뿐만 아니라 {{jsxref("Promise.all", "Promise.all(iterable)")}}, {{jsxref("Promise.race", "Promise.race(iterable)")}}와 {{jsxref("Array.from", "Array.from()")}} 또한 해당된다.

+ +

Iterable과 함께 사용되는 문법

+ +

for-of loops, spread operator, yield* destructuring assignment는 iterable과 함께 사용되는 구문(statements)과 표현(expressions)이다.

+ +
for(let value of ["a", "b", "c"]){
+    console.log(value);
+}
+// "a"
+// "b"
+// "c"
+
+[..."abc"]; // ["a", "b", "c"]
+
+function* gen(){
+  yield* ["a", "b", "c"];
+}
+
+gen().next(); // { value:"a", done:false }
+
+[a, b, c] = new Set(["a", "b", "c"]);
+a // "a"
+
+
+ +

잘 정의되지 못한 iterables

+ +

만약 Iterable의 @@iterator 메소드가 iterator 객체를 반환하지 않는다면 그것은 잘 정의되지 못한 iterable이라고 할 수 있다. 이러한 iterable을 사용하는 것은 런타임 예외나 예상치 못한 결과를 불러올 수 있다:

+ +
var nonWellFormedIterable = {}
+nonWellFormedIterable[Symbol.iterator] = () => 1
+[...nonWellFormedIterable] // TypeError: [] is not a function
+
+ +

Iterator 예시

+ +

간단한 iterator

+ +
function makeIterator(array){
+    var nextIndex = 0;
+
+    return {
+       next: function(){
+           return nextIndex < array.length ?
+               {value: array[nextIndex++], done: false} :
+               {done: true};
+       }
+    };
+}
+
+var it = makeIterator(['yo', 'ya']);
+
+console.log(it.next().value); // 'yo'
+console.log(it.next().value); // 'ya'
+console.log(it.next().done);  // true
+
+ +

무한 iterator

+ +
function idMaker(){
+    var index = 0;
+
+    return {
+       next: function(){
+           return {value: index++, done: false};
+       }
+    };
+}
+
+var it = idMaker();
+
+console.log(it.next().value); // '0'
+console.log(it.next().value); // '1'
+console.log(it.next().value); // '2'
+// ...
+
+ +

Generator와 함께 사용된 iterator

+ +
function* makeSimpleGenerator(array){
+    var nextIndex = 0;
+
+    while(nextIndex < array.length){
+        yield array[nextIndex++];
+    }
+}
+
+var gen = makeSimpleGenerator(['yo', 'ya']);
+
+console.log(gen.next().value); // 'yo'
+console.log(gen.next().value); // 'ya'
+console.log(gen.next().done);  // true
+
+
+
+function* idMaker(){
+    var index = 0;
+    while(true)
+        yield index++;
+}
+
+var gen = idMaker();
+
+console.log(gen.next().value); // '0'
+console.log(gen.next().value); // '1'
+console.log(gen.next().value); // '2'
+// ...
+
+ +

generator object 는 iterator 또는 iterable 인가?

+ +

generator object 는 iterator 이면서 iterable 입니다.

+ +
var aGeneratorObject = function*(){
+    yield 1;
+    yield 2;
+    yield 3;
+}();
+typeof aGeneratorObject.next;
+// "function", 이것은 next 메서드를 가지고 있기 때문에 iterator입니다.
+typeof aGeneratorObject[Symbol.iterator];
+// "function", 이것은 @@iterator 메서드를 가지고 있기 때문에 iterable입니다.
+aGeneratorObject[Symbol.iterator]() === aGeneratorObject;
+// true, 이 Object의 @@iterator 메서드는 자기자신(iterator)을 리턴하는 것으로 보아 잘 정의된 iterable이라고 할 수 있습니다.
+[...aGeneratorObject];
+// [1, 2, 3]
+
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop("27.0")}}{{CompatNo}}26{{CompatNo}}
IteratorResult object instead of throwing{{CompatVersionUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("27.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(39.0)}}
IteratorResult object instead of throwing{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("29.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +

Firefox-specific notes

+ +

IteratorResult object returned instead of throwing

+ +

Starting with Gecko 29 {{geckoRelease(29)}}, the completed generator function no longer throws a {{jsxref("TypeError")}} "generator has already finished". Instead, it returns an IteratorResult object like { value: undefined, done: true } ({{bug(958951)}}).

+ +

Iterator property and @@iterator symbol

+ +

From Gecko 17 (Firefox 17 / Thunderbird 17 / SeaMonkey 2.14) to Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2) the iterator property was used (bug 907077), and from Gecko 27 to Gecko 35 the "@@iterator" placeholder was used. In Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33), the @@iterator symbol got implemented (bug 918828).

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-iteration', 'Iteration')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-iteration', 'Iteration')}}{{Spec2('ESDraft')}} 
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/lexical_grammar/index.html b/files/ko/web/javascript/reference/lexical_grammar/index.html new file mode 100644 index 0000000000..74e4e63788 --- /dev/null +++ b/files/ko/web/javascript/reference/lexical_grammar/index.html @@ -0,0 +1,657 @@ +--- +title: 어휘 문법 +slug: Web/JavaScript/Reference/Lexical_grammar +tags: + - JavaScript + - Keyword + - Lexical Grammar + - 문법 +translation_of: Web/JavaScript/Reference/Lexical_grammar +--- +
{{JsSidebar("More")}}
+ +

이 페이지는 JavaScript의 어휘 문법(lexical grammar)을 설명합니다. ECMAScript 소스 본문은 왼쪽에서 오른쪽 방향으로 분석되고 토큰, 제어문자, 줄바꿈, 주석, 또는 공백으로 구성되는 입력 요소 시퀀스로 바뀝니다. 또한 ECMAScript는 특별한 키워드와 리터럴을 정의하고 있으며 명령문 끝에 자동으로 세미콜론을 추가하는 규칙이 있습니다.

+ +

제어 문자

+ +

제어 문자는 눈에 보이지 않지만 스크립트 소스 본문 해석을 제어하는 데 사용됩니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
유니코드 형식 제어 문자
코드 포인트이름축약형설명
U+200CZero width non-joiner<ZWNJ> +

특정 언어에서 문자들이 연결선으로 묶이지 않게 하기 위해 문자 사이에 위치한다(Wikipedia).

+
U+200DZero width joiner<ZWJ> +

특정 언어에서, 보통은 연결되지 않는 문자이나 해당 문자를 연결된 형태로 그리기 위해서(to be rendered) 사용하며 문자 사이에 위치한다(Wikipedia).

+
U+FEFFByte order mark<BOM> +

스크립트 맨 앞에 두어 스크립트 본문의 byte order와 유니코드를 표시하는 데에 사용한다.(Wikipedia).

+
+ +

공백

+ +

공백 문자는 소스 본문을 읽기 좋게 만들고 토큰을 구분합니다. 이 공백 문자들은 보통 코드의 기능에 필요한 것은 아닙니다. 최소화 도구(Minification tools)는 종종 전송해야하는 데이터 크기를 줄이기 위해서 공백을 제거합니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
공백 문자
코드 포인트이름축약형설명이스케이프 시퀀스
U+0009Character tabulation<HT>Horizontal tabulation\t
U+000BLine tabulation<VT>Vertical tabulation\v
U+000CForm feed<FF>Page breaking control character (Wikipedia).\f
U+0020Space<SP>Normal space
U+00A0No-break space<NBSP>Normal space, but no point at which a line may break
OthersOther Unicode space characters<USP>Spaces in Unicode on Wikipedia
+ +

개행 문자

+ +

공백문자와 더불어, 개행 문자는 소스 본문의 가독성을 향상시킵니다. 하지만, 몇몇 상황에서 개행 문자는 코드 내부에 숨겨지기 때문에 자바스크립트 코드 실행에 영향을 미칩니다. 개행 문자는 자동 새미콜론 삽입(automatic semicolon insertion) 규칙에도 영향을 줍니다. 개행 문자는 표준 표현방식(regular expressions)의 클래스인 \s로 매치됩니다.

+ +

아래의 유니코드 문자만이 ECMAScript에서 라인 종결자로 다뤄지며, 라인을 바꾸는 다른 문자들은 공백으로 생각하시면 됩니다(예를 들어, Next Line, NEL, U+0085는 공백으로 간주).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
개행 문자
코드 포인트이름축약형설명이스케이프 시퀀스
U+000ALine Feed<LF>New line character in UNIX systems.\n
U+000DCarriage Return<CR>New line character in Commodore and early Mac systems.\r
U+2028Line Separator<LS>Wikipedia
U+2029Paragraph Separator<PS>Wikipedia
+ +

주석

+ +

주석은 힌트, 필기, 제안이나 주의할 점들을 자바스크립트 코드에 넣을 때 사용합니다. 이는 더 쉽게 읽고 이해할 수 있게 도와줍니다. 또한 특정 코드가 실행되지 않도록 막아주기도 합니다. 따라서 주석은 유용한 디버깅 도구라고도 할 수 있습니다.

+ +

자바스크립트에는 코드 속에 주석을 쓰는 두 가지 방식이 있습니다.

+ +

첫 번째, '//'로 첨언하기입니다. 이는 아래의 예시처럼 같은 줄에 있는 모든 코드를 주석으로 바꿉니다.

+ +
function comment() {
+  // 자바스크립트의 각주 한 줄입니다.
+  console.log("Hello world!");
+}
+comment();
+
+ +

두 번째, 좀 더 유연하게 쓸 수 있는 '/* */'로 첨언하기입니다.

+ +

예를 들면, 한 줄에 첨언할 때는 이렇게 쓸 수 있습니다 :

+ +
function comment() {
+  /* 자바스크립트 각주 한 줄입니다. */
+  console.log("Hello world!");
+}
+comment();
+ +

여러 줄로 첨언할 때는, 이렇게 씁니다 :

+ +
function comment() {
+  /* This comment spans multiple lines. Notice
+     that we don't need to end the comment until we're done. */
+  console.log("Hello world!");
+}
+comment();
+ +

원한다면, 라인 중간에도 사용할 수 있습니다. 물론 코드의 가독성이 떨어지게 됩니다. 그러니 주의를 기울여 사용해야 합니다:

+ +

function comment(x) {

+ +
  console.log("Hello " + x /* insert the value of x */ + " !");
+}
+comment("world");
+ +

게다가, 코드 실행을 막기 위해 코드를 무용화 시키는데도 사용할 수 있습니다. 아래처럼 코드를 코멘트로 감싸는 거죠:

+ +
function comment() {
+  /* console.log("Hello world!"); */
+}
+comment();
+ +

In this case, the console.log() call is never issued, since it's inside a comment. Any number of lines of code can be disabled this way.

+ +

해시뱅 주석

+ +

A specialized third comment syntax, the hashbang comment, is in the process of being standardized in ECMAScript (see the Hashbang Grammar proposal).

+ +

A hashbang comment behaves exactly like a single line-only (//) comment, but it instead begins with #! and is only valid at the absolute start of a script or module. Note also that no whitespace of any kind is permitted before the #!. The comment consists of all the characters after #! up to the end of the first line; only one such comment is permitted.

+ +

The hashbang comment specifies the path to a specific JavaScript interpreter
+ that you want to use to execute the script. An example is as follows:

+ +
#!/usr/bin/env node
+
+console.log("Hello world");
+
+ +
+

Note: Hashbang comments in JavaScript mimic shebangs in Unix used to run files with proper interpreter.

+
+ +
+

Although BOM before hashbang comment will work in a browser it is not advised to use BOM in a script with hasbang. BOM will not work when you try to run the script in Unix/Linux. So use UTF-8 without BOM if you want to run scripts directly from shell.

+
+ +

You must only use the #! comment style to specify a JavaScript interpreter. In all other cases just use a // comment (or mulitiline comment).

+ +

키워드

+ +

ECMAScript 2015 기준 예약 키워드

+ + + +

확장 예약 키워드

+ +

The following are reserved as future keywords by the ECMAScript specification. They have no special functionality at present, but they might at some future time, so they cannot be used as identifiers.

+ +

These are always reserved:

+ + + +

The following are only reserved when they are found in strict mode code:

+ + + +

The following are only reserved when they are found in module code:

+ + + +

구형 표준의 확장 예약 키워드

+ +

The following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).

+ + + +

Additionally, the literals null, true, and false cannot be used as identifiers in ECMAScript.

+ +

예약어 사용법

+ +

Reserved words actually only apply to Identifiers (vs. IdentifierNames) . As described in es5.github.com/#A.1, these are all IdentifierNames which do not exclude ReservedWords.

+ +
a.import
+a['import']
+a = { import: 'test' }.
+
+ +

On the other hand the following is illegal because it's an Identifier, which is an IdentifierName without the reserved words. Identifiers are used for FunctionDeclaration, FunctionExpression, VariableDeclaration and so on. IdentifierNames are used for MemberExpression, CallExpression and so on.

+ +
function import() {} // Illegal.
+ +

리터럴

+ +

Null 리터럴

+ +

See also null for more information.

+ +
null
+ +

불리언 리터럴

+ +

See also Boolean for more information.

+ +
true
+false
+ +

숫자 리터럴

+ +

10진법

+ +
1234567890
+42
+
+// Caution when using with a leading zero:
+0888 // 888 parsed as decimal
+0777 // parsed as octal, 511 in decimal
+
+ +

Note that decimal literals can start with a zero (0) followed by another decimal digit, but If all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. This won't throw in JavaScript, see {{bug(957513)}}. See also the page about parseInt().

+ +
Exponential
+ +

The decimal exponential literal is specified by the following format: beN; where b is a base number (integer or floating), followed by e char (which serves as separator or exponent indicator) and N, which is exponent or power number – a signed integer (as per 2019 ECMA-262 specs): 

+ +
0e-5   // => 0
+0e+5   // => 0
+5e1    // => 50
+175e-2 // => 1.75
+1e3    // => 1000
+1e-3   // => 0.001
+ +

2진법

+ +

Binary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "B" (0b or 0B). Because this syntax is new in ECMAScript 2015, see the browser compatibility table, below. If the digits after the 0b are not 0 or 1, the following SyntaxError is thrown: "Missing binary digits after 0b".

+ +
var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
+var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
+var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
+ +

8진법

+ +

Octal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "O" (0o or 0O). Because this syntax is new in ECMAScript 2015, see the browser compatibility table, below. If the digits after the 0o are outside the range (01234567), the following SyntaxError is thrown: "Missing octal digits after 0o".

+ +
var n = 0O755; // 493
+var m = 0o644; // 420
+
+// Also possible with just a leading zero (see note about decimals above)
+0755
+0644
+
+ +

16진법

+ +

Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "X" (0x or 0X). If the digits after 0x are outside the range (0123456789ABCDEF), the following SyntaxError is thrown: "Identifier starts immediately after numeric literal".

+ +
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
+0x123456789ABCDEF   // 81985529216486900
+0XA                 // 10
+
+ +

BigInt literal

+ +

The {{jsxref("BigInt")}} type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. BigInt literals are created by appending n to the end of an integer.

+ +
123456789123456789n     // 123456789123456789
+0o777777777777n         // 68719476735
+0x123456789ABCDEFn      // 81985529216486895‬
+0b11101001010101010101n // 955733
+
+ +

Note that legacy octal numbers with just a leading zero won't work for BigInt:

+ +
// 0755n
+// SyntaxError: invalid BigInt syntax
+ +

For octal BigInt numbers, always use zero followed by the letter "o" (uppercase or lowercase):

+ +
0o755n
+ +

For more information about BigInt, see also JavaScript data structures.

+ +

Numeric separators

+ +

To improve readability for numeric literals, underscores (_U+005F) can be used as separators:

+ +
// separators in decimal numbers
+1_000_000_000_000
+1_050.95
+
+// separators in binary numbers
+0b1010_0001_1000_0101
+
+// separators in octal numbers
+0o2_2_5_6
+
+// separators in hex numbers
+0xA0_B0_C0
+
+// separators in BigInts
+1_000_000_000_000_000_000_000n
+
+ +

Note these limitations:

+ +
// More than one underscore in a row is not allowed
+100__000; // SyntaxError
+
+// Not allowed at the end of numeric literals
+100_; // SyntaxError
+
+// Can not be used after leading 0
+0_1; // SyntaxError
+
+ +

객체 리터럴

+ +

See also {{jsxref("Object")}} and Object initializer for more information.

+ +
var o = { a: 'foo', b: 'bar', c: 42 };
+
+// shorthand notation. New in ES2015
+var a = 'foo', b = 'bar', c = 42;
+var o = {a, b, c};
+
+// instead of
+var o = { a: a, b: b, c: c };
+
+ +

배열 리터럴

+ +

See also {{jsxref("Array")}} for more information.

+ +
[1954, 1974, 1990, 2014]
+ +

문자열 리터럴

+ +

A string literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for these closing quote code points:

+ + + +

Prior to the proposal to make all JSON text valid ECMA-262, U+2028 <LS> and U+2029 <PS>, were also disallowed from appearing unescaped in string literals.

+ +

Any code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values. When generating these String values Unicode code points are UTF-16 encoded.

+ +
'foo'
+"bar"
+ +

16진수 이스케이프 시퀀스

+ +

Hexadecimal escape sequences consist of \x followed by exactly two hexadecimal digits representing a code unit or code point in the range 0x0000 to 0x00FF.

+ +
'\xA9' // "©"
+
+ +

유니코드 이스케이프 시퀀스

+ +

A Unicode escape sequence consists of exactly four hexadecimal digits following \u. It represents a code unit in the UTF-16 encoding. For code points U+0000 to U+FFFF, the code unit is equal to the code point. Code points U+10000 to U+10FFFF require two escape sequences representing the two code units (a surrogate pair) used to encode the character; the surrogate pair is distinct from the code point.

+ +

See also {{jsxref("String.fromCharCode()")}} and {{jsxref("String.prototype.charCodeAt()")}}.

+ +
'\u00A9' // "©" (U+A9)
+ +

유니코드 코드 포인트 시퀀스

+ +

A Unicode code point escape consists of \u{, followed by a code point in hexadecimal base, followed by }. The value of the hexadecimal digits must be in the range 0 and 0x10FFFF inclusive. Code points in the range U+10000 to U+10FFFF do not need to be represented as a surrogate pair. Code point escapes were added to JavaScript in ECMAScript 2015 (ES6).

+ +

See also {{jsxref("String.fromCodePoint()")}} and {{jsxref("String.prototype.codePointAt()")}}.

+ +
'\u{2F804}' // CJK COMPATIBILITY IDEOGRAPH-2F804 (U+2F804)
+
+// the same character represented as a surrogate pair
+'\uD87E\uDC04'
+ +

정규 표현식 리터럴

+ +

See also RegExp for more information.

+ +
/ab+c/g
+
+// An "empty" regular expression literal
+// The empty non-capturing group is necessary
+// to avoid ambiguity with single-line comments.
+/(?:)/
+ +

템플릿 리터럴

+ +

See also template strings for more information.

+ +
`string text`
+
+`string text line 1
+ string text line 2`
+
+`string text ${expression} string text`
+
+tag `string text ${expression} string text`
+ +

자동 세미콜론 삽입

+ +

Some JavaScript statements must be terminated with semicolons and are therefore affected by automatic semicolon insertion (ASI):

+ + + +

The ECMAScript specification mentions three rules of semicolon insertion.

+ +

1. A semicolon is inserted before, when a Line terminator or "}" is encountered that is not allowed by the grammar.

+ +
{ 1 2 } 3
+
+// is transformed by ASI into
+
+{ 1 2 ;} 3;
+ +

2. A semicolon is inserted at the end, when the end of the input stream of tokens is detected and the parser is unable to parse the single input stream as a complete program.

+ +

Here ++ is not treated as a postfix operator applying to variable b, because a line terminator occurs between b and ++.

+ +
a = b
+++c
+
+// is transformend by ASI into
+
+a = b;
+++c;
+
+ +

3. A semicolon is inserted at the end, when a statement with restricted productions in the grammar is followed by a line terminator. These statements with "no LineTerminator here" rules are:

+ + + +
return
+a + b
+
+// is transformed by ASI into
+
+return;
+a + b;
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2("ES1")}}Initial definition.
{{SpecName('ES5.1', '#sec-7', 'Lexical Conventions')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}{{Spec2('ES6')}}Added: Binary and Octal Numeric literals, Unicode code point escapes, Templates
{{SpecName('ESDraft', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.grammar")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/liveconnect/index.html b/files/ko/web/javascript/reference/liveconnect/index.html new file mode 100644 index 0000000000..dfa43d52d0 --- /dev/null +++ b/files/ko/web/javascript/reference/liveconnect/index.html @@ -0,0 +1,17 @@ +--- +title: LiveConnect +slug: Web/JavaScript/Reference/LiveConnect +translation_of: Archive/Web/LiveConnect +--- +

이 절(section)은 생성자, 메소드와 함께 LiveConnect에 쓰이는 Java 클래스를 상세히 기록합니다. 이 클래스들은 Java 객체가 JavaScript 코드에 접근할 수 있게 합니다.

+

JSException

+
+
+ public 클래스 JSExceptionRuntimeException를 상속하고, JavaScript가 에러를 반환하면 발생됩니다.
+
+

JSObject

+
+
+ public 클래스 JSObjectObject를 상속합니다. JavaScript 개체는 클래스 JSObject의 인스턴스(instance)로 싸여 Java가 JavaScript 개체를 다루게 하도록 Java에 건네집니다.
+
+

{{ languages( { "en": "en/Core_JavaScript_1.5_Reference/LiveConnect", "pl": "pl/Dokumentacja_j\u0119zyka_JavaScript_1.5/LiveConnect" } ) }}

diff --git a/files/ko/web/javascript/reference/operators/addition/index.html b/files/ko/web/javascript/reference/operators/addition/index.html new file mode 100644 index 0000000000..0a624fdd16 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/addition/index.html @@ -0,0 +1,77 @@ +--- +title: Addition (+) +slug: Web/JavaScript/Reference/Operators/Addition +translation_of: Web/JavaScript/Reference/Operators/Addition +--- +
{{jsSidebar("Operators")}}
+ +

증가 연산자addition operator (+)는 숫자 또는 여러 문자열의 더합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-addition.html")}}
+ +
+ + + +

Syntax

+ +
Operator: x + y
+
+ +

Examples

+ +

Numeric addition

+ +
// Number + Number -> addition
+1 + 2 // 3
+
+// Boolean + Number -> addition
+true + 1 // 2
+
+// Boolean + Boolean -> addition
+false + false // 0
+
+ +

String concatenation

+ +
// String + String -> concatenation
+'foo' + 'bar' // "foobar"
+
+// Number + String -> concatenation
+5 + 'foo' // "5foo"
+
+// String + Boolean -> concatenation
+'foo' + false // "foofalse"
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-addition-operator-plus', 'Addition operator')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.addition")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html b/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html new file mode 100644 index 0000000000..8b2b274aa6 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/arithmetic_operators/index.html @@ -0,0 +1,290 @@ +--- +title: 산술 연산자 +slug: Web/JavaScript/Reference/Operators/Arithmetic_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

산술 연산자는 숫자 값(리터럴 또는 변수)을 피연산자로 받아 하나의 숫자 값을 반환합니다. 표준 산술 연산자는 덧셈(+), 뺄셈(-), 곱셈(*), 나눗셈(/)입니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-arithmetic.html")}}
+ + + +

덧셈 (+)

+ +

덧셈 연산자는 숫자 피연산자를 더한 값, 또는 문자열을 연결한 값을 생성합니다.

+ +

구문

+ +
연산자: x + y
+
+ +

예제

+ +
// Number + Number -> 합
+1 + 2 // 3
+
+// Boolean + Number -> 합
+true + 1 // 2
+
+// Boolean + Boolean -> 합
+false + false // 0
+
+// Number + String -> 연결
+5 + "foo" // "5foo"
+
+// String + Boolean -> 연결
+"foo" + false // "foofalse"
+
+// String + String -> 연결
+"foo" + "bar" // "foobar"
+
+ +

뺄셈 (-)

+ +

뺄셈 연산자는 두 개의 피연산자를 뺀 값을 생성합니다.

+ +

구문

+ +
연산자: x - y
+
+ +

예제

+ +
5 - 3 // 2
+3 - 5 // -2
+"foo" - 3 // NaN
+ +

나눗셈 (/)

+ +

나눗셈 연산자는 왼쪽 피연산자를 피제수로, 오른쪽 피연산자를 제수로 한 몫을 생성합니다.

+ +

구문

+ +
연산자: x / y
+
+ +

예제

+ +
1 / 2      // JavaScript에선 0.5
+1 / 2      // Java에선 0
+// (양쪽 피연산자 모두 명시적인 부동소수점 숫자가 아님)
+
+1.0 / 2.0  // JavaScript와 Java 둘 다 0.5
+
+2.0 / 0    // JavaScript에서 Infinity
+2.0 / 0.0  // 동일하게 Infinity
+2.0 / -0.0 // JavaScript에서 -Infinity
+ +

곱셈 (*)

+ +

곱셈 연산자는 두 연산자의 곱을 생성합니다.

+ +

구문

+ +
연산자: x * y
+
+ +

예제

+ +
2 * 2 // 4
+-2 * 2 // -4
+Infinity * 0 // NaN
+Infinity * Infinity // Infinity
+"foo" * 2 // NaN
+
+ +

나머지 (%)

+ +

나머지 연산자는 왼쪽 피연산자를 오른쪽 피연산자로 나눴을 때의 나머지를 반환합니다. 결과는 항상 피제수의 부호를 따라갑니다.

+ +

구문

+ +
연산자: var1 % var2
+
+ +

예제

+ +
12 % 5 // 2
+-1 % 2 // -1
+NaN % 2 // NaN
+1 % 2 // 1
+2 % 3 // 2
+-4 % 2 // -0
+5.5 % 2 // 1.5
+
+ +

거듭제곱 (**)

+ +

거듭제곱 연산자는 첫 번째 피연산자를 밑으로, 두 번째 피연산자를 지수로 한 값을 생성합니다. 즉, var1var2가 변수일 때, var1var2의 값을 생성합니다. 거듭제곱 연산자는 우결합성을 가집니다. 따라서 a ** b ** ca ** (b ** c)와 같습니다.

+ +

구문

+ +
연산자: var1 ** var2
+
+ +

참고

+ +

PHP와 Python 등 거듭제곱 연산자를 가진 대부분의 언어는 거듭제곱 연산자의 우선순위가 +와 - 등 단항 연산자보다 높습니다. 그러나 Bash는 단항 연산자가 거듭제곱 연산자보다 우선순위가 높은 등 일부 예외도 있습니다. JavaScript는 단항 연산자(+/-/~/!/delete/void/typeof)를 왼쪽 피연산자 앞에 배치할 수 없으므로, 모호한 표현도 작성할 수 없습니다.

+ +
-2 ** 2;
+// Bash에서 4, 다른 언어에서는 -4.
+// 모호한 표현이므로 JavaScript에서는 유효하지 않음
+
+
+-(2 ** 2);
+// JavaScript에서 -4, 작성자의 의도가 명확함
+
+ +

예제

+ +
2 ** 3 // 8
+3 ** 2 // 9
+3 ** 2.5 // 15.588457268119896
+10 ** -1 // 0.1
+NaN ** 2 // NaN
+
+2 ** 3 ** 2 // 512
+2 ** (3 ** 2) // 512
+(2 ** 3) ** 2 // 64
+
+ +

결과의 부호를 뒤집으려면 다음과 같이 작성합니다.

+ +
-(2 ** 2) // -4
+
+ +

거듭제곱의 밑을 음수로 강제하려면 다음과 같이 작성합니다.

+ +
(-2) ** 2 // 4
+
+ +
+

참고: JavaScript는 비트 연산자 ^ (논리 XOR)도 가지고 있습니다. **^는 다릅니다. (예 : 2 ** 3 === 8이지만 2 ^ 3 === 1)

+
+ +

증가 (++)

+ +

증가 연산자는 피연산자를 증가(1을 덧셈)시키고, 그 값을 반환합니다.

+ + + +

구문

+ +
연산자: x++ or ++x
+
+ +

예제

+ +
// 접미사
+var x = 3;
+y = x++; // y = 3, x = 4
+
+// 접두사
+var a = 2;
+b = ++a; // a = 3, b = 3
+
+ +

감소 (--)

+ +

감소 연산자는 피연산자를 감소(1을 뺄셈)시키고, 그 값을 반환합니다.

+ + + +

구문

+ +
연산자: x-- or --x
+
+ +

예제

+ +
// 접미사
+var x = 3;
+y = x--; // y = 3, x = 2
+
+// 접두사
+var a = 2;
+b = --a; // a = 1, b = 1
+
+ +

단항 부정 (-)

+ +

단항 부정 연산자는 피연산자의 앞에 위치하며 부호를 뒤집습니다.

+ +

구문

+ +
연산자: -x
+
+ +

예제

+ +
var x = 3;
+y = -x; // y = -3, x = 3
+
+// 단항 부정 연산자는 숫자가 아닌 값을 숫자로 변환함
+var x = "4";
+y = -x; // y = -4
+ +

단항 양부호 (+)

+ +

단항 양부호 연산자는 피연산자의 앞에 위치하며 피연산자의 값 그대로 평가되지만, 값이 숫자가 아닐 경우 숫자로 변환을 시도합니다. 단항 부정(-) 연산자도 숫자가 아닌 값을 변환할 수 있지만, 단항 양부호가 속도도 제일 빠르고 다른 연산도 수행하지 않으므로 선호해야 할 방법입니다. 문자열로 표현한 정수 및 부동소수점 실수, 문자열이 아닌 true, false, null도 변환할 수 있습니다. 10진수와 (앞에 "0x"가 붙은) 16진수 정수 모두 지원합니다. 음수도 지원하지만 16진수 음수에는 사용할 수 없습니다. 어떤 값을 분석할 수 없으면 {{jsxref("NaN")}}으로 평가됩니다.

+ +

구문

+ +
연산자: +x
+
+ +

예제

+ +
+3     // 3
++"3"   // 3
++true  // 1
++false // 0
++null  // 0
++function(val) { return val } // NaN
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-additive-operators', 'Additive operators')}}
{{SpecName('ESDraft', '#sec-postfix-expressions', 'Postfix expressions')}}
{{SpecName('ESDraft', '#sec-11.5', 'Multiplicative operators')}}
{{SpecName('ESDraft', '#sec-11.4', 'Unary operator')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.arithmetic")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/assignment_operators/index.html b/files/ko/web/javascript/reference/operators/assignment_operators/index.html new file mode 100644 index 0000000000..d7f195c803 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/assignment_operators/index.html @@ -0,0 +1,394 @@ +--- +title: 할당 연산자 +slug: Web/JavaScript/Reference/Operators/Assignment_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators#Assignment_operators +--- +
{{jsSidebar("Operators")}}
+ +

할당 연산자는 오른쪽 피연산자의 값을 왼쪽 피연산자에 할당합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-assignment.html")}}
+ + + +

개요

+ +

기본 할당연산자는 등호(=)로, 오른쪽 피연산자의 값을 왼쪽 피연산자에 할당합니다. 즉, x = yy의 값을 x에 할당힙니다. 다른 할당 연산자는 보통 표준 연산의 축약형으로, 다음 표에서 종류와 예시를 확인할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
이름단축 연산자의미
할당x = yx = y
덧셈 할당x += yx = x + y
뺄셈 할당x -= yx = x - y
곱셈 할당x *= yx = x * y
나눗셈 할당x /= yx = x / y
나머지 연산 할당x %= yx = x % y
지수 연산 할당x **= yx = x ** y
왼쪽 시프트 할당x <<= yx = x << y
오른쪽 시프트 할당x >>= yx = x >> y
부호없는 오른쪽 시프트 할당x >>>= yx = x >>> y
비트 AND 할당x &= yx = x & y
비트 XOR 할당x ^= yx = x ^ y
비트 OR 할당x |= yx = x | y
+ +

할당

+ +

단순 할당 연산자는 값을 변수에 할당합니다. 할당 연산자는 할당의 결과값으로 평가됩니다. 할당 연산자를 연속해서 사용해, 다수의 변수에 하나의 값을 한꺼번에 할당할 수 있습니다. 예제를 참고하세요.

+ +

구문

+ +
연산자: x = y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  x = 5
+//  y = 10
+//  z = 25
+
+x = y     // x는 10
+x = y = z // x, y, z 모두 25
+
+ +

덧셈 할당

+ +

덧셈 할당 연산자는 변수에 오른쪽 피연산자의 값을 더하고, 그 결과를 변수에 할당합니다. 두 피연산자의 자료형이 덧셈 할당 연산자의 행동을 결정합니다. 덧셈 연산자처럼 합 또는 연결이 가능합니다. 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "덧셈 연산자", "#Addition", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x += y
+의미: x = x + y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  foo = "foo"
+//  bar = 5
+//  baz = true
+
+
+// Number + Number -> 합
+bar += 2 // 7
+
+// Boolean + Number -> 합
+baz += 1 // 2
+
+// Boolean + Boolean -> 합
+baz += false // 1
+
+// Number + String -> 연결
+bar += 'foo' // "5foo"
+
+// String + Boolean -> 연결
+foo += false // "foofalse"
+
+// String + String -> 연결
+foo += 'bar' // "foobar"
+
+ +

뺄셈 할당

+ +

뺄셈 할당 연산자는 변수에서 오른쪽 피연산자의 값을 빼고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "뺄셈 연산자", "#Subtraction", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x -= y
+의미: x = x - y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  bar = 5
+
+bar -= 2     // 3
+bar -= "foo" // NaN
+
+ +

곱셈 할당

+ +

곱셈 할당 연산자는 변수에 오른쪽 피연산자의 값을 곱하고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "곱셈 연산자", "#Multiplication", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x *= y
+의미: x = x * y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  bar = 5
+
+bar *= 2     // 10
+bar *= "foo" // NaN
+
+ +

나눗셈 할당

+ +

나눗셈 할당 연산자는 변수를 오른쪽 피연산자로 나누고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "나눗셈 연산자", "#Division", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x /= y
+의미: x = x / y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  bar = 5
+
+bar /= 2     // 2.5
+bar /= "foo" // NaN
+bar /= 0     // Infinity
+
+ +

나머지 연산 할당

+ +

나머지 연산 할당은 변수를 오른쪽 피연산자로 나눈 나머지를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "나머지 연산자", "#Remainder", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x %= y
+의미: x = x % y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  bar = 5
+
+bar %= 2     // 1
+bar %= "foo" // NaN
+bar %= 0     // NaN
+
+ +

거듭제곱 할당

+ +

거듭제곱 할당 연산자는 변수를 오른쪽 피연산자만큼 거듭제곱한 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Arithmetic_Operators", "거듭제곱 연산자", "#Exponentiation", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x **= y
+의미: x = x ** y
+
+ +

예제

+ +
// 다음과 같은 변수를 가정
+//  bar = 5
+
+bar **= 2     // 25
+bar **= "foo" // NaN
+ +

왼쪽 시프트 할당

+ +

왼쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 왼쪽으로 이동하고, 그 결과를 변수에 할당합니다. 더 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "left shift operator", "#Left_shift", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x <<= y
+의미: x = x << y
+
+ +

예제

+ +
var bar = 5; //  (00000000000000000000000000000101)
+bar <<= 2; // 20 (00000000000000000000000000010100)
+
+ +

오른쪽 시프트 할당

+ +

오른쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 우측으로 이동하고, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "right shift operator", "#Right_shift", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x >>= y
+의미: x = x >> y
+
+ +

예제

+ +
var bar = 5; //   (00000000000000000000000000000101)
+bar >>= 2;   // 1 (00000000000000000000000000000001)
+
+var bar -5; //    (-00000000000000000000000000000101)
+bar >>= 2;  // -2 (-00000000000000000000000000000010)
+
+ +

부호 없는 오른쪽 시프트 할당

+ +

부호 없는 오른쪽 시프트 할당 연산자는 변수의 비트를 오른쪽 피연산자의 값만큼 우측으로 이동하고, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", " unsigned right shift operator", "#Unsigned_right_shift", 1)}}을 참고하세요.

+ +

구문

+ +
연산자: x >>>= y
+의미: x = x >>> y
+
+ +

예제

+ +
var bar = 5; //   (00000000000000000000000000000101)
+bar >>>= 2;  // 1 (00000000000000000000000000000001)
+
+var bar = -5; // (-00000000000000000000000000000101)
+bar >>>= 2; // 1073741822 (00111111111111111111111111111110)
+ +

비트 AND 할당

+ +

비트 AND 할당 연산자는 양쪽 피연산자의 이진 표현을 AND 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은{{jsxref("Operators/Bitwise_Operators", "bitwise AND operator", "#Bitwise_AND", 1)}}을 참고하세요.

+ +

구문

+ +
연산자: x &= y
+의미: x = x & y
+
+ +

예제

+ +
var bar = 5;
+// 5:     00000000000000000000000000000101
+// 2:     00000000000000000000000000000010
+bar &= 2; // 0
+
+ +

비트 XOR 할당

+ +

비트 XOR 할당 연산자는 양쪽 피연산자의 이진 표현을 XOR 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "bitwise XOR operator", "#Bitwise_XOR", 1)}}를 참고하세요.

+ +

구문

+ +
연산자: x ^= y
+의미: x = x ^ y
+
+ +

예제

+ +
var bar = 5;
+bar ^= 2; // 7
+// 5: 00000000000000000000000000000101
+// 2: 00000000000000000000000000000010
+// -----------------------------------
+// 7: 00000000000000000000000000000111
+
+ +

비트 OR 할당

+ +

비트 OR 할당 연산자는 양쪽 피연산자의 이진 표현을 OR 연산한 후, 그 결과를 변수에 할당합니다. 자세한 내용은 {{jsxref("Operators/Bitwise_Operators", "bitwise OR operator", "#Bitwise_OR", 1)}}를 참고하세요.

+ +

문법

+ +
연산자: x |= y
+의미: x = x | y
+
+ +

예제

+ +
var bar = 5;
+bar |= 2; // 7
+// 5: 00000000000000000000000000000101
+// 2: 00000000000000000000000000000010
+// -----------------------------------
+// 7: 00000000000000000000000000000111
+
+ +

예제

+ +

다른 할당 연산자를 갖는 왼쪽 피연산자

+ +

드물게, 할당 연산자(예: x += y)와 그 의미를 나타낸 표현(x = x + y)이 동일하지 않은 경우가 있습니다. 할당 연산자의 왼쪽 피연산자가 다른 할당 연산자를 포함할 때, 왼쪽 피연산자는 한 번만 평가됩니다. 예를 들면 다음과 같습니다.

+ +
a[i++] += 5         // i는 한 번만 평가됨
+a[i++] = a[i++] + 5 // i는 두 번 평가됨
+
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-assignment-operators', 'Assignment operators')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.assignment")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/async_function/index.html b/files/ko/web/javascript/reference/operators/async_function/index.html new file mode 100644 index 0000000000..d1ec146ca4 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/async_function/index.html @@ -0,0 +1,96 @@ +--- +title: async function 표현식 +slug: Web/JavaScript/Reference/Operators/async_function +translation_of: Web/JavaScript/Reference/Operators/async_function +--- +
{{jsSidebar("Operators")}}
+ +

async function 키워드는 표현식 내에서 async 함수를 정의하기 위해 사용됩니다.

+ +

또한 async function statement을 사용하여 async 함수를 정의할 수 있습니다.

+ +

문법

+ +
async function [name]([param1[, param2[, ..., paramN]]]) { statements }
+ +

ES2015에서와 같이 arrow functions를 사용해도 됩니다.

+ +

인수

+ +
+
name
+
함수 이름. 생략가능하며 이경우함수는 anonymous 형식임  이름은 함수 몸체에 대해 지역적으로 사용.
+
paramN
+
함수에 전달될 인수의 이름.
+
statements
+
함수 몸체를 구성하는 명령문들.
+
+ +

설명

+ +

async function 표현식은 {{jsxref('Statements/async_function', 'async function 선언')}} 문법과 유사하며, 거의 동일합니다. async function 표현식과 async function 선언문의 주요 차이점은 익명함수로써의 사용 여부로, async function 표현식은 함수 이름을 생략하면 익명함수를 만듭니다. async function 표현식은 {{Glossary("IIFE")}}(즉시실행함수)로 사용할 수 있습니다. functions문서를 참고하세요.

+ +

Examples

+ +

Simple example

+ +
function resolveAfter2Seconds(x) {
+  return new Promise(resolve => {
+    setTimeout(() => {
+      resolve(x);
+    }, 2000);
+  });
+};
+
+
+var add = async function(x) { // async function 표현식을 변수에 할당
+  var a = await resolveAfter2Seconds(20);
+  var b = await resolveAfter2Seconds(30);
+  return x + a + b;
+};
+
+add(10).then(v => {
+  console.log(v);  // 4초 뒤에 60 출력
+});
+
+
+(async function(x) { // async function 표현식을 IIFE로 사용
+  var p_a = resolveAfter2Seconds(20);
+  var p_b = resolveAfter2Seconds(30);
+  return x + await p_a + await p_b;
+})(10).then(v => {
+  console.log(v);  // 2초 뒤에 60 출력
+});
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}{{Spec2('ESDraft')}}Initial definition in ES2017.
+ +

Browser compatibility

+ +
{{Compat("javascript.operators.async_function_expression")}} 
+ +
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/await/index.html b/files/ko/web/javascript/reference/operators/await/index.html new file mode 100644 index 0000000000..00b5fd3eff --- /dev/null +++ b/files/ko/web/javascript/reference/operators/await/index.html @@ -0,0 +1,137 @@ +--- +title: await +slug: Web/JavaScript/Reference/Operators/await +translation_of: Web/JavaScript/Reference/Operators/await +--- +
{{jsSidebar("Operators")}}
+ +
await연산자는 {{jsxref("Promise")}}를 기다리기 위해 사용됩니다. 연산자는 {{jsxref("Statements/async_function", "async function")}} 내부에서만 사용할 수 있습니다.
+ +

구문

+ +
[rv] = await expression;
+ +
+
expression
+
{{jsxref("Promise")}} 혹은 기다릴 어떤 값입니다.
+
rv
+
+

{{jsxref("Promise")}}에 의해 만족되는 값이 반환됩니다. {{jsxref("Promise")}}가 아닌 경우에는 그 값 자체가 반환됩니다.

+
+
+ +

설명

+ +

await 문은 Promise가 fulfill되거나 reject 될 때까지 async 함수의 실행을 일시 정지하고, Promise가 fulfill되면 async 함수를 일시 정지한 부분부터 실행합니다. 이때  await 문의 반환값은 Promise 에서 fulfill된 값이 됩니다.

+ +

만약 Promisereject되면, await 문은 reject된 값을 throw합니다.

+ +

await 연산자 다음에 나오는 문의 값이 Promise가 아니면 해당 값을 resolved Promise로 변환시킵니다.

+ +

An await can split execution flow, allowing the caller of the await's function to resume execution before the deferred continuation of the await's function. After the await defers the continuation of its function, if this is the first await executed by the function, immediate execution also continues by returning to the function's caller a pending Promise for the completion of the await's function and resuming execution of that caller.

+ +

예제

+ +

만약 Promiseawait에 넘겨지면, awaitPromise가 fulfill되기를 기다렸다가, 해당 값을 리턴합니다.

+ +
function resolveAfter2Seconds(x) {
+  return new Promise(resolve => {
+    setTimeout(() => {
+      resolve(x);
+    }, 2000);
+  });
+}
+
+async function f1() {
+  var x = await resolveAfter2Seconds(10);
+  console.log(x); // 10
+}
+
+f1();
+
+ +

{{jsxref("Global_Objects/Promise/then", "Thenable objects")}} will be fulfilled just the same.

+ +
async function f2() {
+  const thenable = {
+    then: function(resolve, _reject) {
+      resolve('resolved!')
+    }
+  };
+  console.log(await thenable); // resolved!
+}
+
+f2();
+ +

만약 값이 Promise가 아니라면, 해당 값은 resolvePromise로 변환되며 이를 기다립니다.

+ +
async function f2() {
+  var y = await 20;
+  console.log(y); // 20
+}
+f2();
+
+ +

만약 Promisereject되면, reject된 값이 throw됩니다.

+ +
async function f3() {
+  try {
+    var z = await Promise.reject(30);
+  } catch(e) {
+    console.log(e); // 30
+  }
+}
+f3();
+
+ +

try블럭 없이 rejected Promise다루기

+ +
var response = await promisedFunction().catch((err) => { console.error(err); });
+// response will be undefined if the promise is rejected
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("ESDraft", "#sec-async-function-definitions", "async functions")}}{{Spec2("ESDraft")}}
{{SpecName("ES2018", "#sec-async-function-definitions", "async functions")}}{{Spec2("ES2018")}}
{{SpecName("ES2017", "#sec-async-function-definitions", "async functions")}}{{Spec2("ES2017")}}Initial definition.
+ +

Browser compatibility

+ +
+
+ + +

{{Compat("javascript.operators.await")}}

+
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/bitwise_operators/index.html b/files/ko/web/javascript/reference/operators/bitwise_operators/index.html new file mode 100644 index 0000000000..e94e176e08 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/bitwise_operators/index.html @@ -0,0 +1,540 @@ +--- +title: 비트 연산자 +slug: Web/JavaScript/Reference/Operators/Bitwise_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

비트 연산자는 피연산자를 10진수, 16진수, 8진수가 아니라, 32개의 비트(0과 1) 집합으로 취급합니다. 예를 들어, 10진수 9의 2진수 표기법은 1001입니다. 이렇게, 비트 연산자는 값의 2진수 표현을 사용해 연산하지만, 결과는 표준 JavaScript 숫자 값으로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-bitwiseoperators.html")}}
+ + + +

다음은 JavaScript의 비트 연산자를 요약한 표입니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
연산자사용방법설명
비트 ANDa & b피연산자를 비트로 바꿨을 때 각각 대응하는 비트가 모두 1이면 그 비트값에 1을 반환.
비트 ORa | b피연산자를 비트로 바꿨을 때 각각 대응하는 비트가 모두 1이거나 한 쪽이 1이면 1을 반환.
비트 XORa ^ b피연산자를 비트로 바꿨을 때 대응하는 비트가 서로 다르면 1을 반환.
비트 NOT~ a피연산자의 반전된 값을 반환.
왼쪽 시프트a << bShifts a in binary representation b (< 32) bits to the left, shifting in zeros from the right.
부호 유지 오른쪽 시프트a >> bShifts a in binary representation b (< 32) bits to the right, discarding bits shifted off.
부호 버림 오른쪽 시프트a >>> bShifts a in binary representation b (< 32) bits to the right, discarding bits shifted off, and shifting in zeros from the left.
+ +

부호 있는 32비트 정수

+ +

The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format, except for zero-fill right shift which results in an unsigned 32-bit integer.

+ +

Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all the number's bits inverted (bitwise NOT of the number, or ones' complement of the number) plus one.

+ +

For example, the following encodes the integer 314:

+ +
00000000000000000000000100111010
+
+ +

The following encodes ~314, i.e. the one's complement of 314:

+ +
11111111111111111111111011000101
+
+ +

Finally, the following encodes -314, i.e. the two's complement of 314:

+ +
11111111111111111111111011000110
+
+ +

The two's complement guarantees that the left-most bit is 0 when the number is positive and 1 when the number is negative. Thus, it is called the sign bit.

+ +

The number 0 is the integer that is composed completely of 0 bits.

+ +
0 (base 10) = 00000000000000000000000000000000 (base 2)
+
+ +

The number -1 is the integer that is composed completely of 1 bits.

+ +
-1 (base 10) = 11111111111111111111111111111111 (base 2)
+
+ +

The number -2147483648 (hexadecimal representation: -0x80000000) is the integer that is composed completely of 0 bits except the first (left-most) one.

+ +
-2147483648 (base 10) = 10000000000000000000000000000000 (base 2)
+
+ +

The number 2147483647 (hexadecimal representation: 0x7fffffff) is the integer that is composed completely of 1 bits except the first (left-most) one.

+ +
2147483647 (base 10) = 01111111111111111111111111111111 (base 2)
+
+ +

The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable throught a 32bit signed number.

+ +

비트 논리 연산자

+ +

비트 논리 연산자는 다음과 같이 사용됩니다.

+ + + +

& (비트 AND)

+ +

비트 연산자 AND를 비트 쌍으로 실행합니다.

+ +

Performs the AND operation on each pair of bits. a AND b yields 1 only if both a and b are 1. The truth table for the AND operation is:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
aba AND b
000
010
100
111
+ +
     9 (base 10) = 00000000000000000000000000001001 (base 2)
+    14 (base 10) = 00000000000000000000000000001110 (base 2)
+                   --------------------------------
+14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
+
+ +

Bitwise ANDing any number x with 0 yields 0. Bitwise ANDing any number x with -1 yields x.

+ +

| (비트 OR)

+ +

Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1. The truth table for the OR operation is:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
aba OR b
000
011
101
111
+ +
     9 (base 10) = 00000000000000000000000000001001 (base 2)
+    14 (base 10) = 00000000000000000000000000001110 (base 2)
+                   --------------------------------
+14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
+
+ +

Bitwise ORing any number x with 0 yields x.

+ +

Bitwise ORing any number x with -1 yields -1.

+ +

^ (비트 XOR)

+ +

Performs the XOR operation on each pair of bits. a XOR b yields 1 if a and b are different. The truth table for the XOR operation is:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
aba XOR b
000
011
101
110
+ +
     9 (base 10) = 00000000000000000000000000001001 (base 2)
+    14 (base 10) = 00000000000000000000000000001110 (base 2)
+                   --------------------------------
+14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
+
+ +

Bitwise XORing any number x with 0 yields x.

+ +

Bitwise XORing any number x with -1 yields ~x.

+ +

~ (비트 NOT)

+ +

Performs the NOT operator on each bit. NOT a yields the inverted value (a.k.a. one's complement) of a. The truth table for the NOT operation is:

+ + + + + + + + + + + + + + + + +
aNOT a
01
10
+ +
 9 (base 10) = 00000000000000000000000000001001 (base 2)
+               --------------------------------
+~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
+
+ +

Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.

+ +

비트 시프트 연산자

+ +

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

+ +

Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand. The right operand should be less than 32, but if not only the low five bits will be used.

+ +

<< (Left shift)

+ +

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

+ +

For example, 9 << 2 yields 36:

+ +
     9 (base 10): 00000000000000000000000000001001 (base 2)
+                  --------------------------------
+9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
+
+ +

Bitwise shifting any number x to the left by y bits yields x * 2^y.

+ +

>> (Sign-propagating right shift)

+ +

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".

+ +

For example, 9 >> 2 yields 2:

+ +
     9 (base 10): 00000000000000000000000000001001 (base 2)
+                  --------------------------------
+9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
+
+ +

Likewise, -9 >> 2 yields -3, because the sign is preserved:

+ +
     -9 (base 10): 11111111111111111111111111110111 (base 2)
+                   --------------------------------
+-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
+
+ +

>>> (Zero-fill right shift)

+ +

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative.

+ +

For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. For example, 9 >>> 2 yields 2, the same as 9 >> 2:

+ +
      9 (base 10): 00000000000000000000000000001001 (base 2)
+                   --------------------------------
+9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
+
+ +

However, this is not the case for negative numbers. For example, -9 >>> 2 yields 1073741821, which is different than -9 >> 2 (which yields -3):

+ +
      -9 (base 10): 11111111111111111111111111110111 (base 2)
+                    --------------------------------
+-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
+
+ +

예제

+ +

Flags and bitmasks

+ +

The bitwise logical operators are often used to create, manipulate, and read sequences of flags, which are like binary variables. Variables could be used instead of these sequences, but binary flags take much less memory (by a factor of 32).

+ +

Suppose there are 4 flags:

+ + + +

These flags are represented by a sequence of bits: DCBA. When a flag is set, it has a value of 1. When a flag is cleared, it has a value of 0. Suppose a variable flags has the binary value 0101:

+ +
var flags = 5;   // binary 0101
+
+ +

This value indicates:

+ + + +

Since bitwise operators are 32-bit, 0101 is actually 00000000000000000000000000000101, but the preceding zeroes can be neglected since they contain no meaningful information.

+ +

A bitmask is a sequence of bits that can manipulate and/or read flags. Typically, a "primitive" bitmask for each flag is defined:

+ +
var FLAG_A = 1; // 0001
+var FLAG_B = 2; // 0010
+var FLAG_C = 4; // 0100
+var FLAG_D = 8; // 1000
+
+ +

New bitmasks can be created by using the bitwise logical operators on these primitive bitmasks. For example, the bitmask 1011 can be created by ORing FLAG_A, FLAG_B, and FLAG_D:

+ +
var mask = FLAG_A | FLAG_B | FLAG_D; // 0001 | 0010 | 1000 => 1011
+
+ +

Individual flag values can be extracted by ANDing them with a bitmask, where each bit with the value of one will "extract" the corresponding flag. The bitmask masks out the non-relevant flags by ANDing with zeros (hence the term "bitmask"). For example, the bitmask 0100 can be used to see if flag C is set:

+ +
// if we own a cat
+if (flags & FLAG_C) { // 0101 & 0100 => 0100 => true
+   // do stuff
+}
+
+ +

A bitmask with multiple set flags acts like an "either/or". For example, the following two are equivalent:

+ +
// if we own a bat or we own a cat
+if ((flags & FLAG_B) || (flags & FLAG_C)) { // (0101 & 0010) || (0101 & 0100) => 0000 || 0100 => true
+   // do stuff
+}
+
+ +
// if we own a bat or cat
+var mask = FLAG_B | FLAG_C; // 0010 | 0100 => 0110
+if (flags & mask) { // 0101 & 0110 => 0100 => true
+   // do stuff
+}
+
+ +

Flags can be set by ORing them with a bitmask, where each bit with the value one will set the corresponding flag, if that flag isn't already set. For example, the bitmask 1100 can be used to set flags C and D:

+ +
// yes, we own a cat and a duck
+var mask = FLAG_C | FLAG_D; // 0100 | 1000 => 1100
+flags |= mask;   // 0101 | 1100 => 1101
+
+ +

Flags can be cleared by ANDing them with a bitmask, where each bit with the value zero will clear the corresponding flag, if it isn't already cleared. This bitmask can be created by NOTing primitive bitmasks. For example, the bitmask 1010 can be used to clear flags A and C:

+ +
// no, we don't have an ant problem or own a cat
+var mask = ~(FLAG_A | FLAG_C); // ~0101 => 1010
+flags &= mask;   // 1101 & 1010 => 1000
+
+ +

The mask could also have been created with ~FLAG_A & ~FLAG_C (De Morgan's law):

+ +
// no, we don't have an ant problem, and we don't own a cat
+var mask = ~FLAG_A & ~FLAG_C;
+flags &= mask;   // 1101 & 1010 => 1000
+
+ +

Flags can be toggled by XORing them with a bitmask, where each bit with the value one will toggle the corresponding flag. For example, the bitmask 0110 can be used to toggle flags B and C:

+ +
// if we didn't have a bat, we have one now, and if we did have one, bye-bye bat
+// same thing for cats
+var mask = FLAG_B | FLAG_C;
+flags = flags ^ mask;   // 1100 ^ 0110 => 1010
+
+ +

Finally, the flags can all be flipped with the NOT operator:

+ +
// entering parallel universe...
+flags = ~flags;    // ~1010 => 0101
+
+ +

Conversion snippets

+ +

Convert a binary string to a decimal number:

+ +
var sBinString = "1011";
+var nMyNumber = parseInt(sBinString, 2);
+alert(nMyNumber); // prints 11, i.e. 1011
+
+ +

Convert a decimal number to a binary string:

+ +
var nMyNumber = 11;
+var sBinString = nMyNumber.toString(2);
+alert(sBinString); // prints 1011, i.e. 11
+
+ +

Automate Mask Creation

+ +

If you have to create many masks from some boolean values, you can automatize the process:

+ +
function createMask () {
+  var nMask = 0, nFlag = 0, nLen = arguments.length > 32 ? 32 : arguments.length;
+  for (nFlag; nFlag < nLen; nMask |= arguments[nFlag] << nFlag++);
+  return nMask;
+}
+var mask1 = createMask(true, true, false, true); // 11, i.e.: 1011
+var mask2 = createMask(false, false, true); // 4, i.e.: 0100
+var mask3 = createMask(true); // 1, i.e.: 0001
+// etc.
+
+alert(mask1); // prints 11, i.e.: 1011
+
+ +

Reverse algorithm: an array of booleans from a mask

+ +

If you want to create an array of booleans from a mask you can use this code:

+ +
function arrayFromMask (nMask) {
+  // nMask must be between -2147483648 and 2147483647
+  if (nMask > 0x7fffffff || nMask < -0x80000000) { throw new TypeError("arrayFromMask - out of range"); }
+  for (var nShifted = nMask, aFromMask = []; nShifted; aFromMask.push(Boolean(nShifted & 1)), nShifted >>>= 1);
+  return aFromMask;
+}
+
+var array1 = arrayFromMask(11);
+var array2 = arrayFromMask(4);
+var array3 = arrayFromMask(1);
+
+alert("[" + array1.join(", ") + "]");
+// prints "[true, true, false, true]", i.e.: 11, i.e.: 1011
+
+ +

You can test both algorithms at the same time…

+ +
var nTest = 19; // our custom mask
+var nResult = createMask.apply(this, arrayFromMask(nTest));
+
+alert(nResult); // 19
+
+ +

For didactic purpose only (since there is the Number.toString(2) method), we show how it is possible to modify the arrayFromMask algorithm in order to create a string containing the binary representation of a number, rather than an array of booleans:

+ +
function createBinaryString (nMask) {
+  // nMask must be between -2147483648 and 2147483647
+  for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32; nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
+  return sMask;
+}
+
+var string1 = createBinaryString(11);
+var string2 = createBinaryString(4);
+var string3 = createBinaryString(1);
+
+alert(string1);
+// prints 00000000000000000000000000001011, i.e. 11
+
+ +

명세

+ + + + + + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-bitwise-not-operator', 'Bitwise NOT Operator')}}
{{SpecName('ESDraft', '#sec-binary-bitwise-operators', 'Binary Bitwise Operators')}}
{{SpecName('ESDraft', '#sec-bitwise-shift-operators', 'Bitwise Shift Operators')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.bitwise")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/class/index.html b/files/ko/web/javascript/reference/operators/class/index.html new file mode 100644 index 0000000000..d15b532fbc --- /dev/null +++ b/files/ko/web/javascript/reference/operators/class/index.html @@ -0,0 +1,100 @@ +--- +title: class 식 +slug: Web/JavaScript/Reference/Operators/class +tags: + - ECMAScript 2015 + - Expression + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/class +--- +
{{jsSidebar("Operators")}}
+ +

class 표현식은 ECMAScript 2015 (ES6)에서 클래스를 정의하는 한 방법입니다. function 식과 비슷하게, class 식은 기명(named) 또는 익명(unnamed)일 수 있습니다. 기명인 경우, 클래스명은 클래스 본체(body)에서만 지역(local)입니다. JavaScript 클래스는 프로토타입(원형) 기반 상속을 사용합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-classexpression.html")}}
+ + + +

구문

+ +
var MyClass = class [className] [extends] {
+  // class body
+};
+ +

설명

+ +

class 식은 class 문과 구문이 비슷합니다. 그러나, class 식의 경우 클래스명("binding identifier")을 생략할 수 있는데 class 문으로는 할 수 없습니다.

+ +

class 문과 같이, class 식의 본체는 엄격 모드에서 실행됩니다.

+ + + +

예제

+ +

간단한 class 식

+ +

이게 바로 변수 "Foo"를 사용하여 참조할 수 있는 간단한 익명 class 식입니다.

+ +
var Foo = class {
+  constructor() {}
+  bar() {
+    return "Hello World!";
+  }
+};
+
+var instance = new Foo();
+instance.bar(); // "Hello World!"
+Foo.name; // ""
+
+ +

Named  class 식

+ +

당신이 클래스 몸통 내에서 현재 클래스를 참조하고 싶다면, 유명 class 식을 만들 수 있습니다. 이 이름은 오직 class 식 자체 범위에서만 볼 수 있습니다.

+ +
var Foo = class NamedFoo {
+  constructor() {}
+  whoIsThere() {
+    return NamedFoo.name;
+  }
+}
+var bar = new Foo();
+bar.whoIsThere(); // "NamedFoo"
+NamedFoo.name; // ReferenceError: NamedFoo가 정의되지 않음
+Foo.name; // "NamedFoo"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.class")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/comma_operator/index.html b/files/ko/web/javascript/reference/operators/comma_operator/index.html new file mode 100644 index 0000000000..d2c4caae0e --- /dev/null +++ b/files/ko/web/javascript/reference/operators/comma_operator/index.html @@ -0,0 +1,91 @@ +--- +title: 쉼표 연산자 +slug: Web/JavaScript/Reference/Operators/Comma_Operator +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Comma_Operator +--- +
{{jsSidebar("Operators")}}
+ +

쉼표 연산자는 각각의 피연산자를 왼쪽에서 오른쪽 순서로 평가하고, 마지막 연산자의 값을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}
+ + + +

구문

+ +
expr1, expr2, expr3...
+ +

매개변수

+ +
+
expr1, expr2, expr3...
+
아무 표현식.
+
+ +

설명

+ +

단일 표현식을 요구하는 곳에 복수의 표현식을 사용하고 싶을 때 쉼표 연산자를 사용할 수 있습니다. 가장 흔히 사용되는 곳은 for 반복문에 다수의 매개변수를 제공할 때입니다.

+ +

쉼표 연산자는 배열, 객체, 함수의 매개변수와 호출 인수에서 사용하는 쉼표와는 전혀 다릅니다.

+ +

예제

+ +

a를 한 행에 10개의 요소를 가진 2차원 배열이라고 가정할 때, 아래 예제는 쉼표 연산자를 사용해 한 번에 i는 증가시키고 j는 감소시킵니다.

+ +

다음 코드는 2차원 배열의 대각선에 위치하는 요소의 값을 출력합니다.

+ +
for (var i = 0, j = 9; i <= 9; i++, j--)
+  console.log("a[" + i + "][" + j + "] = " + a[i][j]);
+
+ +

쉼표 연산자를 할당에 사용하면, 할당 연산이 표현식에 포함되지 않아 예상한 결과와는 다소 다를 수 있습니다. 다음 예제에서, ab = 3의 값(3)을 할당받지만, c = 4 표현식 역시 평가되어 콘솔에 기록됩니다. 연산자 우선순위와 결합성 때문입니다.

+ +
var a, b, c;
+
+a = b = 3, c = 4; // 콘솔에는 4를 반환
+console.log(a); // 3 (제일 왼쪽)
+
+var x, y, z;
+
+x = (y = 5, z = 6); // 콘솔에는 6을 반환
+console.log(x); // 6 (제일 오른쪽)
+
+ +

연산 후 반환

+ +

쉼표 연산자를 사용하는 다른 방법은 값을 반환하기 전에 연산을 수행하는 것입니다. 쉼표 연산자는 마지막 표현식의 평가 결과만 반환하지만, 이전 피연산자에 대해서도 평가는 수행하므로 다음과 같은 코드를 작성할 수 있습니다.

+ +
function myFunc () {
+  var x = 0;
+
+  return (x += 1, x); // ++x 와 같은 효과
+}
+ +

명세

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.comma")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/comparison_operators/index.html b/files/ko/web/javascript/reference/operators/comparison_operators/index.html new file mode 100644 index 0000000000..ecfd46d6e5 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/comparison_operators/index.html @@ -0,0 +1,215 @@ +--- +title: 비교 연산자 +slug: Web/JavaScript/Reference/Operators/Comparison_Operators +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

JavaScript는 엄격한 비교와 형변환 비교 두 가지의 비교 방법을 모두 가지고 있습니다. 엄격(일치) 비교(===)는 두 피연산자가 같은 자료형에, 그 내용도 일치해야만 참입니다. 추상(동등) 비교(==)는 비교 전에 두 피연산자를 동일한 자료형으로 변환합니다. 관계 추상 비교(<=)의 경우 {{glossary("primitive", "원시값")}}으로 바꾸고, 같은 자료형으로 다시 바꾼후 비교를 수행합니다.

+ +

문자열의 경우 {{glossary("unicode", "유니코드")}} 값을 사용한 사전순으로 비교합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-comparisonoperators.html")}}
+ + + +

비교 연산의 특징은 다음과 같습니다.

+ + + +

동치 연산자

+ +

동등 연산자 (==)

+ +

동등 연산자는 두 피연산자의 자료형이 같지 않은 경우 같아지도록 변환한 후, 엄격 비교를 수행합니다. 피연산자가 모두 객체라면, JavaScript는 내부 참조를 보고, 둘 다 메모리의 같은 객체를 바라보고 있는지 판별합니다.

+ +

구문

+ +
x == y
+
+ +

예제

+ +
  1   ==  1        // true
+ "1"  ==  1        // true
+  1   == '1'       // true
+  0   == false     // true
+  0   == null      // false
+
+  0   == undefined // false
+null  == undefined // true
+
+ +

부등 연산자 (!=)

+ +

부등 연산자는 두 피연산자가 같지 않은 경우 참을 반환합니다. 피연산자의 자료형이 일치하지 않는 경우 적절한 자료형으로의 변환을 시도합니다. 피연산자가 모두 객체라면, JavaScript는 내부 참조를 보고, 서로 메모리의 다른 객체를 바라보고 있는지 판별합니다.

+ +

구문

+ +
x != y
+ +

예제

+ +
1 !=   2     // true
+1 !=  "1"    // false
+1 !=  '1'    // false
+1 !=  true   // false
+0 !=  false  // false
+
+ +

일치 연산자 (===)

+ +

일치 연산자는 자료형 변환 없이 두 연산자가 엄격히 같은지 판별합니다.

+ +

구문

+ +
x === y
+ +

예제

+ +
3 === 3   // true
+3 === '3' // false
+ +

불일치 연산자 (!==)

+ +

일치 연산자는 두 연산자가 같지 않거나, 같은 자료형이 아닐 때 참을 반환합니다.

+ +

구문

+ +
x !== y
+ +

예제

+ +
3 !== '3' // true
+4 !== 3   // true
+
+ +

관계 연산자

+ +

이 항목의 모든 연산자는 비교 전에 피연산자를 {{glossary("primitive", "원시값")}}으로 변환합니다. 둘 다 문자열이 되는 경우 사전순으로 비교하고, 그렇지 않으면 숫자로 변환합니다. {{jsxref("NaN")}}과의 비교는 항상 false를 반환합니다.

+ +

초과 연산자 (>)

+ +

초과 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 큰 경우 참을 반환합니다.

+ +

구문

+ +
x > y
+ +

예제

+ +
4 > 3 // true
+
+ +

이상 연산자 (>=)

+ +

이상 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 크거나 같으면 참을 반환합니다.

+ +

구문

+ +
 x >= y
+ +

예제

+ +
4 >= 3 // true
+3 >= 3 // true
+
+ +

미만 연산자 (<)

+ +

미만 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 작은 경우 참을 반환합니다.

+ +

구문

+ +
x < y
+ +

예제

+ +
3 < 4 // true
+ +

이하 연산자 (<=)

+ +

이하 연산자는 왼쪽 피연산자가 오른쪽 피연산자보다 작거나 같으면 참을 반환합니다.

+ +

구문

+ +
 x <= y
+ +

예제

+ +
3 <= 4 // true
+
+ +

동치 연산자 사용하기

+ +

표준 동치, 동등 연산자(==, !=)는 두 피연산자를 비교하기 위해 추상 동치 비교 알고리즘(Abstract Equlity Comparison Algorithm)을 사용합니다. 피연산자 간 자료형이 일치하지 않으면 우선 변환을 시도합니다. 예를 들어 표현식 5 == '5'에서는 비교 전 오른쪽 문자열을 {{jsxref("Number")}}로 변환합니다.

+ +

엄격 동치, 일치 연산자(===, !==)는 엄격 동치 비교 알고리즘(Strict Equality Comparison Algorithm)을 사용하며, 같은 자료형을 가진 피연산자를 비교하기 위해 사용합니다. 피연산자 간 자료형이 일치하지 않으면 항상 false이므로, 5 !== '5'입니다.

+ +

피연산자의 값은 물론 특정 자료형이어야 하는 경우 일치 연산자를 사용하세요. 그렇지 않은 경우 형변환을 자동으로 해주는 동등 연산자를 사용할 수도 있습니다.

+ +

비교 과정에 자료형 변환이 필요한 경우 JavaScript는 {{jsxref("String")}}, {{jsxref("Number")}}, {{jsxref("Boolean")}}, {{jsxref("Object")}} 자료형을 다음과 같이 변환합니다.

+ + + +
참고: String 객체는 자료형 객체지, 문자열이 아닙니다! String 객체는 거의 쓰이지 않으며, 이런 성질로 인해 아래의 결과는 예상치 못한 값일 수 있습니다.
+ +
// true as both operands are type String (i.e. string primitives):
+'foo' === 'foo'
+
+var a = new String('foo');
+var b = new String('foo');
+
+// false as a and b are type Object and reference different objects
+a == b
+
+// false as a and b are type Object and reference different objects
+a === b
+
+// true as a and 'foo' are of different type and, the Object (a)
+// is converted to String 'foo' before comparison
+a == 'foo'
+ +

명세

+ + + + + + + + + + + + + +
Status
{{SpecName('ESDraft', '#sec-equality-operators', 'Equality Operators')}}
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.comparison")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/conditional_operator/index.html b/files/ko/web/javascript/reference/operators/conditional_operator/index.html new file mode 100644 index 0000000000..90f59ea4cd --- /dev/null +++ b/files/ko/web/javascript/reference/operators/conditional_operator/index.html @@ -0,0 +1,193 @@ +--- +title: 삼항 조건 연산자 +slug: Web/JavaScript/Reference/Operators/Conditional_Operator +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator +--- +
{{jsSidebar("Operators")}}
+ +

조건부 삼항 연산자는 JavaScript에서 세 개의 피연산자를 취할 수 있는 유일한 연산자입니다. 보통 if 명령문의 단축 형태로 쓰입니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-conditionaloperators.html")}}
+ + + +

구문

+ +
condition ? exprIfTrue : exprIfFalse 
+ +

매개변수

+ +
+
condition
+
An expression whose value is used as a condition.
+
exprIfTrue
+
An expression which is evaluated if the condition evaluates to a {{Glossary("truthy")}} value (one which equals or can be converted to true).
+
exprIfFalse
+
An expression which is executed if the condition is {{Glossary("falsy")}} (that is, has a value which can be converted to false).
+
+ +

설명

+ +

condition이 true이면, 연산자는 expr1의 값을 반환하며, 반대의 경우 expr2를 반환한다.

+ +

예제

+ +

여러분이 술을 마실수 있는지 확인할 수 있는 간단한 예제가 여기 있습니다.

+ +
var age = 29;
+var canDrinkAlcohol = (age > 19) ? "True, over 19" : "False, under 19";
+console.log(canDrinkAlcohol); // "True, over 19"
+
+ +

isMember 변수의 값을 기준으로 다른 메시지를 보여주고자 한다면, 다음과 같이 표현할 수 있다.

+ +
"The fee is " + (isMember ? "$2.00" : "$10.00")
+
+ +

또한 다음과 같이 삼항(ternary)의 결과에 따라 변수를 할당할 수도 있다.

+ +
var elvisLives = Math.PI > 4 ? "Yep" : "Nope";
+ +

다음의 예제처럼, 다중 삼항(ternary) 평가도 가능하다(주의: 조건 연산은 우측부터 그룹핑 됩니다.)

+ +
var firstCheck = false,
+    secondCheck = false,
+    access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted";
+
+console.log( access ); // logs "Access granted"
+ +

또한 다중 조건 IF 문과 같은 방식으로 여러개의 조건을 사용할 수도 있습니다.

+ +
var condition1 = true,
+    condition2 = false,
+    access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false");
+
+console.log(access); // logs "true false"
+ +

참고 : 괄호는 필수는 아니며 기능에 영향을주지 않습니다. 결과가 어떻게 처리되는지 시각화하는 데 도움이됩니다.

+ +

삼항(ternary) 평가는 다른 연산을 하기 위해 쓸 수도 있습니다.

+ +
var stop = false, age = 16;
+
+age > 18 ? location.assign("continue.html") : stop = true;
+
+ +

하나의 케이스 당 둘 이상의 단일 작업을 수행하려면 쉼표로 구분하고 괄호로 묶으세요.

+ +
var stop = false, age = 23;
+
+age > 18 ? (
+    alert("OK, you can go."),
+    location.assign("continue.html")
+) : (
+    stop = true,
+    alert("Sorry, you are much too young!")
+);
+
+ +

또한, 값을 할당하는 동안 하나 이상의 연산도 가능합니다. 이 경우에, 괄호 안의 값중 마지막 쉼표 (,) 다음의 값이 최종 할당 값이 됩니다.

+ +
var age = 16;
+
+var url = age > 18 ? (
+    alert("OK, you can go."),
+    // alert returns "undefined", but it will be ignored because
+    // isn't the last comma-separated value of the parenthesis
+    "continue.html" // the value to be assigned if age > 18
+) : (
+    alert("You are much too young!"),
+    alert("Sorry :-("),
+    // etc. etc.
+    "stop.html" // the value to be assigned if !(age > 18)
+);
+
+location.assign(url); // "stop.html"
+ + + +

삼항 연산자로 반환하기

+ +

삼항 연산자는 if / else 문을 사용하는 함수를 반환하는 데 적합합니다.

+ +
var func1 = function( .. ) {
+  if (condition1) { return value1 }
+  else { return value2 }
+}
+
+var func2 = function( .. ) {
+  return condition1 ? value1 : value2
+}
+ +

다음과 같이 법적으로 술을 마실수 있는지 여부를 반환하는 함수를 만들수 있습니다.

+ +
function canDrinkAlcohol(age) {
+  return (age > 21) ? "True, over 21" : "False, under 21";
+}
+var output = canDrinkAlcohol(26);
+console.log(output); // "True, over 21"
+ +

if / else 문을 대체하는 삼항연산자가 return을 여러 번 사용하고 if 블록 내부에서 한줄만 나올때 return을 대체 할 수 있는 좋은 방법이됩니다.

+ +

삼항연산자를 여러 행으로 나누고 그 앞에 공백을 사용하면 긴 if / else 문을 매우 깔끔하게 만들 수 있습니다. 이것은 동일한 로직을 표현하지만 코드를 읽기 쉽게 만들어 줍니다.

+ +
var func1 = function( .. ) {
+  if (condition1) { return value1 }
+  else if (condition2) { return value2 }
+  else if (condition3) { return value3 }
+  else { return value4 }
+}
+
+var func2 = function( .. ) {
+  return condition1 ? value1
+       : condition2 ? value2
+       : condition3 ? value3
+       :              value4
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.conditional")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/delete/index.html b/files/ko/web/javascript/reference/operators/delete/index.html new file mode 100644 index 0000000000..037c3bcd98 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/delete/index.html @@ -0,0 +1,282 @@ +--- +title: delete 연산자 +slug: Web/JavaScript/Reference/Operators/delete +tags: + - JavaScript + - Operator + - Property + - Reference +translation_of: Web/JavaScript/Reference/Operators/delete +--- +
{{jsSidebar("Operators")}}
+ +

delete 연산자는 객체의 속성을 제거합니다. 제거한 객체의 참조를 어디에서도 사용하지 않는다면 나중에 자원을 회수합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-deleteoperator.html")}}
+ + + +

구문

+ +
delete expression 
+ +

expression은 속성 참조여야 합니다. 예컨대,

+ +
delete object.property
+delete object['property']
+
+ +

매개변수

+ +
+
object
+
객체의 이름, 또는 평가했을 때 객체를 반환하는 표현식.
+
property
+
제거하려는 속성.
+
+ +

반환 값

+ +

true. 단, 비엄격 모드에서 속성이 {{jsxref("Object.prototype.hasOwnProperty", "자신의 속성", "", 0)}}이며 설정 불가능한 경우 false.

+ +

예외

+ +

엄격 모드에서, 속성이 자신의 속성이며 설정 불가능한 경우 {{jsxref("TypeError")}}.

+ +

설명

+ +

일반적으로 생각하고 있는것과는 다르게 delete 는 메모리 해제에 관하여 직접적으로 어떠한 작업도 하지 않습니다. 메모리 관리는 breaking references를 통하여 간접적으로 일어납니다. 자세한 걸 알고 싶다면 memory management 를 보세요.

+ +

delete연산자는 오브젝트로 부터 해당 프로퍼티를 삭제합니다. 삭제를 하면 true를 반환, 아니면 false를 반환합니다. 그렇지만 아래 경우를 고려해야만 합니다. 

+ + + +

간단한 예제입니다.

+ +
var Employee = {
+  age: 28,
+  name: 'abc',
+  designation: 'developer'
+}
+
+console.log(delete Employee.name);   // returns true
+console.log(delete Employee.age);    // returns true
+
+// 존재하지 않는 속성을 삭제하려하면
+// true를 리턴합니다.
+console.log(delete Employee.salary); // returns true
+
+ +

설정 불가능한 속성

+ +

non-configurable 속성은 delete로 삭제할 수 없으며, false를 반환할 것입니다(*strict mode에서는 SyntaxError를 발생시킴).

+ +
var Employee = {};
+Object.defineProperty(Employee, 'name', {configurable: false});
+
+console.log(delete Employee.name);  // returns false
+
+ +

{{jsxref("Statements/var","var")}}, {{jsxref("Statements/let","let")}}, {{jsxref("Statements/const","const")}}로 선언된 변수는 non-configurable 속성으로 구분되며, delete로 삭제될 수 없습니다.

+ +
var nameOther = 'XYZ';
+
+// 우리는 이를 사용해 글로벌 속성에 접근 할 수 있습니다:
+Object.getOwnPropertyDescriptor(window, 'nameOther');
+
+// output: Object { value: "XYZ",
+//                  writable: true,
+//                  enumerable: true,
+//                  configurable: false }
+
+// "nameOther"은 var로 선언되었기 때문에
+// 이는 "non-configurable" 속성으로 구분됩니다.
+
+delete nameOther;   // return false
+ +

strict mode, this would have raised an exception.

+ +

엄격 vs. 비엄격 모드

+ +

엄격 모드에서 delete로 변수나 함수를 삭제하려고 하면 {{jsxref("SyntaxError")}}가 발생합니다. 

+ +

var로 정의된 변수는 non-configurable로 구분됩니다. 다음 예제에서, salary는 non-configurable이며 삭제될 수 없습니다. non-strict mode에서 non-configurable에 delete를 쓰면 false를 반환합니다.

+ +
function Employee() {
+  delete salary;
+  var salary;
+}
+
+Employee();
+
+ +

그러나 strict mode에서는 false를 반환하는 대신, SyntaxError를 발생시킵니다.

+ +
"use strict";
+
+function Employee() {
+  delete salary;  // SyntaxError
+  var salary;
+}
+
+// 이와 마찬가지로, delete로 함수를 삭제하는 것도
+// SyntaxError를 발생시킵니다.
+
+function DemoFunction() {
+  //some code
+}
+
+delete DemoFunction; // SyntaxError
+
+ +

예제

+ +
// 전역스코프에 adminName라는 프로퍼티를 만듭니다.
+adminName = 'xyz';
+
+// 전역스코프에 empCount라는 프로퍼티를 만듭니다.
+// var를 사용해서 선언했으므로, 이는 non-configurable로 구분됩니다.
+// let 이나 const를 사용하더라도 마찬가지로 non-configurable 입니다.
+var empCount = 43;
+
+EmployeeDetails = {
+  name: 'xyz',
+  age: 5,
+  designation: 'Developer'
+};
+
+// adminName은 전역변수입니다.
+// 이는 var를 사용하여 선언되지 않았기에 configurable하며 delete로 삭제될 수 있습니다.
+delete adminName;       // returns true
+
+// 이와 반대로, empCount는 var를 사용하였기에 non-configurable이며
+// 그러므로 delete로 삭제할 수 없습니다.
+delete empCount;       // returns false
+
+// delete는 객체의 프로퍼티를 지울 때 사용됩니다.
+delete EmployeeDetails.name; // returns true
+
+// 해당 프로퍼티가 존재하지 않는 상황에서도 "true"를 리턴합니다.
+delete EmployeeDetails.salary; // returns true
+
+// 내장되어있는 정적 프로퍼티에는 delete가 영향을 미치지 않습니다.
+delete Math.PI; // returns false
+
+// EmployeeDetails 은 전역스코프의 프로퍼티 입니다.
+// "var"를 사용하지 않고 선언되었기 때문에 이는 configurable입니다.
+delete EmployeeDetails;   // returns true
+
+function f() {
+  var z = 44;
+
+  // 지역변수에는 delete가 영향을 미치지 않습니다.
+  delete z;     // returns false
+}
+ +

delete와 프로토타입 체인

+ +

In the following example, we delete an own property of an object while a property with the same name is available on the prototype chain:

+ +
function Foo() {
+  this.bar = 10;
+}
+
+Foo.prototype.bar = 42;
+
+var foo = new Foo();
+
+// Returns true, since the own property
+// has been deleted on the foo object
+delete foo.bar;
+
+// foo.bar is still available, since it
+// is available in the prototype chain.
+console.log(foo.bar);
+
+// We delete the property on the prototype
+delete Foo.prototype.bar;
+
+// logs "undefined" since the property
+// is no longer inherited
+console.log(foo.bar);           
+ +

객체 요소 제거하기

+ +

When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

+ +

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete.

+ +
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
+delete trees[3];
+if (3 in trees) {
+    // this does not get executed
+}
+ +

If you want an array element to exist but have an undefined value, use the undefined value instead of the delete operator. In the following example, trees[3] is assigned the value undefined, but the array element still exists:

+ +
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
+trees[3] = undefined;
+if (3 in trees) {
+    // this gets executed
+}
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-delete-operator', 'The delete Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-delete-operator', 'The delete Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.4.1', 'The delete Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.4.1', 'The delete Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.2.
+ +

브라우저 호환성

+ +
{{Compat("javascript.operators.delete")}}
+ +

크로스 브라우저 참고사항

+ +

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

+ +

If you want to use an ordered associative array in a cross-browser environment, use a {{jsxref("Map")}} object if available, or simulate this structure with two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/destructuring_assignment/index.html b/files/ko/web/javascript/reference/operators/destructuring_assignment/index.html new file mode 100644 index 0000000000..d078e94c38 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/destructuring_assignment/index.html @@ -0,0 +1,409 @@ +--- +title: 구조 분해 할당 +slug: Web/JavaScript/Reference/Operators/Destructuring_assignment +tags: + - Destructuring + - ECMAScript 2015 + - JavaScript + - Operator + - Reference + - 구조 분해 +translation_of: Web/JavaScript/Reference/Operators/Destructuring_assignment +--- +
{{jsSidebar("Operators")}}
+ +

구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-destructuringassignment.html")}}
+ + + +

구문

+ +
var a, b, rest;
+[a, b] = [10, 20];
+console.log(a); // 10
+console.log(b); // 20
+
+[a, b, ...rest] = [10, 20, 30, 40, 50];
+console.log(a); // 10
+console.log(b); // 20
+console.log(rest); // [30, 40, 50]
+
+({ a, b } = { a: 10, b: 20 });
+console.log(a); // 10
+console.log(b); // 20
+
+
+// Stage 4(finished) proposal
+({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
+console.log(a); // 10
+console.log(b); // 20
+console.log(rest); // {c: 30, d: 40}
+
+ +

설명

+ +

객체 및 배열 리터럴 표현식을 사용하면 즉석에서 쉽게 데이터 뭉치를 만들 수 있습니다.

+ +
var x = [1, 2, 3, 4, 5];
+ +

구조 분해 할당의 구문은 위와 비슷하지만, 대신 할당문의 좌변에서 사용하여, 원래 변수에서 어떤 값을 분해해 할당할지 정의합니다.

+ +
var x = [1, 2, 3, 4, 5];
+var [y, z] = x;
+console.log(y); // 1
+console.log(z); // 2
+
+ +

구조 분해 할당은 Perl이나 Python 등 다른 언어가 가지고 있는 기능입니다.

+ +

배열 구조 분해

+ +

기본 변수 할당

+ +
var foo = ["one", "two", "three"];
+
+var [one, two, three] = foo;
+console.log(one); // "one"
+console.log(two); // "two"
+console.log(three); // "three"
+
+ +

선언에서 분리한 할당

+ +

변수의 선언이 분리되어도 구조 분해를 통해 값을 할당할 수 있습니다.

+ +
var a, b;
+
+[a, b] = [1, 2];
+console.log(a); // 1
+console.log(b); // 2
+
+ +

기본값

+ +

변수에 기본값을 할당하면, 분해한 값이 {{jsxref("undefined")}}일 때 그 값을 대신 사용합니다.

+ +
var a, b;
+
+[a=5, b=7] = [1];
+console.log(a); // 1
+console.log(b); // 7
+
+ +

변수 값 교환하기

+ +

하나의 구조 분해 표현식만으로 두 변수의 값을 교환할 수 있습니다.

+ +

구조 분해 할당 없이 두 값을 교환하려면 임시 변수가 필요합니다. (일부 로우 레벨 언어에서는 XOR 교체 트릭을 사용할 수 있습니다)

+ +
var a = 1;
+var b = 3;
+
+[a, b] = [b, a];
+console.log(a); // 3
+console.log(b); // 1
+
+ +

함수가 반환한 배열 분석

+ +

함수는 이전부터 배열을 반환할 수 있었습니다. 구조 분해를 사용하면 반환된 배열에 대한 작업을 더 간결하게 수행할 수 있습니다.

+ +

아래 예제에서 f()는 출력으로 배열 [1, 2]을 반환하는데, 하나의 구조 분해만으로 값을 분석할 수 있습니다.

+ +
function f() {
+  return [1, 2];
+}
+
+var a, b;
+[a, b] = f();
+console.log(a); // 1
+console.log(b); // 2
+
+ +

일부 반환 값 무시하기

+ +

다음과 같이 필요하지 않은 반환 값을 무시할 수 있습니다.

+ +
function f() {
+  return [1, 2, 3];
+}
+
+var [a, , b] = f();
+console.log(a); // 1
+console.log(b); // 3
+
+ +

반환 값을 모두 무시할 수도 있습니다.

+ +
[,,] = f();
+
+ +

변수에 배열의 나머지를 할당하기

+ +

배열을 구조 분해할 경우, 나머지 구문을 이용해 분해하고 남은 부분을 하나의 변수에 할당할 수 있습니다.

+ +
var [a, ...b] = [1, 2, 3];
+console.log(a); // 1
+console.log(b); // [2, 3]
+
+ +

나머지 요소의 오른쪽 뒤에 쉼표가 있으면 {{jsxref("SyntaxError")}}가 발생합니다.

+ +
var [a, ...b,] = [1, 2, 3];
+// SyntaxError: rest element may not have a trailing comma
+
+ +

정규 표현식과 일치하는 값 해체하기

+ +

정규 표현식의 exec() 메서드는 일치하는 부분를 찾으면 그 문자열에서 정규식과 일치하는 부분 전체를 배열의 맨 앞에, 그리고 그 뒤에 정규식에서 괄호로 묶인 각 그룹과 일치하는 부분을 포함하는 배열을 반환합니다. 구조 분해 할당은 필요하지 않은 경우 일치하는 전체 부분은 무시하고 필요한 부분만 쉽게 빼올 수 있습니다.

+ +
function parseProtocol(url) {
+  var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
+  if (!parsedURL) {
+    return false;
+  }
+  console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"]
+
+  var [, protocol, fullhost, fullpath] = parsedURL;
+  return protocol;
+}
+
+console.log(parseProtocol('https://developer.mozilla.org/en-US/Web/JavaScript')); // "https"
+ +

객체 구조 분해

+ +

기본 할당

+ +
var o = {p: 42, q: true};
+var {p, q} = o;
+
+console.log(p); // 42
+console.log(q); // true
+
+ +

선언 없는 할당

+ +

구조 분해를 통해 변수의 선언과 분리하여 변수에 값을 할당할 수 있습니다.

+ +
var a, b;
+
+({a, b} = {a: 1, b: 2});
+ +
+

참고: 할당 문을 둘러싼 ( .. )는 선언 없이 객체 리터럴(object literal) 비구조화 할당을 사용할 때 필요한 구문입니다.

+ +

{a, b} = {a:1, b:2}는 유효한 독립 구문이 아닙니다. 좌변의 {a, b}이 객체 리터럴이 아닌 블록으로 간주되기 때문입니다.

+ +

하지만, ({a, b} = {a:1, b:2})는 유효한데, var {a, b} = {a:1, b:2}와 같습니다.

+ +

( .. ) 표현식 앞에는 세미콜론이 있어야 합니다. 그렇지 않을 경우 이전 줄과 연결되어 함수를 실행하는데 이용될 수 있습니다.

+
+ +

새로운 변수 이름으로 할당하기

+ +

객체로부터 속성을 해체하여 객체의 원래 속성명과는 다른 이름의 변수에 할당할 수 있습니다.

+ +
var o = {p: 42, q: true};
+var {p: foo, q: bar} = o;
+
+console.log(foo); // 42
+console.log(bar); // true
+ +

기본값

+ +

객체로부터 해체된 값이 undefined인 경우, 변수에 기본값을 할당할 수 있습니다.

+ +
var {a = 10, b = 5} = {a: 3};
+
+console.log(a); // 3
+console.log(b); // 5
+ +

기본값 갖는 새로운 이름의 변수에 할당하기

+ +

새로운 변수명 할당과 기본값 할당을 한번에 할 수 있습니다.

+ +
var {a: aa = 10, b: bb = 5} = {a: 3};
+
+console.log(aa); // 3
+console.log(bb); // 5
+
+ +

함수 매개변수의 기본값 설정하기

+ +

ES5 버전

+ +
function drawES5Chart(options) {
+  options = options === undefined ? {} : options;
+  var size = options.size === undefined ? 'big' : options.size;
+  var cords = options.cords === undefined ? { x: 0, y: 0 } : options.cords;
+  var radius = options.radius === undefined ? 25 : options.radius;
+  console.log(size, cords, radius);
+  // 이제 드디어 차트 그리기 수행
+}
+
+drawES5Chart({
+  cords: { x: 18, y: 30 },
+  radius: 30
+});
+ +

ES2015 버전

+ +
function drawES2015Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
+  console.log(size, cords, radius);
+  // 차트 그리기 수행
+}
+
+drawES2015Chart({
+  cords: { x: 18, y: 30 },
+  radius: 30
+});
+ +
+

위의 drawES2015Chart 함수의 원형에서 구조 분해된 좌변에 빈 오브젝트 리터럴을 할당하는 것을 볼 수 있습니다 {size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}. 빈 오브젝트를 우변에 할당하지 않고도 함수를 작성할 수 있습니다. 하지만, 지금의 형태에서는 단순히 drawES2015Chart()와 같이 어떤 매개변수 없이도 호출할 수 있지만, 우변의 빈 오브젝트 할당을 없앤다면 함수 호출시 적어도 하나의 인자가 제공되어야만 합니다. 이 함수가 어떠한 매개변수 없이도 호출할 수 있길 원한다면 지금 형태가 유용하고, 무조건 객체를 넘기길 원하는 경우에는 빈 객체 할당을 하지 않는 것이 유용할 수 있습니다.

+
+ +

중첩된 객체 및 배열의 구조 분해

+ +
var metadata = {
+    title: "Scratchpad",
+    translations: [
+       {
+        locale: "de",
+        localization_tags: [ ],
+        last_edit: "2014-04-14T08:43:37",
+        url: "/de/docs/Tools/Scratchpad",
+        title: "JavaScript-Umgebung"
+       }
+    ],
+    url: "/en-US/docs/Tools/Scratchpad"
+};
+
+var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
+
+console.log(englishTitle); // "Scratchpad"
+console.log(localeTitle);  // "JavaScript-Umgebung"
+ +

for of 반복문과 구조 분해

+ +
var people = [
+  {
+    name: "Mike Smith",
+    family: {
+      mother: "Jane Smith",
+      father: "Harry Smith",
+      sister: "Samantha Smith"
+    },
+    age: 35
+  },
+  {
+    name: "Tom Jones",
+    family: {
+      mother: "Norah Jones",
+      father: "Richard Jones",
+      brother: "Howard Jones"
+    },
+    age: 25
+  }
+];
+
+for (var {name: n, family: { father: f } } of people) {
+  console.log("Name: " + n + ", Father: " + f);
+}
+
+// "Name: Mike Smith, Father: Harry Smith"
+// "Name: Tom Jones, Father: Richard Jones"
+ +

함수 매개변수로 전달된 객체에서 필드 해체하기

+ +
function userId({id}) {
+  return id;
+}
+
+function whois({displayName: displayName, fullName: {firstName: name}}){
+  console.log(displayName + " is " + name);
+}
+
+var user = {
+  id: 42,
+  displayName: "jdoe",
+  fullName: {
+      firstName: "John",
+      lastName: "Doe"
+  }
+};
+
+console.log("userId: " + userId(user)); // "userId: 42"
+whois(user); // "jdoe is John"
+ +

이 예제는 user 객체로부터 id, displayNamefirstName 을 해체해 출력합니다.

+ +

계산된 속성 이름과 구조 분해

+ +

계산된 속성 이름(computed property name)은, 객체 리터럴과 비슷하게 구조 분해에도 사용될 수 있습니다.

+ +
let key = "z";
+let { [key]: foo } = { z: "bar" };
+
+console.log(foo); // "bar"
+
+ +

객체 구조 분해에서 Rest

+ +

Rest/Spread Properties for ECMAScript 제안(stage 3)에서는 구조 분해에 rest 구문을 추가하고 있습니다. rest 속성은 구조 분해 패턴으로 걸러지지 않은 열거형 속성의 키를 가진 나머지 항목들을 모읍니다.

+ +
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
+a; // 10
+b; // 20
+rest; // { c: 30, d: 40 }
+
+ +

속성 이름이 유효한 JavaScript 식별자명이 아닌 경우

+ +

구조 분해는 JavaScript {{glossary("Identifier", "식별자")}} 이름으로 적합하지 않은 속성명이 제공된 경우에도 이용할 수 있습니다. 이 때는 대체할 유효한 식별자명을 제공해야 합니다.

+ +
const foo = { 'fizz-buzz': true };
+const { 'fizz-buzz': fizzBuzz } = foo;
+
+console.log(fizzBuzz); // "true"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +
+
+ + +

{{Compat("javascript.operators.destructuring")}}

+
+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/equality/index.html b/files/ko/web/javascript/reference/operators/equality/index.html new file mode 100644 index 0000000000..5ebe238590 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/equality/index.html @@ -0,0 +1,123 @@ +--- +title: 동등 연산자(==) +slug: Web/JavaScript/Reference/Operators/Equality +translation_of: Web/JavaScript/Reference/Operators/Equality +--- +
{{jsSidebar("Operators")}}
+ +

동등 연산자(==)는 두 개의 피연산자가 동일한지 확인하며, Boolean값을 반환합니다. 일치 연산자(===)와는 다르게 다른 타입의 피연산자들끼리의 비교를 시도합니다. 

+ +
{{EmbedInteractiveExample("pages/js/expressions-equality.html")}}
+ + + +

문법

+ +
x == y
+
+ +

상세 설명

+ +

동등 연산자 (== 와 !=)는 두 피연산자를 비교하기 위해 Abstract Equality Comparison Algorithm를 사용합니다. 다음과 같이 간략히 설명할 수 있습니다:

+ + + +

일치연산자 (===)와의 가장 두드러지는 차이점은 일치 연산자는 타입변환을 시도하지 않는다는 것입니다. 일치 연산자는 다른 타입을 가진 피연산자는 다르다고 판단합니다.

+ +

예시

+ +

타입변환 없이 비교

+ +
1 == 1;              // true
+"hello" == "hello";  // true
+ +

타입변환을 이용한 비교

+ +
"1" ==  1;            // true
+1 == "1";             // true
+0 == false;           // true
+0 == null;            // false
+0 == undefined;       // false
+0 == !!null;          // true, look at Logical NOT operator
+0 == !!undefined;     // true, look at Logical NOT operator
+null == undefined;    // true
+
+const number1 = new Number(3);
+const number2 = new Number(3);
+number1 == 3;         // true
+number1 == number2;   // false
+ +

객체들 간의 비교

+ +
const object1 = {"key": "value"}
+const object2 = {"key": "value"};
+
+object1 == object2 // false
+object2 == object2 // true
+ +

String과 String objects의 비교

+ +

new String() 을 통해 생성된 문자열들은 객체입니다. 이 객체중 하나를 문자열과 비교한다면, String 객체가 문자열로 변환된 후 비교될 것입니다. 그러나 두개의 피연산자 모두 String 객체라면, 객체로써 비교가 이루어지기 때문에 같은 값으로 취급될려면 같은 객체를 참조하고 있어야 합니다:

+ +
const string1 = "hello";
+const string2 = String("hello");
+const string3 = new String("hello");
+const string4 = new String("hello");
+
+console.log(string1 == string2); // true
+console.log(string1 == string3); // true
+console.log(string2 == string3); // true
+console.log(string3 == string4); // false
+console.log(string4 == string4); // true
+ +

Comparing Dates and strings

+ +
const d = new Date('December 17, 1995 03:24:00');
+const s = d.toString(); // for example: "Sun Dec 17 1995 03:24:00 GMT-0800 (Pacific Standard Time)"
+console.log(d == s);    //true
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-equality-operators', 'Equality operators')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.equality")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/expression_closures/index.html b/files/ko/web/javascript/reference/operators/expression_closures/index.html new file mode 100644 index 0000000000..bf44be6cd7 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/expression_closures/index.html @@ -0,0 +1,79 @@ +--- +title: 표현식 클로저 +slug: Web/JavaScript/Reference/Operators/Expression_closures +tags: + - Function + - JavaScript + - Non-standard + - Obsolete + - Operator + - Reference +translation_of: Archive/Web/JavaScript/Expression_closures +--- +
{{JSSidebar("Operators")}}{{Non-standard_Header}}{{Obsolete_Header("gecko60")}} +
Non-standard. Do not use!
+The expression closure syntax is a deprecated Firefox-specific feature and has been removed starting with Firefox 60. For future-facing usages, consider using arrow functions.
+
+ +

클로져는 간단한 함수를 작성하기 위한 짧은 함수구문 입니다.

+ +

Syntax

+ +
function [name]([param1[, param2[, ..., paramN]]])
+   expression
+
+ +

Parameters

+ +
+
name
+
함수의 이름입니다. 익명함수의 경우에는 생략할 수 있습니다. 이름은 함수본문에만 국한됩니다.
+
paramN
+
함수에 전달할 인수의 이름입니다. 함수는 최대 255개의 인수를 가질 수 있습니다.
+
expression
+
함수의 본문을 구성하는 표현식입니다.
+
+ +

Description

+ +

이 추가적인 기능은 람다 표기법과 비슷한 언어를 제공하기위해 간단한 기능을 작성하는데 필요한 단축형일 뿐입니다.

+ +

JavaScript 1.7 and older:

+ +
function(x) { return x * x; }
+ +

JavaScript 1.8:

+ +
function(x) x * x
+ +

이 구문을 사용하면 중괄호나 'return'문을 생략하여 암시적으로 만들 수 있습니다. 코드를 더 짧게 만들 수 있는 것 이외의 이방법으로 얻을 수 있는 추가 이점은 없습니다.

+ +

Examples

+ +

바인딩 이벤트 리스너의 간단한 예제:

+ +
 document.addEventListener('click', function() false, true);
+
+ +

JavaScript 1.6의 일부 배열 함수에 이 표기법을 사용합니다:

+ +
elems.some(function(elem) elem.type == 'text');
+
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.expression_closures")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/function/index.html b/files/ko/web/javascript/reference/operators/function/index.html new file mode 100644 index 0000000000..5f4977bfc7 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/function/index.html @@ -0,0 +1,154 @@ +--- +title: 함수 표현식 +slug: Web/JavaScript/Reference/Operators/function +tags: + - Function + - JavaScript + - Operator + - Primary Expressions +translation_of: Web/JavaScript/Reference/Operators/function +--- +
{{jsSidebar("Operators")}}
+ +

function 키워드는 어떤 표현식(expression) 내에서 함수를 정의하는 데 사용될 수 있습니다.

+ +

또한 Function 생성자와 함수 선언(function declaration)을 이용해 함수를 정의할 수도 있습니다.  

+ +
{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html")}}
+ + + +

구문

+ +
var myFunction = function [name]([param1[, param2[, ..., paramN]]]) { statements };
+ +

ES2015에서 화살표 함수(arrow functions)를 사용할 수도 있습니다.

+ +

매개변수

+ +
+
name
+
함수 이름. 함수가 이름 없는(anonymous) 함수인 경우, 생략될 수 있음. 이 함수 이름은 함수의 몸통 내에서만 사용할 수 있습니다.
+
paramN
+
함수로 전달되는 인수(argument) 의 이름.
+
statements
+
함수 몸통을 구성하는 문(statement).
+
+ +

설명

+ +

함수 표현식(function expression)은 function 문과 매우 비슷하고 구문(syntax)이 거의 같습니다 (자세한 사항은 function 문 참조). 함수 표현식과 function 문 사이의 주요 차이점은 함수 이름으로, 함수 표현식으로 익명 함수를 만들 경우 이 이름을 생략할 수 있습니다. 함수 표현식은 정의하자마자 실행되는  IIFE (즉시 호출되는 함수 표현식)로 사용될 수 있습니다. 더 자세한 정보는 함수 장 참조.

+ +

Function expression 끌어올리기

+ +

자바스크립트에서 함수 표현식은 {{jsxref("Statements/function", "함수 선언", "#Function_declaration_hoisting")}}과는 달리 끌어올려지지 않습니다. 함수 표현식을 정의하기 전에는 사용할 수 없습니다.

+ +
console.log(notHoisted) // undefined
+//even the variable name is hoisted, the definition wasn't. so it's undefined.
+notHoisted(); // TypeError: notHoisted is not a function
+
+var notHoisted = function() {
+   console.log('bar');
+};
+ +

유명(named) 함수 표현식

+ +

함수 몸통 안 쪽에서 현재 함수를 참고하고 싶다면, 유명 함수를 생성해야 합니다. 이 함수 이름은 함수의 몸통(범위) 안에서만 사용할 수 있습니다. 이로써 비표준 arguments.callee 속성을 사용하는 것을 피할 수도 있습니다.

+ +
var math = {
+  'factit': function factorial(n) {
+    console.log(n)
+    if (n <= 1)
+      return 1;
+    return n * factorial(n - 1);
+  }
+};
+
+math.factit(3) //3;2;1;
+
+ +

함수가 할당된 변수는 name 속성을 가지게됩니다. 다른 변수에 할당되더라도 그 name 속성의 값은 변하지 않습니다. 함수의 이름이 생략되었다면, name 속성의 값은 그 변수의 이름(암묵적 이름)이 될 것입니다. 함수의 이름이 있다면 name 속성의 값은 그 함수의 이름(명시적 이름)이 될 것입니다. 이는 화살표 함수(arrow functions)에도 적용됩니다 (화살표 함수는 이름을 가지지 않으므로 해당 변수에 암묵적인 이름만 줄 수 있습니다).

+ +
var foo = function() {}
+foo.name // "foo"
+
+var foo2 = foo
+foo2.name // "foo"
+
+var bar = function baz() {}
+bar.name // "baz"
+
+console.log(foo === foo2); // true
+console.log(typeof baz); // undefined
+console.log(bar === baz); // false (errors because baz == undefined)
+
+ +

 

+ +

Examples

+ +

다음 예제는 이름 없는 함수를 정의하고 그 함수를 x에 할당합니다. 함수는 인수의 제곱을 반환합니다:

+ +
var x = function(y) {
+   return y * y;
+};
+ +

callback으로 더 자주 사용됩니다:

+ +
button.addEventListener('click', function(event) {
+    console.log('button is clicked!')
+})
+ +

 

+ +

 

+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}}초기 정의. JavaScript 1.5에서 구현됨.
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.function")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/operators/function_star_/index.html b/files/ko/web/javascript/reference/operators/function_star_/index.html new file mode 100644 index 0000000000..7187f985bc --- /dev/null +++ b/files/ko/web/javascript/reference/operators/function_star_/index.html @@ -0,0 +1,85 @@ +--- +title: function* expression +slug: Web/JavaScript/Reference/Operators/function* +tags: + - ECMAScript6 + - Function + - Generator + - JavaScript +translation_of: Web/JavaScript/Reference/Operators/function* +--- +
{{jsSidebar("Operators")}}
+ +

function* keyword 는 표현식 내에서 generator function 을 정의합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-functionasteriskexpression.html")}}
+ +

Syntax

+ +
function* [name]([param1[, param2[, ..., paramN]]]) {
+   statements
+}
+ +

Parameters

+ +
+
name
+
함수명. 생략하면, 익명 함수가 됩니다.  함수명은 함수내에만 한정됩니다.
+
paramN
+
함수에 전달되는 인수의 이름. 함수는 최대 255 개의 인수를 가질 수 있습니다.
+
statements
+
함수의 본체를 구성하는 구문들.
+
+ +

Description

+ +

function* expression 은 {{jsxref('Statements/function*', 'function* statement')}} 과 매우 유사하고 형식도 같습니다. function* expression 과 function* statement 의 주요한 차이점은 함수명으로, function* expressions 에서는 익명 함수로 만들기 위해 함수명이 생략될 수 있습니다.보다 자세한 내용은 functions 을 참조하십시오.

+ +

Examples

+ +

아래의 예제는 이름이 없는 generator function 을 정의하고 이를 x 에 할당합니다. function 은 인자로 들어온 값의 제곱을 생산(yield)합니다.

+ +
var x = function*(y) {
+   yield y * y;
+};
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#', 'function*')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'function*')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{Compat("javascript.operators.function_star")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/generator_comprehensions/index.html b/files/ko/web/javascript/reference/operators/generator_comprehensions/index.html new file mode 100644 index 0000000000..927b613dc6 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/generator_comprehensions/index.html @@ -0,0 +1,174 @@ +--- +title: 생성기 내포 +slug: Web/JavaScript/Reference/Operators/Generator_comprehensions +tags: + - JavaScript + - Non-standard + - Obsolete + - Reference +translation_of: Archive/Web/JavaScript/Generator_comprehensions +--- +
{{JSSidebar("Operators")}}{{Non-standard_Header}}{{Obsolete_Header("gecko58")}} +
+

Non-standard. Do not use!
+ The generator comprehensions syntax is non-standard and removed starting with Firefox 58. For future-facing usages, consider using {{JSxRef("Statements/function*", "generator", "", 1)}}.

+
+
+ +

The generator comprehension syntax was a JavaScript expression which allowed you to quickly assemble a new generator function based on an existing iterable object. However, it has been removed from the standard and the Firefox implementation. Do not use it!

+ +

Syntax

+ +
(for (x of iterable) x)
+(for (x of iterable) if (condition) x)
+(for (x of iterable) for (y of iterable) x + y)
+
+ +

Description

+ +

Inside generator comprehensions, these two kinds of components are allowed:

+ + + +

The for-of iteration is always the first component. Multiple for-of iterations or if statements are allowed.

+ +

A significant drawback of {{JSxRef("Operators/Array_comprehensions","array comprehensions","","true")}} is that they cause an entire new array to be constructed in memory. When the input to the comprehension is itself a small array the overhead involved is insignificant — but when the input is a large array or an expensive (or indeed infinite) generator the creation of a new array can be problematic.

+ +

Generators enable lazy computation of sequences, with items calculated on-demand as they are needed. Generator comprehensions are syntactically almost identical to array comprehensions — they use parentheses instead of braces— but instead of building an array they create a generator that can execute lazily. You can think of them as short hand syntax for creating generators.

+ +

Suppose we have an iterator it which iterates over a large sequence of integers. We want to create a new iterator that will iterate over their doubles. An array comprehension would create a full array in memory containing the doubled values:

+ +
var doubles = [for (i in it) i * 2];
+
+ +

A generator comprehension on the other hand would create a new iterator which would create doubled values on demand as they were needed:

+ +
var it2 = (for (i in it) i * 2);
+console.log(it2.next()); // The first value from it, doubled
+console.log(it2.next()); // The second value from it, doubled
+
+ +

When a generator comprehension is used as the argument to a function, the parentheses used for the function call means that the outer parentheses can be omitted:

+ +
var result = doSomething(for (i in it) i * 2);
+
+ +

The significant difference between the two examples being that by using the generator comprehension, you would only have to loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it.

+ +

Examples

+ +

Simple generator comprehensions

+ +
(for (i of [1, 2, 3]) i * i );
+// generator function which yields 1, 4, and 9
+
+[...(for (i of [1, 2, 3]) i * i )];
+// [1, 4, 9]
+
+var abc = ['A', 'B', 'C'];
+(for (letters of abc) letters.toLowerCase());
+// generator function which yields "a", "b", and "c"
+
+ +

Generator comprehensions with if statement

+ +
var years = [1954, 1974, 1990, 2006, 2010, 2014];
+
+(for (year of years) if (year > 2000) year);
+// generator function which yields 2006, 2010, and 2014
+
+(for (year of years) if (year > 2000) if (year < 2010) year);
+// generator function which yields 2006, the same as below:
+
+(for (year of years) if (year > 2000 && year < 2010) year);
+// generator function which yields 2006
+
+ +

Generator comprehensions compared to generator function

+ +

An easy way to understand generator comprehension syntax, is to compare it with the generator function.

+ +

Example 1: Simple generator.

+ +
var numbers = [1, 2, 3];
+
+// Generator function
+(function*() {
+  for (let i of numbers) {
+    yield i * i;
+  }
+})();
+
+// Generator comprehension
+(for (i of numbers) i * i );
+
+// Result: both return a generator which yields [1, 4, 9]
+
+ +

Example 2: Using if in generator.

+ +
var numbers = [1, 2, 3];
+
+// Generator function
+(function*() {
+  for (let i of numbers) {
+    if (i < 3) {
+      yield i * 1;
+    }
+  }
+})();
+
+// Generator comprehension
+(for (i of numbers) if (i < 3) i);
+
+// Result: both return a generator which yields [1, 2]
+ +

Specifications

+ +

Generator comprehensions were initially in the ECMAScript 2015 draft, but got removed in revision 27 (August 2014). Please see older revisions of ES2015 for specification semantics.

+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.generator_comprehensions")}}

+ +

Differences to the older JS1.7/JS1.8 comprehensions

+ +
JS1.7/JS1.8 comprehensions are removed from Gecko 46 ({{bug(1220564)}}).
+ +

Old comprehensions syntax (do not use anymore!):

+ +
(X for (Y in Z))
+(X for each (Y in Z))
+(X for (Y of Z))
+
+ +

Differences:

+ + + +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/grouping/index.html b/files/ko/web/javascript/reference/operators/grouping/index.html new file mode 100644 index 0000000000..a8823ff961 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/grouping/index.html @@ -0,0 +1,92 @@ +--- +title: 그룹 연산자 +slug: Web/JavaScript/Reference/Operators/Grouping +tags: + - JavaScript + - Operator + - Primary Expressions + - Reference +translation_of: Web/JavaScript/Reference/Operators/Grouping +--- +
{{jsSidebar("Operators")}}
+ +

그룹 연산자 ()는 표현식 내에서 평가의 우선순위를 제어합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-groupingoperator.html")}}
+ + + +

구문

+ +
 ( )
+ +

설명

+ +

그룹 연산자는 표현식이나 중첩 표현식 주위를 감싸는 한 쌍의 괄호로 이루어진 연산자로, 감싸인 식이 더 높은 우선순위를 갖도록 일반적인 연산자 우선순위를 재정의합니다. 이름 그대로, 그룹 연산자는 괄호 안의 내용을 묶습니다.

+ +

예제

+ +

다음 예제에서는 곱셈과 나눗셈 이후 덧셈과 뺄셈을 사용하는 일반적인 연산 순서를 그룹 연산자를 사용해 바꿉니다.

+ +
var a = 1;
+var b = 2;
+var c = 3;
+
+// 기본 우선순위
+a + b * c     // 7
+// 이것과 같음
+a + (b * c)   // 7
+
+// 더하기를 곱하기보다 먼저 하도록
+// 우선순위 변경
+(a + b) * c   // 9
+
+// 이것과 같음
+a * c + b * c // 9
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-grouping-operator', 'The Grouping Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-grouping-operator', 'The Grouping Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.1.6', 'The Grouping Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.1.4', 'The Grouping Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.grouping")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/in/index.html b/files/ko/web/javascript/reference/operators/in/index.html new file mode 100644 index 0000000000..dea26b496d --- /dev/null +++ b/files/ko/web/javascript/reference/operators/in/index.html @@ -0,0 +1,188 @@ +--- +title: in 연산자 +slug: Web/JavaScript/Reference/Operators/in +tags: + - JavaScript + - Operator + - Relational Operators + - 관계형 연산자 + - 연산자 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Operators/in +--- +
{{jsSidebar("Operators")}}
+ +

 in 연산자는 명시된 속성이 명시된 객체에 존재하면 true를 반환합니다.

+ +

구문

+ +
속성 in 객체명
+ +

인자

+ +
+
속성
+
속성의 이름이나 배열의 인덱스를 뜻하는 문자열 또는 수 값입니다.
+
+ +
+
객체명
+
객체의 이름입니다.
+
+ +

설명

+ +

 다음 예제들은 in 연산자의 용도를 보여 줍니다.

+ +
// 배열
+var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
+0 in trees         // true를 반환합니다.
+3 in trees         // true를 반환합니다.
+(1 + 2) in trees   // true를 반환합니다. 연산자 우선 순위에 의하여 이 구문의 괄호는 없어도 됩니다.
+6 in trees         // false를 반환합니다.
+"bay" in trees     // false를 반환합니다. 당신은 배열의 내용이 아닌, 인덱스 값을 명시하여야 합니다.
+"length" in trees  // true를 반환합니다. length는 Array(배열) 객체의 속성입니다.
+
+// 미리 정의된 객체
+"PI" in Math       // true를 반환합니다.
+"P" + "I" in Math  // true를 반환합니다.
+
+// 사용자가 정의한 객체
+var myCar = {company: "Lamborghini", model: "Lamborghini Veneno Roadster", year: 2014};
+"company" in myCar // true를 반환합니다.
+"model" in myCar   // true를 반환합니다.
+
+ +

 당신은 반드시 in 연산자의 오른쪽에 객체를 명시하여야 합니다. 예컨대 당신은 String 생성자로 만들어진 문자열을 명시할 수 있지만 문자열 리터럴은 명시할 수 없습니다.

+ +
var color1 = new String("green");
+"length" in color1 // true를 반환합니다.
+
+var color2 = "coral";
+"length" in color2 // color2는 String 객체가 아니기에 오류를 냅니다.
+
+ +

제거되었거나 정의되지 않은 속성에 대하여 in 연산자 사용하기

+ +

 in 연산자는 delete 연산자로 제거된 속성에 대하여 false를 반환합니다.

+ +
var myCar = {company: "Lamborghini", model: "Lamborghini Veneno Roadster", year: 2014};
+delete myCar.company;
+"company" in myCar; // false를 반환합니다.
+
+var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
+delete trees[3];
+3 in trees; // false를 반환합니다.
+
+ +

 만약 당신이 속성을 {{jsxref("Global_Objects/undefined", "undefined")}}로 설정하였는데 그것을 제거하지 않으면, in 연산자는 그 속성에 대하여 true를 반환합니다.

+ +
var myCar = {company: "Lamborghini", model: "Lamborghini Veneno Roadster", year: 2014};
+myCar.company = undefined;
+"company" in myCar; // true를 반환합니다.
+
+ +
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
+trees[3] = undefined;
+3 in trees; // true를 반환합니다.
+
+ +

상속된 속성

+ +

 in 연산자는 프로토타입 체인에 의하여 접근할 수 있는 속성에 대하여 true를 반환합니다.

+ +
"toString" in {}; // true를 반환합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세StatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.7', 'The in Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.7', 'The in Operator')}}{{Spec2('ES3')}}초기의 정의가 담겨 있습니다. JavaScript 1.4에 추가되었습니다.
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
기능ChromeFirefox (Gecko)Internet ExplorerOperaSafari
지원{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
기능AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
지원{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

관련 문서

+ + diff --git a/files/ko/web/javascript/reference/operators/index.html b/files/ko/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..9605b84278 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/index.html @@ -0,0 +1,304 @@ +--- +title: 식 및 연산자 +slug: Web/JavaScript/Reference/Operators +tags: + - JavaScript + - Operators + - Overview + - Reference +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

이 장은 JavaScript의 모든 연산자operator, 식expression 및 키워드를 나열합니다.

+ +

항목별 식 및 연산자

+ +

알파벳순 목록은 왼쪽 사이드바를 보세요.

+ +

기본 식

+ +

기본 키워드 및 JavaScript의 일반 식.

+ +
+
{{JSxRef("Operators/this", "this")}}
+
this 키워드는 실행 문맥의 특별한 속성을 가리킵니다.
+
{{JSxRef("Operators/function", "function")}}
+
function 키워드는 함수를 정의합니다.
+
{{JSxRef("Operators/class", "class")}}
+
class 키워드는 클래스를 정의합니다.
+
{{JSxRef("Operators/function*", "function*")}}
+
function* 키워드는 생성기generator 함수 식을 정의합니다.
+
{{JSxRef("Operators/yield", "yield")}}
+
생성기 함수를 일시정지 및 재개합니다.
+
{{JSxRef("Operators/yield*", "yield*")}}
+
다른 생성기 함수 또는 순회가능 객체로 위임합니다.
+
{{JSxRef("Operators/async_function", "async function")}}
+
async function은 비동기 함수 표현식을 정의합니다.
+
+ +
+
{{JSxRef("Operators/await", "await")}}
+
비동기 함수를 일시 중지했다가 다시 시작하고 promise의 resolution/rejection을 ​​기다립니다.
+
+ +
+
{{JSxRef("Global_Objects/Array", "[]")}}
+
배열 초기자 및 리터럴 구문.
+
{{JSxRef("Operators/Object_initializer", "{}")}}
+
객체 초기자 및 리터럴 구문.
+
{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}
+
정규식 리터럴 구문.
+
{{JSxRef("Operators/Grouping", "( )")}}
+
그룹 연산자.
+
+ +

좌변 식

+ +

좌변값은 할당 대상입니다.

+ +
+
{{JSxRef("Operators/Property_accessors", "Property accessors", "", 1)}}
+
속성 접근자는 객체의 속성 또는 메서드에 대한 접근 방법을 제공합니다.
+ (object.property, object["property"])
+
{{JSxRef("Operators/new", "new")}}
+
new 연산자는 생성자의 인스턴스를 만듭니다.
+
{{JSxRef("Operators/new%2Etarget", "new.target")}}
+
생성자 문맥에서, new.target은 {{jsxref("Operators/new", "new")}}에 의해 호출된 생성자를 말합니다.
+
{{JSxRef("Operators/super", "super")}}
+
super 키워드는 부모 생성자를 호출합니다.
+
{{JSxRef("Operators/Spread_syntax", "...obj")}}
+
전개 연산자는 (함수 호출 시) 매개변수 여럿이나, (배열 리터럴에서) 다수의 요소를 필요로 하는 곳에서 표현식을 확장합니다.
+
+ +

증가 및 감소

+ +

접두/접미 증감 연산자입니다.

+ +
+
{{JSxRef("Operators/Increment", "A++")}}
+
접미 증가 연산자.
+
{{JSxRef("Operators/Decrement", "A--")}}
+
접미 감소 연산자.
+
{{JSxRef("Operators/Increment", "++A")}}
+
접두 증가 연산자.
+
{{JSxRef("Operators/Decrement", "--A")}}
+
접두 감소 연산자.
+
+ +

단항 연산자

+ +

단항 연산은 피연산자가 하나뿐인 연산입니다.

+ +
+
{{JSxRef("Operators/delete", "delete")}}
+
delete 연산자는 객체에서 속성을 지웁니다.
+
{{JSxRef("Operators/void", "void")}}
+
void 연산자는 식의 반환값을 버립니다.
+
{{JSxRef("Operators/typeof", "typeof")}}
+
typeof 연산자는 주어진 객체의 형을 판별합니다.
+
{{JSxRef("Operators/Unary_plus", "+")}}
+
단항 더하기 연산자는 피연산자를 숫자로 변환합니다.
+
{{JSxRef("Operators/Unary_negation", "-")}}
+
단항 부정 연산자는 피연산자를 숫자로 변환한 뒤 부호를 바꿉니다.
+
{{JSxRef("Operators/Bitwise_NOT", "~")}}
+
비트 NOT 연산자.
+
{{JSxRef("Operators/Logical_NOT", "!")}}
+
논리 NOT 연산자.
+
+ +

산술 연산자

+ +

산술 연산자는 피연산자로 숫자 값(리터럴이나 변수)을 취하고 숫자 값 하나를 반환합니다.

+ +
+
{{JSxRef("Operators/Addition", "+")}}
+
덧셈 연산자.
+
{{JSxRef("Operators/Subtraction", "-")}}
+
뺄셈 연산자.
+
{{JSxRef("Operators/Division", "/")}}
+
나눗셈 연산자.
+
{{JSxRef("Operators/Multiplication", "*")}}
+
곱셈 연산자.
+
{{JSxRef("Operators/Remainder", "%")}}
+
나머지 연산자.
+
+ +
+
{{JSxRef("Operators/Exponentiation", "**")}}
+
지수 연산자.
+
+ +

관계 연산자

+ +

비교 연산자는 피연산자를 비교하고, 비교가 참인지 여부를 나타내는 {{jsxref("Boolean")}} 값을 반환합니다.

+ +
+
{{JSxRef("Operators/in", "in")}}
+
in 연산자는 객체에 주어진 속성이 있는지를 결정합니다.
+
{{JSxRef("Operators/instanceof", "instanceof")}}
+
instanceof 연산자는 객체가 다른 객체의 인스턴스인지 판별합니다.
+
{{JSxRef("Operators/Less_than", "<")}}
+
작음 연산자.
+
{{JSxRef("Operators/Greater_than", ">")}}
+
큼 연산자.
+
{{JSxRef("Operators/Less_than_or_equal", "<=")}}
+
작거나 같음 연산자.
+
{{JSxRef("Operators/Greater_than_or_equal", ">=")}}
+
크거나 같음 연산자.
+
+ +
+

참고: => 는 연산자가 아니고, 화살표 함수의 표기법입니다.

+
+ +

같음 연산자

+ +

같음 연산자의 평가 결과는 항상 {{jsxref("Boolean")}} 형으로 비교가 참인지 나타냅니다.

+ +
+
{{JSxRef("Operators/Equality", "==")}}
+
동등 연산자.
+
{{JSxRef("Operators/Inequality", "!=")}}
+
부등 연산자.
+
{{JSxRef("Operators/Strict_equality", "===")}}
+
일치identity 연산자.
+
{{JSxRef("Operators/Strict_inequality", "!==")}}
+
불일치 연산자.
+
+ +

비트 시프트 연산자

+ +

피연산자의 모든 비트를 이동shift하는 연산.

+ +
+
{{JSxRef("Operators/Left_shift", "<<")}}
+
비트 좌로 시프트 연산자.
+
{{JSxRef("Operators/Right_shift", ">>")}}
+
비트 우로 시프트 연산자.
+
{{JSxRef("Operators/Unsigned_right_shift", ">>>")}}
+
비트 부호 없는 우로 시프트 연산자.
+
+ +

이진 비트 연산자

+ +

비트 연산자는 피연산자를 32비트 집합(0과 1)으로 다루고 표준 JavaScript 숫자 값을 반환합니다.

+ +
+
{{JSxRef("Operators/Bitwise_AND", "&")}}
+
비트 AND.
+
{{JSxRef("Operators/Bitwise_OR", "|")}}
+
비트 OR.
+
{{JSxRef("Operators/Bitwise_XOR", "^")}}
+
비트 XOR.
+
+ +

이진 논리 연산자

+ +

논리 연산자는 보통 사용될 때 불리언(논리) 값으로 사용되고, 불리언 값을 반환합니다.

+ +
+
{{JSxRef("Operators/Logical_AND", "&&")}}
+
논리 AND.
+
{{JSxRef("Operators/Logical_OR", "||")}}
+
논리 OR.
+
{{JSxRef("Operators/Nullish_coalescing_operator", "??")}}
+
Nullish 통합 연산자.
+
+ +

조건부(삼항) 연산자

+ +
+
{{JSxRef("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
+
+ +

조건부 연산자는 조건의 논리값에 따라 두 값 중 하나를 반환합니다.

+ +

선택적 연결 연산자

+ +
+
{{JSxRef("Operators/Optional_chaining", "?.")}}
+
+

선택적 연결 연산자는 참조가 nullish (null 또는 undefined) 인 경우 오류를 발생시키는 대신 undefined를 반환합니다.

+
+
+ +

할당 연산자

+ +

할당 연산자는 값을 그 우변 피연산자의 값에 따라 좌변 피연산자에 할당합니다.

+ +
+
{{JSxRef("Operators/Assignment", "=")}}
+
할당 연산자.
+
{{JSxRef("Operators/Multiplication_assignment", "*=")}}
+
곱셈 할당.
+
{{JSxRef("Operators/Exponentiation_assignment", "**=")}}
+
Exponentiation assignment.
+
{{JSxRef("Operators/Division_assignment", "/=")}}
+
나눗셈 할당.
+
{{JSxRef("Operators/Remainder_assignment", "%=")}}
+
나머지 할당.
+
{{JSxRef("Operators/Addition_assignment", "+=")}}
+
덧셈 할당.
+
{{JSxRef("Operators/Subtraction_assignment", "-=")}}
+
뺄셈 할당
+
{{JSxRef("Operators/Left_shift_assignment", "<<=")}}
+
좌로 이동 할당.
+
{{JSxRef("Operators/Right_shift_assignment", ">>=")}}
+
우로 이동 할당.
+
{{JSxRef("Operators/Unsigned_right_shift_assignment", ">>>=")}}
+
부호 없는 우로 이동 할당.
+
{{JSxRef("Operators/Bitwise_AND_assignment", "&=")}}
+
비트 AND 할당.
+
{{JSxRef("Operators/Bitwise_XOR_assignment", "^=")}}
+
비트 XOR 할당.
+
{{JSxRef("Operators/Bitwise_OR_assignment", "|=")}}
+
비트 OR 할당.
+
+ +
+
{{JSxRef("Operators/Logical_AND_assignment", "&&=")}}
+
논리적 AND 할당.
+
{{JSxRef("Operators/Logical_OR_assignment", "||=")}}
+
논리적 OR 할당.
+
{{JSxRef("Operators/Logical_nullish_assignment", "??=")}}
+
논리적 nullish 할당.
+
+ +
+
{{JSxRef("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{JSxRef("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

구조 분해 할당은 배열 또는 객체의 속성을 배열 또는 객체 리터럴과 비슷해 보이는 구문을 사용하여 변수에 할당할 수 있게 합니다.

+
+
+ +

쉼표 연산자

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
쉼표 연산자는 여러 식을 단문으로 평가되게 하고 마지막 식의 결과를 반환합니다.
+
+ +

명세

+ + + + + + + + + + +
명세
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/instanceof/index.html b/files/ko/web/javascript/reference/operators/instanceof/index.html new file mode 100644 index 0000000000..0ac15b7ffe --- /dev/null +++ b/files/ko/web/javascript/reference/operators/instanceof/index.html @@ -0,0 +1,161 @@ +--- +title: instanceof +slug: Web/JavaScript/Reference/Operators/instanceof +tags: + - JavaScript + - Operator + - Reference + - Relational Operators +translation_of: Web/JavaScript/Reference/Operators/instanceof +--- +
{{jsSidebar("Operators")}}
+ +

instanceof 연산자는 생성자의 prototype 속성이 객체의 프로토타입 체인 어딘가 존재하는지 판별합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-instanceof.html")}}
+ + + +

구문

+ +
object instanceof constructor
+ +

매개변수

+ +
+
object
+
판별할 객체.
+
constructor
+
판별 목표 함수.
+
+ +

설명

+ +

instanceof 연산자는 object의 프로토타입 체인에 constructor.prototype이 존재하는지 판별합니다.

+ +
// 생성자 정의
+function C(){}
+function D(){}
+
+var o = new C();
+
+// true, 왜냐하면 Object.getPrototypeOf(o) === C.prototype
+o instanceof C;
+
+// false, 왜냐하면 D.prototype이 o 객체의 프로토타입 체인에 없음
+o instanceof D;
+
+o instanceof Object; // true, 왜냐하면
+C.prototype instanceof Object // true
+
+C.prototype = {};
+var o2 = new C();
+
+o2 instanceof C; // true
+
+// false, 왜냐하면 C.prototype이
+// 더 이상 o의 프로토타입 체인에 없음
+o instanceof C;
+
+D.prototype = new C(); // C를 D의 [[Prototype]] 링크로 추가
+var o3 = new D();
+o3 instanceof D; // true
+o3 instanceof C; // true, 왜냐하면 이제 C.prototype이 o3의 프로토타입 체인에 존재
+
+ +

instanceof 의 값은 생성자 prototype 프로퍼티의 변화에 따라 바뀔수 있으며, Object.setPrototypeOf의 사용함에 따라서도 바뀔 수 있음에 주의하세요. 또한 non-standard의 __proto__ 슈도-프로퍼티도 사용할 수 있도록 만들어 줍니다.

+ +

instanceof 와 multiple context (예. 프레임 또는 창)

+ +

다른 스코프는 다른 실행 환경을 가집니다. 이것은 다른 스코프는 다른 고정된 요소들(다른 전역 오브젝트, 다른 생성자들 등)을 가지고 있음을 의미합니다. 이 사실은 예상치 못한 결과를 가져올 수도 있습니다. 예를 들면, []  instanceof window.frames[0].Arrayfalse를 리턴할 것입니다. 왜냐하면, Array.prototype !== window.frames[0].Array 이며, arrays 는 상위로부터 상속받기 때문입니다. 이것은 처음에는 말이 되지 않을 수도 있습니다. 하지만, 스크립트에서 여러 프레임이나 창을 다루며, 객체를 함수를 통하여 하나의 컨텍스트에서 다른 컨텍스트로 오브젝트를 넘기게 된다면,  이건 충분히 일어날 수 있는 일이며, 아주 큰 이슈가 될 것입니다. 예를 들어, 주어진 오브젝트가 실제로 Array.isArray(myObj)를 사용한 Array인지 안전하게 확인 할 수 있습니다. 

+ +
Mozilla 개발자들을 위한 메모:
+XPCOM instanceof 을 사용하는 코드에서는 특별한 효과를 가집니다. :  obj instanceof xpcomInterface (예. Components.interfaces.nsIFile)가 obj.QueryInterface(xpcomInterface) 호출하고, 만약 QueryInterface 가 성공하면 true 를 리턴합니다. 이 호출의 부가 효과로는 obj 에서 성공적인 instanceof 테스트 후에 xpcomInterface's의 프로퍼티를 사용할 수 있습니다. 스탠다드 JavaScript 전역속성들과는 달리, 테스트 obj instanceof xpcomInterface는 obj가 다른 스코프에 있더라도 작동합니다.
+ +

예제

+ +

String과 Date는 타입 Object이며, 예외적인 경우임을 입증하기

+ +

아래의 코드는 instanceofStringDate 오브젝트도 타입 Object임을 확인하기 위해 사용합니다.(이 오브젝트들은 Object 로부터 파생되었습니다.)

+ +

그러나, 여기서 오브젝트 리터럴 노테이션으로 생성된 오브젝트는 예외적입니다. : 비록 프로토 타입이 정의되지 않았지만, instanceof Object true를 리턴합니다.

+ +
var simpleStr = "This is a simple string";
+var myString  = new String();
+var newStr    = new String("String created with constructor");
+var myDate    = new Date();
+var myObj     = {};
+
+simpleStr instanceof String; // returns false, prototype chain을 확인하고, undefined를 찾는다.
+myString  instanceof String; // returns true
+newStr    instanceof String; // returns true
+myString  instanceof Object; // returns true
+
+myObj instanceof Object;    // returns true, undefined prototype 임에도 불구하고 true.
+({})  instanceof Object;    // returns true, 위의 경우와 동일.
+
+myString instanceof Date;   // returns false
+
+myDate instanceof Date;     // returns true
+myDate instanceof Object;   // returns true
+myDate instanceof String;   // returns false
+
+ +

mycar는 타입 Car와 타입 Object임을 입증하기

+ +

다음의 코드는 Car 오브젝트 타입과 그 오브젝트 타입의 인스턴스 mycar를 생성합니다. instanceof 연산자는 mycar 오브젝트는 타입 Car 와 타입 Object 라는 것은 보여줍니다.

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+var mycar = new Car("Honda", "Accord", 1998);
+var a = mycar instanceof Car;    // returns true
+var b = mycar instanceof Object; // returns true
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES3')}} +

초기 정의. JavaScript 1.4에서 구현됨.

+
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.instanceof")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/new.target/index.html b/files/ko/web/javascript/reference/operators/new.target/index.html new file mode 100644 index 0000000000..9c480c1513 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/new.target/index.html @@ -0,0 +1,93 @@ +--- +title: new.target +slug: Web/JavaScript/Reference/Operators/new.target +tags: + - Classes + - ECMAScript 2015 + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Operators/new.target +--- +
{{JSSidebar("Operators")}}
+ +

new.target 속성(property)은 함수 또는 생성자가 new 연산자를 사용하여 호출됐는지를 감지할 수 있습니다. new 연산자로 인스턴스화된 생성자 및 함수에서, new.target은 생성자 또는 함수 참조를 반환합니다. 일반 함수 호출에서는, new.target은 {{jsxref("undefined")}}입니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-newtarget.html")}}
+ + + +

구문

+ +
new.target
+ +

설명

+ +

new.target 구문은 키워드 "new", 점 및 속성명 "target"으로 구성됩니다. 보통 "new."은 속성 접근을 위한 문맥(context)으로 제공하지만 여기서 "new."은 정말 객체가 아닙니다. 그러나, 생성자 호출에서 new.targetnew에 의해 호출된 생성자를 가리키고 그래서 "new."은 가상 문맥이 됩니다.

+ +

new.target 속성은 모든 함수가 이용할 수 있는 메타 속성입니다. 화살표 함수에서, new.target은 둘러싸는 함수의 new.target을 말합니다.

+ +

+ +

함수 호출에서 new.target

+ +

일반 함수 호출(생성자 함수 호출과는 반대로)에서, new.target은 {{jsxref("undefined")}}입니다. 이는 함수가 생성자로서 new로 호출된 경우를 감지할 수 있습니다.

+ +
function Foo() {
+  if (!new.target) throw "Foo() must be called with new";
+  console.log("Foo instantiated with new");
+}
+
+Foo(); // throws "Foo() must be called with new"
+new Foo(); // logs "Foo instantiated with new"
+
+ +

생성자에서 new.target

+ +

클래스 생성자에서, new.targetnew에 의해 직접 호출된 생성자를 가리킵니다. 이는 그 생성자가 부모 클래스에 있고 자식 생성자로부터 위임받은 경우도 그 경우입니다.

+ +
class A {
+  constructor() {
+    console.log(new.target.name);
+  }
+}
+
+class B extends A { constructor() { super(); } }
+
+var a = new A(); // logs "A"
+var b = new B(); // logs "B"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-built-in-function-objects', 'Built-in Function Objects')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-built-in-function-objects', 'Built-in Function Objects')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.new_target")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/new/index.html b/files/ko/web/javascript/reference/operators/new/index.html new file mode 100644 index 0000000000..a28d21de18 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/new/index.html @@ -0,0 +1,187 @@ +--- +title: new operator +slug: Web/JavaScript/Reference/Operators/new +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/new +--- +
{{jsSidebar("Operators")}}
+ +

new 연산자는 사용자 정의 객체 타입 또는 내장 객체 타입의 인스턴스를 생성한다.

+ +

{{EmbedInteractiveExample("pages/js/expressions-newoperator.html")}}

+ + + +

구문

+ +
new constructor[([arguments])]
+ +

매개변수

+ +
+
constructor
+
객체 인스턴스의 타입을 기술(명세)하는 함수
+
+ +
+
arguments
+
constructor와 함께 호출될 값 목록
+
+ +

설명

+ +

사용자 정의 객체를 생성에는 두 단계가 필요하다:

+ +
    +
  1. 함수를 작성하여 객체 타입을 정의한다.
  2. +
  3. new 연산자로 객체의 인스턴스를 생성한다.
  4. +
+ +

객체의 타입을 정의하기 위해, 객체의 이름과 속성을 명세하는 함수를 만든다. 객체는 그 자체가 또 다른 객체인 속성을 가질 수 있다. 아래의 예를 본다.

+ +

코드 new Foo(...)가 실행될 때 다음과 같은 일이 발생한다:

+ +
    +
  1. Foo.prototype을 상속하는 새로운 객체가 하나 생성된다.
  2. +
  3. 명시된 인자 그리고 새롭게 생성된 객체에 바인드된 this와 함께 생성자 함수 Foo가 호출된다.new Foonew Foo()와 동일하다. 즉 인자가 명시되지 않은 경우, 인자 없이 Foo가 호출된다.
  4. +
  5. 생성자 함수에 의해 리턴된 객체는 전체 new 호출 결과가 된다. 만약 생성자 함수가 명시적으로 객체를 리턴하지 않는 경우, 첫 번째 단계에서 생성된 객체가 대신 사용된다.(일반적으로 생성자는 값을 리턴하지 않는다. 그러나 일반적인 객체 생성을 재정의(override)하기 원한다면 그렇게 하도록 선택할 수 있다.)
  6. +
+ +

언제든 이전에 정의된 객체에 속성을 추가할 수 있다. 예를 들면, car1.color = "black" 구문은 color 속성을 car1에 추가하고 해당 속성에 "black"이란 값을 할당한다. 그러나, 이것이 다른 객체들에게는 영향을 주지 않는다. 동일한 타입의 모든 객체들에게 새로운 속성을 추가하려면, Car 객체 타입의 정의에 이 속성을 추가해야한다.

+ +

Function.prototype 속성을 사용하여 이전에 정의된 객체 타입에 공유 속성을 추가할 수 있다. 이것은 객체 타입의 인스턴스 하나에만 적용되는 것이 아니라 이 함수로 생성하는 모든 객체와 공유하는 속성을 정의한다.

+ +

다음의 코드는 car 타입의 모든 객체에 "original color" 값을 갖는 color 속성을 추가한다. 그리고 car1 객체 인스턴스에서만 이 값을 문자열 "black"으로 덮어쓴다. 더 많은 정보는 prototype을 참조한다.

+ +
function Car() {}
+car1 = new Car();
+car2 = new Car();
+
+console.log(car1.color);    // undefined
+
+Car.prototype.color = "original color";
+console.log(car1.color);    // original color
+
+car1.color = 'black';
+console.log(car1.color);   // black
+
+console.log(car1.__proto__.color) //original color
+console.log(car2.__proto__.color) //original color
+console.log(car1.color)  // black
+console.log(car2.color) // original color
+
+ +

예제

+ +

객체 타입과 객체 인스턴스

+ +

cars를 위한 객체 타입을 생성하기 원한다고 가정해 보자. 이 객체 타입이 car로 불리기 원하고, make, model, 그리고 year 속성을 갖게 하고 싶다. 이렇게 하기 위해서 다음과 같은 함수를 작성할 것이다:

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+
+ +

이제 다음과 같이, mycar로 불리는 객체를 생성할 수 있다:

+ +
var mycar = new Car("Eagle", "Talon TSi", 1993);
+
+ +

이 구문은 mycar 를 생성하고 명시한 값을 속성값으로 설정한다. 그래서 mycar.make의 값은 문자열 "Eagle"이고, mycar.year는 정수 1993이며 나머지도 마찬가지이다.

+ +

new를 호출해서 얼마든지 car 객체를 생성할 수 있다. 예를 들면:

+ +
var kenscar = new Car("Nissan", "300ZX", 1992);
+
+ +

속성 그 자신이 다른 객체인 객체의 속성

+ +

person이라고 불리는 객체를 다음과 같이 정의한다고 가정해보자:

+ +
function Person(name, age, sex) {
+  this.name = name;
+  this.age = age;
+  this.sex = sex;
+}
+
+ +

그리고 다음과 같이 두 개의 person 객체 인스턴스를 새롭게 생성한다:

+ +
var rand = new Person("Rand McNally", 33, "M");
+var ken = new Person("Ken Jones", 39, "M");
+
+ +

그런 다음 owner 속성을 포함하는 car의 정의를 다시 쓸 수 있다. 이 owner 속성은 다음과 같은 person 객체를 취한다:

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+}
+
+ +

새로운 객체의 인스턴스를 생성하기 위해 다음과 같이 사용한다:

+ +
var car1 = new Car("Eagle", "Talon TSi", 1993, rand);
+var car2 = new Car("Nissan", "300ZX", 1992, ken);
+
+ +

새로운 객체를 생성할 때 문자열이나 숫자 값을 넘겨주는 대신에, 위의 구문은 owner를 위한 매개변수로 randken 객체를 넘겨준다. car2의 owner name을 확인해보기 위해서, 다음의 속성에 접근할 수 있다:

+ +
car2.owner.name
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-new-operator', 'The new Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-new-operator', 'The new Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.new")}}

+ +

관련 문서

+ + diff --git a/files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html b/files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html new file mode 100644 index 0000000000..cae74ea29d --- /dev/null +++ b/files/ko/web/javascript/reference/operators/nullish_coalescing_operator/index.html @@ -0,0 +1,161 @@ +--- +title: Nullish coalescing operator +slug: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator +translation_of: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator +--- +

{{JSSidebar("Operators")}}

+ +

널 병합 연산자 (??) 는 왼쪽 피연산자가 {{jsxref("null")}} 또는 {{jsxref("undefined")}}일 때 오른쪽 피연산자를 반환하고, 그렇지 않으면 왼쪽 피연산자를 반환하는 논리 연산자이다.

+ +

논리 연산자 OR (||)와 달리, 왼쪽 피연산자가 null 또는 undefined가 아닌 falsy 값이면 반환된다. 즉, 만약 다른 변수 foo에게 기본 값을 제공하기 위해 ||을 사용 경우, falsy 값( '' 또는 0)을 사용하는 것을 고려했다면 예기치 않는 동작이 발생할 수 있다. 더 많은 예제는 아래를 보자.

+ +
{{EmbedInteractiveExample("pages/js/expressions-nullishcoalescingoperator.html")}}
+ + + +

문법

+ +
leftExpr ?? rightExpr
+
+ +

설명

+ +

널 병합 연산자는 만약 왼쪽 표현식이 {{jsxref("null")}} 또는 {{jsxref("undefined")}}인 경우, 오른쪽 표현식의 결과를 반환한다.

+ +

변수에 기본값 할당

+ +

이전에는 변수에 기본값을 할당하고 싶을 때, 논리 연산자 OR (||)을 사용하는 것이 일반적인 패턴이다:

+ +
let foo;
+...
+//  foo is never assigned any value so it is still undefined
+let someDummyText = foo || 'Hello!';
+ +

그러나 || boolean 논리 연산자 때문에, 왼쪽 피연산자는 boolean으로 강제로 변환되었고 falsy 한 값(0, '', NaN, null, undefined)은 반환되지 않았다. 이 동작은 만약 0, '' or NaN을 유효한 값으로 생각한 경우 예기치 않는 결과를 초래할 수 있다.

+ +
let count;
+let text;
+...
+count = 0;
+text = "";
+...
+let qty = count || 42;
+let message = text || "hi!";
+console.log(qty);     // 42 and not 0
+console.log(message); // "hi!" and not ""
+
+ +

널 병합 연산자는 첫 번째 연산자가 null 또는 undefined로 평가될 때만, 두 번째 피연산자를 반환함으로써 이러한 위험을 피한다:

+ +
let myText = ''; // An empty string (which is also a falsy value)
+
+let notFalsyText = myText || 'Hello world';
+console.log(notFalsyText); // Hello world
+
+let preservingFalsy = myText ?? 'Hi neighborhood';
+console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
+
+ +

단락

+ +

OR과 AND 같은 논리 연산자들과 마찬가지로, 만약 왼쪽이 null 또는 undefined가 아님이 판명되면 오른쪽 표현식은 평가되지 않는다.

+ +
function A() { console.log('A was called'); return undefined;}
+function B() { console.log('B was called'); return false;}
+function C() { console.log('C was called'); return "foo";}
+
+console.log( A() ?? C() );
+// logs "A was called" then "C was called" and then "foo"
+// as A() returned undefined so both expressions are evaluated
+
+console.log( B() ?? C() );
+// logs "B was called" then "false"
+// as B() returned false (and not null or undefined), the right
+// hand side expression was not evaluated
+
+ +

No chaining with AND or OR operators

+ +

AND (&&) 와 OR 연산자 (||)를 ??와 직접적으로 결합하여 사용하는 것은 불가능하다. 이 경우 SyntaxError가 발생된다.

+ +
null || undefined ?? "foo"; // raises a SyntaxError
+true || undefined ?? "foo"; // raises a SyntaxError
+ +

그러나 우선 순위를 명시적으로 나타내기 위해 괄호를 사용하면 가능하다:

+ +
(null || undefined ) ?? "foo"; // returns "foo"
+
+ +

Optional chaining 연산자(?.)와의 관계

+ +

널 병합 연산자는 명확한 값으로 undefined과 null을 처리하고, optional chaining 연산자 (?.)null or undefined일 수 있는 객체의 속성에 접근할 때 유용하다.

+ +
let foo = { someFooProp: "hi" };
+
+console.log(foo.someFooProp?.toUpperCase());  // "HI"
+console.log(foo.someBarProp?.toUpperCase()); // undefined
+
+ +

예제

+ +

이 예제는 기본 값을 제공하지만 null or undefined 이외의 값을 를 유지한다. 

+ +
function getMiscObj(){
+  return {
+    aNullProperty: null,
+    emptyText: "", // this is not falsy
+    someNumber: 42
+  };
+};
+
+const miscObj = getMiscObj();
+
+const newObj = {};
+newObj.propA = miscObj.aNullProperty ?? "default for A";
+newObj.propB = miscObj.emptyText ?? "default for B";
+newObj.propC = miscObj.someNumber ?? 0;
+
+console.log(newObj.propA); // "default for A"
+console.log(newObj.propB); // "" (as the empty string is not null or undefined)
+console.log(newObj.propC); // 42
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
Proposal for the "nullish coalescing" operatorStage 3
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.nullish_coalescing")}}

+ +

구현 진행

+ +

The following table provides a daily implementation status for this feature, because this feature has not yet reached cross-browser stability. The data is generated by running the relevant feature tests in Test262, the standard test suite of JavaScript, in the nightly build, or latest release of each browser's JavaScript engine.

+ +
{{EmbedTest262ReportResultsTable("coalesce-expression")}}
+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/operators/object_initializer/index.html b/files/ko/web/javascript/reference/operators/object_initializer/index.html new file mode 100644 index 0000000000..825c854848 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/object_initializer/index.html @@ -0,0 +1,302 @@ +--- +title: 객체 초기자 +slug: Web/JavaScript/Reference/Operators/Object_initializer +tags: + - ECMAScript 2015 + - ECMAScript6 + - JSON + - JavaScript + - Literal + - Methods + - Object + - Primary Expression + - computed + - mutation + - properties +translation_of: Web/JavaScript/Reference/Operators/Object_initializer +--- +
{{JsSidebar("Operators")}}
+ +

객체는 new Object(), Object.create() 또는 리터럴 표기법 (initializer 표기법)을 사용하여 초기화될 수 있습니다. 객체 초기자(object initializer)는 0개 이상인 객체 속성명 및 관련값 쌍 목록이 콤마로 분리되어 중괄호({})로 묶인 형태입니다.

+ +

{{EmbedInteractiveExample("pages/js/expressions-objectinitializer.html", "taller")}}

+ + + +

구문

+ +
var o = {};
+var o = { a: "foo", b: 42, c: {} };
+
+var a = "foo", b = 42, c = {};
+var o = { a: a, b: b, c: c };
+
+var o = {
+  property: function ([parameters]) {},
+  get property() {},
+  set property(value) {},
+};
+
+ +

ECMAScript 2015의 새로운 표기법

+ +

이 표기법에 대한 지원은 호환성 표를 참조해 주세요. 비지원 환경에서, 이 표기법은 구문 오류로 이어집니다.

+ +
// 단축 속성명 (ES2015)
+let a = "foo", b = 42, c = {}
+let o = { a, b, c }
+
+// 단축 메서드명 (ES2015)
+var o = {
+  property([parameters]) {}
+}
+
+// 계산된 속성명 (ES2015)
+var prop = 'foo'
+var o = {
+  [prop]: 'hey',
+  ['b' + 'ar']: 'there'
+}
+ +

설명

+ +

객체 초기자는 {{jsxref("Object")}}의 초기화를 기술하는 표현식(expression)입니다. 객체는 객체를 설명하는 데 사용되는속성으로 구성됩니다. 객체의 속성값은 {{Glossary("primitive")}} 데이터 형 또는 다른 객체를 포함할 수 있습니다.

+ +

객체 리터럴 표기법 vs JSON

+ +

객체 리터럴 표기법은 JavaScript Object Notation (JSON)과 같지 않습니다. 비슷해 보이지만, 차이가 있습니다:

+ + + +

예제

+ +

객체 생성

+ +

속성이 없는 빈 객체는 다음과 같이 만들 수 있습니다:

+ +
var object = {};
+ +

그러나, 리터럴(literal) 또는 초기자(initializer) 표기법의 이점은, 빠르게 중괄호 내 속성이 있는 객체를 만들 수 있다는 것입니다. 당신은 그저 쉼표로 구분된 키: 값 쌍 목록을 표기합니다.

+ +

다음 코드는 키가 "foo", "age""baz"인 세 속성이 있는 객체를 만듭니다. 이들 키값은 문자열 "bar", 숫자 42 그리고 세 번째 속성은 그 값으로 다른 객체를 갖습니다.

+ +
var object = {
+  foo: "bar",
+  age: 42,
+  baz: { myProp: 12 },
+}
+ +

속성 접근

+ +

일단 객체를 생성하면, 읽거나 바꿀 수 있습니다. 객체 속성은 점 표기법 또는 각괄호 표기법을 사용하여 액세스될 수 있습니다. (자세한 사항은 속성 접근자 참조.)

+ +
object.foo; // "bar"
+object["age"]; // 42
+
+object.foo = "baz";
+
+ +

속성 정의

+ +

우리는 이미 초기자 구문을 사용한 속성 표기법을 배웠습니다. 가끔, 객체 안에 두고 싶은 코드 속 변수가 있습니다. 다음과 같은 코드가 보입니다:

+ +
var a = "foo",
+    b = 42,
+    c = {};
+
+var o = {
+  a: a,
+  b: b,
+  c: c
+};
+ +

ECMAScript 2015의 경우, 똑같은 일을 할 수 있는 더 짧은 표기법이 있습니다:

+ +
var a = "foo",
+    b = 42,
+    c = {};
+
+// 단축 속성명 (ES6)
+var o = { a, b, c }
+
+// 다시 말해서,
+console.log((o.a === {a}.a)) // true
+
+ +

중복된 속성명

+ +

속성이 같은 이름을 쓰는 경우, 두 번째 속성은 첫 번째를 겹쳐씁니다.

+ +
var a = {x: 1, x: 2};
+console.log(a); // {x: 2}
+
+ +

ECMAScript 5 엄격 모드 코드에서, 중복된 속성명은 {{jsxref("SyntaxError")}}로 간주됐습니다. 런타임에 중복을 가능케 하는 속성 계산명 도입으로, ECMAScript 2015는 이 제한을 제거했습니다.

+ +
function haveES6DuplicatePropertySemantics(){
+  "use strict";
+  try {
+    ({ prop: 1, prop: 2 });
+
+    // 오류 미 발생, 중복 속성명은 엄격 모드에서 허용됨
+    return true;
+  } catch (e) {
+    // 오류 발생, 중복은 엄격 모드에서 금지됨
+    return false;
+  }
+}
+ +

메서드 정의

+ +

객체의 속성은 함수getter 또는 setter 메서드를 참조할 수도 있습니다.

+ +
var o = {
+  property: function ([parameters]) {},
+  get property() {},
+  set property(value) {},
+};
+ +

ECMAScript 2015에서는, 단축 표기법을 이용할 수 있습니다, 그래서 키워드 "function"은 더 이상 필요치 않습니다.

+ +
// 단축 메서드 명 (ES6)
+var o = {
+  property([parameters]) {},
+}
+ +

ECMAScript 2015에는 값이 생성기 함수인 속성을 간결하게 정의하는 법도 있습니다:

+ +
var o = {
+  *generator() {
+    ...........
+  }
+};
+ +

ECMAScript 5에서는 다음과 같이 작성할 수 있습니다 (하지만 ES5는 생성기가 없음을 주의하세요):

+ +
var o = {
+  generatorMethod: function* () {
+    ...........
+  }
+};
+ +

메서드에 관한 자세한 사항 및 예는, 메서드 정의 참조.

+ +

계산된 속성명

+ +

ECMAScript 2015를 시작으로, 객체 초기화 구문은 계산된 속성명(computed property name)도 지원합니다. 각괄호 [] 안에 식을 넣을 수 있고, 식이 계산되고 그 결과가 속성명으로 사용됩니다. 이는 이미 속성을 읽고 설정하는 데 사용했을 수 있는 속성 접근자 구문의 각괄호 표기법을 연상시킵니다.  

+ +

이제 당신은 객체 리터럴에서도 같은 구문을 쓸 수 있습니다:

+ +
// 계산된 속성명 (ES6)
+var i = 0;
+var a = {
+  ["foo" + ++i]: i,
+  ["foo" + ++i]: i,
+  ["foo" + ++i]: i
+};
+
+console.log(a.foo1); // 1
+console.log(a.foo2); // 2
+console.log(a.foo3); // 3
+
+var param = 'size';
+var config = {
+  [param]: 12,
+  ["mobile" + param.charAt(0).toUpperCase() + param.slice(1)]: 4
+};
+
+console.log(config); // { size: 12, mobileSize: 4 }
+ +

전개 속성

+ +

ECMASCript의 나머지/전개 속성 제안 (stage 4) 으로 전개(spread) 속성이 객체 리터럴에 추가됩니다. 이 속성은 제공된 객체의 열거 가능한(enumerable) 속성을 새 객체로 복사합니다.

+ +

(prototype을 제외하는) 얕은 복제(Shallow-cloning) 나 객체 합침(merging objects)이 이제{{jsxref("Object.assign()")}} 보다 짧은 문법으로 가능해집니다.

+ +
let obj1 = { foo: 'bar', x: 42 }
+let obj2 = { foo: 'baz', y: 13 }
+
+let clonedObj = { ...obj1 }
+// Object { foo: "bar", x: 42 }
+
+let mergedObj = { ...obj1, ...obj2 }
+// Object { foo: "baz", x: 42, y: 13 }
+ +
+

{{jsxref("Object.assign()")}}는 setters를 작동시키지만, 전개 연산자(spread operator)는 아니라는 걸 주목하세요!

+
+ +

프로토타입 변이

+ +

__proto__: value 또는 "__proto__": value 형태의 속성 정의는 이름이 __proto__인 속성을 만들지 않습니다. 대신, 제공된 값이 객체 또는 null이면, 생성된 객체의 [[Prototype]]을 그 값으로 바꿉니다. (값이 객체나 null이 아니면, 객체는 바뀌지 않습니다.)

+ +
var obj1 = {};
+assert(Object.getPrototypeOf(obj1) === Object.prototype);
+
+var obj2 = { __proto__: null };
+assert(Object.getPrototypeOf(obj2) === null);
+
+var protoObj = {};
+var obj3 = { "__proto__": protoObj };
+assert(Object.getPrototypeOf(obj3) === protoObj);
+
+var obj4 = { __proto__: "not an object or null" };
+assert(Object.getPrototypeOf(obj4) === Object.prototype);
+assert(!obj4.hasOwnProperty("__proto__"));
+
+ +

단일 프로토타입 변이(mutation)만 객체 리터럴에 허용됩니다: 다중 프로토타입 변이는 구문 오류입니다.

+ +

"colon" 표기법을 쓰지 않는 속성 정의는 프로토타입 변이가 아닙니다: 그들은 다른 이름을 사용하는 비슷한 정의와 동일하게 동작하는 속성 정의입니다.

+ +
var __proto__ = "variable";
+
+var obj1 = { __proto__ };
+assert(Object.getPrototypeOf(obj1) === Object.prototype);
+assert(obj1.hasOwnProperty("__proto__"));
+assert(obj1.__proto__ === "variable");
+
+var obj2 = { __proto__() { return "hello"; } };
+assert(obj2.__proto__() === "hello");
+
+var obj3 = { ["__prot" + "o__"]: 17 };
+assert(obj3.__proto__ === 17);
+
+ +

스펙

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-object-initializer', 'Object Initializer')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.object_initializer")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/operators/optional_chaining/index.html b/files/ko/web/javascript/reference/operators/optional_chaining/index.html new file mode 100644 index 0000000000..cdf88c138b --- /dev/null +++ b/files/ko/web/javascript/reference/operators/optional_chaining/index.html @@ -0,0 +1,187 @@ +--- +title: Optional chaining +slug: Web/JavaScript/Reference/Operators/Optional_chaining +translation_of: Web/JavaScript/Reference/Operators/Optional_chaining +--- +
{{JSSidebar("Operators")}}
+ +

{{SeeCompatTable}}

+ +

optional chaining 연산자 ?. 는 체인의 각 참조가 유효한지 명시적으로 검증하지 않고, 연결된 객체 체인 내에 깊숙이 위치한 속성 값을 읽을 수 있다. ?. 연산자는 . 체이닝 연산자와 유사하게 작동하지만, 만약 참조가 {{glossary("nullish")}} ({{JSxRef("null")}} 또는 {{JSxRef("undefined")}})이라면, 에러가 발생하는 것 대신에 표현식의 리턴 값은 undefined로 단락된다. 함수 호출에서 사용될 때, 만약 주어진 함수가 존재하지 않는다면, undefined를 리턴한다.

+ +

이것은 참조가 누락될 가능성이 있는 경우 연결된 속성으로 접근할 때 더 짧고 간단한 표현식이 생성된다. 어떤 속성이 필요한지에 대한 보증이 확실하지 않는 경우 객체의 내용을 탐색하는 동안 도움이 될 수 있다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-optionalchainingoperator.html")}}
+ +
+ + + +

문법

+ +
obj?.prop
+obj?.[expr]
+arr?.[index]
+func?.(args)
+
+ +

설명

+ +

optional chaining 연산자는 참조나 기능이 undefined 또는 null일 수 있을 때 연결된 객체의 값에 접근하는 단순화할 수 있는 방법을 제공한다.

+ +

예를 들어, 중첩된 구조를 가진 객체에서 obj가 있다. optional chaining이 없이 깊이 중첩된 하위 속성을 찾으려면, 다음과 같이 참조를 확인해야 한다:

+ +
let nestedProp = obj.first && obj.first.second;
+ +

obj.first의 값은 obj.first.second의 값에 접근하기 전에 null (그리고 undefined)가 아니라는 점을 검증한다. 이는 만약에 obj.first를 테스트 없이 obj.first.second 에 직접 접근할 때 일어날 수 있는 에러를 방지한다. 

+ +

그러나 optional chaining 연산자(?.)를 사용하여, obj.first.second 에 접근하기 전에 obj.first의 상태에 따라 명시적으로 테스트하거나 단락시키지 않아도 된다:

+ +
let nestedProp = obj.first?.second;
+ +

. 대신에 ?. 연산자를 사용함으로써, 자바스크립트는 obj.first.second에 접근하기 전에 obj.first가 null 또는 undefined가 아니라는 것을 암묵적으로 확인하는 것을 알고 있다. 만약 obj.firstnull 또는 undefined이라면, 그 표현식은 자동으로 단락되어 undefined가 반환된다.

+ +

이는 다음과 같다:

+ +
let nestedProp = ((obj.first === null || obj.first === undefined) ? undefined : obj.first.second);
+ +

함수의 호출과 Optional chaining

+ +

존재하지 않을 수 있는 매서드를 호출할 때, optional chaining을 사용할 수 있다. 예를 들어, 구현 기간이나 사용자 장치에서 사용할 수 없는 기능 때문에 메서드를 사용할 수 없는 API를 사용할 경우,  유용할 수 있다.

+ +

함수 호출과 optional chaining을 사용함으로써 메서드를 찾을 수 없는 경우에 예외를 발생시키는 것 대신에 그 표현식은 자동으로 undefined를 반환한다:

+ +
let result = someInterface.customMethod?.();
+ +
+

메모: 만약 속성에 해당 이름이 있지만 함수가 아니라면, ?.의 사용은 여전히 예외를 발생시킨다. {{JSxRef("TypeError")}} exception (x.y is not a function).

+
+ +

optional callbacks과 event handlers 다루기

+ +

만약 객체에서 destructuring assignment로 callbacks 또는 fetch 메서드를 사용한다면, 그 존재 여부를 테스트하지 않으면 함수로 호출할 수 없는 존재 하지 않는 값을 가질 수 있다. ?.을 사용하면, 다음 추가 테스트를 피할 수 있다:

+ +
// Written as of ES2019
+function doSomething(onContent, onError) {
+  try {
+    // ... do something with the data
+  }
+  catch (err) {
+    if (onError) { // Testing if onError really exists
+      onError(err.message);
+    }
+  }
+}
+
+ +
// Using optional chaining with function calls
+function doSomething(onContent, onError) {
+  try {
+   // ... do something with the data
+  }
+  catch (err) {
+    onError?.(err.message); // no exception if onError is undefined
+  }
+}
+
+ +

표현식에서 Optional chaining

+ +

optional chaining 연산자를 속성에 표현식으로 접근할 때 대괄호 표기법(the bracket notation of the property accessor)을 사용할 수 있다:

+ +
let nestedProp = obj?.['prop' + 'Name'];
+
+ +

Optional chaining으로 배열 항목에 접근하기

+ +
let arrayItem = arr?.[42];
+ +

예제

+ +

기본 예제

+ +

이 예제는 해당 멤버가 없을 때, map에서 멤버 bar의 name의 속성 값을 찾는다. 그러므로 결과는 undefined이다.

+ +
let myMap = new Map();
+myMap.set("foo", {name: "baz", desc: "inga"});
+
+let nameBar = myMap.get("bar")?.name;
+ +

단락 평가

+ +

표현식에서 optional chaining을 사용할 때, 만약 왼쪽에 있는 피연산자가 null or undefined인  경우, 그 표현식은 평가되지 않는다. 예들 들어:

+ +
let potentiallyNullObj = null;
+let x = 0;
+let prop = potentiallyNullObj?.[x++];
+
+console.log(x); // 0  x는 증가하지 않음
+
+ +

optional chaining 연산자 쌓기

+ +

중첩된 구조에서는 optional chaining을 여러 번 사용할 수 있다:

+ +
let customer = {
+  name: "Carl",
+  details: {
+    age: 82,
+    location: "Paradise Falls" // detailed address is unknown
+  }
+};
+let customerCity = customer.details?.address?.city;
+
+// … this also works with optional chaining function call
+let duration = vacations.trip?.getTime?.();
+
+ +

널 병합 연산자와 같이 사용하기

+ +

널 병합 연산자는 optional chaining를 사용한 후에 아무 값도 찾을 수 없을 때 기본 값을 주기 위해 사용될 수 있다:

+ +
let customer = {
+  name: "Carl",
+  details: { age: 82 }
+};
+const customerCity = customer?.city ?? "Unknown city";
+console.log(customerCity); // Unknown city
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
Proposal for the "optional chaining" operatorStage 4
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.operators.optional_chaining")}}

+
+ +

구현 진행

+ +

The following table provides a daily implementation status for this feature, because this feature has not yet reached cross-browser stability. The data is generated by running the relevant feature tests in Test262, the standard test suite of JavaScript, in the nightly build, or latest release of each browser's JavaScript engine.

+ +
{{EmbedTest262ReportResultsTable("optional-chaining")}}
+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/operators/pipeline_operator/index.html b/files/ko/web/javascript/reference/operators/pipeline_operator/index.html new file mode 100644 index 0000000000..42eb62e545 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/pipeline_operator/index.html @@ -0,0 +1,76 @@ +--- +title: 파이프 연산자 +slug: Web/JavaScript/Reference/Operators/Pipeline_operator +tags: + - Experimental + - JavaScript + - Operator +translation_of: Web/JavaScript/Reference/Operators/Pipeline_operator +--- +
{{jsSidebar("Operators")}} {{SeeCompatTable}}
+ +

파이프 연산자(|>)는 실험적 기능(stage 1)으로, 표현식의 값을 함수에 전달합니다. 파이프 연산자를 활용하면 중첩 함수 호출을 좀 더 읽기 좋은 형식으로 작성할 수 있습니다. 결과물은 문법적 설탕syntactic sugar으로, 하나의 인수를 제공하는 함수 호출은 다음 코드처럼 쓸 수 있습니다.

+ +
let url = "%21" |> decodeURI;
+ +

전통적인 구문에서는 아래처럼 호출합니다.

+ +
let url = decodeURI("%21");
+
+ +

구문

+ +
expression |> function
+
+ +

지정한 expression의 값이 function의 유일한 매개변수로 전달됩니다.

+ +

예제

+ +

함수 체이닝

+ +

파이프 연산자를 사용해, 여러 번 중첩된 함수 호출을 읽기 편한 형태로 바꿀 수 있습니다.

+ +
const double = (n) => n * 2;
+const increment = (n) => n + 1;
+
+// 파이프 연산자 없이
+double(increment(double(double(5)))); // 42
+
+// 파이프 연산자 사용
+5 |> double |> double |> increment |> double; // 42
+
+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
Pipeline operator draftStage 1Not part of the ECMAScript specification yet.
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.operators.pipeline")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/property_accessors/index.html b/files/ko/web/javascript/reference/operators/property_accessors/index.html new file mode 100644 index 0000000000..83ae2e0b80 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/property_accessors/index.html @@ -0,0 +1,153 @@ +--- +title: 속성 접근자 +slug: Web/JavaScript/Reference/Operators/Property_Accessors +tags: + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/Property_Accessors +--- +
{{jsSidebar("Operators")}}
+ +

속성 접근자는 점 또는 괄호 표기법으로 객체의 속성에 접근할 수 있도록 해줍니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-propertyaccessors.html")}}
+ + + +

구문

+ +
object.property
+object['property']
+
+ +

설명

+ +

객체는 속성의 이름을 키로 사용하는 연관 배열(다른 이름으로는 맵, 딕셔너리, 해시, 룩업 테이블)로 생각할 수 있습니다. 보통 객체의 속성을 메서드와 구별해서 말하곤 하지만, 서로의 차이는 관례에 불과합니다. 메서드는 호출할 수 있는 속성일 뿐으로, 속성의 값이 {{jsxref("Function")}}을 가리키는 참조라면 그 속성을 메서드라고 합니다.

+ +

속성에 접근하는 법은 점 표기법과 괄호 표기법 두 가지가 있습니다.

+ +

점 표기법

+ +
get = object.property;
+object.property = set;
+
+ +

이 코드에서, property는 유효한 JavaScript {{glossary("identifier", "식별자")}}여야합니다. 따라서 object.$1은 유효하지만 object.1은 아닙니다.

+ +
document.createElement('pre');
+
+ +

여기서는 "createElement"라는 이름을 가진 메서드를 document에서 찾아 호출하고 있습니다.

+ +

소숫점 없는 숫자 리터럴의 메서드를 호출하고 싶으면, 메서드의 접근자 앞에 공백을 한 칸 추가해 점이 소숫점으로 인식되지 않도록 해야 합니다.

+ +
77 .toExponential();
+// or
+77
+.toExponential();
+// or
+(77).toExponential();
+// or
+77..toExponential();
+// or
+77.0.toExponential();
+// because 77. === 77.0, no ambiguity
+
+ +

괄호 표기법

+ +
get = object[property_name];
+object[property_name] = set;
+
+ +

괄호 표기법에서는 property_name으로 문자열이나 {{jsxref("Symbol")}}을 사용할 수 있습니다. 문자열은 유효한 식별자가 아니어도 괜찮습니다. "1foo", "!bar!", 심지어 " "(공백)도 가능합니다.

+ +
document['createElement']('pre');
+
+ +

이 코드는 점 표기법의 예시와 동일합니다.

+ +

괄호 앞에 공백이 올 수도 있습니다.

+ +
document ['createElement']('pre');
+
+ +

속성 이름

+ +

속성의 이름은 문자열이나 {{jsxref("Symbol")}}입니다. 숫자 등의 다른 자료형은 문자열로 변환됩니다.

+ +
var object = {};
+object['1'] = 'value';
+console.log(object[1]);
+
+ +

위 코드의 1'1'로 변환되므로, 출력 결과는 "value"입니다.

+ +
var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
+object[foo] = 'value';
+console.log(object[bar]);
+
+ +

위의 코드 역시 foobar가 같은 문자열(SpiderMonkey JavaScript 엔진에서는 문자열 "['object Object']")로 변환되므로, 출력 결과는 동일하게 "value"입니다.

+ +

메서드 바인딩

+ +

메서드는 해당 메서드의 객체에 바인딩되지 않습니다. 특히 this는 메서드 내에 고정되지 않으므로 this가 항상 현재 메서드를 포함하는 객체를 참조하는건 아닙니다. 대신, this는 함수 호출 방식에 따라 "전달"됩니다. 메서드 바인딩을 참고하세요.

+ +

eval() 주의사항

+ +

JavaScript 초심자로써는 괄호 표기법을 사용할 수 있는 장소에 {{jsxref("eval", "eval()")}}을 남용하기 쉽습니다. 간혹 스크립트에서 다음과 같은 구문을 찾아볼 수 있습니다.

+ +
x = eval('document.forms.form_name.elements.' + strFormControl + '.value');
+
+ +

eval()은 느리고, 가능하다면 최대한 피해야 합니다. 또한, strFormControl은 유효한 식별자여야 하지만, 폼 컨트롤의 ID나 이름은 식별자가 아닐 수도 있습니다. 따라서 괄호 표기법을 대신 사용하는 것이 좋습니다.

+ +
x = document.forms["form_name"].elements[strFormControl].value;
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ESDraft', '#sec-property-accessors', 'Property Accessors')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-property-accessors', 'Property Accessors')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.2.1', 'Property Accessors')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.2.1', 'Property Accessors')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.0에서 구현됨.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.property_accessors")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/remainder/index.html b/files/ko/web/javascript/reference/operators/remainder/index.html new file mode 100644 index 0000000000..beeb0033a3 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/remainder/index.html @@ -0,0 +1,73 @@ +--- +title: 나머지 연산자 (%) +slug: Web/JavaScript/Reference/Operators/Remainder +translation_of: Web/JavaScript/Reference/Operators/Remainder +--- +
{{jsSidebar("Operators")}}
+ +

나머지 연산자(%)는 피제수가 제수에 의해 나누어진 후, 그 나머지를 반환합니다. 항상 피제수의 부호를 따릅니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-remainder.html")}}
+ +
+ + + +

문법

+ +
Operator: var1 % var2
+
+ +

예시

+ +

(+)피제수의 나머지

+ +
 12 % 5  //  2
+ 1 % -2 //  1
+ 1 % 2  //  1
+ 2 % 3  //  2
+5.5 % 2 // 1.5
+
+ +

(-)피제수의 나머지

+ +
-12 % 5 // -2
+-1 % 2  // -1
+-4 % 2  // -0
+ +

NaN의 나머지

+ +
NaN % 2 // NaN
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-multiplicative-operators', 'Remainder operator')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.remainder")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/spread_syntax/index.html b/files/ko/web/javascript/reference/operators/spread_syntax/index.html new file mode 100644 index 0000000000..d2174a53bb --- /dev/null +++ b/files/ko/web/javascript/reference/operators/spread_syntax/index.html @@ -0,0 +1,255 @@ +--- +title: 전개 구문 +slug: Web/JavaScript/Reference/Operators/Spread_syntax +tags: + - ECMAScript 2015 + - Iterator + - JavaScript + - Reference + - Spread + - 전개 연산자 +translation_of: Web/JavaScript/Reference/Operators/Spread_syntax +--- +
{{jsSidebar("Operators")}}
+ +

전개 구문을 사용하면 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 (함수로 호출할 경우) 또는 요소 (배열 리터럴의 경우)로 확장하여, 0개 이상의 키-값의 쌍으로 객체로 확장시킬 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-spreadsyntax.html")}}
+ + + +

구문

+ +

함수 호출:

+ +
myFunction(...iterableObj);
+
+ +

배열 리터럴과 문자열:

+ +
[...iterableObj, '4', 'five', 6];
+ +

객체 리터럴(ECMAScript 2018에서 추가):

+ +
let objClone = { ...obj };
+ +

예제

+ +

함수 호출에서의 전개

+ +

apply() 대체

+ +

일반적으로 배열의 엘리먼트를 함수의 인수로 사용하고자 할 때 {{jsxref( "Function.prototype.apply()")}} 를 사용하였습니다.

+ +
function myFunction(x, y, z) { }
+var args = [0, 1, 2];
+myFunction.apply(null, args);
+ +

전개 구문을 사용해 위 코드는 다음과 같이 작성될 수 있습니다.

+ +
function myFunction(x, y, z) { }
+var args = [0, 1, 2];
+myFunction(...args);
+ +

인수 목록의 모든 인수는 전개 구문을 사용할 수 있으며, 여러번 사용될 수도 있습니다.

+ +
function myFunction(v, w, x, y, z) { }
+var args = [0, 1];
+myFunction(-1, ...args, 2, ...[3]);
+ +

new에 적용

+ +

{{jsxref("Operators/new", "new")}}를 사용해 생성자를 호출 할 때, 배열과 apply (apply[[Call]] 을 하지만 [[Construct]] 는 그렇지 않음) 를 직접 사용하는 것은 불가했습니다. 하지만, 전개 구문 덕분에 배열을 new 와 함께 쉽게 사용될 수 있습니다.

+ +
var dateFields = [1970, 0, 1];  // 1 Jan 1970
+var d = new Date(...dateFields);
+
+ +

전개 구문 없이 파라미터의 배열과 함께 new를 사용하려면, 부분적인 어플리케이션을 통해 간접적으로 해야 합니다.

+ +
function applyAndNew(constructor, args) {
+   function partial () {
+      return constructor.apply(this, args);
+   };
+   if (typeof constructor.prototype === "object") {
+      partial.prototype = Object.create(constructor.prototype);
+   }
+   return partial;
+}
+
+
+function myConstructor () {
+   console.log("arguments.length: " + arguments.length);
+   console.log(arguments);
+   this.prop1="val1";
+   this.prop2="val2";
+};
+
+var myArguments = ["hi", "how", "are", "you", "mr", null];
+var myConstructorWithArguments = applyAndNew(myConstructor, myArguments);
+
+console.log(new myConstructorWithArguments);
+// (internal log of myConstructor):           arguments.length: 6
+// (internal log of myConstructor):           ["hi", "how", "are", "you", "mr", null]
+// (log of "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}
+ +

배열 리터럴에서의 전개

+ +

더 강력한 배열 리터럴

+ +

전개 구문 없이, 이미 존재하는 배열을 일부로 하는 새로운 배열을 생성하기에, 배열 리터럴 문법은 더 이상 충분하지 않으며 {{jsxref("Array.prototype.push", "push()")}}, {{jsxref("Array.prototype.splice", "splice()")}}, {{jsxref("Array.prototype.concat", "concat()")}} 등의 조합을 사용하는 대신 명령형 코드를 사용해야 했습니다. 전개 구문으로 이는 훨씬 더 간결해졌습니다.

+ +
var parts = ['shoulders', 'knees'];
+var lyrics = ['head', ...parts, 'and', 'toes'];
+// ["head", "shoulders", "knees", "and", "toes"]
+
+ +

인수 목록을 위한 spread 처럼, ... 은 배열 리터럴의 어디에서든 사용될 수 있으며 여러번 사용될 수도 있습니다.

+ +

배열 복사

+ +
var arr = [1, 2, 3];
+var arr2 = [...arr]; // arr.slice() 와 유사
+arr2.push(4);
+
+// arr2 은 [1, 2, 3, 4] 이 됨
+// arr 은 영향을 받지 않고 남아 있음
+
+ +
+

참고: Spread 문법은 배열을 복사할 때 1 레벨 깊이에서 효과적으로 동작합니다. 그러므로, 다음 예제와 같이 다차원 배열을 복사하는것에는 적합하지 않을 수 있습니다. ({{jsxref("Object.assign()")}} 과 전개 구문이 동일합니다)

+
+ +
var a = [[1], [2], [3]];
+var b = [...a];
+b.shift().shift(); // 1
+// 이제 배열 a 도 영향을 받음: [[], [2], [3]]
+
+ +

배열을 연결하는 더 나은 방법

+ +

{{jsxref("Array.prototype.concat()")}} 은 배열을 존재하는 배열의 끝에 이어붙이는데 종종 사용됩니다. 전개 구문 없이, 이는 다음과 같이 작성됩니다.

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+// arr2 의 모든 항목을 arr1 에 붙임
+arr1 = arr1.concat(arr2);
+ +

전개 구문을 사용해 이는 다음과 같아집니다.

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+arr1 = [...arr1, ...arr2]; // arr1 은 이제 [0, 1, 2, 3, 4, 5]
+
+ +

{{jsxref("Array.prototype.unshift()")}}는 존재하는 배열의 시작 지점에 배열의 값들을 삽입하는데 종종 사용됩니다. 전개 구문 없이, 이는 다음과 같이 작성됩니다.

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+// arr2 의 모든 항목을 arr1 의 앞에 붙임
+Array.prototype.unshift.apply(arr1, arr2) // arr1 은 이제 [3, 4, 5, 0, 1, 2] 가 됨
+ +

전개 구문으로, 이는 다음과 같아집니다.

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+arr1 = [...arr2, ...arr1]; // arr1 은 이제 [3, 4, 5, 0, 1, 2] 가 됨
+
+ +
+

참고: unshift()와 달리, 위 예제는 새로운 arr1을 만들며 기존 배열을 변형하지 않습니다.

+
+ +

객체 리터럴에서의 전개

+ +

ECMAScript의 Rest/Spread 프로퍼티 제안 (stage 4) 은 객체 리터럴에 속성 전개를 추가합니다. 이는 제공된 객체가 소유한 열거형 프로퍼티를 새로운 객체로 복사합니다.

+ +

얕은 복제(prototype 제외) 또는 객체의 병합은 이제 {{jsxref("Object.assign()")}} 보다 더 짧은 문법을 사용해 가능합니다.

+ +
var obj1 = { foo: 'bar', x: 42 };
+var obj2 = { foo: 'baz', y: 13 };
+
+var clonedObj = { ...obj1 };
+// Object { foo: "bar", x: 42 }
+
+var mergedObj = { ...obj1, ...obj2 };
+// Object { foo: "baz", x: 42, y: 13 }
+ +

{{jsxref("Object.assign()")}} 은 setters 를 트리거하지만 전개 구문은 그렇지 않음을 유의합니다.

+ +

{{jsxref("Object.assign()")}} 함수를 대체하거나 흉내낼 수 없음을 유의합니다.

+ +
var obj1 = { foo: 'bar', x: 42 };
+var obj2 = { foo: 'baz', y: 13 };
+const merge = ( ...objects ) => ( { ...objects } );
+
+var mergedObj = merge ( obj1, obj2);
+// Object { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }
+
+var mergedObj = merge ( {}, obj1, obj2);
+// Object { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }
+ +

위 예제에서, 전개 구문은 예상대로 동작하지 않습니다. 나머지 매개변수로 인해, 인수 배열을 객체 리터럴로 전개합니다.

+ +

이터러블 전용

+ +

전개 구문 (spread 프로퍼티인 경우 제외) 은 iterable 객체에만 적용됩니다.

+ +
var obj = {'key1': 'value1'};
+var array = [...obj]; // TypeError: obj is not iterable
+
+ +

많은 값과 Spread

+ +

함수 호출에서 spread 문법을 사용할 때, 자바스크립트 엔진의 인수 길이 제한을 초과하지 않도록 주의합니다. 자세한 내용은 apply() 를 보세요.

+ +

나머지 구문 (매개변수)

+ +

나머지 구문은 전개 구문과 정확히 같아보이지만, 대신 배열이나 객체를 분해할 때 사용됩니다. 어떤 면에서, 나머지 구문은 전개 구문과 반대입니다. 전개는 배열을 그 엘리먼트로 '확장' 하는 반면, 나머지는 여러 엘리먼트를 수집하며 이를 하나의 엘리먼트로 '압축' 합니다. 나머지 매개변수 문서를 보세요.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('ES2015', '#sec-array-initializer')}}{{Spec2('ES2015')}}명세의 여러 섹션에서 정의 됨: Array Initializer, Argument Lists
{{SpecName('ES2018', '#sec-object-initializer')}}{{Spec2('ES2018')}}Object Initializer 에서 정의됨
{{SpecName('ESDraft', '#sec-array-initializer')}}{{Spec2('ESDraft')}}변동 없음.
{{SpecName('ESDraft', '#sec-object-initializer')}}{{Spec2('ESDraft')}}변동 없음.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.spread")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/super/index.html b/files/ko/web/javascript/reference/operators/super/index.html new file mode 100644 index 0000000000..fbcb123c57 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/super/index.html @@ -0,0 +1,176 @@ +--- +title: super +slug: Web/JavaScript/Reference/Operators/super +tags: + - Classes + - JavaScript + - Left-hand-side expressions + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/super +--- +
{{jsSidebar("Operators")}}
+ +

super 키워드는 부모 오브젝트의 함수를 호출할 때 사용됩니다.

+ +

super.propsuper[expr] 표현식은 클래스 와 객체리터럴의 어떠한 메서드 정의 방법에서도 유효합니다.

+ +

문법

+ +
super([arguments]); // 부모 생성자 호출
+super.functionOnParent([arguments]);
+
+ +

설명

+ +

생성자에서는 super 키워드 하나만 사용되거나 this 키워드가 사용되기 전에 호출되어야 합니다. 또한 super 키워드는 부모 객체의 함수를 호출하는데 사용될 수 있습니다.

+ +

예제

+ +

클래스에서 super 사용하기

+ +

이 예제는 옆의 링크에서 발췌하였습니다. classes sample (live demo).

+ +
class Polygon {
+  constructor(height, width) {
+    this.name = 'Polygon';
+    this.height = height;
+    this.width = width;
+  }
+  sayName() {
+    console.log('Hi, I am a ', this.name + '.');
+  }
+}
+
+class Square extends Polygon {
+  constructor(length) {
+    this.height; // 참조오류가 발생합니다. super가 먼저 호출되어야 합니다.
+
+    // 여기서, 부모클래스의 생성자함수를 호출하여 높이값을 넘겨줍니다.
+    // Polygon의 길이와 높이를 넘겨줍니다.
+    super(length, length);
+
+    // 참고: 파생 클래스에서 super() 함수가 먼저 호출되어야
+    // 'this' 키워드를 사용할 수 있습니다. 그렇지 않을 경우 참조오류가 발생합니다.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.area = value;
+  }
+}
+ +

정적 메서드에서 Super 호출

+ +

static 메서드에서도 super를 호출할 수 있습니다.

+ +
class Human {
+  constructor() {}
+  static ping() {
+    return 'ping';
+  }
+}
+
+class Computer extends Human {
+  constructor() {}
+  static pingpong() {
+    return super.ping() + ' pong';
+  }
+}
+Computer.pingpong(); // 'ping pong'
+
+ +

super의 속성 삭제

+ +

delete 연산자를 사용할 수 없으며 super.prop 또는 super[expr] 표현식을 사용하여 부모 클래스의 속성을 삭제할 경우 {{jsxref("ReferenceError")}} 오류가 발생합니다.

+ +
class Base {
+  constructor() {}
+  foo() {}
+}
+class Derived {
+  constructor() {}
+  delete() {
+    delete super.foo;
+  }
+}
+
+new Derived().delete(); // 참조오류: 'super'완 관련된 삭제가 유효하지 않습니다. 
+ +

Super.prop은 non-writable 속성을 덮어 쓸 수 없습니다

+ +

예를 들어 {{jsxref("Object.defineProperty")}}로 속성을 정의할 때, super의 속성 값을 덮어 쓸 수 없습니다.

+ +
class X {
+  constructor() {
+    Object.defineProperty(this, "prop", {
+      configurable: true,
+      writable: false,
+      value: 1
+    });
+  }
+  f() {
+    super.prop = 2;
+  }
+}
+
+var x = new X();
+x.f();
+console.log(x.prop); // 1
+
+ +

객체 리터럴에서 super.prop 사용하기

+ +

Super는 object initializer / literal 표기법에서 사용할 수 있습니다. 아래의 예제에서, 두개의 객체는 메서드를 정의합니다. 두번째 객체에서, super는  첫번째 객체의 메서드를 호출합니다. 이 예제는 {{jsxref("Object.setPrototypeOf()")}}를 이용하여  obj2 prototype에 obj1을 세팅하여, super가 obj1의 method1을 찾을 수 있도록 합니다.

+ +
var obj1 = {
+  method1() {
+    console.log("method 1");
+  }
+}
+
+var obj2 = {
+  method2() {
+   super.method1();
+  }
+}
+
+Object.setPrototypeOf(obj2, obj1);
+obj2.method2(); // logs "method 1"
+
+ +

명세서

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-super-keyword', 'super')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.super")}}

+ +

참고

+ + diff --git a/files/ko/web/javascript/reference/operators/this/index.html b/files/ko/web/javascript/reference/operators/this/index.html new file mode 100644 index 0000000000..8a2807a5d8 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/this/index.html @@ -0,0 +1,398 @@ +--- +title: this +slug: Web/JavaScript/Reference/Operators/this +tags: + - JavaScript + - Operator + - Primary Expressions + - Reference +translation_of: Web/JavaScript/Reference/Operators/this +--- +
{{jsSidebar("Operators")}}
+ +

JavaScript에서 함수의 this 키워드는 다른 언어와 조금 다르게 동작합니다. 또한 엄격 모드와 비엄격 모드에서도 일부 차이가 있습니다.

+ +

대부분의 경우 this의 값은 함수를 호출한 방법에 의해 결정됩니다. 실행중에는 할당으로 설정할 수 없고 함수를 호출할 때 마다 다를 수 있습니다. ES5는 {{jsxref('Operators/this', "함수를 어떻게 호출했는지 상관하지 않고 this 값을 설정할 수 있는")}} {{jsxref("Function.prototype.bind()", "bind")}} 메서드를 도입했고, ES2015는 스스로의 this 바인딩을 제공하지 않는 화살표 함수를 추가했습니다(이는 렉시컬 컨텍스트안의 this값을 유지합니다).

+ +
{{EmbedInteractiveExample("pages/js/expressions-this.html")}}
+ + + +

구문

+ +
this
+ +

+ +

실행 컨텍스트(global, function 또는 eval)의 프로퍼티는 비엄격 모드에서 항상 객체를 참조하며, 엄격 모드에서는 어떠한 값이든 될 수 있습니다.

+ +

전역 문맥

+ +

전역 실행 문맥global execution context에서 this는 엄격 모드 여부에 관계 없이 전역 객체를 참조합니다.

+ +
// 웹 브라우저에서는 window 객체가 전역 객체
+console.log(this === window); // true
+
+a = 37;
+console.log(window.a); // 37
+
+this.b = "MDN";
+console.log(window.b)  // "MDN"
+console.log(b)         // "MDN"
+ +
+

노트: global {{jsxref("globalThis")}} 프로퍼티를 사용하여 코드가 실행중인 현재 컨텍스트와 관계없이 항상 전역 객체를 얻을 수 있습니다.

+
+ +

함수 문맥

+ +

함수 내부에서 this의 값은 함수를 호출한 방법에 의해 좌우됩니다.

+ +

단순 호출

+ +

다음 예제는 엄격 모드가 아니며 this의 값이 호출에 의해 설정되지 않으므로, 기본값으로 브라우저에서는 {{domxref("Window", "window")}}인 전역 객체를 참조합니다.

+ +
function f1() {
+  return this;
+}
+
+// 브라우저
+f1() === window; // true
+
+// Node.js
+f1() === global; // true
+ +

반면에 엄격 모드에서 this 값은 실행 문맥에 진입하며 설정되는 값을 유지하므로 다음 예시에서 보여지는 것 처럼 thisundefined로 남아있습니다.

+ +
function f2(){
+  "use strict"; // 엄격 모드 참고
+  return this;
+}
+
+f2() === undefined; // true
+
+ +
+

두번째 예제에서 f2를 객체의 메서드나 속성(예: window.f2())으로써가 아닌 직접 호출했기 때문에  this는 {{jsxref("undefined")}}여야 합니다. 그러나 엄격 모드를 처음 지원하기 시작한 초기 브라우저에서는 구현하지 않았고, window 객체를 잘못 반환했습니다.

+
+ +

this의 값을 한 문맥에서 다른 문맥으로 넘기려면 다음 예시와 같이 {{jsxref("Function.prototype.call()", "call()")}}이나 {{jsxref("Function.prototype.apply", "apply()")}}를 사용하세요.

+ +

예시 1

+ +
// call 또는 apply의 첫 번째 인자로 객체가 전달될 수 있으며 this가 그 객체에 묶임
+var obj = {a: 'Custom'};
+
+// 변수를 선언하고 변수에 프로퍼티로 전역 window를 할당
+var a = 'Global';
+
+function whatsThis() {
+  return this.a;  // 함수 호출 방식에 따라 값이 달라짐
+}
+
+whatsThis();          // this는 'Global'. 함수 내에서 설정되지 않았으므로 global/window 객체로 초기값을 설정한다.
+whatsThis.call(obj);  // this는 'Custom'. 함수 내에서 obj로 설정한다.
+whatsThis.apply(obj); // this는 'Custom'. 함수 내에서 obj로 설정한다.
+
+ +

예시 2

+ +
function add(c, d) {
+  return this.a + this.b + c + d;
+}
+
+var o = {a: 1, b: 3};
+
+// 첫 번째 인자는 'this'로 사용할 객체이고,
+// 이어지는 인자들은 함수 호출에서 인수로 전달된다.
+add.call(o, 5, 7); // 16
+
+// 첫 번째 인자는 'this'로 사용할 객체이고,
+// 두 번째 인자는 함수 호출에서 인수로 사용될 멤버들이 위치한 배열이다.
+add.apply(o, [10, 20]); // 34
+
+ +

비엄격 모드에서 this로 전달된 값이 객체가 아닌 경우, callapply는 이를 객체로 변환하기 위한 시도를 합니다. nullundefined 값은 전역 객체가 됩니다. 7이나 'foo'와 같은 원시값은 관련된 생성자를 사용해 객체로 변환되며, 따라서 원시 숫자 7new Number(7)에 의해 객체로 변환되고 문자열 'foo'new String('foo')에 의해 객체로 변환됩니다.

+ +
function bar() {
+  console.log(Object.prototype.toString.call(this));
+}
+
+bar.call(7);     // [object Number]
+bar.call('foo'); // [object String]
+bar.call(undefined); // [object global]
+
+ +

bind 메서드

+ +

ECMAScript 5는 {{jsxref("Function.prototype.bind")}}를 도입했습니다. f.bind(someObject)를 호출하면 f와 같은 본문(코드)과 범위를 가졌지만 this는 원본 함수를 가진 새로운 함수를 생성합니다. 새 함수의 this는 호출 방식과 상관없이 영구적으로bind()의 첫 번째 매개변수로 고정됩니다.

+ +
function f() {
+  return this.a;
+}
+
+var g = f.bind({a: 'azerty'});
+console.log(g()); // azerty
+
+var h = g.bind({a: 'yoo'}); // bind는 한 번만 동작함!
+console.log(h()); // azerty
+
+var o = {a: 37, f: f, g: g, h: h};
+console.log(o.a, o.f(), o.g(), o.h()); // 37, 37, azerty, azerty
+ +

화살표 함수

+ +

화살표 함수에서 this는 자신을 감싼 정적 범위lexical context입니다. 전역 코드에서는 전역 객체를 가리킵니다.

+ +
var globalObject = this;
+var foo = (() => this);
+console.log(foo() === globalObject); // true
+ +
+

참고: 화살표 함수를 call(), bind(), apply()를 사용해 호출할 때 this의 값을 정해주더라도 무시합니다. 사용할 매개변수를 정해주는 건 문제 없지만, 첫 번째 매개변수(thisArg)는 null을 지정해야 합니다.

+
+ +
// 객체로서 메서드 호출
+var obj = {func: foo};
+console.log(obj.func() === globalObject); // true
+
+// call을 사용한 this 설정 시도
+console.log(foo.call(obj) === globalObject); // true
+
+// bind를 사용한 this 설정 시도
+foo = foo.bind(obj);
+console.log(foo() === globalObject); // true
+ +

어떤 방법을 사용하든 foothis는 생성 시점의 것으로 설정됩니다(위 예시에서는 global 객체). 다른 함수 내에서 생성된 화살표 함수에도 동일하게 적용됩니다. this는 싸여진 렉시컬 컨텍스트의 것으로 유지됩니다.

+ +
// this를 반환하는 메소드 bar를 갖는 obj를 생성합니다.
+// 반환된 함수는 화살표 함수로 생성되었으므로,
+// this는 감싸진 함수의 this로 영구적으로 묶입니다.
+// bar의 값은 호출에서 설정될 수 있으며, 이는 반환된 함수의 값을 설정하는 것입니다.
+var obj = {
+  bar: function() {
+    var x = (() => this);
+    return x;
+  }
+};
+
+// obj의 메소드로써 bar를 호출하고, this를 obj로 설정
+// 반환된 함수로의 참조를 fn에 할당
+var fn = obj.bar();
+
+// this 설정 없이 fn을 호출하면,
+// 기본값으로 global 객체 또는 엄격 모드에서는 undefined
+console.log(fn() === obj); // true
+
+// 호출 없이 obj의 메소드를 참조한다면 주의하세요.
+var fn2 = obj.bar;
+// 화살표 함수의 this를 bar 메소드 내부에서 호출하면
+// fn2의 this를 따르므로 window를 반환할것입니다.
+console.log(fn2()() == window); // true
+ +

위 예시에서, obj.bar에 할당된 함수(익명 함수 A라고 지칭)는 화살표 함수로 생성된 다른 함수(익명 함수 B라고 지칭)를 반환합니다. 결과로써 함수 B가 호출될 때 B의 this는 영구적으로 obj.bar(함수 A)의 this로 설정됩니다. 반환됨 함수(함수 B)가 호출될 때, this는 항상 초기에 설정된 값일 것입니다. 위 코드 예시에서, 함수 B의 this는 함수 A의 thisobj로 설정되므로, 일반적으로 thisundefined나 global 객체로 설정하는 방식으로 호출할 때도(또는 이전 예시에서처럼 global 실행 컨텍스트에서 다른 방법을 사용할 때에도) obj의 설정은 유지됩니다.

+ +

객체의 메서드로서

+ +

함수를 어떤 객체의 메서드로 호출하면 this의 값은 그 객체를 사용합니다.

+ +

다음 예제에서 o.f()를 실행할 때 o 객체가 함수 내부의 this와 연결됩니다.

+ +
var o = {
+  prop: 37,
+  f: function() {
+    return this.prop;
+  }
+};
+
+console.log(o.f()); // 37
+
+ +

이 행동이 함수가 정의된 방법이나 위치에 전혀 영향을 받지 않는 것에 유의해라. 이전 예제에서, o 의 정의 중 f 함수를 구성원으로 내부에 정의 하였다.  그러나, 간단하게 함수를 먼저 정의하고 나중에 o.f를 추가할 수 있다. 이렇게 하면 동일한 동작 결과 이다 :

+ +
var o = {prop: 37};
+
+function independent() {
+  return this.prop;
+}
+
+o.f = independent;
+
+console.log(o.f()); // logs 37
+
+ +

이는 함수가 o의 멤버 f로 부터 호출 된 것만이 중요하다는 것을 보여준다.

+ +

마찬가지로, 이 this 바인딩은 가장 즉각으로 멤버 대상에 영향을 받는다. 다음 예제에서, 함수를 실행할 때, 객체 o.b의 메소드 g 로서 호출한다. 이것이 실행되는 동안, 함수 내부의 thiso.b를 나타낸다. 객체는 그 자신이 o의 멤버 중 하나라는 사실은 중요하지 않다. 가장 즉각적인 참조가  중요한 것이다.

+ +
o.b = {g: independent, prop: 42};
+console.log(o.b.g()); // logs 42
+
+ +

객체의 프로토타입 체인에서의 this

+ +

같은 개념으로 객체의 프로토타입 체인 어딘가에 정의한 메서드도 마찬가지입니다. 메서드가 어떤 객체의 프로토타입 체인 위에 존재하면, this의 값은 그 객체가 메서드를 가진 것 마냥 설정됩니다.

+ +
var o = {
+  f:function() { return this.a + this.b; }
+};
+var p = Object.create(o);
+p.a = 1;
+p.b = 4;
+
+console.log(p.f()); // 5
+
+ +

이 예제에서, f 속성을 가지고 있지 않은 변수 p가 할당된 객체는, 프로토타입으로 부터 상속받는다. 그러나 그것은 결국 o에서 f 이름을 가진 멤버를 찾는 되는 문제가 되지 않는다 ; p.f를 찾아 참조하기 시작하므로, 함수 내부의 this p 처럼 나타나는 객체 값을 취한다. 즉, fp의 메소드로서 호출된 이후로, thisp를 나타낸다. 이것은 JavaScript의 프로토타입 상속의 흥미로운 기능이다.

+ +

접근자와 설정자의 this

+ +

다시 한 번 같은 개념으로, 함수를 접근자와 설정자에서 호출하더라도 동일합니다. 접근자나 설정자로 사용하는 함수의 this는 접근하거나 설정하는 속성을 가진 객체로 묶입니다.

+ +
function sum() {
+  return this.a + this.b + this.c;
+}
+
+var o = {
+  a: 1,
+  b: 2,
+  c: 3,
+  get average() {
+    return (this.a + this.b + this.c) / 3;
+  }
+};
+
+Object.defineProperty(o, 'sum', {
+    get: sum, enumerable: true, configurable: true});
+
+console.log(o.average, o.sum); // 2, 6
+
+ +

생성자로서

+ +

함수를 {{jsxref("Operators/new", "new")}} 키워드와 함께 생성자로 사용하면 this는 새로 생긴 객체에 묶입니다.

+ +
+

While the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn't an object, then the this object is returned).

+
+ +
/*
+ * Constructors work like this:
+ *
+ * function MyConstructor(){
+ *   // Actual function body code goes here.
+ *   // Create properties on |this| as
+ *   // desired by assigning to them.  E.g.,
+ *   this.fum = "nom";
+ *   // et cetera...
+ *
+ *   // If the function has a return statement that
+ *   // returns an object, that object will be the
+ *   // result of the |new| expression.  Otherwise,
+ *   // the result of the expression is the object
+ *   // currently bound to |this|
+ *   // (i.e., the common case most usually seen).
+ * }
+ */
+
+function C() {
+  this.a = 37;
+}
+
+var o = new C();
+console.log(o.a); // 37
+
+
+function C2() {
+  this.a = 37;
+  return {a: 38};
+}
+
+o = new C2();
+console.log(o.a); // 38
+
+ +

DOM 이벤트 처리기로서

+ +

함수를 이벤트 처리기로 사용하면 this는 이벤트를 발사한 요소로 설정됩니다. 일부 브라우저는 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} 외의 다른 방법으로 추가한 처리기에 대해선 이 규칙을 따르지 않습니다.

+ +
// 처리기로 호출하면 관련 객체를 파랗게 만듦
+function bluify(e) {
+  // 언제나 true
+  console.log(this === e.currentTarget);
+  // currentTarget과 target이 같은 객체면 true
+  console.log(this === e.target);
+  this.style.backgroundColor = '#A5D9F3';
+}
+
+// 문서 내 모든 요소의 목록
+var elements = document.getElementsByTagName('*');
+
+// 어떤 요소를 클릭하면 파랗게 변하도록
+// bluify를 클릭 처리기로 등록
+for (var i = 0; i < elements.length; i++) {
+  elements[i].addEventListener('click', bluify, false);
+}
+ +

인라인 이벤트 핸들러에서

+ +

코드를 인라인 이벤트 처리기로 사용하면 this는 처리기를 배치한 DOM 요소로 설정됩니다.

+ +
<button onclick="alert(this.tagName.toLowerCase());">
+  this 표시
+</button>
+ +

위의 경고창은 button을 보여줍니다. 다만 바깥쪽 코드만 this를 이런 방식으로 설정합니다.

+ +
<button onclick="alert((function() { return this; })());">
+  내부 this 표시
+</button>
+ +

위의 경우, 내부 함수의 this는 정해지지 않았으므로 전역/window 객체를 반환합니다. 즉 비엄격 모드에서 this를 설정하지 않은 경우의 기본값입니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ES2015')}}
{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.this")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/typeof/index.html b/files/ko/web/javascript/reference/operators/typeof/index.html new file mode 100644 index 0000000000..acdd2eedbb --- /dev/null +++ b/files/ko/web/javascript/reference/operators/typeof/index.html @@ -0,0 +1,227 @@ +--- +title: typeof +slug: Web/JavaScript/Reference/Operators/typeof +tags: + - JavaScript + - Operator + - Reference + - Unary +translation_of: Web/JavaScript/Reference/Operators/typeof +--- +
{{jsSidebar("Operators")}}
+ +

typeof 연산자는 피연산자의 평가 전 자료형을 나타내는 문자열을 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}
+ + + +

구문

+ +

typeof 연산자는 피연산자 앞에 위치합니다.

+ +
typeof operand
+typeof(operand)
+ +

매개변수

+ +
+
operand
+
자료형을 가져올 객체 또는 {{glossary("Primitive", "원시값")}}을 나타내는 표현식.
+
+ +

설명

+ +

typeof가 반환할 수 있는 값을 아래 표에서 볼 수 있습니다. 자료형과 원시값에 대한 자세한 정보는 JavaScript 자료형과 자료구조 페이지를 참고하세요.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeResult
{{glossary("Undefined")}}"undefined"
{{glossary("Null")}}"object" ({{anch("null", "아래")}} 참고)
{{glossary("Boolean")}}"boolean"
{{glossary("Number")}}"number"
{{glossary("BigInt")}}"bigint"
{{glossary("String")}}"string"
{{glossary("Symbol")}} (ECMAScript 2015에서 추가)"symbol"
호스트 객체 (JS 환경에서 제공)구현체마다 다름
{{glossary("Function")}} 객체 (ECMA-262 표현으로는 [[Call]]을 구현하는 객체)"function"
다른 모든 객체"object"
+ +
+

Note: ECMAScript 2019 and older permitted implementations to have typeof return any implementation-defined string value for non-callable non-standard exotic objects.

+ +

The only known browser to have actually taken advantage of this is old Internet Explorer (see below).

+
+ +

예제

+ +
// Numbers
+typeof 37 === 'number';
+typeof 3.14 === 'number';
+typeof Math.LN2 === 'number';
+typeof Infinity === 'number';
+typeof NaN === 'number'; // Despite being "Not-A-Number"
+typeof Number(1) === 'number'; // but never use this form!
+
+typeof 42n === 'bigint';
+
+
+// Strings
+typeof "" === 'string';
+typeof "bla" === 'string';
+typeof (typeof 1) === 'string'; // typeof always returns a string
+typeof String("abc") === 'string'; // but never use this form!
+
+
+// Booleans
+typeof true === 'boolean';
+typeof false === 'boolean';
+typeof Boolean(true) === 'boolean'; // but never use this form!
+
+
+// Symbols
+typeof Symbol() === 'symbol'
+typeof Symbol('foo') === 'symbol'
+typeof Symbol.iterator === 'symbol'
+
+
+// Undefined
+typeof undefined === 'undefined';
+typeof declaredButUndefinedVariable === 'undefined';
+typeof undeclaredVariable === 'undefined';
+
+
+// Objects
+typeof {a:1} === 'object';
+
+// use Array.isArray or Object.prototype.toString.call
+// to differentiate regular objects from arrays
+typeof [1, 2, 4] === 'object';
+
+typeof new Date() === 'object';
+
+
+// The following is confusing. Don't use!
+typeof new Boolean(true) === 'object';
+typeof new Number(1) === 'object';
+typeof new String("abc") === 'object';
+
+
+// Functions
+typeof function(){} === 'function';
+typeof class C {} === 'function';
+typeof Math.sin === 'function';
+
+ +

추가 정보

+ +

null

+ +
// This stands since the beginning of JavaScript
+typeof null === 'object';
+
+ +

자바스크립트를 처음 구현할 때, 자바스크립트 값은 타입 태그와 값으로 표시되었습니다. 객체의 타입 태그는 0이었습니다. null은 Null pointer(대부분의 플랫폼에서 0x00)로 표시되었습니다. 그 결과 null은 타입 태그로 0을 가지며, 따라서 typeof는 object를 반환합니다. (참고 문서)

+ +

ECMAScript에 수정이 제안(opt-in을 통해)되었으나 거절되었습니다. 제안된 것은 다음과 같습니다. typeof null === 'null'.

+ +

Regular expressions

+ +

Callable regular expressions were a non-standard addition in some browsers.

+ +
typeof /s/ === 'function'; // Chrome 1-12 Non-conform to ECMAScript 5.1
+typeof /s/ === 'object';   // Firefox 5+  Conform to ECMAScript 5.1
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.typeof")}}

+ +

IE 참고사항

+ +

On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:

+ +
typeof alert === 'object'
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/void/index.html b/files/ko/web/javascript/reference/operators/void/index.html new file mode 100644 index 0000000000..79fe2c1837 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/void/index.html @@ -0,0 +1,122 @@ +--- +title: void +slug: Web/JavaScript/Reference/Operators/void +tags: + - JavaScript + - Operator + - Reference + - Unary +translation_of: Web/JavaScript/Reference/Operators/void +--- +
{{jsSidebar("Operators")}}
+ +

void 연산자는 주어진 표현식을 평가하고 {{jsxref("undefined")}}를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-voidoperator.html")}}
+ + + +

구문

+ +
void expression
+ +

설명

+ +

void는 값을 생성하는 표현식을 평가해서 {{jsxref("undefined")}}를 반환합니다.

+ +

오직 undefined 원시값을 얻기 위해 void 0 또는 void(0)처럼 사용하는 경우도 볼 수 있습니다. 이런 경우 전역 {{jsxref("undefined")}}를 대신 사용해도 됩니다.

+ +

void 연산자의 우선순위도 유념해야 합니다. 그룹 연산자(괄호)를 사용하면 void 연산자를 사용한 식의 평가 과정을 더 명확하게 보일 수 있습니다.

+ +
void 2 == '2'; // undefined == '2', false
+void (2 == '2'); // void true, undefined
+
+ +

IIFE

+ +

즉시 실행 함수 표현식({{Glossary("IIFE")}})을 사용할 때 void를 사용하면 function 키워드를 선언문이 아니라 표현식처럼 간주하도록 강제할 수 있습니다.

+ +
void function iife() {
+    var bar = function () {};
+    var baz = function () {};
+    var foo = function () {
+        bar();
+        baz();
+     };
+    var biz = function () {};
+
+    foo();
+    biz();
+}();
+
+ +

JavaScript URI

+ +

javascript:로 시작하는 URI를 지원하는 브라우저에서는, URI에 있는 코드의 평가 결과가 {{jsxref("undefined")}}가 아니라면 페이지의 콘텐츠를 반환 값으로 대체합니다. void 연산자를 사용하면 undefined를 반환할 수 있습니다. 다음 예제를 확인하세요.

+ +
<a href="javascript:void(0);">
+  클릭해도 아무 일도 없음
+</a>
+<a href="javascript:void(document.body.style.backgroundColor='green');">
+  클릭하면 배경색이 녹색으로
+</a>
+
+ +
+

참고: javascript: 의사 프로토콜보다 이벤트 처리기와 같은 대체재 사용을 권장합니다.

+
+ +

새지 않는 화살표 함수

+ +

Arrow functions introduce a short-hand braceless syntax that returns an expression. This can cause unintended side effects by returning the result of a function call that previously returned nothing. To be safe, when the return value of a function is not intended to be used, it can be passed to the void operator to ensure that (for example) changing APIs do not cause arrow functions' behaviors to change.

+ +
button.onclick = () => void doSomething();
+ +

This ensures the return value of doSomething changing from undefined to true will not change the behavior of this code.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-void-operator', 'The void Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-void-operator', 'The void Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.4.2', 'The void Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.4.2', 'The void Operator')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.4.2', 'The void Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1
+ +

브라우저 호환성

+ +

{{Compat("javascript.operators.void")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/operators/yield/index.html b/files/ko/web/javascript/reference/operators/yield/index.html new file mode 100644 index 0000000000..ef884816d2 --- /dev/null +++ b/files/ko/web/javascript/reference/operators/yield/index.html @@ -0,0 +1,182 @@ +--- +title: yield +slug: Web/JavaScript/Reference/Operators/yield +tags: + - ECMAScript 2015 + - Generators + - Iterator + - JavaScript + - Operator + - 반복자 + - 생성기 +translation_of: Web/JavaScript/Reference/Operators/yield +--- +
{{jsSidebar("Operators")}}
+ +

yield 키워드는 제너레이터 함수 ({{jsxref("Statements/function*", "function*")}} 또는  레거시 generator 함수)를 중지하거나 재개하는데 사용됩니다.

+ +

문법

+ +
[rv] = yield [expression];
+ +
+
expression
+
제너레이터 함수에서 제너레이터 프로토콜을 통해 반환할 값을 정의합니다.  값이 생략되면, undefined를 반환합니다.
+
rv
+
+

제너레이터 실행을 재개 하기 위해서, optional value을 제너레이터의 next() 메서드로 전달하여 반환합니다.

+
+
+ +

설명

+ +

yield 키워드는 제너레이터 함수의 실행을 중지시키거나 그리고  yield 키워드 뒤에오는 표현식[expression]의 값은 제너레이터의 caller로 반환된다. 제너레이터 버전의 return 키워드로 생각 할 수 있다.

+ +

yield 키워드는 실질적으로  value 와 done 이라는 두 개의 속성을 가진 IteratorResult 객체를 반환한다. value 속성은 yield 표현(expression)의 실행 결과를 나타내고, done 속성은 제너레이터 함수가 완전히 종료되었는지 여부를 불린(Boolean) 형태로 보여줍니다. 

+ +

yield 표현식에서 중지되면 ,제너레이터의 next()가 메서드가 호출될 때까지 제너레이터의 코드 실행이 중지된다. 제너레이터의 next()메서드를 호출할 때마다 제너레이터는 실행을 재개하며 그리고 다음의 같은 경우에 진행될 때 실행된다:

+ + + +

만약에 optional value가 제너레이터의 next() 메서드로 전달되면, optional value는  제너레이터의 현재 yield의 연산으로 반환되는 값이 된다.

+ +

generator 코드 경로, yield연산자, {{jsxref("Generator.prototype.next()")}}에 이르기까지 새로운 시작 값을 지정할 수 있는 능력과 제네레이터는 커다란 힘과 제어를 제공한다.

+ +

예시

+ +

다음 코드는 제너레이터 함수의 선언의 예시이다.

+ +
function* foo(){
+  var index = 0;
+  while (index <= 2) // when index reaches 3,
+                     // yield's done will be true
+                     // and its value will be undefined;
+    yield index++;
+}
+ +

제너레이터 함수가 정의되면 , 아래 코드와 보여지는 것처럼 iterator로 만들어 사용할 수 있다.

+ +
var iterator = foo();
+console.log(iterator.next()); // { value: 0, done: false }
+console.log(iterator.next()); // { value: 1, done: false }
+console.log(iterator.next()); // { value: 2, done: false }
+console.log(iterator.next()); // { value: undefined, done: true }
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#', 'Yield')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#', 'Yield')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
IteratorResult object instead of throwing{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}{{ CompatUnknown}}{{CompatUnknown}}
IteratorResult object instead of throwing{{CompatUnknown}}{{CompatGeckoMobile("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Firefox-specific notes

+ + + +

See also

+ + diff --git a/files/ko/web/javascript/reference/operators/yield_star_/index.html b/files/ko/web/javascript/reference/operators/yield_star_/index.html new file mode 100644 index 0000000000..3bbb10146d --- /dev/null +++ b/files/ko/web/javascript/reference/operators/yield_star_/index.html @@ -0,0 +1,164 @@ +--- +title: yield* +slug: Web/JavaScript/Reference/Operators/yield* +tags: + - ECMAScript 2015 + - Generators + - Iterable + - Iterator + - JavaScript + - Operator + - Reference +translation_of: Web/JavaScript/Reference/Operators/yield* +--- +
{{jsSidebar("Operators")}}
+ +

yield* 표현식은 다른 {{jsxref("Statements/function*", "generator")}} 또는 이터러블(iterable) 객체에 yield를 위임할 때 사용됩니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-yieldasterisk.html")}}
+ + + +

구문

+ +
yield* [[expression]];
+ +
+
expression
+
이터러블(iterable) 객체를 반환하는 표현식.
+
+ +

설명

+ +

yield* 표현은 피연산자를 반복하고 반환되는 값을 yield합니다.

+ +

yield* 표현 자체의 값은 반복자(iterator)가 종료될 때 반환되는 값입니다. (i.e., done이 true일 때)

+ +

예제

+ +

다른 생성기(generator)에 위임하기

+ +

다음 코드는, next() 호출을 통해 g1()으로부터 yield 되는 값을 g2()에서 yield 되는 것처럼 만듭니다.

+ +
function* g1() {
+  yield 2;
+  yield 3;
+  yield 4;
+}
+
+function* g2() {
+  yield 1;
+  yield* g1();
+  yield 5;
+}
+
+var iterator = g2();
+
+console.log(iterator.next()); // { value: 1, done: false }
+console.log(iterator.next()); // { value: 2, done: false }
+console.log(iterator.next()); // { value: 3, done: false }
+console.log(iterator.next()); // { value: 4, done: false }
+console.log(iterator.next()); // { value: 5, done: false }
+console.log(iterator.next()); // { value: undefined, done: true }
+
+ +

다른 이터러블(iterable) 객체

+ +

생성기 객체 말고도, yield*는 다른 반복 가능한 객체도 yield 할 수 있습니다. e.g. 배열, 문자열 또는 arguments 객체

+ +
function* g3() {
+  yield* [1, 2];
+  yield* "34";
+  yield* Array.from(arguments);
+}
+
+var iterator = g3(5, 6);
+
+console.log(iterator.next()); // { value: 1, done: false }
+console.log(iterator.next()); // { value: 2, done: false }
+console.log(iterator.next()); // { value: "3", done: false }
+console.log(iterator.next()); // { value: "4", done: false }
+console.log(iterator.next()); // { value: 5, done: false }
+console.log(iterator.next()); // { value: 6, done: false }
+console.log(iterator.next()); // { value: undefined, done: true }
+
+ +

yield* 표현 자체의 값

+ +

yield* 는 구문이 아닌 표현입니다. 따라서 값으로 평가됩니다.

+ +
function* g4() {
+  yield* [1, 2, 3];
+  return "foo";
+}
+
+var result;
+
+function* g5() {
+  result = yield* g4();
+}
+
+var iterator = g5();
+
+console.log(iterator.next()); // { value: 1, done: false }
+console.log(iterator.next()); // { value: 2, done: false }
+console.log(iterator.next()); // { value: 3, done: false }
+console.log(iterator.next()); // { value: undefined, done: true },
+                              // g4() 는 여기서 { value: "foo", done: true }를 반환합니다
+
+console.log(result);          // "foo"
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator-function-definitions-runtime-semantics-evaluation', 'Yield')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator-function-definitions-runtime-semantics-evaluation', 'Yield')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.yield_star")}}

+ +

Firefox에 한정된 내용

+ + + +

같이 보기

+ + diff --git "a/files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" "b/files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" new file mode 100644 index 0000000000..2e1140eed5 --- /dev/null +++ "b/files/ko/web/javascript/reference/operators/\353\205\274\353\246\254_\354\227\260\354\202\260\354\236\220(logical_operators)/index.html" @@ -0,0 +1,249 @@ +--- +title: 논리 연산자 +slug: Web/JavaScript/Reference/Operators/논리_연산자(Logical_Operators) +tags: + - JavaScript + - Logic + - Not + - Operator + - Reference + - and + - or + - 논리 +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

논리 연산자는 보통 {{jsxref("Boolean")}}(논리적) 값과 함께 쓰이며, 불리언 값을 반환합니다. 그런데, &&|| 연산자는 사실 피연산자 중 하나의 값을 반환합니다. 그러므로 불리언 외의 다른 값과 함께 사용하면 불리언 값이 아닌 것을 반환할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-logicaloperator.html")}}
+ + + +

설명

+ +

다음 표는 논리 연산자의 종류입니다. (expr은 불리언을 포함해서 아무 자료형이나 가능합니다)

+ + + + + + + + + + + + + + + + + + + + + + + + +
연산자구문설명
논리 AND (&&)expr1 && expr2expr1true로 변환할 수 있는 경우 expr2을 반환하고, 그렇지 않으면 expr1을 반환합니다.
논리 OR (||)expr1 || expr2 +

expr1true로 변환할 수 있으면 expr1을 반환하고, 그렇지 않으면 expr2를 반환합니다.

+
논리 NOT (!)!expr단일 피연산자를 true로 변환할 수 있으면 false를 반환합니다. 그렇지 않으면 true를 반환합니다.
+ +

값을 true로 변환하면 값이 {{Glossary("truthy", "참")}}인 것입니다.
+ 값을 false로 변환할 수 있으면 값이 {{Glossary("falsy", "거짓")}}인 것입니다.

+ +

거짓으로 변환할 수 있는 표현의 예는 다음과 같습니다.

+ + + +

&& 연산자와 || 연산자를 불리언 값이 아닌 피연산자와 함께 사용될 수 있지만, 반환 값을 항상 불리언 원시값으로 변환할 수 있으므로 불리언 연산자로 생각할 수 있습니다. 반환 값을 직접 불리언으로 바꾸려면 {{jsxref("Boolean")}} 함수나 이중 부정 연산자를 사용하세요.

+ +

단락 평가

+ +

논리 표현식을 좌측부터 평가하므로, 아래 규칙에 따라 단락(short-circuit) 평가를 수행합니다.

+ + + +

"단락"이란, 위 규칙에서 expr을 평가하지 않는다는 뜻입니다. 따라서 평가 중 발생해야 할 부작용(예: expr이 함수 호출이면 절대 호출하지 않음)도 나타나지 않습니다. 단락 평가가 발생하는 원인은 첫 번째 피연산자를 평가한 순간 이미 연산자의 결과가 정해지기 때문입니다. 다음 예제를 살펴보세요.

+ +
function A(){ console.log('A 호출'); return false; }
+function B(){ console.log('B 호출'); return true; }
+
+console.log( A() && B() );
+// 함수 호출로 인해 콘솔에 "A 호출" 기록
+// 그 후 연산자의 결과값인 "false" 기록
+
+console.log( B() || A() );
+// 함수 호출로 인해 콘솔에 "B 호출" 기록
+// 그 후 연산자의 결과인 "true" 기록
+
+ +

연산자 우선순위

+ +

다음 두 식은 똑같아 보이지만, && 연산자는 || 이전에 실행되므로 서로 다릅니다. 연산자 우선순위를 참고하세요.

+ +
true || false && false      // returns true, because && is executed first
+(true || false) && false    // returns false, because operator precedence cannot apply
+ +

논리 AND (&&)

+ +

다음은 &&(논리 AND) 연산자의 예제입니다.

+ +
a1 = true  && true       // t && t returns true
+a2 = true  && false      // t && f returns false
+a3 = false && true       // f && t returns false
+a4 = false && (3 == 4)   // f && f returns false
+a5 = 'Cat' && 'Dog'      // t && t returns "Dog"
+a6 = false && 'Cat'      // f && t returns false
+a7 = 'Cat' && false      // t && f returns false
+a8 = ''    && false      // f && f returns ""
+a9 = false && ''         // f && f returns false
+ +

논리 OR (||)

+ +

다음은 ||(논리 OR) 연산자의 예제입니다.

+ +
o1 = true  || true       // t || t returns true
+o2 = false || true       // f || t returns true
+o3 = true  || false      // t || f returns true
+o4 = false || (3 == 4)   // f || f returns false
+o5 = 'Cat' || 'Dog'      // t || t returns "Cat"
+o6 = false || 'Cat'      // f || t returns "Cat"
+o7 = 'Cat' || false      // t || f returns "Cat"
+o8 = ''    || false      // f || f returns false
+o9 = false || ''         // f || f returns ""
+o10 = false || varObject // f || object returns varObject
+
+ +

논리 NOT (!)

+ +

다음은 !(논리 NOT) 연산자의 예제입니다.

+ +
n1 = !true               // !t returns false
+n2 = !false              // !f returns true
+n3 = !''                 // !f returns true
+n4 = !'Cat'              // !t returns false
+
+ +

이중 NOT (!!)

+ +

NOT 연산자 다수를 연속해서 사용하면 아무 값이나 불리언 원시값으로 강제 변환할 수 있습니다. 변환 결과는 피연산자 값의 "참스러움"이나 "거짓스러움"에 따릅니다. ({{Glossary("truthy", "참")}}과 {{Glossary("falsy", "거짓")}}을 참고하세요)

+ +

동일한 변환을 {{jsxref("Boolean")}} 함수로도 수행할 수 있습니다.

+ +
n1 = !!true                   // !!truthy returns true
+n2 = !!{}                     // !!truthy returns true: any object is truthy...
+n3 = !!(new Boolean(false))   // ...even Boolean objects with a false .valueOf()!
+n4 = !!false                  // !!falsy returns false
+n5 = !!""                     // !!falsy returns false
+n6 = !!Boolean(false)         // !!falsy returns false
+
+ +

불리언 변환 규칙

+ +

AND에서 OR로 변환

+ +

불리언 계산에서, 다음 두 코드는 항상 같습니다.

+ +
bCondition1 && bCondition2
+
+ +
!(!bCondition1 || !bCondition2)
+ +

OR에서 AND로 변환

+ +

불리언 계산에서, 다음 두 코드는 항상 같습니다.

+ +
bCondition1 || bCondition2
+
+ +
!(!bCondition1 && !bCondition2)
+ +

NOT 간 변환

+ +

불리언 계산에서, 다음 두 코드는 항상 같습니다.

+ +
!!bCondition
+
+ +
bCondition
+ +

중첩 괄호 제거

+ +

논리 표현식은 항상 왼쪽에서 오른쪽으로 평가되므로, 몇 가지 규칙을 따르면 복잡한 표현식에서 괄호를 제거할 수 있습니다.

+ +

중첩 AND 제거

+ +

불리언의 합성 계산에서, 다음 두 코드는 항상 같습니다.

+ +
bCondition1 || (bCondition2 && bCondition3)
+
+ +
bCondition1 || bCondition2 && bCondition3
+ +

중첩 OR 제거

+ +

불리언의 합성 계산에서, 다음 두 코드는 항상 같습니다.

+ +
bCondition1 && (bCondition2 || bCondition3)
+
+ +
!(!bCondition1 || !bCondition2 && !bCondition3)
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-11.11')}}{{Spec2('ES5.1')}}Defined in several sections of the specification: Logical NOT Operator, Binary Logical Operators
{{SpecName('ES6', '#sec-binary-logical-operators')}}{{Spec2('ES6')}}Defined in several sections of the specification: Logical NOT Operator, Binary Logical Operators
{{SpecName('ESDraft', '#sec-binary-logical-operators')}}{{Spec2('ESDraft')}}Defined in several sections of the specification: Logical NOT Operator, Binary Logical Operators
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.operators.logical")}}

+ +

같이 보기

+ + diff --git "a/files/ko/web/javascript/reference/operators/\353\260\260\354\227\264/index.html" "b/files/ko/web/javascript/reference/operators/\353\260\260\354\227\264/index.html" new file mode 100644 index 0000000000..4bdd29b61c --- /dev/null +++ "b/files/ko/web/javascript/reference/operators/\353\260\260\354\227\264/index.html" @@ -0,0 +1,200 @@ +--- +title: 배열 내포 +slug: Web/JavaScript/Reference/Operators/배열 +tags: + - JavaScript + - Non-standard + - Obsolete + - Operator + - Reference +translation_of: Archive/Web/JavaScript/Array_comprehensions +--- +
{{jsSidebar("Operators")}}
+ +
표준이 아닙니다. 사용하지 않는 것을 권장합니다!
+Array comprehensions 문법은 비표준이며 Firefox 58부터는 제거됩니다. 향후 사용할 수 없게 되기 때문에 사용하지 않는것을 고려해보세요.
+{{jsxref("Array.prototype.map")}}, {{jsxref("Array.prototype.filter")}}, {{jsxref("Functions/Arrow_functions", "arrow functions", "", 1)}}, and {{jsxref("Operators/Spread_operator", "spread syntax", "", 1)}}.
+ +
{{Obsolete_Header(58)}}
+ +

array comprehension 문법은 기존의 배열을 기반으로 새로운 배열을 신속하게 어셈블 할 수 있는 JavaScript 표현식입니다. 그러나 표준 및 Firefox 구현에서 제거되었습니다. 사용하지 마세요!

+ +

Syntax

+ +
[for (x of iterable) x]
+[for (x of iterable) if (condition) x]
+[for (x of iterable) for (y of iterable) x + y]
+
+ +

Description

+ +

배열의 이해로 넘어가서, 다음 두가지의 요소들이 사용가능하다.

+ + + +

for-of 반복문은 항상 첫번째 요소이다. 여러개의 for-of 반복문이나 if 제어문을 사용할 수 있다.

+ +

배열 선언은 ECMAScript 2016에서 이전부터 표준으로 정립되어왔으며, 이는 다른 형태의 데이터(contents)를 이용해서 새로운 배열을 구성할 수 있게 해 준다.

+ +

아래의 선언은 숫자로 이루어진 배열 내 각각의 숫자들을 이용해서 double형의 새로운 배열을 만들어준다.

+ +
var numbers = [1, 2, 3, 4];
+var doubled = [for (i of numbers) i * 2];
+console.log(doubled); // logs 2,4,6,8
+
+ +

이것은 {{jsxref("Array.prototype.map", "map()")}} 연산자와 같은 기능을 한다.

+ +
var doubled = numbers.map(i => i * 2);
+
+ +

배열들은 또한 다양한 표현을 통해 몇몇개의 배열 원소들은 선택할 수 도 있다. 아래의 예제는 바로 홀수만 선택하는 예제이다.

+ +
var numbers = [1, 2, 3, 21, 22, 30];
+var evens = [for (i of numbers) if (i % 2 === 0) i];
+console.log(evens); // logs 2,22,30
+
+ +

{{jsxref("Array.prototype.filter", "filter()")}} 또한 같은 목적으로 얼마든지 사용가능하다.

+ +
var evens = numbers.filter(i => i % 2 === 0);
+
+ +

{{jsxref("Array.prototype.map", "map()")}} 그리고 {{jsxref("Array.prototype.filter", "filter()")}} 스타일과 같은 연산자들은 단한 배열 선언과 결합할 수 있다. 아래는 짝수만 필터링하고, 그 원소들을 2배씩하는 배열들을 만드는 예제이다.

+ +
var numbers = [1, 2, 3, 21, 22, 30];
+var doubledEvens = [for (i of numbers) if (i % 2 === 0) i * 2];
+console.log(doubledEvens); // logs 4,44,60
+
+ +

배열에서의 [ ] (꺽쇠괄호) 는 범위의 목적으로 암시적인 괄호를 의미한다. {{jsxref("Statements/let","let")}}를 사용하면서 정의된다면, 예제의 i와 같은 변수들이 사용된다. 이는 배열 밖에서 사용할 수 없음을 나타낸다.

+ +

배열의 원소에 넣어지는 것은 굳이 배열일 필요는 없다 iterators and generators 물론 가능하다.

+ +

심지어 문자열도 배열의 원소로 넣을 수 있다. 필터와 지도 액션과 같은 데에 이용할 수 있다.

+ +
var str = 'abcdef';
+var consonantsOnlyStr = [for (c of str) if (!(/[aeiouAEIOU]/).test(c)) c].join(''); // 'bcdf'
+var interpolatedZeros = [for (c of str) c + '0' ].join(''); // 'a0b0c0d0e0f0'
+
+ +

또한 입력 폼이 유지되지 않으므로, 문자열을 뒤집기 위해 {{jsxref("Array.prototype.join", "join()")}} 를 사용해야 한다.

+ +

Examples

+ +

단순 배열

+ +
[for (i of [1, 2, 3]) i * i ];
+// [1, 4, 9]
+
+var abc = ['A', 'B', 'C'];
+[for (letters of abc) letters.toLowerCase()];
+// ["a", "b", "c"]
+ +

if문에서의 배열

+ +
var years = [1954, 1974, 1990, 2006, 2010, 2014];
+[for (year of years) if (year > 2000) year];
+// [ 2006, 2010, 2014 ]
+[for (year of years) if (year > 2000) if (year < 2010) year];
+// [ 2006], the same as below:
+[for (year of years) if (year > 2000 && year < 2010) year];
+// [ 2006]
+
+ +

map과 filter를 비교한 배열

+ +

배열문법을 가장 쉽게 이해하는 방법은, 배열에서 {{jsxref("Array.map", "map")}} 그리고 {{jsxref("Array.filter", "filter")}}메소드를 비교하는 것이다.

+ +
var numbers = [1, 2, 3];
+
+numbers.map(function (i) { return i * i });
+numbers.map(i => i * i);
+[for (i of numbers) i * i];
+// all are [1, 4, 9]
+
+numbers.filter(function (i) { return i < 3 });
+numbers.filter(i => i < 3);
+[for (i of numbers) if (i < 3) i];
+// all are [1, 2]
+
+ +

2개의 배열

+ +

2개의 배열과 2개의 for-of 반복문을 살펴본다.

+ +
var numbers = [1, 2, 3];
+var letters = ['a', 'b', 'c'];
+
+var cross = [for (i of numbers) for (j of letters) i + j];
+// ["1a", "1b", "1c", "2a", "2b", "2c", "3a", "3b", "3c"]
+
+var grid = [for (i of numbers) [for (j of letters) i + j]];
+// [
+//  ["1a", "1b", "1c"],
+//  ["2a", "2b", "2c"],
+//  ["3a", "3b", "3c"]
+// ]
+
+[for (i of numbers) if (i > 1) for (j of letters) if(j > 'a') i + j]
+// ["2b", "2c", "3b", "3c"], the same as below:
+
+[for (i of numbers) for (j of letters) if (i > 1) if(j > 'a') i + j]
+// ["2b", "2c", "3b", "3c"]
+
+[for (i of numbers) if (i > 1) [for (j of letters) if(j > 'a') i + j]]
+// [["2b", "2c"], ["3b", "3c"]], not the same as below:
+
+[for (i of numbers) [for (j of letters) if (i > 1) if(j > 'a') i + j]]
+// [[], ["2b", "2c"], ["3b", "3c"]]
+
+ +

명세

+ +

ECMAScript 2015 초안에 있었지만 개정 27(2014년 8월)에서 삭제되었습니다. specification semantics에 대해서는 ES2015의 이전 버전을 참조하세요.

+ +

Browser compatibility

+ +

{{Compat("javascript.operators.array_comprehensions")}}

+ +

오래된 JS1.7/JS1.8 comprehensions과의 차이점들

+ +
Gecko에서 JS1.7 / JS1.8 comprehensions가 46 버전부터 제거되었습니다. ({{bug(1220564)}}).
+ +

이전에 사용된 문법입니다. (더 이상 사용되지 않음!):

+ +
[X for (Y in Z)]
+[X for each (Y in Z)]
+[X for (Y of Z)]
+
+ +

차이점:

+ + + +

버그 업데이트에 대한 제안은 Bug 1220564, comment 42를 참조하세요.

+ +

더보기

+ + diff --git "a/files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" "b/files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" new file mode 100644 index 0000000000..7a82346d09 --- /dev/null +++ "b/files/ko/web/javascript/reference/operators/\354\227\260\354\202\260\354\236\220_\354\232\260\354\204\240\354\210\234\354\234\204/index.html" @@ -0,0 +1,462 @@ +--- +title: 연산자 우선순위 +slug: Web/JavaScript/Reference/Operators/연산자_우선순위 +tags: + - JavaScript + - Operator + - 연산자 + - 우선순위 +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +
{{jsSidebar("Operators")}}
+ +

연산자 우선순위는 연산자를 실행하는 순서를 결정합니다. 우선순위가 높은 연산자가 먼저 실행됩니다.

+ +
{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}
+ + + +

우선순위와 결합성

+ +

아래와 같이 표현할 수 있는 표현식을 생각해 봅시다. 연산자1과 연산자2의 자리에는 아무 연산자를 넣을 수 있습니다.

+ +
a 연산자1 b 연산자2 c
+ +

두 연산자의 우선순위(아래 표 참조)가 다를 경우, 우선순위가 높은 연산자가 먼저 실행되고 결합성은 영향을 미치지 않습니다. 아래 예제에서는 덧셈이 곱셈보다 먼저 쓰였음에도 곱셈의 우선순위가 높기 때문에 먼저 실행됩니다.

+ +
console.log(3 + 10 * 2);   // 23을 출력
+console.log(3 + (10 * 2)); // 23을 출력, 괄호는 불필요함
+console.log((3 + 10) * 2); // 26을 출력, 괄호로 인해 실행 순서가 바뀜
+
+ +

좌결합성(왼쪽에서 오른쪽으로)은 표현식이 (a 연산자1 b) 연산자2 c와 같이, 우결합성(오른쪽에서 왼쪽으로)은 a 연산자1 (b 연산자2 c)와 같이 계산된다는 의미입니다. 대입 연산자는 우결합성이므로 다음과 같은 코드를 작성할 수 있습니다.

+ +
a = b = 5; // a = (b = 5);와 같음
+
+ +

이때 대입 연산자는 대입된 값을 반환하므로 ab의 값이 5가 됨을 예상할 수 있습니다. 우선 b의 값이 5로 설정되고, 그 다음에는 a의 값이 우변인 b = 5의 반환값 5로 설정됩니다.

+ +

다른 예시로, 좌결합성인 다른 산술 연산자와 달리 거듭제곱 연산자 (**)만은 우결합성입니다. 흥미로운 점으로 표현식의 평가는 결합성과 무관하게 항상 왼쪽에서 오른쪽으로 진행됩니다.

+ + + + + + + + + + + + + + + + +
코드출력
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 나눗셈 연산자 (/)에 주목
+console.log(echo("첫째", 6) / echo("둘째", 2));
+
+
+
+첫째 항 평가함
+둘째 항 평가함
+3
+
+
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 거듭제곱 연산자 (**)에 주목
+console.log(echo("첫째", 2) ** echo("둘째", 3));
+
+
+첫째 항 평가함
+둘째 항 평가함
+8
+
+ +

여러 연산자의 우선순위가 같을 때는 결합성을 고려합니다. 위에서와 같이 연산자가 하나이거나 연산자끼리 우선순위가 다를 경우에는 결합성이 결과에 영향을 미치지 않습니다. 아래의 예제에서 같은 종류의 연산자를 여러 번 사용했을 때 결합성이 결과에 영향을 미치는 것을 확인할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + +
코드출력
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 나눗셈 연산자 (/)에 주목
+console.log(echo("첫째", 6) / echo("둘째", 2) / echo("셋째", 3));
+
+
+
+첫째 항 평가함
+둘째 항 평가함
+셋째 항 평가함
+1
+
+
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 거듭제곱 연산자 (**)에 주목
+console.log(echo("첫째", 2) ** echo("둘째", 3) ** echo("셋째", 2));
+
+
+
+첫째 항 평가함
+둘째 항 평가함
+셋째 항 평가함
+512
+
+
+
+function echo(name, num) {
+    console.log(name + " 항 평가함");
+    return num;
+}
+// 첫 번째 거듭제곱 연산자 주변의 괄호에 주목
+console.log((echo("첫째", 2) ** echo("둘째", 3)) ** echo("셋째", 2));
+
+
+첫째 항 평가함
+둘째 항 평가함
+셋째 항 평가함
+64
+
+ +

위의 예제에서 나눗셈은 좌결합성이므로 6 / 3 / 2(6 / 3) / 2와 같습니다. 한편 거듭제곱은 우결합성이므로 2 ** 3 ** 22 ** (3 ** 2)와 같습니다. 그러므로 (2 ** 3) ** 2는 괄호로 인해 실행 순서가 바뀌기 때문에 위 표와 같이 64로 평가됩니다.

+ +

우선순위는 결합성보다 항상 우선하므로, 거듭제곱과 나눗셈을 같이 사용하면 나눗셈보다 거듭제곱이 먼저 계산됩니다. 예를 들어 2 ** 3 / 3 ** 2는 (2 ** 3) / (3 ** 2)와 같으므로 0.8888888888888888로 계산됩니다.

+ +

예제

+ +
3 > 2 && 2 > 1
+// true를 반환
+
+3 > 2 > 1
+// 3 > 2는 true인데, 부등호 연산자에서 true는 1로 변환되므로
+// true > 1은 1 > 1이 되고, 이는 거짓이다.
+// 괄호를 추가하면 (3 > 2) > 1과 같다.
+ +

+ +

다음 표는 우선순위 내림차순(21부터 1까지)으로 정렬되어 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
우선순위연산자 유형결합성연산자
21{{jsxref("Operators/Grouping", "그룹", "", 1)}}없음( … )
20{{jsxref("Operators/Property_Accessors", "멤버 접근", "#점_표기법", 1)}}좌결합성… . …
{{jsxref("Operators/Property_Accessors", "계산된 멤버 접근","#괄호_표기법", "1")}}좌결합성… [ … ]
{{jsxref("Operators/new","new")}} (매개변수 리스트 존재)없음new … ( … )
+

함수 호출

+
좌결합성… ( )
Optional chaining좌결합성?.
19{{jsxref("Operators/new","new")}} (매개변수 리스트 생략)우결합성new …
18{{jsxref("Operators/Arithmetic_Operators","후위 증가","#Increment", 1)}}없음… ++
{{jsxref("Operators/Arithmetic_Operators","후위 감소","#Decrement", 1)}}… --
17논리 NOT우결합성! …
비트 NOT~ …
단항 양부호+ …
단항 부정- …
전위 증가++ …
전위 감소-- …
{{jsxref("Operators/typeof", "typeof")}}typeof …
{{jsxref("Operators/void", "void")}}void …
{{jsxref("Operators/delete", "delete")}}delete …
{{jsxref("Operators/await", "await")}}await …
16거듭제곱우결합성… ** …
15곱셈좌결합성… * …
나눗셈… / …
나머지… % …
14덧셈좌결합성… + …
뺄셈… - …
13비트 왼쪽 시프트좌결합성… << …
비트 오른쪽 시프트… >> …
비트 부호 없는 오른쪽 시프트… >>> …
12미만좌결합성… < …
이하… <= …
초과… > …
이상… >= …
{{jsxref("Operators/in", "in")}}… in …
{{jsxref("Operators/instanceof", "instanceof")}}… instanceof …
11동등좌결합성… == …
부등… != …
일치… === …
불일치… !== …
10비트 AND좌결합성… & …
9비트 XOR좌결합성… ^ …
8비트 OR좌결합성… | …
7널 병합 연산자좌결합성… ?? …
6논리 AND좌결합성… && …
5논리 OR좌결합성… || …
4조건우결합성… ? … : …
3할당우결합성… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}}우결합성yield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1쉼표 / 시퀀스좌결합성… , …
diff --git a/files/ko/web/javascript/reference/statements/async_function/index.html b/files/ko/web/javascript/reference/statements/async_function/index.html new file mode 100644 index 0000000000..5a986c8af4 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/async_function/index.html @@ -0,0 +1,243 @@ +--- +title: async function +slug: Web/JavaScript/Reference/Statements/async_function +tags: + - Example + - JavaScript + - Promise + - async + - await +translation_of: Web/JavaScript/Reference/Statements/async_function +--- +
{{jsSidebar("Statements")}}
+ +

async function 선언은 {{jsxref("Global_Objects/AsyncFunction","AsyncFunction")}}객체를 반환하는 하나의 비동기 함수를 정의합니다. 비동기 함수는 이벤트 루프를 통해 비동기적으로 작동하는 함수로, 암시적으로 {{jsxref("Promise")}}를 사용하여 결과를 반환합니다. 그러나 비동기 함수를 사용하는 코드의 구문과 구조는, 표준 동기 함수를 사용하는것과 많이 비슷합니다.

+ +
+

또한 {{jsxref("Operators/async_function", "async function expression", "", 1)}}을 사용해서 async function을 선언할 수 있습니다.

+
+ +
{{EmbedInteractiveExample("pages/js/statement-async.html", "taller")}}
+ + + +

Syntax

+ +
async function name([param[, param[, ... param]]]) {
+    statements
+}
+
+ +

매개변수

+ +
+
name
+
함수의 이름.
+
+ +
+
param
+
함수에게 전달되기 위한 인자의 이름.
+
+ +
+
statements
+
함수본문을 구성하는 내용.
+
+

반환 값

+ +

Promise : async 함수에 의해 반환 된 값으로 해결되거나 async함수 내에서 발생하는 캐치되지 않는 예외로 거부되는 값.

+
+
+ +

Description

+ +

async 함수에는 {{jsxref ( "Operators / await", "await")}}식이 포함될 수 있습니다. 이 식은 async 함수의 실행을 일시 중지하고 전달 된 Promise의 해결을 기다린 다음 async 함수의 실행을 다시 시작하고 완료후 값을 반환합니다.

+ +
+

await 키워드는 async 함수에서만 유효하다는 것을 기억하십시오. async 함수의 본문 외부에서 사용하면 SyntaxError가 발생합니다.

+
+ +
+

async/await함수의 목적은 사용하는 여러 promise의 동작을 동기스럽게 사용할 수 있게 하고, 어떠한 동작을 여러 promise의 그룹에서 간단하게 동작하게 하는 것이다.
+ promise가 구조화된 callback과 유사한 것 처럼 async/await또한 제네레이터(generator)와 프로미스(promise)를 묶는것과 유사하다.

+
+ +

async 함수는 항상 promise를 반환합니다. 만약 async 함수의 반환값이 명시적으로 promise가 아니라면 암묵적으로 promise로 감싸집니다.

+ +

예를 들어

+ +
async function foo() {
+    return 1
+}
+ +

위 코드는 아래와 같습니다.

+ +
function foo() {
+    return Promise.resolve(1)
+}
+ +

async 함수의 본문은 0개 이상의 await 문으로 분할된 것으로 생각할 수 있습니다. 첫번째 await 문을 포함하는 최상위 코드는 동기적으로 실행됩니다. 따라서 await 문이 없는 async 함수는 동기적으로 실행됩니다. 하지만 await 문이 있다면 async 함수는 항상 비동기적으로 완료됩니다.

+ +

예를 들어

+ +
async function foo() {
+    await 1
+}
+ +

위 코드는 아래와 같습니다.

+ +
function foo() {
+    return Promise.resolve(1).then(() => undefined)
+}
+
+ +

Examples

+ +

Simple example

+ +
var resolveAfter2Seconds = function() {
+  console.log("starting slow promise");
+  return new Promise(resolve => {
+    setTimeout(function() {
+      resolve(20);
+      console.log("slow promise is done");
+    }, 2000);
+  });
+};
+
+var resolveAfter1Second = function() {
+  console.log("starting fast promise");
+  return new Promise(resolve => {
+    setTimeout(function() {
+      resolve(10);
+      console.log("fast promise is done");
+    }, 1000);
+  });
+};
+
+var sequentialStart = async function() {
+  console.log('==SEQUENTIAL START==');
+
+  // If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise.
+  const slow = await resolveAfter2Seconds();
+  console.log(slow);
+
+  const fast = await resolveAfter1Second();
+  console.log(fast);
+}
+
+var concurrentStart = async function() {
+  console.log('==CONCURRENT START with await==');
+  const slow = resolveAfter2Seconds(); // starts timer immediately
+  const fast = resolveAfter1Second();
+
+  console.log(await slow);
+  console.log(await fast); // waits for slow to finish, even though fast is already done!
+}
+
+var stillConcurrent = function() {
+  console.log('==CONCURRENT START with Promise.all==');
+  Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => {
+    console.log(messages[0]); // slow
+    console.log(messages[1]); // fast
+  });
+}
+
+var parallel = function() {
+  console.log('==PARALLEL with Promise.then==');
+  resolveAfter2Seconds().then((message)=>console.log(message));
+  resolveAfter1Second().then((message)=>console.log(message));
+}
+
+sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"
+// wait above to finish
+setTimeout(concurrentStart, 4000); // after 2 seconds, logs "slow" and then "fast"
+// wait again
+setTimeout(stillConcurrent, 7000); // same as concurrentStart
+// wait again
+setTimeout(parallel, 10000); // trully parallel: after 1 second, logs "fast", then after 1 more second, "slow"
+ +
+

await 와 Promise#then을 혼동하지 마세요

+ +

sequentialStart 에서, 첫 번째 await는 2초의 대기 시간을 갖고,  다시 두 번째 await에서 1초의 대기 시간을 갖습니다. 두 번째 타이머는 첫 번째 타이머가 완료될 때 까지 생성되지 않습니다.

+ +

concurrentStart 에서, 두 타이머 모두 생성 된 다음 await 합니다. 타이머가 동시에 실행되고 있지만, await 호출은 여전히 연속적 실행중이므로, 두 번째 await 는 첫 번째 호출이 끝날 때 까지 대기합니다. 이렇게하면 3초가 아니라, 가장 느린 타이머에 필요한 2초가 필요합니다. stillConcurrent 에서도 Promise.all 을 사용하여 같은 일이 발생합니다.

+ +

두 개 이상의 프러미스를 동시에 wait 하고 싶다면, Promise#then을 사용하여 예제와 같이 parallel 를 수행할 수 있습니다.

+
+ +

async함수를 사용한 promise chain 재작성

+ +

{{jsxref("Promise")}} 를 반환하는 API는 promise chain을 만들며 여러 파트의 함수로 나뉜다.
+ 아래 코드를 보자.

+ +
function getProcessedData(url) {
+  return downloadData(url) // returns a promise
+    .catch(e => {
+      return downloadFallbackData(url) // returns a promise
+    })
+    .then(v => {
+      return processDataInWorker(v); // returns a promise
+    });
+}
+
+ +

위의 코드는 하나의 async함수로 아래와 같이 쓰여질 수도 있다.

+ +
async function getProcessedData(url) {
+  let v;
+  try {
+    v = await downloadData(url);
+  } catch (e) {
+    v = await downloadFallbackData(url);
+  }
+  return processDataInWorker(v);
+}
+
+ +

위 예제에서는 return 구문에 await 구문이 없다는 것에 주목하자. 이는 async function의 반환값이 암묵적으로 {{jsxref("Promise.resolve")}}로 감싸지기 때문이다.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}{{Spec2('ESDraft')}}Initial definition in ES2017.
{{SpecName('ES8', '#sec-async-function-definitions', 'async function')}}{{Spec2('ES8')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.async_function")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/block/index.html b/files/ko/web/javascript/reference/statements/block/index.html new file mode 100644 index 0000000000..aab5d0dc3f --- /dev/null +++ b/files/ko/web/javascript/reference/statements/block/index.html @@ -0,0 +1,132 @@ +--- +title: block +slug: Web/JavaScript/Reference/Statements/block +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/block +--- +
{{jsSidebar("Statements")}}
+ +

블록문(또는 다른 언어에서는 복합문)은 0개 이상의 구문을 묶을 때 사용합니다. 블록은 한 쌍의 중괄호로 구성하며 선택적으로 {{jsxref("Statements/label", "이름", "", 0)}}을 붙일 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-block.html")}}
+ + + +

구문

+ +

블록문

+ +
{
+  StatementList
+}
+ +

유명 블록문

+ +
LabelIdentifier: {
+  StatementList
+}
+
+ +
+
StatementList
+
블록문 내의 문.
+
LabelIdentifier
+
시각적인 구분, 또는 {{jsxref("Statements/break", "break")}}문의 대상으로 쓸 {{jsxref("Statements/label", "label")}}.
+
+ +

설명

+ +

다른 언어에서 블록문은 복합문이라고 부르기도 합니다. 블록문을 쓰면 JavaScript가 하나의 문을 기대하는 곳에서 다수의 문을 실행할 수 있습니다. JavaScript에서 이렇게 문을 묶는건 흔히 쓰이는 기법입니다. 반대 개념으로는 {{jsxref("Statements/empty", "공백문", "", 0)}}이 있으며, 이는 하나의 문을 기대하는 곳에 아무것도 제공하지 않는 것입니다.

+ +

블록 범위 규칙

+ +

var 사용 시

+ +

{{jsxref("Statements/var", "var")}}로 선언한 변수는 블록 범위를 가지지 않습니다. 블록 내에서 선언한 변수의 범위는 함수나 스크립트가 되어, 값 할당의 영향이 블록 바깥까지 미칩니다. 다른 말로는 블록문이 범위를 만들지 않습니다. "독립" 블록문도 유효한 구문이긴 하지만, C와 Java의 블록에 기대하는걸 JavaScript에서도 기대하면 안됩니다. 예를 들어보겠습니다.

+ +
var x = 1;
+{
+  var x = 2;
+}
+console.log(x); // 2 기록
+ +

콘솔 출력 결과는 2입니다. 블록 밖의 var x와 블록 안의 var x는 같은 범위에 속하기 때문입니다. C나 Java에서 같은 코드를 작성한다면 1을 출력할 것입니다.

+ +

letconst 사용 시

+ +

반면 {{jsxref("Statements/let", "let")}}과 {{jsxref("Statements/const", "const")}}로 선언한 식별자는 블록 범위를 가집니다.

+ +
let x = 1;
+{
+  let x = 2;
+}
+console.log(x); // 1 기록
+
+ +

x = 2는 선언한 블록으로 범위가 제한됩니다.

+ +

const도 마찬가지입니다.

+ +
const c = 1;
+{
+  const c = 2;
+}
+console.log(c); // 1 기록, SyntaxError 없음
+ +

블록 내의 const c = 2SyntaxError: Identifier 'c' has already been declared를 던지지 않는 점에 주목하세요. 블록 범위 안이라 별개의 식별자이기 때문입니다.

+ +

ES2015의 엄격 모드부터, 블록 내의 함수는 해당 블록으로 범위가 제한됩니다. ES2015 이전의 엄격 모드에서는 블록 레벨 함수를 사용할 수 없었습니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-block', 'Block statement')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-block', 'Block statement')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-12.1', 'Block statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-12.1', 'Block statement')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-12.1', 'Block statement')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.block")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/break/index.html b/files/ko/web/javascript/reference/statements/break/index.html new file mode 100644 index 0000000000..fdbb79e719 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/break/index.html @@ -0,0 +1,119 @@ +--- +title: break +slug: Web/JavaScript/Reference/Statements/break +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/break +--- +
{{jsSidebar("Statements")}}
+ +

break은 현재 반복문, {{jsxref("Statements/switch", "switch")}} 문, 또는 {{jsxref("Statements/label", "label")}} 문을 종료하고, 그 다음 문으로 프로그램 제어를 넘깁니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-break.html")}}
+ + + +

구문

+ +
break [label];
+ +
+
label {{optional_inline}}
+
문의 라벨에 연결한 {{glossary("identifier", "식별자")}}. 반복문이나 {{jsxref("Statements/switch", "switch")}}에서 사용하는게 아니면 필수로 제공해야 합니다.
+
+ +

설명

+ +

break 문은 프로그램이 label 달린 문에서 빠져나오게 하는 선택사항 label을 포함합니다. break 문은 참조되는 label 내에 중첩되어야 합니다. label 달린 문은 어떤 {{jsxref("Statements/block", "block")}} 문이든 될 수 있습니다. 꼭, loop 문을 달 필요가 없습니다.

+ +

예제

+ +

다음 함수는 i가 3일 때 {{jsxref("Statements/while", "while")}} loop를 종료하는 break 문이 있고, 그러고는 3 * x값을 반환합니다.

+ +
function testBreak(x) {
+  var i = 0;
+
+  while (i < 6) {
+    if (i == 3) {
+      break;
+    }
+    i += 1;
+  }
+
+  return i * x;
+}
+ +

다음 코드는 label 달린 블록이 있는 break 문을 사용합니다. break 문은 자신이 참조하는 label 내에 중첩되어야 합니다. inner_blockouter_block내에 중첩되어야 함을 주의하세요.

+ +
outer_block: {
+  inner_block: {
+    console.log('1');
+    break outer_block; // inner_block과 outer_block 둘다 빠져나옴
+    console.log(':-('); // 건너뜀
+  }
+  console.log('2'); // 건너뜀
+}
+
+ +

다음 코드는 또한 label 달린 블록이 있는 break 문을 사용하지만 그 break 문이 block_2를 참조하지만 block_1 내에 있기에 구문 오류(Syntax Error)가 발생합니다. break 문은 항상 자신이 참조하는 label 내에 중첩되어야 합니다.

+ +
block_1: {
+  console.log('1');
+  break block_2; // SyntaxError: label을 찾을 수 없음
+}
+
+block_2: {
+  console.log('2');
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Unlabeled version.
{{SpecName('ES3')}}{{Spec2('ES3')}}Labeled version added.
{{SpecName('ES5.1', '#sec-12.8', 'Break statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-break-statement', 'Break statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-break-statement', 'Break statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.statements.break")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/class/index.html b/files/ko/web/javascript/reference/statements/class/index.html new file mode 100644 index 0000000000..bfb1c95027 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/class/index.html @@ -0,0 +1,119 @@ +--- +title: class +slug: Web/JavaScript/Reference/Statements/class +tags: + - Classes + - Declaration + - ECMAScript 2015 + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/class +--- +
{{jsSidebar("Statements")}}
+ +

class 선언은 프로토타입 기반 상속을 사용하여, 주어진 이름의 새로운 클래스를 만듭니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-class.html")}}
+ + + +
+

{{jsxref("Operators/class", "클래스 표현", "", 1)}}을 사용하여 클래스를 정의할 수도 있습니다. 표현식과 달리 선언문으로는 같은 클래스를 다시 선언하면 오류가 발생합니다.

+
+ +

구문

+ +
class name [extends] {
+  // class body
+}
+
+ +

설명

+ +

클래스 본문은 엄격 모드에서 실행됩니다. 생성자 속성은 선택 사항입니다..

+ +

클래스 선언은 {{jsxref("Statements/function", "함수 선언", "", 0)}}과 달리 {{Glossary("Hoisting", "호이스팅")}}의 대상이 아닙니다.

+ +

예제

+ +

간단한 클래스 선언

+ +

다음 예제는 우선 Polygon 클래스를 정의하고, Square라는 이름의 새로운 클래스가 Polygon을 상속합니다. 생성자 내부의 super()는 생성자 내에서만, 그리고 {{jsxref("Operators/this", "this")}} 키워드를 사용하기 전에만 쓸 수 있다는 점을 주의하세요.

+ +
class Polygon {
+  constructor(height, width) {
+    this.name = 'Polygon';
+    this.height = height;
+    this.width = width;
+  }
+}
+
+class Square extends Polygon {
+  constructor(length) {
+    super(length, length);
+    this.name = 'Square';
+  }
+}
+ +
+

같은 클래스를 두 번 선언하려고 시도할 때

+ +

클래스 선언문으로 같은 클래스를 두 번 선언하면 오류가 발생합니다.

+ +
class Foo {};
+class Foo {}; // Uncaught SyntaxError: Identifier 'Foo' has already been declared
+
+ +

이전에 표현식으로 정의한 경우에도 오류가 발생합니다.

+ +
var Foo = class {};
+class Foo {}; // Uncaught TypeError: Identifier 'Foo' has already been declared
+
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2016')}} 
{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2017')}} 
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.class")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/statements/const/index.html b/files/ko/web/javascript/reference/statements/const/index.html new file mode 100644 index 0000000000..1cbd7ea7aa --- /dev/null +++ b/files/ko/web/javascript/reference/statements/const/index.html @@ -0,0 +1,136 @@ +--- +title: const +slug: Web/JavaScript/Reference/Statements/const +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - Statement + - constants +translation_of: Web/JavaScript/Reference/Statements/const +--- +
{{jsSidebar("Statements")}}
+ +

const 선언은 블록 범위의 상수를 선언합니다. 상수의 값은 재할당할 수 없으며 다시 선언할 수도 없습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-const.html")}}
+ + + +

구문

+ +
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
+ +
+
nameN
+
상수의 이름. 아무 유효한 {{Glossary("identifier", "식별자")}}를 사용할 수 있습니다.
+
valueN
+
상수의 값. 아무 유효한 표현식이나 가능합니다.
+
+ +

설명

+ +

이 선언은 선언된 함수에 전역 또는 지역일 수 있는 상수를 만듭니다. 상수 초기자(initializer)가 필요합니다. 즉 선언되는 같은 문에 그 값을 지정해야 합니다(이는 나중에 변경될 수 없는 점을 감안하면 말이 됩니다).

+ +

상수는 let 문을 사용하여 정의된 변수와 마찬가지로 블록 범위(block-scope)입니다. 상수의 값은 재할당을 통해 바뀔 수 없고 재선언될 수 없습니다.

+ +

let에 적용한 "일시적 사각 지대"에 관한 모든 고려는, const에도 적용합니다.

+ +

상수는 같은 범위의 상수 또는 변수와 그 이름을 공유할 수 없습니다.

+ +

예제

+ +

다음 예제는 상수가 어떻게 동작하는지 보입니다. 브라우저 콘솔에서 따라해보세요.

+ +
// 주의: 상수 선언에는 대소문자 모두 사용할 수 있지만,
+// 일반적인 관습은 모두 대문자를 사용하는 것입니다.
+
+// MY_FAV를 상수로 정의하고 그 값을 7로 함
+const MY_FAV = 7;
+
+// 에러가 발생함
+MY_FAV = 20;
+
+// 7 출력
+console.log("my favorite number is: " + MY_FAV);
+
+// 상수를 재선언하려는 시도는 오류 발생 - Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared
+const MY_FAV = 20;
+
+// MY_FAV라는 이름은 위에서 상수로 예약되어 있어서 역시 실패함.
+var MY_FAV = 20;
+
+// 역시 오류가 발생함
+let MY_FAV = 20;
+
+// 블록 범위의 특성을 아는게 중요
+if (MY_FAV === 7) {
+    // 블록 범위로 지정된 MY_FAV 라는 변수를 만드므로 괜찮습니다
+    // (let으로 const 변수가 아닌 블록 범위를 선언하는 것과 똑같이 동작합니다)
+    let MY_FAV = 20;
+
+    // MY_FAV는 이제 20입니다
+    console.log('my favorite number is ' + MY_FAV);
+
+    // 이 선언은 전역으로 호이스트되고 에러가 발생합니다.
+    var MY_FAV = 20;
+}
+
+// MY_FAV는 여전히 7
+console.log('my favorite number is ' + MY_FAV);
+
+// const 선언시에 초기값을 생략해서 오류 발생
+const FOO;
+
+// const는 오브젝트에도 잘 동작합니다
+const MY_OBJECT = {'key': 'value'};
+
+// 오브젝트를 덮어쓰면 오류가 발생합니다
+MY_OBJECT = {'OTHER_KEY': 'value'};
+
+// 하지만 오브젝트의 키는 보호되지 않습니다.
+// 그러므로 아래 문장은 문제없이 실행됩니다
+MY_OBJECT.key = 'otherValue'; // 오브젝트를 변경할 수 없게 하려면 Object.freeze() 를 사용해야 합니다
+
+// 배열에도 똑같이 적용됩니다
+const MY_ARRAY = [];
+// 배열에 아이템을 삽입하는 건 가능합니다
+MY_ARRAY.push('A'); // ["A"]
+// 하지만 변수에 새로운 배열을 배정하면 에러가 발생합니다
+MY_ARRAY = ['B']
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES2015', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}{{Spec2('ES2015')}}초기 정의.
{{SpecName('ESDraft', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.const")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/continue/index.html b/files/ko/web/javascript/reference/statements/continue/index.html new file mode 100644 index 0000000000..f0d67deea2 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/continue/index.html @@ -0,0 +1,164 @@ +--- +title: continue +slug: Web/JavaScript/Reference/Statements/continue +translation_of: Web/JavaScript/Reference/Statements/continue +--- +
{{jsSidebar("Statements")}}
+ +

continue 문은 현재 또는 레이블이 지정된 루프의 현재 반복에서 명령문의 실행을 종료하고 반복문의 처음으로 돌아가여 루프문의 다음 코드를 실행합니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-continue.html")}}
+ + + +

구문

+ +
continue [label];
+ +
+
label
+
+

명령문의 레이블과 연관된 식별자.

+
+
+ +

설명

+ +

{{jsxref ( "Statements / break", "break")}} 문과 달리 continue는 루프의 실행을 완전히 종료하지 않고 for, while문에서 다음과 같이 동작합니다.

+ + + + + +

continue 문에는 현재 루프 대신 레이블이 지정된 루프 문의 다음 반복으로 건너 뛰도록하는 선택적 레이블이 포함될 수 있습니다. 이 경우, continue 문은 이 레이블 된 명령문 내에 중첩되어야합니다.

+ +

예제

+ +

Using continue with while

+ +

다음 예제에서는 i의 값이 3일 때 실행되는 continue문을 포함하는 {{jsxref("Statements/while", "while")}}을 보여줍니다. 따라서 n은 1, 3, 7 및 12 값을 갖습니다.

+ +
var i = 0;
+var n = 0;
+
+while (i < 5) {
+  i++;
+
+  if (i === 3) {
+    continue;
+  }
+
+  n += i;
+}
+
+ +

label과 함께 continue 사용하기

+ +

다음 예제에서 checkiandj라는 문에는 checkj라는 문이 있습니다. continue가 발생하면 프로그램은 checkj 문의 맨 위에서 계속됩니다. continue가 발생할 때마다 checkj는 조건이 false를 반환 할 때까지 반복합니다. false가 리턴되면 나머지 checkiandj 문이 완료됩니다.

+ +

continuecheckiandj 레이블이 있으면이 프로그램은 checkiandj 문 맨 위에서 계속됩니다.

+ +

See also {{jsxref("Statements/label", "label")}}.

+ +
var i = 0;
+var j = 8;
+
+checkiandj: while (i < 4) {
+  console.log('i: ' + i);
+  i += 1;
+
+  checkj: while (j > 4) {
+    console.log('j: ' + j);
+    j -= 1;
+
+    if ((j % 2) == 0)
+      continue checkj;
+    console.log(j + ' is odd.');
+  }
+  console.log('i = ' + i);
+  console.log('j = ' + j);
+}
+
+ +

출력:

+ +
i: 0
+
+// start checkj
+j: 8
+7 is odd.
+j: 7
+j: 6
+5 is odd.
+j: 5
+// end checkj
+
+i = 1
+j = 4
+
+i: 1
+i = 2
+j = 4
+
+i: 2
+i = 3
+j = 4
+
+i: 3
+i = 4
+j = 4
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Unlabeled version.
{{SpecName('ES3')}}{{Spec2('ES3')}}Labeled version added.
{{SpecName('ES5.1', '#sec-12.7', 'Continue statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-continue-statement', 'Continue statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-continue-statement', 'Continue statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.continue")}}

+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/debugger/index.html b/files/ko/web/javascript/reference/statements/debugger/index.html new file mode 100644 index 0000000000..4f081282b9 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/debugger/index.html @@ -0,0 +1,79 @@ +--- +title: debugger +slug: Web/JavaScript/Reference/Statements/debugger +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/debugger +--- +
{{jsSidebar("Statements")}}
+ +

debugger은 중단점 설정 등 현재 사용할 수 있는 디버그 기능을 호출합니다. 사용할 수있는 디버깅 기능이 없으면 아무런 동작도 하지 않습니다.

+ +

구문

+ +
debugger;
+ +

예제

+ +

다음 예제에서는 함수가 호출 시 디버거를 활성화하도록 debugger를 삽입한 모습입니다.

+ +
function potentiallyBuggyCode() {
+    debugger;
+    // 버그가 있을 것으로 생각하는 코드를 분석하거나, 한 단계씩 진행해보거나...
+}
+ +

디버거가 활성화되면 디버거 문의 위치에서 실행이 일시중지됩니다. 스크립트 소스의 중단점과 비슷합니다.

+ +

Paused at a debugger statement.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-debugger-statement', 'Debugger statement')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-debugger-statement', 'Debugger statement')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-12.15', 'Debugger statement')}}{{Spec2('ES5.1')}}Initial definition
{{SpecName('ES3', '#sec-7.5.3', 'Debugger statement')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-7.4.3', 'Debugger statement')}}{{Spec2('ES1')}}Only mentioned as reserved word.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.debugger")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/default/index.html b/files/ko/web/javascript/reference/statements/default/index.html new file mode 100644 index 0000000000..d8d107e774 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/default/index.html @@ -0,0 +1,121 @@ +--- +title: default +slug: Web/JavaScript/Reference/Statements/default +tags: + - JavaScript + - Keyword + - Reference +translation_of: Web/JavaScript/Reference/Statements/switch +--- +
{{jsSidebar("Statements")}}
+ +

default 키워드는 {{jsxref("Statements/switch", "switch")}} 구문과 {{jsxref("Statements/export", "export")}} 구문에서 사용할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-default.html")}}
+ + + +

구문

+ +

{{jsxref("Statements/switch", "switch")}} 구문 내에서는 다음과 같이 사용합니다.

+ +
switch (expression) {
+  case value1:
+    //Statements executed when the result of expression matches value1
+    [break;]
+  default:
+    //Statements executed when none of the values match the value of the expression
+    [break;]
+}
+ +

{{jsxref("Statements/export", "export")}} 구문 내에서는 다음과 같이 사용합니다.

+ +
export default nameN 
+ +

설명

+ +

세부사항을 보려면,

+ + + +

예제

+ +

switch에서 default 사용

+ +

아래 예제에서 expr 이 "오렌지" 또는 "사과"일 때, 프로그램은 값을 "오렌지" 또는 "사과"와 일치시키고 해당 명령문을 실행합니다. 기본(default) 키워드는 다른 경우에 도움이 되며 연관된 명령문을 실행합니다.

+ +
switch (expr) {
+  case '오렌지':
+    console.log('오렌지는 1000원입니다.');
+    break;
+  case '사과':
+    console.log('사과는 500원입니다.');
+    break;
+  default:
+    console.log('죄송합니다. ' + expr + '의 재고가 다 떨어졌습니다.');
+}
+ +

export에서 default 사용

+ +

단일 값을 내보내거나 모듈의 기본 값이 필요한 경우, 기본 내보내기를 사용할 수 있습니다.

+ +
// module "my-module.js"
+let cube = function cube(x) {
+  return x * x * x;
+};
+export default cube;
+ +

다른 스크립트에서 가져오는 건 간단합니다.

+ +
// module "my-module.js"
+import cube from 'my-module';  //default export gave us the liberty to say import cube, instead of import cube from 'my-module'
+console.log(cube(3)); // 27
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-switch-statement', 'switch statement')}}{{Spec2('ES6')}}
{{SpecName('ES6', '#sec-exports', 'Exports')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-switch-statement', 'switch statement')}}{{Spec2('ESDraft')}}
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.default")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/do...while/index.html b/files/ko/web/javascript/reference/statements/do...while/index.html new file mode 100644 index 0000000000..f6d2e00c57 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/do...while/index.html @@ -0,0 +1,78 @@ +--- +title: do...while +slug: Web/JavaScript/Reference/Statements/do...while +tags: + - 구문 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Statements/do...while +--- +
{{jsSidebar("Statements")}}
+ +

do...while 문은 테스트 조건이 거짓으로 평가될 때까지 지정된 구문을 실행하는 루프를 만듭니다.
+ 단, 구문이 실행된 뒤에 테스트 조건이 평가됨으로 구문은 무조건 한 번은 실행됩니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-dowhile.html")}}
+ + + +

문법

+ +
do구문
+while (조건식);
+
+ +
+
구문
+
테스트 조건이 참일 때마다 한 번이상 실행되는 구문입니다. 만약 루프 내에서 여러 구문을 반복 실행 시키고 싶으시다면, 다음 명령을 사용합니다.
+
{{jsxref("Statements/block", "block", "", 1)}} 구문을 활용하여 ({ ... }) 이런 식으로 그룹화합니다.
+
+ +
+
조건식
+
루프가 실행될 때마다 평가되는 식입니다. 만약 조건식이 참으로 평가되었다면, 구문 이 다시 실행됩니다. 만약 조건식이 거짓으로 평가되었다면, 자바스크립트는 do...while. 구문 밑에 있는 구문들을 실행시킵니다.
+
+ +

예제

+ +

do...while

+ +

예제에서 do...while 문은 적어도 한번 반복되고 i 변수가 5 보다 작을 때까지 실행됩니다.

+ +
var result = '';
+var i = 0;
+do {
+   i += 1;
+   result += i + ' ';
+}
+while (i > 0 && i < 5);
+// Despite i == 0 this will still loop as it starts off without the test
+
+console.log(result);
+ +

자세한 내용

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-do-while-statement', 'do-while statement')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.do_while")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/empty/index.html b/files/ko/web/javascript/reference/statements/empty/index.html new file mode 100644 index 0000000000..c986c6232a --- /dev/null +++ b/files/ko/web/javascript/reference/statements/empty/index.html @@ -0,0 +1,102 @@ +--- +title: empty +slug: Web/JavaScript/Reference/Statements/Empty +translation_of: Web/JavaScript/Reference/Statements/Empty +--- +
{{jsSidebar("Statements")}}
+ +

empty 문은 JavaScript 아무것도 동작하지 않습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-empty.html")}}
+ + + +

구문

+ +
;
+
+ +

설명

+ +

empty statement은 JavaScript구문에 하나가 필요할 때 어떤 문도 실행되지 않을 것이라는 것을 나타내는 세미 콜론(;)입니다. 여러개의 문장을 원하지만 JavaScript는 block statement을 사용하여 하나만 허용하며 여러개의 문장을 하나로 결합합니다.

+ +

예제

+ +

빈 문은 루프 문과 함께 사용되기도합니다. 빈 루프 본문이있는 다음 예제를 참조하십시오.

+ +
var arr = [1, 2, 3];
+
+// Assign all array values to 0
+for (i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ;
+
+console.log(arr)
+// [0, 0, 0]
+
+ +

참고: 정상적인 세미 콜론을 구분하는 것이 그리 쉽지 않기 때문에, empty statement를 사용할 때는 의도적으로 주석을 달아주는것이 좋습니다. 다음 예 에서는 의도한대로 코드가 동작하지 않을것입니다. 아마도 killTheUniverse()를 if문 안에서 실행하고자 했던것 같습니다.

+ +
if (condition);       // Caution, this "if" does nothing!
+   killTheUniverse()  // So this always gets executed!!!
+
+ +

다른 예 : 중괄호 ({})가없는 if...else 문에서 three가 true이면 아무 일도 일어나지 않고 four를 건너 뛰고 else case의 launchRocket() 함수도 실행되지 않습니다.

+ +
if (one)
+  doOne();
+else if (two)
+  doTwo();
+else if (three)
+  ; // nothing here
+else if (four)
+  doFour();
+else
+  launchRocket();
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.3', 'Empty statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES1')}}Initial definition.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.empty")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/statements/export/index.html b/files/ko/web/javascript/reference/statements/export/index.html new file mode 100644 index 0000000000..1c15d4e7f9 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/export/index.html @@ -0,0 +1,199 @@ +--- +title: export +slug: Web/JavaScript/Reference/Statements/export +tags: + - ECMAScript 2015 + - JavaScript + - Modules + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/export +--- +
{{jsSidebar("Statements")}}
+ +

export 문은 JavaScript 모듈에서 함수, 객체, 원시 값을 내보낼 때 사용합니다. 내보낸 값은 다른 프로그램에서 {{jsxref("Statements/import", "import")}} 문으로 가져가 사용할 수 있습니다.

+ +

내보내는 모듈은 "use strict"의 존재 유무와 상관없이 무조건 엄격 모드입니다. export 문은 HTML 안에 작성한 스크립트에서는 사용할 수 없습니다.

+ +

구문

+ +
// 하나씩 내보내기
+export let name1, name2, …, nameN; // var, const도 동일
+export let name1 = …, name2 = …, …, nameN; // var, const도 동일
+export function functionName(){...}
+export class ClassName {...}
+
+// 목록으로 내보내기
+export { name1, name2, …, nameN };
+
+// 내보내면서 이름 바꾸기
+export { variable1 as name1, variable2 as name2, …, nameN };
+
+// 비구조화로 내보내기
+export const { name1, name2: bar } = o;
+
+// 기본 내보내기
+export default expression;
+export default function (…) { … } // also class, function*
+export default function name1(…) { … } // also class, function*
+export { name1 as default, … };
+
+// 모듈 조합
+export * from …; // does not set the default export
+export * as name1 from …;
+export { name1, name2, …, nameN } from …;
+export { import1 as name1, import2 as name2, …, nameN } from …;
+export { default } from …;
+ +
+
nameN
+
내보낼 식별자 이름. {{jsxref("Statements/import", "import")}}를 사용해 다른 스크립트에서 가져갈 수 있습니다.
+
+ +

설명

+ +

내보내기에는 두 종류, 유명(named)과 기본(default) 내보내기가 있습니다. 모듈 하나에서, 유명 내보내기는 여러 개 존재할 수 있지만 기본 내보내기는 하나만 가능합니다. 각 종류는 위의 구문 중 하나와 대응합니다.

+ + + +

유명 내보내기는 여러 값을 내보낼 때 유용합니다. 가져갈 때는 내보낸 이름과 동일한 이름을 사용해야 합니다.

+ +

반면 기본 내보내기는 어떤 이름으로도 가져올 수 있습니다.

+ +
// test.js
+let k; export default k = 12;
+ +
// 임의의 다른 파일
+import m from './test'; // k가 기본 내보내기이므로, 가져오는 이름으로 k 대신 m을 사용해도 문제 없음
+console.log(m);         // 12 기록
+ +

식별자 충돌을 피하기 위해 유명 내보내기 중 이름을 바꿔줄 수도 있습니다.

+ +
export { myFunction as function1,
+         myVariable as variable };
+ +

다시 내보내기 / 조합

+ +

부모 모듈이 자식 모듈을 가져와서 다시 내보낼 수도 있습니다. 즉, 여러 개의 모듈을 모아놓을 하나의 모듈을 만들 수 있습니다.

+ +
export foo from 'bar.js';
+
+ +

위 구문은 아래와 동일합니다.

+ +
import foo from 'bar.js';
+export foo;
+
+ +

예제

+ +

유명 내보내기 사용

+ +

어떤 모듈에서 다음과 같은 코드를 가진다고 해보겠습니다.

+ +
// module "my-module.js"
+function cube(x) {
+  return x * x * x;
+}
+const foo = Math.PI + Math.SQRT2;
+var graph = {
+    options: {
+        color:'white',
+        thickness:'2px'
+    },
+    draw: function() {
+        console.log('From graph draw function');
+    }
+}
+export { cube, foo, graph };
+ +

다른 스크립트에서는 아래와 같이 사용할 수 있습니다.

+ +
// You should use this script in html with the type module.
+// For example:
+//   <script type="module" src="./demo.js"></script>
+//
+// Open the page in a http server, otherwise there will be a CORS policy error.
+//
+// script demo.js
+
+import { cube, foo, graph } from 'my-module';
+graph.options = {
+    color:'blue',
+    thickness:'3px'
+};
+graph.draw();
+console.log(cube(3)); // 27
+console.log(foo);    // 4.555806215962888
+ +

기본 내보내기 사용

+ +

단일 값을 내보낼 때나 모듈의 폴백fallback 값이 필요할 땐 기본 내보내기를 사용할 수 있습니다.

+ +
// module "my-module.js"
+export default function cube(x) {
+  return x * x * x;
+}
+ +

그런 다음, 다른 스크립트에서 가져오는건 간단합니다:

+ +
import cube from './my-module.js';
+console.log(cube(3)); // 27
+ +

export default를 사용할 때 var, let, const는 사용하지 못합니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-exports', 'Exports')}}{{Spec2('ES2015')}}Initial definition.
+ +

브라우저 호환성

+ +

{{Compat("javascript.statements.export")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/for-await...of/index.html b/files/ko/web/javascript/reference/statements/for-await...of/index.html new file mode 100644 index 0000000000..c52d226e27 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for-await...of/index.html @@ -0,0 +1,144 @@ +--- +title: for await...of +slug: Web/JavaScript/Reference/Statements/for-await...of +tags: + - 구문 + - 반복문 + - 비동기 + - 식 + - 열거 + - 열거자 +translation_of: Web/JavaScript/Reference/Statements/for-await...of +--- +
{{jsSidebar("Statements")}}
+ +

for await...of 구문은 보통 비동기에 대응하는 열거자를 나열할 때 쓰이지만, {{jsxref("String")}}, {{jsxref("Array")}}, Array 같은 객체 (e.g., {{jsxref("Functions/arguments", "arguments")}} or NodeList), {{jsxref("TypedArray")}}, {{jsxref("Map")}}, {{jsxref("Set")}} 같은 동기적으로 열거 가능한 객체 또한 가능하며, 사용자가 직접 정의한 동기 또는 비동기 객체도 나열할 수 있도록 해준다. 일반적인 for ...of 문과 마찬가지로 열거자 심볼이 정의한 속성을 실행하게 되어 열거한 값을 변수로 받아 처리한다.

+ + + +

구문

+ +
for await (variable of iterable) {
+  statement
+}
+
+ +
+
variable
+
열거할 때마다 variable. 문을 통해 변수로 받을 수 있다. variable 문 안에서는 const, let 및 var. 문으로 선언된 변수 및 상수를 선언할 수 있다.
+
iterable
+
열거 가능한 속성이 들어가 있는 객체 및 식을 포함한다.
+
+ +

비동기 열거 속성을 통한 열거 식

+ +

비동기 열거 프로토콜을 담은 객체를 아래와 같이 열거할 수 있다.

+ +
const asyncIterable = {
+  [Symbol.asyncIterator]() {
+    return {
+      i: 0,
+      next() {
+        if (this.i < 3) {
+          return Promise.resolve({ value: this.i++, done: false });
+        }
+
+        return Promise.resolve({ done: true });
+      }
+    };
+  }
+};
+
+(async function() {
+   for await (let num of asyncIterable) {
+     console.log(num);
+   }
+})();
+
+// 0
+// 1
+// 2
+
+ +

비동기 생성자를 통한 열거 식

+ +

비동기 생성자는 애초부터 비동기 열거 프로토콜을 탑재한 채로 정의한다.이를 for await...of 식으로 아래와 같이 사용할 수 있다.

+ +
async function* asyncGenerator() {
+  let i = 0;
+  while (i < 3) {
+    yield i++;
+  }
+}
+
+(async function() {
+  for await (let num of asyncGenerator()) {
+    console.log(num);
+  }
+})();
+// 0
+// 1
+// 2
+ +

좀 더 상세한 비동기 생성자를 통한 for await...of 식의 사용법을 위해 기본 API를 통해 값을 비동기적으로 열거하는 방법을 알아본다.

+ +

아래 예제를 통해 먼저 API를 사용하여 스트림 데이터를 통해 비동기 열거자를 만든 뒤, 스트림에서 응답이 끝나면 최종 응답 데이터 크기를 가져온다.

+ +
async function* streamAsyncIterator(stream) {
+  const reader = stream.getReader();
+  try {
+    while (true) {
+      const { done, value } = await reader.read();
+      if (done) {
+        return;
+      }
+      yield value;
+    }
+  } finally {
+    reader.releaseLock();
+  }
+}
+// 주소로부터 데이터를 받아온 뒤, 응답 크기를 구하는 비동기 생성자 함수.
+async function getResponseSize(url) {
+  const response = await fetch(url);
+  // 여기에 응답 크기를 바이트 단위로 적재한다.
+  let responseSize = 0;
+  // for-await-of 문을 통해 응답이 들어올 때마다 열거 프로토콜을 통해 반복문이 작동한다.
+  for await (const chunk of streamAsyncIterator(response.body)) {
+    // 총 응답 크기를 지속적으로 누적한다.
+    responseSize += chunk.length;
+  }
+
+  console.log(`응답 크기: ${responseSize} 바이트`);
+  // 예상 출력: "응답 크기: 1071472 바이트"
+  return responseSize;
+}
+getResponseSize('https://jsonplaceholder.typicode.com/photos');
+ +

규격

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'ECMAScript Language: The for-in, for-of, and for-await-of Statements')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.for_await_of")}}

+ +

같이보기

+ + diff --git a/files/ko/web/javascript/reference/statements/for...in/index.html b/files/ko/web/javascript/reference/statements/for...in/index.html new file mode 100644 index 0000000000..983e50c91f --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for...in/index.html @@ -0,0 +1,176 @@ +--- +title: for...in +slug: Web/JavaScript/Reference/Statements/for...in +tags: + - JavaScript + - Statement +translation_of: Web/JavaScript/Reference/Statements/for...in +--- +
{{jsSidebar("Statements")}}
+ +

for...in문은 상속된 열거 가능한 속성들을 포함하여 객체에서 문자열로 키가 지정된 모든 열거 가능한 속성에 대해 반복합니다. (Symbol로 키가 지정된 속성은 무시합니다.)

+ +

{{EmbedInteractiveExample("pages/js/statement-forin.html")}}

+ +

문법

+ +
for (variable in object) { ... }
+ +

파라미터

+ +
+
variable
+
매번 반복마다 다른 속성이름(Value name)이 변수(variable)로 지정됩니다.
+
object
+
반복작업을 수행할 객체로 열거형 속성을 가지고 있는 객체.
+
+ +

설명

+ +

for...in문은 열거 가능한 non-Symbol 속성에 대해서만 반복합니다.
+ ArrayObject 등 내장 constructor를 통해 만들어진 객체는  {{jsxref("String")}}의 {{jsxref("String.indexOf", "indexOf()")}}, {{jsxref("Object")}}의 {{jsxref("Object.toString", "toString()")}}와 같이 Object.prototype, String.prototype 로부터 열거가 가능하지 않은 속성들을 상속해왔습니다. for...in문은 객체 자체의 모든 열거 가능한 속성들과 프로토타입 체인으로부터 상속받은 속성들에 대해 반복할 것입니다. (더 가까운 프로토타입의 속성들이 프로토타입 체인 객체로부터 더 멀리 떨어진 프로토 타입의 속성보다 더 우선합니다.)

+ +

속성의 삭제, 추가, 수정 

+ +

for..in 문은 임의의 순서로 객체의 속성들에 대해 반복합니다. (적어도 cross-browser 설정에서는 왜 표면적으로 보이는 반복의 순서를 따를 수 없는지에 대해서  {{jsxref("Operators/delete", "delete")}} 를 참고하십시오.)

+ +

만약 한 반복으로 속성이 수정된 후에 방문하는 경우, 반복문에서의 그 값은 나중의 값으로 정해집니다. 방문하기 전에 삭제된 속성에 대해서는 이후에 방문하지 않습니다. 반복이 발생하는 객체에 추가된 속성은 방문하거나 반복에서 생략할 수 있습니다.

+ +

일반적으로 현재 방문 중인 속성 외에는 반복하는 동안 객체의 속성을 추가, 수정, 제거하지 않는 것이 가장 좋습니다. 추가된 속성을 방문할 것인지, 수정된 속성(현재의 속성 제외)을 수정 이전 혹은 이후에 방문할 것인지, 삭제된 속성을 삭제 이전에 방문할 것인지에 대해서는 보장할 수 없습니다.

+ +

배열의 반복과 for...in

+ +
+

Note: for...in 인덱스의 순서가 중요한 {{jsxref("Array")}}에서 반복을 위해 사용할 수 없습니다.

+
+ +

배열 인덱스는 정수로 된 열거 가능한 속성이며, 일반적인 객체의 속성들과 같습니다. for...in은 특정 순서에 따라 인덱스를 반환하는 것을 보장할 수 없습니다. for...in반복문은 정수가 아닌 이름을 가진 속성, 상속된 모든 열거 가능한 속성들을 반환합니다.

+ +

반복되는 순서는 구현에 따라 다르기 때문에, 배열의 반복이 일관된 순서로 요소를 방문하지 못할 수도 있습니다. 그러므로 방문의 순서가 중요한 배열의 반복시에는 숫자 인덱스를 사용할 수 있는 for 반복문을 사용하는 것이 좋습니다.(또는 {{jsxref("Array.prototype.forEach()")}}, {{jsxref("Statements/for...of", "for...of")}}를 권장합니다.)

+ +

자체 속성만 반복

+ +

만약 당신이 객체의 프로토타입이 아닌 객체 자체에 연결된 속성만 고려한다면 {{jsxref("Object.getOwnPropertyNames", "getOwnPropertyNames()")}}나 {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}}를 사용하십시오.({{jsxref("Object.prototype.propertyIsEnumerable", "propertyIsEnumerable()")}} 또한 가능합니다.)  또는 외부적인 코드 간섭이 없다면 체크 메서드로 내장 프로토타입을 확장할 수 있습니다.

+ +

왜 for...in을 사용합니까?

+ +

for...in이 객체의 반복을 위해 만들어졌지만, 배열의 반복을 위해서는 추천되지 않고,  Array.prototype.forEach()for...of가 이미 존재합니다. 그러면 for...in은 어떻게 사용하는 것이 좋을까요?

+ +

이것은 쉽게 객체의 속성을 확인(콘솔이나 다른 방법으로 출력)할 수 있기 때문에 실질적으로 디버깅을 위해 사용될 수 있습니다. 배열이 데이터의 저장에 있어서는 더 실용적이지만, 키-값 쌍이 선호되는 데이터의 경우(속성이 "key"의 역할을 함) 특정 값을 가진 키가 있는지 확인하려는 경우에 for...in을 사용할 수 있습니다.

+ +

예제

+ +

for...in의 사용

+ +

아래의 예는 열거 가능한 non-Symbol속성들을 반복해서 속성의 이름과 그 값을 기록합니다.

+ +
var obj = {a: 1, b: 2, c: 3};
+
+for (const prop in obj) {
+  console.log(`obj.${prop} = ${obj[prop]}`);
+}
+
+// Output:
+// "obj.a = 1"
+// "obj.b = 2"
+// "obj.c = 3"
+ +

자체 속성 반복

+ +

아래는 {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}} 를 사용하는 예를 보여주고 있습니다. 상속된 속성은 표시되지 않습니다.

+ +
var triangle = {a:1, b:2, c:3};
+
+function ColoredTriangle() {
+  this.color = "red";
+}
+
+ColoredTriangle.prototype = triangle;
+
+function show_own_props(obj, objName) {
+  var result = "";
+
+  for (var prop in obj) {
+    if( obj.hasOwnProperty( prop ) ) {
+      result += objName + "." + prop + " = " + obj[prop] + "\n";
+    }
+  }
+
+  return result;
+}
+
+o = new ColoredTriangle();
+alert(show_own_props(o, "o")); /* alerts: o.color = red */
+
+ +

상세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-12.6.3', 'for...in statement')}}{{Spec2('ES1')}}Initial definition.
+ +

브라우저 호환성

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

{{Compat("javascript.statements.for_in")}}

+ +

Compatibility: Initializer expressions in strict mode

+ +

Prior to SpiderMonkey 40 {{geckoRelease(40)}}, it was possible to use an initializer expression (i=0) in a for...in loop:

+ +
var obj = {a: 1, b: 2, c: 3};
+for (var i = 0 in obj) {
+  console.log(obj[i]);
+}
+// 1
+// 2
+// 3
+ +

This nonstandard behavior is now ignored in version 40 and later, and will present a {{jsxref("SyntaxError")}} ("for-in loop head declarations may not have initializers") error in strict mode ({{bug(748550)}} and {{bug(1164741)}}).

+ +

Other engines such as v8 (Chrome), Chakra (IE/Edge), and JSC (WebKit/Safari) are investigating whether to remove the nonstandard behavior as well.

+ +

관련 문서

+ + diff --git a/files/ko/web/javascript/reference/statements/for...of/index.html b/files/ko/web/javascript/reference/statements/for...of/index.html new file mode 100644 index 0000000000..d082763616 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for...of/index.html @@ -0,0 +1,228 @@ +--- +title: for...of +slug: Web/JavaScript/Reference/Statements/for...of +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/for...of +--- +
{{jsSidebar("Statements")}}
+ +

for...of 명령문반복가능한 객체 ({{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("String")}}, {{jsxref("TypedArray")}}, arguments 객체 등을 포함)에 대해서 반복하고 각 개별 속성값에 대해 실행되는 문이 있는 사용자 정의 반복 후크를 호출하는 루프를 생성합니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-forof.html")}}
+ + + +

구문

+ +
for (variable of iterable) {
+  statement
+}
+
+ +
+
variable
+
각 반복에 서로 다른 속성값이 variable에 할당됩니다.
+
iterable
+
반복되는 열거가능(enumerable)한 속성이 있는 객체.
+
+ +

예제

+ +

{{jsxref("Array")}}에 대해 반복:

+ +
let iterable = [10, 20, 30];
+
+for (let value of iterable) {
+  console.log(value);
+}
+// 10
+// 20
+// 30
+
+ +

let 대신 const도 사용할 수 있습니다, 블록 내부 변수를 수정하지 않는 경우.

+ +
let iterable = [10, 20, 30];
+
+for (const value of iterable) {
+  console.log(value);
+}
+// 10
+// 20
+// 30
+
+ +

{{jsxref("String")}}에 대해 반복:

+ +
let iterable = "boo";
+
+for (let value of iterable) {
+  console.log(value);
+}
+// "b"
+// "o"
+// "o"
+
+ +

{{jsxref("TypedArray")}}에 대해 반복:

+ +
let iterable = new Uint8Array([0x00, 0xff]);
+
+for (let value of iterable) {
+  console.log(value);
+}
+// 0
+// 255
+
+ +

{{jsxref("Map")}}에 대해 반복:

+ +
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
+
+for (let entry of iterable) {
+  console.log(entry);
+}
+// [a, 1]
+// [b, 2]
+// [c, 3]
+
+for (let [key, value] of iterable) {
+  console.log(value);
+}
+// 1
+// 2
+// 3
+
+ +

{{jsxref("Set")}}에 대해 반복:

+ +
let iterable = new Set([1, 1, 2, 2, 3, 3]);
+
+for (let value of iterable) {
+  console.log(value);
+}
+// 1
+// 2
+// 3
+
+ +

DOM 컬렉션에 대해 반복

+ +

{{domxref("NodeList")}} 같은 DOM 컬렉션에 대해 반복: 다음 예는 article의 직계 자손인 paragraph에 read 클래스를 추가합니다:

+ +
// 주의: 이는 NodeList.prototype[Symbol.iterator]가
+// 구현된 플랫폼에서만 작동합니다
+let articleParagraphs = document.querySelectorAll("article > p");
+
+for (let paragraph of articleParagraphs) {
+  paragraph.classList.add("read");
+}
+
+ +

생성기에 대해 반복

+ +

생성기에 대해서도 반복할 수 있습니다:

+ +
function* fibonacci() { // 생성기 함수
+  let [prev, curr] = [1, 1];
+  while (true) {
+    [prev, curr] = [curr, prev + curr];
+    yield curr;
+  }
+}
+
+for (let n of fibonacci()) {
+  console.log(n);
+  // 1000에서 수열을 자름
+  if (n >= 1000) {
+    break;
+  }
+}
+
+ +

다른 반복가능 객체에 대해 반복

+ +

iterable 프로토콜을 명시해서 구현하는 객체에 대해서도 반복할 수 있습니다:

+ +
var iterable = {
+  [Symbol.iterator]() {
+    return {
+      i: 0,
+      next() {
+        if (this.i < 3) {
+          return { value: this.i++, done: false };
+        }
+        return { value: undefined, done: true };
+      }
+    };
+  }
+};
+
+for (var value of iterable) {
+  console.log(value);
+}
+// 0
+// 1
+// 2
+
+ +

for...offor...in의 차이

+ +

for...in 루프는 객체의 모든 열거가능한 속성에 대해 반복합니다.

+ +

for...of 구문은 컬렉션 전용입니다. 모든 객체보다는, [Symbol.iterator] 속성이 있는 모든 컬렉션 요소에 대해 이 방식으로 반복합니다.

+ +

다음 예는 for...of 루프와 for...in 루프의 차이를 보입니다.

+ +
Object.prototype.objCustom = function () {};
+Array.prototype.arrCustom = function () {};
+
+let iterable = [3, 5, 7];
+iterable.foo = "hello";
+
+for (let i in iterable) {
+  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
+}
+
+for (let i of iterable) {
+  console.log(i); // logs 3, 5, 7
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ES6')}}초기 정의.
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ +

{{Compat("javascript.statements.for_of")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/for/index.html b/files/ko/web/javascript/reference/statements/for/index.html new file mode 100644 index 0000000000..cba49dbba6 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for/index.html @@ -0,0 +1,160 @@ +--- +title: for +slug: Web/JavaScript/Reference/Statements/for +tags: + - JavaScript + - Loop + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/for +--- +
{{jsSidebar("Statements")}}
+ +

for 문은 괄호로 감싸고 세미콜론으로 구분한 세 개의 선택식과, 반복을 수행할 문(주로 {{jsxref("Statements/block", "블럭문", "", 0)}})으로 이루어져 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-for.html")}}
+ + + +

구문

+ +
for ([initialization]; [condition]; [final-expression])
+   statement
+
+ +
+
initialization
+
식(할당식 포함) 또는 변수 선언. 주로 카운터 변수를 초기화할 때 사용합니다. var 또는 let 키워드를 사용해 새로운 변수를 선언할 수도 있습니다. var 키워드로 선언한 변수는 반복문에 제한되지 않습니다. 즉 for 문과 같은 범위scope에 위치합니다. let 키워드로 선언한 변수는 반복문의 지역 변수가 됩니다.
+
+ 식의 결과는 버려집니다.
+
condition
+
매 반복마다 평가할 식. 평가 결과가 참이라면 statement를 실행합니다. 이 식을 넣지 않았을 때 계산 결과는 언제나 참이 됩니다. 계산 결과가 거짓이라면 for 문의 바로 다음 식으로 건너 뜁니다.
+
final-expression
+
매 반복 후 평가할 식. 다음번 condition 평가 이전에 발생합니다. 주로 카운터 변수를 증감하거나 바꿀 때 사용합니다.
+
statement
+
조건의 평가 결과가 참일 때 실행하는 문. 여러 문을 반복 실행하려면 {{jsxref("Statements/block", "블럭문", "", 0)}}({ ... })으로 묶어야 합니다. 아무것도 실행하지 않으려면 {{jsxref("Statements/empty", "공백문", "", 0)}} (;)을 사용하세요.
+
+ +

예제

+ +

for 사용하기

+ +

다음 for 문은 변수 i를 선언하고 0으로 초기화하여 시작합니다. i가 9보다 작은지를 확인하고 맞으면 명령문을 수행한 후 i의 값을 1 높입니다.

+ +
for (var i = 0; i < 9; i++) {
+   console.log(i);
+   // 기타 등등
+}
+
+ +

선택적 식 사용

+ +

for 반복문의 3개 식은 모두 선택 사항입니다.

+ +

예를 들어, 변수를 초기화하려고 initialization 블럭을 사용할 필요는 없습니다.

+ +
var i = 0;
+for (; i < 9; i++) {
+    console.log(i);
+    // 기타 등등
+}
+
+ +

initialization 블럭처럼 condition 블럭도 선택 사항입니다. 다만 이 경우, 반복문 본문에 무한 반복을 탈출할 수 있는 장치를 추가해야 합니다.

+ +
for (var i = 0;; i++) {
+   console.log(i);
+   if (i > 3) break;
+   // 기타 등등
+}
+ +

세 가지 모두 생략할 수도 있습니다. 위와 같이 {{jsxref("Statements/break", "break")}} 문을 사용해 반복을 탈출할 수 있도록 추가하고, 변수를 수정해 탈출 조건이 언젠가 참이 되도록 해야 합니다.

+ +
var i = 0;
+
+for (;;) {
+  if (i > 3) break;
+  console.log(i);
+  i++;
+}
+
+ +

문 없이 for 사용하기

+ +

다음 for 반복 사이클은 노드의 위치 오프셋을 final-expression에서 계산해 문이나 블럭문이 필요하지 않으므로 세미콜론을 사용합니다.

+ +
function showOffsetPos(sId) {
+  var nLeft = 0, nTop = 0;
+
+  for (
+    var oItNode = document.getElementById(sId); /* initialization */
+    oItNode; /* condition */
+    nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */
+  ); /* semicolon */
+
+  console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;');
+}
+
+/* Example call: */
+
+showOffsetPos('content');
+
+// Output:
+// "Offset position of "content" element:
+// left: 0px;
+// top: 153px;"
+ +
참고: 여기서 쓰인 세미콜론은, JavaScript가 필수로 요구하는 몇 안되는 세미콜론입니다. 물론 세미콜론 없이는 반복 사이클 선언의 바로 다음 줄을 반복 본문으로 인식합니다.
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-12.6.2', 'for statement')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES3', '#sec-12.6.3', 'for statement')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12.6.3', 'for statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-for-statement', 'for statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.statements.for")}}

+ +

참조

+ + diff --git a/files/ko/web/javascript/reference/statements/for_each...in/index.html b/files/ko/web/javascript/reference/statements/for_each...in/index.html new file mode 100644 index 0000000000..9fa9901aae --- /dev/null +++ b/files/ko/web/javascript/reference/statements/for_each...in/index.html @@ -0,0 +1,85 @@ +--- +title: for each...in +slug: Web/JavaScript/Reference/Statements/for_each...in +tags: + - Deprecated + - E4X + - JavaScript + - Obsolete + - Statement +translation_of: Archive/Web/JavaScript/for_each...in +--- +
{{jsSidebar("Statements")}}
+ +
+

The for each...in statement is deprecated as the part of ECMA-357 (E4X) standard. E4X support has been removed. Consider using for...of instead.
+
+ Firefox now warns about the usage of for each...in and it no longer works starting with Firefox 57.
+ Please see Warning: JavaScript 1.6's for-each-in loops are deprecated for migration help.

+
+ +

for each...in 문은 객체의 모든 속성 값에 대해 지정된 변수를 반복합니다. 각각의 고유한 특성에 대해 지정된 명령문이 실행됩니다.

+ +

Syntax

+ +
for each (variable in object) {
+  statement
+}
+ +
+
variable
+
var 키워드로 선택적으로 선언된 속성 값을 반복하는 변수입니다. 이 변수는 루프가 아니라 함수의 local이 됩니다.
+
+ +
+
object
+
반복될 객체입니다.
+
+ +
+
statement
+
각 속성에 대해 실행할 명령문입니다. 루프 내에서 여러 명령문을 실행하려면 블록 명령문 ({...})을 사용하여 해당 명령문을 그룹화하십시오.
+
+ +

Description

+ +

일부 기본 제공 속성은 반복되지 않습니다. 여기에는 객체 기본 제공 메서드 전부가 포함됩니다.

+ +

ex) String의 indexOf 메소드.

+ +

그러나 사용자가 정의한 모든 속성은 반복됩니다.

+ +

Examples

+ +

Using for each...in

+ +

Warning: Never use a loop like this on arrays. Only use it on objects. See for...in for more details.

+ +

The following snippet iterates over an object's properties, calculating their sum:

+ +
var sum = 0;
+var obj = {prop1: 5, prop2: 13, prop3: 8};
+
+for each (var item in obj) {
+  sum += item;
+}
+
+console.log(sum); // logs "26", which is 5+13+8
+ +

Specifications

+ +

Not part of a current ECMA-262 specification. Implemented in JavaScript 1.6 and deprecated.

+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.for_each_in")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/statements/function/index.html b/files/ko/web/javascript/reference/statements/function/index.html new file mode 100644 index 0000000000..fe1eee366a --- /dev/null +++ b/files/ko/web/javascript/reference/statements/function/index.html @@ -0,0 +1,177 @@ +--- +title: 함수 선언 +slug: Web/JavaScript/Reference/Statements/function +tags: + - Function + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/function +--- +
{{jsSidebar("Statements")}}
+ +

함수 선언(function declaration)은 지정된 매개변수(parameter)를 갖는 함수를 정의합니다.

+ +

{{jsxref("Function")}} 생성자나 {{jsxref("Operators/function", "함수 표현식(function expression)")}}을 사용해서 정의할 수도 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-function.html")}}
+ + + +

구문

+ +
function name([param[, param,[..., param]]]) { [statements] }
+
+ +
+
name
+
함수 이름.
+
+ +
+
param
+
함수로 전달되는 인수(argument)의 이름. 인수의 최대 개수는 엔진마다 다름.
+
+ +
+
statements
+
함수의 몸통(body)을 구성하는 문(statement).
+
+ +

설명

+ +

함수 선언으로 생성된 함수는 Function 객체로, Function 객체의 모든 속성(property), 메서드 및 행위 특성(behavior)을 갖습니다. 함수에 관한 더 자세한 정보는 {{jsxref("Function")}} 참조하시기 바랍니다.

+ +

함수는 또한 표현식({{jsxref("Operators/function", "함수 표현식")}} 참조)을 사용하여 생성될 수 있습니다.

+ +

기본적으로 함수는 undefined를 반환합니다. 다른 값을 반환하기 위해서는, 함수는 반환값을 지정하는 {{jsxref("Statements/return", "return")}} 문이 있어야 합니다.

+ +

조건부로 생성되는 함수

+ +

함수는 조건부로 선언될 수 있습니다. 즉, function 문은 if 문 안에 들어갈 수 있습니다. 하지만, 구현에 따라 결과에 일관성이 없으므로 이 패턴은 실제 코드에서는 사용해선 안됩니다. 조건부로 함수를 생성하고자 한다면, 함수 표현식(function expression)을 대신 사용하세요.

+ +
var hoisted = "foo" in this;
+console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
+if (false) {
+  function foo(){ return 1; }
+}
+
+// In Chrome:
+// 'foo' name is hoisted. typeof foo is undefined
+//
+// In Firefox:
+// 'foo' name is hoisted. typeof foo is undefined
+//
+// In Edge:
+// 'foo' name is not hoisted. typeof foo is undefined
+//
+// In Safari:
+// 'foo' name is hoisted. typeof foo is function
+
+ +

결과는 참으로 평가되는 조건과 정확하게 일치합니다.

+ +
var hoisted = "foo" in this;
+console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
+if (true) {
+  function foo(){ return 1; }
+}
+
+// In Chrome:
+// 'foo' name is hoisted. typeof foo is undefined
+//
+// In Firefox:
+// 'foo' name is hoisted. typeof foo is undefined
+//
+// In Edge:
+// 'foo' name is not hoisted. typeof foo is undefined
+//
+// In Safari:
+// 'foo' name is hoisted. typeof foo is function
+
+ +

함수 선언 끌어올리기

+ +

자바스크립트에서 함수 선언은 그 선언을 둘러싼 함수의 최상부나 전역 범위(global scope)로 끌어올려집니다.

+ +
hoisted(); // logs "foo"
+
+function hoisted() {
+  console.log("foo");
+}
+
+ +

{{jsxref("Operators/function", "함수 표현식")}}은 끌어올려지지 않으므로 주의하세요:

+ +
notHoisted(); // TypeError: notHoisted is not a function
+
+var notHoisted = function() {
+   console.log("bar");
+};
+
+ +

예제

+ +

function 사용하기

+ +

다음 코드는 제품 a, bc의 단위 판매량이 주어졌을 때, 총 판매량을 반환하는 함수를 선언합니다.

+ +
function calc_sales(units_a, units_b, units_c) {
+   return units_a*79 + units_b * 129 + units_c * 699;
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-13', 'Function definition')}}{{Spec2('ES1')}}초기 정의. JavaScript 1.0에서 구현됨.
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.function")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/function_star_/index.html b/files/ko/web/javascript/reference/statements/function_star_/index.html new file mode 100644 index 0000000000..9178c28602 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/function_star_/index.html @@ -0,0 +1,159 @@ +--- +title: function* +slug: Web/JavaScript/Reference/Statements/function* +tags: + - ECMAScript6 + - Generator + - Iterator + - JavaScript +translation_of: Web/JavaScript/Reference/Statements/function* +--- +
{{jsSidebar("Statements")}}
+ +

function* 선언 (끝에 별표가 있는 function keyword) 은 generator function 을 정의하는데, 이 함수는 {{jsxref("Global_Objects/Generator","Generator")}} 객체를 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-functionasterisk.html")}}
+ + + +

generator function 은 {{jsxref("Global_Objects/GeneratorFunction", "GeneratorFunction")}} 생성자와 {{jsxref("Operators/function*", "function* expression")}} 을 사용해서 정의할 수 있습니다.

+ +

문법

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
함수명.
+
+ +
+
param
+
함수에 전달되는 인수의 이름. 함수는 인수를 255개까지 가질 수 있다.
+
+ +
+
statements
+
함수의 본체를 구성하는 구문들.
+
+ +

설명

+ +

Generator는 빠져나갔다가 나중에 다시 돌아올 수 있는 함수입니다. 이때 컨텍스트(변수 값)는 출입 과정에서 저장된 상태로 남아 있습니다.

+ +

Generator 함수는 호출되어도 즉시 실행되지 않고, 대신 함수를 위한 Iterator 객체가 반환됩니다. Iterator의 next() 메서드를 호출하면 Generator 함수가 실행되어 {{jsxref("Operators/yield", "yield")}} 문을 만날 때까지 진행하고, 해당 표현식이 명시하는 Iterator로부터의 반환값을 반환합니다. {{jsxref("Operators/yield*", "yield*")}} 표현식을 마주칠 경우, 다른 Generator 함수가 위임(delegate)되어 진행됩니다.

+ +

이후 next() 메서드가 호출되면 진행이 멈췄던 위치에서부터 재실행합니다. next() 가 반환하는 객체는 yield문이 반환할 값(yielded value)을 나타내는 value 속성과, Generator 함수 안의 모든 yield 문의 실행 여부를 표시하는 boolean 타입의 done 속성을 갖습니다. next() 를 인자값과 함께 호출할 경우, 진행을 멈췄던 위치의 yield 문을  next() 메서드에서 받은 인자값으로 치환하고 그 위치에서 다시 실행하게 됩니다.

+ +

예시

+ +

간단한 예제

+ +
function* idMaker(){
+  var index = 0;
+  while(index < 3)
+    yield index++;
+}
+
+var gen = idMaker();
+
+console.log(gen.next().value); // 0
+console.log(gen.next().value); // 1
+console.log(gen.next().value); // 2
+console.log(gen.next().value); // undefined
+// ...
+
+ +

yield* 를 사용한 예제

+ +
function* anotherGenerator(i) {
+  yield i + 1;
+  yield i + 2;
+  yield i + 3;
+}
+
+function* generator(i){
+  yield i;
+  yield* anotherGenerator(i);
+  yield i + 10;
+}
+
+var gen = generator(10);
+
+console.log(gen.next().value); // 10
+console.log(gen.next().value); // 11
+console.log(gen.next().value); // 12
+console.log(gen.next().value); // 13
+console.log(gen.next().value); // 20
+
+ +

Generator 에 인자값을 넘기는 예제

+ +
function* logGenerator() {
+  console.log(yield);
+  console.log(yield);
+  console.log(yield);
+}
+
+var gen = logGenerator();
+
+// the first call of next executes from the start of the function
+// until the first yield statement
+gen.next();
+gen.next('pretzel'); // pretzel
+gen.next('california'); // california
+gen.next('mayonnaise'); // mayonnaise
+
+ +

Generator 는 생성자로서 사용될 수 없다

+ +
function* f() {}
+var obj = new f; // throws "TypeError: f is not a constructor"
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#', 'function*')}}{{Spec2('ES2015')}}Initial definition.
+ +

Browser compatibility

+ +

{{Compat("javascript.statements.generator_function")}}

+ +

관련 항목

+ + diff --git a/files/ko/web/javascript/reference/statements/if...else/index.html b/files/ko/web/javascript/reference/statements/if...else/index.html new file mode 100644 index 0000000000..cde42b2a80 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/if...else/index.html @@ -0,0 +1,177 @@ +--- +title: if...else +slug: Web/JavaScript/Reference/Statements/if...else +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/if...else +--- +
{{jsSidebar("Statements")}}
+ +

if은 지정한 조건이 {{glossary("truthy", "참")}}인 경우 명령문(statement)을 실행합니다. 조건이 {{glossary("falsy", "거짓")}}인 경우 또 다른 명령문이 실행 될 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-ifelse.html")}}
+ + + +

구문

+ +
if (condition)
+   statement1
+[else
+   statement2]
+
+ +
+
condition
+
참 또는 거짓으로 평가되는 표현식입니다.
+
+ +
+
statement1
+
조건이 참으로 평가될 경우 실행되는 문입니다.
+ 중첩된 if구문을 포함하여 어떤 구문이든 쓸 수 있습니다. 다중구문을 사용할 경우  ({ ... })블럭 구문 으로 그룹화 하고 실행하지 않으려면  구문을 사용합니다.
+
+ +
+
statement2
+
이 구문은 조건이 거짓일경우 다른 조항이 있을 때 실행되는 구문입니다. 블록 문과 if문의 중첩을 호함한 모든문이 될 수 있습니다.
+
+ +

설명

+ +

다중의 if...else 문은 else if 절을 만들기 위해 중첩될 수 있다.
+ 자바스크립트에서는 elseif (하나의 단어) 키워드가 존재하지 않는다.

+ +
if (조건1)
+   명령문1
+else if (조건2)
+   명령문2
+else if (조건3)
+   명령문3
+...
+else
+   명령문N
+
+ +

아래 작업한 것을 보면,  if문을 중첩 사용하면 들여쓰기된 것이 제대로 보여집니다.

+ +
if (조건1)
+   명령문1
+else
+   if (조건2)
+      명령문2
+   else
+      if (조건3)
+...
+
+ +

하나의 절에서 여러개의 명령문들을 실행하려면,   그 명령문들을 그룹화하는 블록 명령문 ({ ... }) 블럭구문을 사용한다.
+ 일반적으로, 블럭구문을 항상 사용하는 것은 좋은 연습입니다. 특히 중첩된 if 문과 관련되어
+ 있는 코드안에서 사용하면 더욱 좋습니다.

+ +
if (조건) {
+   명령문들1
+} else {
+   명령문들2
+}
+
+ +

원시 불리언 값인 true (참) 과 false (거짓) 을 불리언 객체의 truthiness (참으로 보이는 것) 과 falsiness (거짓으로 보이는 것)으로 혼동하면 안된다. false, undefined, null, 0, NaN, 또는 빈 스트링 ("") 이 아닌 모든 값, 그리고 false 값인 불리언 객체를 포함하는 모든 객체는 조건으로 사용될 때 truthy 로 간주된다. 예:

+ +
var b = new Boolean(false);
+if (b) // 이 조건은 참으로 보이는 것 (truthy) 이다.
+
+ +

예시

+ +

if...else 사용하기

+ +
if (cipher_char === from_char) {
+   result = result + to_char;
+   x++;
+} else {
+   result = result + clear_char;
+}
+
+ +

else if 사용하기

+ +

자바스크립트에는 elseif 구문이 없다. 그러나, else if  를 사용할 수 있다.

+ +
if (x > 5) {
+
+} else if (x > 50) {
+
+} else {
+
+}
+ +

조건식의 값을 지정하기

+ +

조건식을 단순하게 지정하는 것은 좋지 않습니다.
+ 왜냐하면,  코드를 흘깃 보면 값을 지정한것을 평등한것으로  혼동할 수 있기 때문입니다. 예를들어, 다음코드를 사용하지 마세요:

+ +
if (x = y) {
+   /* do the right thing */
+}
+
+ +

당신이 조건식에 값의 지정을 해야할 경우, 일반적인 관행은 그 할당된 것 주위에 추가 괄호를 넣어야 합니다. 예를들면:

+ +
if ((x = y)) {
+   /* do the right thing */
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-if-statement', 'if statement')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-if-statement', 'if statement')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-12.5', 'if statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-12.5', 'if statement')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-12.5', 'if statement')}}{{Spec2('ES1')}}Initial definition
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.if_else")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/import/index.html b/files/ko/web/javascript/reference/statements/import/index.html new file mode 100644 index 0000000000..ce3a1536cb --- /dev/null +++ b/files/ko/web/javascript/reference/statements/import/index.html @@ -0,0 +1,156 @@ +--- +title: import +slug: Web/JavaScript/Reference/Statements/import +tags: + - ECMAScript6 + - Modules + - import +translation_of: Web/JavaScript/Reference/Statements/import +--- +
{{jsSidebar("Statements")}}
+ +

정적 import 문은 다른 모듈에서 내보낸 바인딩을 가져올 때 사용합니다.

+ +

가져오는 모듈은 "use strict"의 존재 유무와 상관없이 무조건 엄격 모드입니다. HTML 안에 작성한 스크립트에서는 import를 사용할 수 없습니다.

+ +

함수형 구문을 가진 동적 import()도 있으며, type="module"을 필요로 하지 않습니다.

+ +

{{htmlelement("script")}} 태그의 nomodule 속성을 사용해 하위호환성을 유지할 수 있습니다.

+ +

동적 가져오기는 모듈을 조건적으로 가져오고 싶거나, 필요할 때에만 가져올 때 유용합니다. 반면 초기 의존성을 불러올 때엔 정적 가져오기가 더 좋고, 정적 코드 분석 도구와 {{glossary("Tree shaking", "트리 셰이킹")}}을 적용하기 쉽습니다.

+ +

구문

+ +
import defaultExport from "module-name";
+import * as name from "module-name";
+import { export1 } from "module-name";
+import { export1 as alias1 } from "module-name";
+import { export1 , export2 } from "module-name";
+import { foo , bar } from "module-name/path/to/specific/un-exported/file";
+import { export1 , export2 as alias2 , [...] } from "module-name";
+import defaultExport, { export1 [ , [...] ] } from "module-name";
+import defaultExport, * as name from "module-name";
+import "module-name";
+var promise = import("module-name");
+ +
+
defaultExport
+
모듈에서 가져온 기본 내보내기를 가리킬 이름.
+
module-name
+
가져올 대상 모듈. 보통, 모듈을 담은 .js 파일로의 절대 또는 상대 경로입니다. 번들러에 따라 확장자를 허용하거나, 필요로 할 수도 있으므로 작업 환경을 확인하세요. 따옴표와 쌍따옴표 문자열만 사용 가능합니다.
+
name
+
가져온 대상에 접근할 때 일종의 이름공간으로 사용할, 모듈 객체의 이름.
+
exportN
+
내보낸 대상 중 가져올 것의 이름.
+
aliasN
+
가져온 유명 내보내기를 가리킬 이름.
+
+ +

설명

+ +

name 파라미터는 export 되는 멤버를 받을 오브젝트의 이름입니다. member 파라미터는 각각의 멤버를 지정하지만, name 파라미터는 모두를 가져옵니다. 모듈에서 name 은 멤버 대신 하나의 default 파라미터를 통해 export 하는 경우에도 동작할 수 있습니다. 다음의 명확한 예제 문법을 살펴봅시다.

+ +

모듈 전체를 가져옵니다. export 한 모든 것들을 현재 범위(스크립트 파일 하나로 구분되는 모듈 범위) 내에 myModule 로 바인딩되어 들어갑니다.

+ +
import * as myModule from "my-module.js";
+
+ +

모듈에서 하나의 멤버만 가져옵니다. 현재 범위 내에 myMember 이 들어갑니다.

+ +
import {myMember} from "my-module.js";
+ +

모듈에서 여러 멤버들을 가져옵니다. 현재 범위 내에 foobar 이 들어갑니다.

+ +
import {foo, bar} from "my-module.js";
+ +

멤버를 가져올 때 좀 더 편리한 별명을 지정해줍니다. 현재 범위 내에 shortName 이 들어갑니다.

+ +
import {reallyReallyLongModuleMemberName as shortName} from "my-module.js";
+ +

모듈에서 여러 멤버들을 편리한 별명을 지정하며 가져옵니다.

+ +
import {reallyReallyLongModuleMemberName as shortName, anotherLongModuleName as short} from "my-module.js";
+ +

어떠한 바인딩 없이 모듈 전체의 사이드 이펙트만 가져옵니다.

+ +
import "my-module.js";
+ +

기본값 가져오기

+ +

default export 를 통해 내보낸 것을 기본값으로 가져올 수 있습니다. (object, function, class 등). export 와 상반된 import 명령어를 통해 기본값을 가져오는 것이 가능합니다.

+ +

기본값으로 바로 가져오는 가장 간단한 버전:

+ +
import myModule from "my-module.js";
+ +

위와 함께 기본 구문도 같이 사용할 수 있습니다 (namespace 가져오기 또는 이름 지정하여 가져오기). 이러한 경우, 기본값 가져오는 부분을 먼저 선언해야 할 것입니다. 예를 들어:

+ +
import myDefault, * as myModule from "my-module.js";
+// myModule used as a namespace
+ +

또는

+ +
import myDefault, {foo, bar} from "my-module.js";
+// specific, named imports
+
+ +

예제

+ +

AJAX JSON 리퀘스트 처리를 돕는 보조 파일을 가져옵니다.

+ +
// --file.js--
+function getJSON(url, callback) {
+  let xhr = new XMLHttpRequest();
+  xhr.onload = function () {
+    callback(this.responseText)
+  };
+  xhr.open("GET", url, true);
+  xhr.send();
+}
+
+export function getUsefulContents(url, callback) {
+  getJSON(url, data => callback(JSON.parse(data)));
+}
+
+// --main.js--
+import { getUsefulContents } from "file.js";
+getUsefulContents("http://www.example.com", data => {
+  doSomethingUseful(data);
+});
+ +

명세

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-imports', 'Imports')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-imports', 'Imports')}}{{Spec2('ESDraft')}}
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.import")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/index.html b/files/ko/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..cd83b9f1c0 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/index.html @@ -0,0 +1,143 @@ +--- +title: 문 및 선언 +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - Reference + - statements +translation_of: Web/JavaScript/Reference/Statements +--- +
{{jsSidebar("Statements")}}
+ +

JavaScript 응용 프로그램은 적절한 구문을 갖는 문으로 구성됩니다. 한 문이 여러 줄에 걸칠 수 있습니다. 여러 문은 각 문이 세미콜론으로 구분된 경우 한 줄에 나올 수 있습니다. 이는 키워드 하나가 아니라, 키워드 그룹입니다.

+ +

항목별 문 및 선언

+ +

알파벳순 목록은 왼쪽 사이드바를 보세요.

+ +

흐름 제어

+ +
+
{{jsxref("Statements/block", "Block")}}
+
블록문은 0개 이상의 문을 묶을 때 쓰입니다. 블록은 중괄호 한 쌍으로 구분됩니다.
+
{{jsxref("Statements/break", "break")}}
+
현재 루프, switch 또는 label 문을 종료하고 프로그램 제어를 종료된 문의 다음 문으로 넘겨줍니다.
+
{{jsxref("Statements/continue", "continue")}}
+
현재 또는 레이블 달린 루프의 현재 반복 중인 문의 실행을 종료하고 루프의 실행은 다음 반복으로 이어집니다.
+
{{jsxref("Statements/Empty", "empty")}}
+
empty 문은 내용이 없는 빈 문을 제공하기 위해 사용됩니다, 비록 JavaScript 구문이 문을 기대할 것이지만.
+
{{jsxref("Statements/if...else", "if...else")}}
+
지정된 조건이 true면 문을 실행. 조건이 false인 경우, 다른 문이 실행될 수 있습니다.
+
{{jsxref("Statements/switch", "switch")}}
+
식의 값이 case 절과 일치하는지 식을 평가하고 case 절과 관련된 문을 실행합니다.
+
{{jsxref("Statements/throw", "throw")}}
+
사용자 정의 예외가 발생합니다.
+
{{jsxref("Statements/try...catch", "try...catch")}}
+
시도(try)할 문 블록을 표시하고 예외가 발생되어야 하는 응답을 지정합니다.
+
+ +

선언

+ +
+
{{jsxref("Statements/var", "var")}}
+
변수를 선언합니다, 변수를 값으로 초기화할 수 있습니다.
+
{{jsxref("Statements/let", "let")}}
+
블록 범위 지역 변수를 선언합니다, 변수를 값으로 초기화할 수 있습니다.
+
{{jsxref("Statements/const", "const")}}
+
읽기 전용 유명(named) 상수를 선언합니다.
+
+ +

함수 및 클래스

+ +
+
{{jsxref("Statements/function", "function")}}
+
지정된 매개변수를 갖는 함수를 선언합니다.
+
{{jsxref("Statements/function*", "function*")}}
+
반복기를 더 쉽게 작성할 수 있게 하는 생성기 함수.
+
{{jsxref("Statements/return", "return")}}
+
함수에 의해 반환되는 값을 지정합니다.
+
{{jsxref("Statements/class", "class")}}
+
클래스를 선언합니다.
+
+ +

반복

+ +
+
{{jsxref("Statements/do...while", "do...while")}}
+
테스트 조건이 거짓으로 평가될 때까지 지정된 문을 실행하는 루프를 만듭니다. 조건은 문을 실행한 후 평가됩니다, 그 결과 지정된 문은 적어도 한 번 실행됩니다.
+
{{jsxref("Statements/for", "for")}}
+
괄호로 묶이고 세미콜론으로 구분된 선택사항 식 셋으로 구성된 루프를 만듭니다, 루프에서 실행되는 문이 뒤따릅니다.
+
{{jsxref("Statements/for_each...in", "for each...in")}} {{deprecated_inline}} {{non-standard_inline}}
+
객체의 모든 속성값에 대해 지정된 변수를 반복합니다. 각 개별 속성에 대해, 지정된 문이 실행됩니다.
+
{{jsxref("Statements/for...in", "for...in")}}
+
임의의 순서로 객체의 열거 속성을 반복합니다. 각 개별 속성에 대해, 문은 실행될 수 있습니다.
+
{{jsxref("Statements/for...of", "for...of")}}
+
반복 가능한 객체 ({{jsxref("Global_Objects/Array","배열","","true")}}, 배열 같은 객체, 반복기 및 생성기 포함) 를 반복합니다, 각 개별 속성값에 대해 실행되는 문을 가진 사용자 정의 반복 후크를 호출하는.
+
{{jsxref("Statements/while", "while")}}
+
테스트 조건이 true로 평가되는 한 지정된 문을 실행하는 루프를 만듭니다. 조건은 문을 실행하기 전에 평가됩니다.
+
+ +

기타

+ +
+
{{jsxref("Statements/debugger", "debugger")}}
+
이용 가능한 디버깅 기능을 호출합니다. 이용 가능한 기능이 없는 경우, 이 문은 아무 효과가 없습니다.
+
{{jsxref("Statements/export", "export")}}
+
외부 모듈, 다른 스크립트에 가져올(import) 수 있도록 함수를 내보내(export)는데 사용됩니다.
+
{{jsxref("Statements/import", "import")}}
+
외부 모듈, 다른 스크립트에서 내보낸 함수를 가져오는데 사용됩니다.
+
{{jsxref("Statements/label", "label")}}
+
break 또는 continue 문을 사용하여 참조할 수 있는 식별자 있는 문을 제공합니다.
+
+ +
+
{{jsxref("Statements/with", "with")}} {{deprecated_inline}}
+
문의 스코프 체인을 확장합니다.
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}초기 정의
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}신규: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.statements")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/label/index.html b/files/ko/web/javascript/reference/statements/label/index.html new file mode 100644 index 0000000000..49d6054031 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/label/index.html @@ -0,0 +1,241 @@ +--- +title: label +slug: Web/JavaScript/Reference/Statements/label +translation_of: Web/JavaScript/Reference/Statements/label +--- +
{{jsSidebar("Statements")}}
+ +

레이블 구문은 {{jsxref("Statements/break", "break")}}나 {{jsxref("Statements/continue", "continue")}} 구문과 함께 사용할 수 있다. 원하는 식별자로 구문 앞에 레이블을 추가할 수 있다.

+ +
+

레이블을 붙인 반복문이나 블록가 자주 사용되는 것은 아니다. 반복문으로 점프하는 대신에 함수를 호출할 수도 있다.

+
+ +

문법

+ +
label :
+   statement
+
+ +
+
label
+
자바스크립트에서 사용할 수 있는 식별자면 모두 가능하다.
+
statement
+
구문. break는 모든 레이블 구문에서 사용될 수 있으며, continue는 반복 레이블 구문에서만 사용할 수 있다.
+
+ +

설명

+ +

반복문에 레이블을 붙이고, break나 continue 구문을 사용해 반복문의 어느 위치에서 작업을 멈추고 어느 위치에서 다시 수행할지를 알려줄 수 있다.

+ +

자바스크립트에는 goto 구문이 없다는 것에 주의. break나 continue에서만 레이블을 사용할 수 있다.

+ +

strict mode  코드에서 "let"을 레이블 이름으로 사용할 수 없다. {{jsxref("SyntaxError")}}를 발생시킨다. (let은 허용되지 않는 식별자이다.)

+ +

예제

+ +

for문에서 레이블 continue 사용하기

+ +
var i, j;
+
+loop1:
+for (i = 0; i < 3; i++) {      //첫번째 for문은 "loop1" 레이블을 붙였다.
+   loop2:
+   for (j = 0; j < 3; j++) {   //두번째 for문은 "loop2" 레이블을 붙였다.
+      if (i === 1 && j === 1) {
+         continue loop1;
+      }
+      console.log('i = ' + i + ', j = ' + j);
+   }
+}
+
+// 출력 결과:
+//   "i = 0, j = 0"
+//   "i = 0, j = 1"
+//   "i = 0, j = 2"
+//   "i = 1, j = 0"
+//   "i = 2, j = 0"
+//   "i = 2, j = 1"
+//   "i = 2, j = 2"
+// 다음 두 경우를 어떻게 스킵하는지 주목 : "i = 1, j = 1", "i = 1, j = 2"
+
+ +

레이블 continue문 사용하기

+ +

items, tests 배열을 보면 이 예제는 tests를 통과하는 items의 수를 세고 있다.

+ +
var itemsPassed = 0;
+var i, j;
+
+top:
+for (i = 0; i < items.length; i++) {
+  for (j = 0; j < tests.length; j++) {
+    if (!tests[j].pass(items[i])) {
+      continue top;
+    }
+  }
+
+  itemsPassed++;
+}
+ +

for문에 레이블 break문 사용하기

+ +
var i, j;
+
+loop1:
+for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
+   loop2:
+   for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
+      if (i === 1 && j === 1) {
+         break loop1;
+      }
+      console.log('i = ' + i + ', j = ' + j);
+   }
+}
+
+// Output is:
+//   "i = 0, j = 0"
+//   "i = 0, j = 1"
+//   "i = 0, j = 2"
+//   "i = 1, j = 0"
+// Notice the difference with the previous continue example
+ +

레이블 break문 사용하기

+ +

items, tests 배열을 보면, 다음 예제는 items가 tests를 모두 통과하는지 판단한다.

+ +
var allPass = true;
+var i, j;
+
+top:
+for (i = 0; items.length; i++)
+  for (j = 0; j < tests.length; i++)
+    if (!tests[j].pass(items[i])) {
+      allPass = false;
+      break top;
+    }
+ +

레이블 붙인 블록에 break 사용하기

+ +

간단한 블록에도 레이블을 사용할 수 있지만, 반복문 아닌 레이블에는 break문만 사용할 수 있다.

+ +
foo: {
+  console.log('face');
+  break foo;
+  console.log('this will not be executed');
+}
+console.log('swap');
+
+// 로그는 이렇게 출력된다:
+
+// "face"
+// "swap 
+ +

레이블 붙인 함수 선언문

+ +

ECMAScript 2015에서, 레이블 붙인 함수 선언문은 web compatibility annex of the specification의 non-strict 모드에서 표준화되어 있다.

+ +
L: function F() {}
+ +

strict mode  에서는 {{jsxref("SyntaxError")}}를 발생시킨다.

+ +
'use strict';
+L: function F() {}
+// SyntaxError: functions cannot be labelled
+ +

Generator functions는 strict code도 non-strict code에서도 레이블 붙일 수 없다.

+ +
L: function* F() {}
+// SyntaxError: generator functions cannot be labelled
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.12', 'Labelled statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-labelled-statements', 'Labelled statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-labelled-statements', 'Labelled statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

더 알아보기

+ + diff --git a/files/ko/web/javascript/reference/statements/let/index.html b/files/ko/web/javascript/reference/statements/let/index.html new file mode 100644 index 0000000000..3d02a34fba --- /dev/null +++ b/files/ko/web/javascript/reference/statements/let/index.html @@ -0,0 +1,246 @@ +--- +title: let +slug: Web/JavaScript/Reference/Statements/let +translation_of: Web/JavaScript/Reference/Statements/let +--- +
{{jsSidebar("Statements")}}
+ +

let 구문은 블록 유효 범위를 갖는 지역 변수를 선언하며, 선언과 동시에 임의의 값으로 초기화할 수도 있다.

+ +
{{EmbedInteractiveExample("pages/js/statement-let.html")}}
+ + + +

Syntax

+ +
let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];
+ +

Parameters

+ +
+
var1, var2, …, varN
+
변수명. 유효한 식별자이면 가능하다.
+
value1, value2, …, valueN
+
변수의 초기값. 유효한 표현식이면 가능하다.
+
+ +

Description

+ +

let은 변수가 선언된 블록, 구문 또는 표현식 내에서만 유효한 변수를 선언한다. 이는 var 키워드가 블록 범위를 무시하고 전역 변수나 함수 지역 변수로 선언되는 것과 다른 점이다.

+ +

"let"을 사용해야 하는 이유에 대해서는 이어지는 링크를 참조하시오.

+ +

유효 범위 규칙

+ +

let 으로 선언된 변수는 변수가 선언된 블록 내에서만 유효하며, 당연하지만 하위 블록에서도 유효하다. 이러한 점에서는 letvar는 유사하지만, var는 함수 블록 이외의 블록은 무시하고 선언된다는 점이 다르다.

+ +
function varTest() {
+  var x = 1;
+  if (true) {
+    var x = 2;  // 상위 블록과 같은 변수!
+    console.log(x);  // 2
+  }
+  console.log(x);  // 2
+}
+
+function letTest() {
+  let x = 1;
+  if (true) {
+    let x = 2;  // 상위 블록과 다른 변수
+    console.log(x);  // 2
+  }
+  console.log(x);  // 1
+}
+
+ +

프로그램이나 함수의 최상위에서는 letvar은 서로 다르게 행동한다. let은 전역 객체의 속성 값을 생성하지 않는다.

+ +
var x = 'global';
+let y = 'global';
+console.log(this.x); // "global" 전역 객체의 속성 x를 생성
+console.log(this.y); // undefined 전역 객체의 속성 y를 생성하지 않음
+
+ +

비공개 변수 모사

+ +

생성자와 함께 사용하여 클로저를 사용하지 않고 비공개 변수를 만들고 접근할 수 있다.

+ +
var Thing;
+
+{
+  let privateScope = new WeakMap();
+  let counter = 0;
+
+  Thing = function() {
+    this.someProperty = 'foo';
+
+    privateScope.set(this, {
+      hidden: ++counter,
+    });
+  };
+
+  Thing.prototype.showPublic = function() {
+    return this.someProperty;
+  };
+
+  Thing.prototype.showPrivate = function() {
+    return privateScope.get(this).hidden;
+  };
+}
+
+console.log(typeof privateScope);
+// "undefined"
+
+var thing = new Thing();
+
+console.log(thing);
+// Thing {someProperty: "foo"}
+
+thing.showPublic();
+// "foo"
+
+thing.showPrivate();
+// 1
+
+ +

임시적인 사각 지역과 오류

+ +

같은 변수를 같은 함수나 블록 범위 내에서 재선언하면 {{jsxref("SyntaxError")}}가 발생한다.

+ +
if (x) {
+  let foo;
+  let foo; // SyntaxError thrown.
+}
+ +

ECMAScript 2015에서는let선언 끌어올리기의 적용을 받지 않습니다.  이는 let 선언이 현재 실행되는 구간의 최상위로 옮겨지지 않는다는 것을 의미합니다. 따라서 변수가 초기화(선언)되기 전에 참조할 경우 ReferenceError가 발생합니다.(var로 선언된 변수는 undefined 값을 가지는 것과는 대조적입니다.) "임시적인 사각 지역"은 블록 시작 부분부터 변수 선언이 실행되기 전까지 입니다.

+ +

(let들의 정의가 평가되기까지 초기화가 되지 않는다는 의미이지. 호이스팅이 되지않아 정의가 되지 않는다는 의미와는 다르다고 생각함_헷갈리면 안된다.)

+ +
function do_something() {
+  console.log(bar); // undefined
+  console.log(foo); // ReferenceError
+  var bar = 1;
+  let foo = 2;
+}
+ +

switch 구문을 사용할 때는 실제 블록이 하나 뿐이므로 중복 선언 오류가 발생하기 쉽습니다.

+ +
let x = 1;
+switch(x) {
+  case 0:
+    let foo;
+    break;
+
+  case 1:
+    let foo; // 재선언에 의한 SyntaxError.
+    break;
+}
+ +

하지만 case 조건을 새로운 블록으로 감싸면 위의 코드와는 다르게 재선언 오류가 발생하지 않습니다.

+ +
let x = 1;
+
+switch(x) {
+  case 0: {
+    let foo;
+    break;
+  }
+  case 1: {
+    let foo;
+    break;
+  }
+}
+ +

임시적인 사각 지역과 typeof

+ +

선언되지 않은 변수와 undefined 값을 지닌 변수와는 다르게, 임시적인 사각 지역에 있는 변수에 변수형 확인을 위해 typeof을 사용하면 ReferenceError가 발생합니다:

+ +
// 'undefined' 출력
+console.log(typeof undeclaredVariable);
+// 'ReferenceError' 발생
+console.log(typeof i);
+let i = 10;
+ +

정적 유효 범위와 결합된 임시적인 사각 지역 예시

+ +

정적 유효 범위로 인해, 표현 (foo + 55) 내부의 "foo"는 33을 값으로 가지는 상위 블록의 foo가 아니라 if 블록의 foo로 해석됩니다. 해당 행에서 if 블록의 "foo"는 이미 정적 유효 범위에 생성되었지만, 선언의 초기화가 완료(선언 구문의 종료)되지 않았습니다. 따라서 여전히 임시적인 사각 지역에 해당됩니다.

+ +
function test(){
+   var foo = 33;
+   if (true) {
+      let foo = (foo + 55); // ReferenceError
+   }
+}
+test();
+ +

이 현상은 다음과 같은 상황에서 혼란을 유발할 수 있습니다. 지시 구문  let n of n.a은 이미 for loop 블록에 속해 있으며, 구문자 "n.a"는 속성 'a'를 지시 구문 자기자신의 앞부분에 위치한 객체 'n'에서 참조하려 합니다. 해당 객체 'n'은 위와 마찬가지로 선언이 종료되지 않았기에 임시적인 사각 지역에 해당합니다.

+ +
function go(n) {
+  // 정의되어 있는 n!
+  console.log(n); // Object {a: [1,2,3]}
+
+  for (let n of n.a) { // ReferenceError
+    console.log(n);
+  }
+}
+
+go({a: [1, 2, 3]});
+
+ +

그 외 상황들

+ +

블록을 사용할 때, let은 변수의 유효 범위를 블록으로 제한합니다. 함수 내 또는 전역을 유효 범위로 가지는 var와의 차이점을 숙지하세요.

+ +
var a = 1;
+var b = 2;
+
+if (a === 1) {
+  var a = 11; // 전역 변수
+  let b = 22; // if 블록 변수
+
+  console.log(a);  // 11
+  console.log(b);  // 22
+}
+
+console.log(a); // 11
+console.log(b); // 2
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}{{Spec2('ES2015')}}Initial definition. Does not specify let expressions or let blocks.
{{SpecName('ESDraft', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.let")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/statements/return/index.html b/files/ko/web/javascript/reference/statements/return/index.html new file mode 100644 index 0000000000..e865cb9a65 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/return/index.html @@ -0,0 +1,159 @@ +--- +title: return +slug: Web/JavaScript/Reference/Statements/return +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/return +--- +
{{jsSidebar("Statements")}}
+ +

return 명령문은 함수 실행을 종료하고, 주어진 값을 함수 호출 지점으로 반환합니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-return.html")}}
+ + + +

구문

+ +
return [[expression]]; 
+ +
+
expression
+
반환할 값으로 사용할 표현식. 생략할 경우 {{jsxref("undefined")}}를 대신 반환합니다.
+
+ +

설명

+ +

함수 본문에서 return 명령문에 도달하면 함수의 실행은 그 지점에서 중단됩니다. 값을 제공한 경우 함수를 호출한 곳에 그 값을 반환합니다. 예를 들어, 다음 함수는 숫자 매개변수 x의 제곱을 반환합니다.

+ +
function square(x) {
+   return x * x;
+}
+var demo = square(3);
+// demo는 9
+ +

값을 명시하지 않으면 대신 undefined를 반환합니다.

+ +

다음 return 명령문 모두 함수 실행을 끊습니다.

+ +
return;
+return true;
+return false;
+return x;
+return x + y / 3;
+
+ +

자동 세미콜론 삽입

+ +

return 명령문은 자동 세미콜론 삽입(ASI)의 영향을 받습니다. return 키워드와 표현식 사이에는 줄바꿈 문자가 올 수 없습니다.

+ +
return
+a + b;
+
+ +

위 코드는 ASI로 인해 아래처럼 처리됩니다.

+ +
return;
+a + b;
+
+ +

콘솔이 "unreachable code after return statement" 경고를 출력할 것입니다.

+ +
Gecko 40 {{geckoRelease(40)}}부터, return 이후에 위치하여 도달할 수 없는 코드를 발견하면 콘솔에 경고를 출력합니다.
+ +

문제를 해결하려면 괄호를 사용해 ASI를 방지해야 합니다.

+ +
return (
+  a + b
+);
+
+ +

예제

+ +

함수 중단

+ +

함수는 return을 호출하는 지점에서 즉시 실행을 멈춥니다.

+ +
function counter() {
+  for (var count = 1; ; count++) {  // 무한 반복
+    console.log(count + "A"); // 5까지
+      if (count === 5) {
+        return;
+      }
+      console.log(count + "B");  // 4까지
+    }
+  console.log(count + "C");  // 절대 나타나지 않음
+}
+
+counter();
+
+// 출력:
+// 1A
+// 1B
+// 2A
+// 2B
+// 3A
+// 3B
+// 4A
+// 4B
+// 5A
+
+ +

함수 반환하기

+ +

클로저에 대해서도 더 알아보세요.

+ +
function magic(x) {
+  return function calc(x) { return x * 42 };
+}
+
+var answer = magic();
+answer(1337); // 56154
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.return")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/switch/index.html b/files/ko/web/javascript/reference/statements/switch/index.html new file mode 100644 index 0000000000..b4eb68e5a7 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/switch/index.html @@ -0,0 +1,306 @@ +--- +title: switch +slug: Web/JavaScript/Reference/Statements/switch +translation_of: Web/JavaScript/Reference/Statements/switch +--- +
{{jsSidebar("Statements")}}
+ +

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.

+ +
{{EmbedInteractiveExample("pages/js/statement-switch.html")}}
+ + + +

문법

+ +
switch (expression) {
+  case value1:
+    //Statements executed when the
+    //result of expression matches value1
+    [break;]
+  case value2:
+    //Statements executed when the
+    //result of expression matches value2
+    [break;]
+  ...
+  case valueN:
+    //Statements executed when the
+    //result of expression matches valueN
+    [break;]
+  [default:
+    //Statements executed when none of
+    //the values match the value of the expression
+    [break;]]
+}
+ +
+
expression
+

+ 각각의 case 절에 맞추어볼 결과에 대한 expression
+
case valueN {{optional_inline}}
+
어떤 case 절은  expression와 맞추어보는데 사용된다. 만약 expression 이 특정 valueN과 일치 된다면, switch statement 문이 끝나거나 break가 오떄까지 case 절 내부가 실행된다.
+
default {{optional_inline}}
+
default 절; 만약 있다면,  어떤 case의 절도 expression 값과 일치되지 않는다면, default 절이 실행된다.
+
+ +

설명

+ +

A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using the strict comparison, ===) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.)

+ +

If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.

+ +

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

+ +

예제

+ +

Using switch

+ +

In the following example, if expr evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program breaks out of switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

+ +
switch (expr) {
+  case 'Oranges':
+    console.log('Oranges are $0.59 a pound.');
+    break;
+  case 'Apples':
+    console.log('Apples are $0.32 a pound.');
+    break;
+  case 'Bananas':
+    console.log('Bananas are $0.48 a pound.');
+    break;
+  case 'Cherries':
+    console.log('Cherries are $3.00 a pound.');
+    break;
+  case 'Mangoes':
+  case 'Papayas':
+    console.log('Mangoes and papayas are $2.79 a pound.');
+    break;
+  default:
+    console.log('Sorry, we are out of ' + expr + '.');
+}
+
+console.log("Is there anything else you'd like?");
+
+ +

break를 쓰지않으면 어떻게 되는가?

+ +

If you forget a break then the script will run from the case where the criterion is met and will run the case after that regardless if criterion was met. See example here:

+ +
var foo = 0;
+switch (foo) {
+  case -1:
+    console.log('negative 1');
+    break;
+  case 0: // foo is 0 so criteria met here so this block will run
+    console.log(0);
+    // NOTE: the forgotten break would have been here
+  case 1: // no break statement in 'case 0:' so this case will run as well
+    console.log(1);
+    break; // it encounters this break so will not continue into 'case 2:'
+  case 2:
+    console.log(2);
+    break;
+  default:
+    console.log('default');
+}
+ +

Can I put a default between cases?

+ +

Yes, you can! JavaScript will drop you back to the default if it can't find a match:

+ +
var foo = 5;
+switch (foo) {
+  case 2:
+    console.log(2);
+    break; // it encounters this break so will not continue into 'default:'
+  default:
+    console.log('default')
+    // fall-through
+  case 1:
+    console.log('1');
+}
+
+ +

It also works when you put default before all other cases.

+ +

Methods for multi-criteria case

+ +

Source for this technique is here:

+ +

Switch statement multiple cases in JavaScript (Stack Overflow)

+ +

Multi-case - single operation

+ +

This method takes advantage of the fact that if there is no break below a case statement it will continue to execute the next case statement regardless if the case meets the criteria. See the section titled "What happens if I forgot a break?"

+ +

This is an example of a single operation sequential switch statement, where four different values perform exactly the same.

+ +
var Animal = 'Giraffe';
+switch (Animal) {
+  case 'Cow':
+  case 'Giraffe':
+  case 'Dog':
+  case 'Pig':
+    console.log('This animal will go on Noah\'s Ark.');
+    break;
+  case 'Dinosaur':
+  default:
+    console.log('This animal will not.');
+}
+ +

Multi-case - chained operations

+ +

This is an example of a multiple-operation sequential switch statement, where, depending on the provided integer, you can receive different output. This shows you that it will traverse in the order that you put the case statements, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into these case statements as well.

+ +
var foo = 1;
+var output = 'Output: ';
+switch (foo) {
+  case 0:
+    output += 'So ';
+  case 1:
+    output += 'What ';
+    output += 'Is ';
+  case 2:
+    output += 'Your ';
+  case 3:
+    output += 'Name';
+  case 4:
+    output += '?';
+    console.log(output);
+    break;
+  case 5:
+    output += '!';
+    console.log(output);
+    break;
+  default:
+    console.log('Please pick a number from 0 to 5!');
+}
+ +

이 예제의 결과:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueLog text
foo is NaN or not 1, 2, 3, 4, 5 or 0Please pick a number from 0 to 5!
0Output: So What Is Your Name?
1Output: What Is Your Name?
2Output: Your Name?
3Output: Name?
4Output: ?
5Output: !
+ +

Block-scope variables within switch statements

+ +

With ECMAScript 2015 (ES6) support made available in most modern browsers, there will be cases where you would want to use let and const statements to declare block-scoped variables.

+ +

Take a look at this example:

+ +
const action = 'say_hello';
+switch (action) {
+  case 'say_hello':
+    let message = 'hello';
+    console.log(message);
+    break;
+  case 'say_hi':
+    let message = 'hi';
+    console.log(message);
+    break;
+  default:
+    console.log('Empty action received.');
+    break;
+}
+ +

This example will output the error Uncaught SyntaxError: Identifier 'message' has already been declared which you were not probably expecting.

+ +

This is because the first let message = 'hello'; conflicts with second let statement let message = 'hi'; even they're within their own separate case statements case 'say_hello': and case 'say_hi':; ultimately this is due to both let statements being interpreted as duplicate declarations of the same variable name within the same block scope.

+ +

We can easily fix this by wrapping our case statements with brackets:

+ +
const action = 'say_hello';
+switch (action) {
+  case 'say_hello': { // added brackets
+    let message = 'hello';
+    console.log(message);
+    break;
+  } // added brackets
+  case 'say_hi': { // added brackets
+    let message = 'hi';
+    console.log(message);
+    break;
+  } // added brackets
+  default: { // added brackets
+    console.log('Empty action received.');
+    break;
+  } // added brackets
+}
+ +

This code will now output hello in the console as it should, without any errors at all.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태설명
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.11', 'switch statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-switch-statement', 'switch statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-switch-statement', 'switch statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.switch")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/throw/index.html b/files/ko/web/javascript/reference/statements/throw/index.html new file mode 100644 index 0000000000..ff5ccb2333 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/throw/index.html @@ -0,0 +1,198 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Statements/throw +translation_of: Web/JavaScript/Reference/Statements/throw +--- +
{{jsSidebar("Statements")}}
+ +

throw 문은 사용자 정의 예외를 던질 수 있습니다. 현재 함수의 실행이 중지되고 (throw 이후의 명령문은 실행되지 않습니다.), 컨트롤은 콜 스택의 첫 번째 catch 블록으로 전달됩니다. 호출자 함수 사이에 catch 블록이 없으면 프로그램이 종료됩니다. 

+ +
{{EmbedInteractiveExample("pages/js/statement-throw.html")}}
+ + + +

Syntax

+ +
throw expression; 
+ +
+
expression
+
예외를 던지는 구문
+
+ +

Description

+ +

예외를 발생하기 위해 throw 문을 사용하세요. 
+ 예외를 던지면 expression은 예외 값을 지정합니다.
+ 다음 각각은 예외를 던집니다:

+ +
throw 'Error2'; // generates an exception with a string value
+throw 42;       // generates an exception with the value 42
+throw true;     // generates an exception with the value true
+ +

또한 throw 문은 자동 세미콜론 삽입 (ASI)에 의해 영향을 받으며 throw 키워드와 표현식 사이에 줄 종결자는 허용되지 않으므로 주의해야합니다.

+ +

예제

+ +

객체 throw 하기

+ +

예외를 던질 때 객체를 지정할 수 있습니다. 그러면 catch 블록에서 객체의 속성을 참조 할 수 있습니다.
+ 다음 예제에서는 UserException 유형의 객체를 만들고 throw 구문에서 이 객체를 사용합니다.

+ +
function UserException(message) {
+   this.message = message;
+   this.name = 'UserException';
+}
+function getMonthName(mo) {
+   mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
+   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
+      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+   if (months[mo] !== undefined) {
+      return months[mo];
+   } else {
+      throw new UserException('InvalidMonthNo');
+   }
+}
+
+try {
+   // statements to try
+   var myMonth = 15; // 15 is out of bound to raise the exception
+   var monthName = getMonthName(myMonth);
+} catch (e) {
+   monthName = 'unknown';
+   console.log(e.message, e.name); // pass exception object to err handler
+}
+
+ +

객체를 throw 하는 다른 예제

+ +

다음 예제는 입력 문자열에서 미국 우편 번호를 테스트합니다.
+ 우편 번호가 잘못된 형식을 사용하는 경우 throw 문은 ZipCodeFormatException 유형의 개체를 만들어 예외를 던집니다.

+ +
/*
+ * Creates a ZipCode object.
+ *
+ * Accepted formats for a zip code are:
+ *    12345
+ *    12345-6789
+ *    123456789
+ *    12345 6789
+ *
+ * If the argument passed to the ZipCode constructor does not
+ * conform to one of these patterns, an exception is thrown.
+ */
+
+function ZipCode(zip) {
+   zip = new String(zip);
+   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
+   if (pattern.test(zip)) {
+      // zip code value will be the first match in the string
+      this.value = zip.match(pattern)[0];
+      this.valueOf = function() {
+         return this.value
+      };
+      this.toString = function() {
+         return String(this.value)
+      };
+   } else {
+      throw new ZipCodeFormatException(zip);
+   }
+}
+
+function ZipCodeFormatException(value) {
+   this.value = value;
+   this.message = 'does not conform to the expected format for a zip code';
+   this.toString = function() {
+      return this.value + this.message;
+   };
+}
+
+/*
+ * This could be in a script that validates address data
+ * for US addresses.
+ */
+
+const ZIPCODE_INVALID = -1;
+const ZIPCODE_UNKNOWN_ERROR = -2;
+
+function verifyZipCode(z) {
+   try {
+      z = new ZipCode(z);
+   } catch (e) {
+      if (e instanceof ZipCodeFormatException) {
+         return ZIPCODE_INVALID;
+      } else {
+         return ZIPCODE_UNKNOWN_ERROR;
+      }
+   }
+   return z;
+}
+
+a = verifyZipCode(95060);         // returns 95060
+b = verifyZipCode(9560);          // returns -1
+c = verifyZipCode('a');           // returns -1
+d = verifyZipCode('95060');       // returns 95060
+e = verifyZipCode('95060 1234');  // returns 95060 1234
+
+ +

Rethrow an exception

+ +

throw를 사용하여 예외를 잡은 후에 예외를 다시 던질 수 있습니다.
+ 다음 예제에서는 숫자 값으로 예외를 잡고 값이 50 이상이면 예외를 다시 throw합니다.
+ 반환 된 예외는 둘러싸는 함수 또는 최상위 수준으로 전파되어 사용자가 볼 수 있도록합니다

+ +
try {
+   throw n; // throws an exception with a numeric value
+} catch (e) {
+   if (e <= 50) {
+      // statements to handle exceptions 1-50
+   } else {
+      // cannot handle this exception, so rethrow
+      throw e;
+   }
+}
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ + + +

{{Compat("javascript.statements.throw")}}

+ +

추가적으로 볼 것

+ + diff --git a/files/ko/web/javascript/reference/statements/try...catch/index.html b/files/ko/web/javascript/reference/statements/try...catch/index.html new file mode 100644 index 0000000000..c7cdf05b1f --- /dev/null +++ b/files/ko/web/javascript/reference/statements/try...catch/index.html @@ -0,0 +1,273 @@ +--- +title: try...catch +slug: Web/JavaScript/Reference/Statements/try...catch +translation_of: Web/JavaScript/Reference/Statements/try...catch +--- +
+

{{jsSidebar("Statements")}}

+ +

try...catch 문은 실행할 코드블럭을 표시하고 예외(exception)가 발생(throw)할 경우의 응답을 지정합니다.

+ +

{{EmbedInteractiveExample("pages/js/statement-trycatch.html")}}

+
+ +

문법

+ +
try {
+  try_statements
+}
+[catch (exception_var) {
+  catch_statements
+}]
+[finally {
+  finally_statements
+}]
+ +
+
try_statements
+
실행될 선언들
+
+ +
+
catch_statements
+
try 블록에서 예외가 발생했을 때 실행될 선언들
+
+ +
+
exception_var
+
catch 블록과 관련된 예외 객체를 담기 위한 식별자
+
+ +
+
finally_statements
+
try 선언이 완료된 이후에 실행된 선언들. 이 선언들은 예외 발생 여부와 상관없이 실행된다.
+
+ +

설명

+ +

try 선언의 구성은 하나 혹은 그 이상의 선언을 포함한 try 블록 및 catch 항목이나 finally 항목 중 최소한 하나 혹은 둘 다 포함하여 이루어진다. 즉, try 선언에는 세 가지 형식이 존재한다.

+ +
    +
  1. try...catch
  2. +
  3. try...finally
  4. +
  5. try...catch...finally
  6. +
+ +

catch 블록은 try 블록 안에서 예외가 발생(throw)하는 경우 무엇을 할지 명시하는 코드를 포함합니다.  try 블록 (또는 try 블록 내에서 호출된 함수) 내의 명령문이 예외를 throw 하면 제어가 catch 블록으로 이동합니다. try 블록에 예외가 발생하지 않으면 catch 블록을 건너뜁니다.

+ +

finally 블록은 try 블록과 catch 블록(들)이 실행을 마친 후 항상 실행됩니다. 예외가 발생했는지에 관계없이 항상 실행됩니다.

+ +

하나 이상의 try 문을 중첩 할 수 있습니다. 내부의 try 문에 catch 블록이 없으면, 둘러싼 try 문의 catch 블록이 입력됩니다.

+ +

또한 try 문을 사용하여 예외처리를 합니다. 예외처리에 대해 더 알고 싶다면, JavaScript Guide 를 참고하세요.

+ +

무조건적 catch

+ +

try-block 내에서 예외가 발생하면 catch-block이 실행됩니다. 예를 들어, 다음 코드에서 예외가 발생하면 제어가 catch 블록으로 전송됩니다.

+ + + +
try {
+   throw "myException"; // generates an exception
+}
+catch (e) {
+   // statements to handle any exceptions
+   logMyErrors(e); // pass exception object to error handler
+}
+
+ +

조건적 catch

+ +

다음과 같이 try...catch블록을 if...else if...else 구조와 결합하여 '조건부 catch-blocks'을 만들 수 있습니다.

+ + + +
try {
+  myroutine(); // may throw three types of exceptions
+} catch (e) {
+  if (e instanceof TypeError) {
+    // statements to handle TypeError exceptions
+  } else if (e instanceof RangeError) {
+    // statements to handle RangeError exceptions
+  } else if (e instanceof EvalError) {
+    // statements to handle EvalError exceptions
+  } else {
+    // statements to handle any unspecified exceptions
+    logMyErrors(e); // pass exception object to error handler
+  }
+}
+
+ + + +

이에 대한 일반적인 사용 사례는 예상 오류의 작은 하위 집합 만 포착 (및 침묵) 한 다음 다른 경우에 오류를 다시 발생시키는 것입니다.

+ +
try {
+  myRoutine();
+} catch (e) {
+  if (e instanceof RangeError) {
+    // statements to handle this very common expected error
+  } else {
+    throw e;  // re-throw the error unchanged
+  }
+}
+ +

The exception identifier

+ +

try-block에서 예외가 발생하면 exception_var (즉, catch (e)내부의 e)가 예외 값을 보유합니다. 이 식별자를 사용하여 발생한 예외에 대한 정보를 얻을 수 있습니다. 이 식별자는 catch-block의 {{Glossary("Scope", "scope")}}에서만 사용할 수 있습니다.

+ + + +
function isValidJSON(text) {
+  try {
+    JSON.parse(text);
+    return true;
+  } catch {
+    return false;
+  }
+}
+ +

The finally-block

+ +

The finally-block contains statements to execute after the try-block and catch-block(s) execute, but before the statements following the try...catch...finally-block. Note that the finally-block executes regardless of whether an exception is thrown. Also, if an exception is thrown, the statements in the finally-block execute even if no catch-block handles the exception.

+ + + +

The following example shows one use case for the finally-block. The code opens a file and then executes statements that use the file; the finally-block makes sure the file always closes after it is used even if an exception was thrown.

+ +
openMyFile();
+try {
+  // tie up a resource
+  writeMyFile(theData);
+}
+finally {
+  closeMyFile(); // always close the resource
+}
+ +

Examples

+ +

Nested try-blocks

+ +

First, let's see what happens with this:

+ +
try {
+  try {
+    throw new Error('oops');
+  }
+  finally {
+    console.log('finally');
+  }
+}
+catch (ex) {
+  console.error('outer', ex.message);
+}
+
+// Output:
+// "finally"
+// "outer" "oops"
+
+ +

Now, if we already caught the exception in the inner try-block by adding a catch-block

+ +
try {
+  try {
+    throw new Error('oops');
+  }
+  catch (ex) {
+    console.error('inner', ex.message);
+  }
+  finally {
+    console.log('finally');
+  }
+}
+catch (ex) {
+  console.error('outer', ex.message);
+}
+
+// Output:
+// "inner" "oops"
+// "finally"
+
+ +

And now, let's rethrow the error.

+ +
try {
+  try {
+    throw new Error('oops');
+  }
+  catch (ex) {
+    console.error('inner', ex.message);
+    throw ex;
+  }
+  finally {
+    console.log('finally');
+  }
+}
+catch (ex) {
+  console.error('outer', ex.message);
+}
+
+// Output:
+// "inner" "oops"
+// "finally"
+// "outer" "oops"
+
+ +

Any given exception will be caught only once by the nearest enclosing catch-block unless it is rethrown. Of course, any new exceptions raised in the "inner" block (because the code in catch-block may do something that throws), will be caught by the "outer" block.

+ +

Returning from a finally-block

+ +

If the finally-block returns a value, this value becomes the return value of the entire try-catch-finally statement, regardless of any return statements in the try and catch-blocks. This includes exceptions thrown inside of the catch-block:

+ +
(function() {
+  try {
+    try {
+      throw new Error('oops');
+    }
+    catch (ex) {
+      console.error('inner', ex.message);
+      throw ex;
+    }
+    finally {
+      console.log('finally');
+      return;
+    }
+  }
+  catch (ex) {
+    console.error('outer', ex.message);
+  }
+})();
+
+// Output:
+// "inner" "oops"
+// "finally"
+ +

The outer "oops" is not thrown because of the return in the finally-block. The same would apply to any value returned from the catch-block.

+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-try-statement', 'try statement')}}
+ +

Browser compatibility

+ +

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

+ +

{{Compat("javascript.statements.try_catch")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/statements/var/index.html b/files/ko/web/javascript/reference/statements/var/index.html new file mode 100644 index 0000000000..4366c3ed73 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/var/index.html @@ -0,0 +1,195 @@ +--- +title: var +slug: Web/JavaScript/Reference/Statements/var +tags: + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/var +--- +
{{jsSidebar("Statements")}}
+ +

var문은 변수를 선언하고, 선택적으로 초기화할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/js/statement-var.html")}}
+ + + +

구문

+ +
var varname1 [= value1 [, varname2 [, varname3 ... [, varnameN]]]];
+ +
+
varnameN
+
변수 이름. 어떤 유효한 식별자도 될 수 있습니다.
+
+ +
+
valueN
+
변수의 초기값. 어떤 유효한 표현도 될 수 있습니다.
+
+ +

설명

+ +

어디에 선언이 되어있든 간에 변수들은 어떠한 코드가 실행되기 전에  처리가 됩니다. var로 선언된 변수의 범위는 현재 실행 문맥인데, 그 문맥은 둘러싼 함수, 혹은 함수의 외부에 전역으로 선언된 변수도 될 수 있습니다.

+ +

선언된 변수들의 값 할당은 할당이 실행될 때 전역변수(이것은 전역 오브젝트의 프로퍼티가 됩니다)처럼 생성이 됩니다. 선언된 변수들과 선언되지 않은 변수들의 차이점은 다음과 같습니다:

+ +

1. 선언된 변수들은 변수가 선언된 실행 콘텍스트(execution context) 안에서 만들어집니다. 선언되지 않은 변수들은 항상 전역변수 입니다.

+ +
function x() {
+  y = 1;   // strict 모드에서는 ReferenceError를 출력합니다.
+  var z = 2;
+}
+
+x();
+
+console.log(y); // 로그에 "1" 출력합니다.
+console.log(z); // ReferenceError: z is not defined outside x를 출력합니다.
+
+ +

2. 선언된 변수들은 어떠한 코드가 실행되기 전에 만들어집니다. 선언되지 않은 변수들은 변수들을 할당하는 코드가 실행되기 전까지는 존재하지 않습니다.

+ +
console.log(a);                // ReferenceError를 출력합니다.
+console.log('still going...'); // 결코 실행되지 않습니다.
+ +
var a;
+console.log(a);                // 브라우저에 따라 로그에 "undefined" 또는 "" 출력합니다.
+console.log('still going...'); // 로그에 "still going..." 출력합니다.
+ +

3. 선언된 변수들은 변수들의 실행 콘텍스트(execution context)의 프로퍼티를 변경되지 않습니다. 선언되지 않은 변수들은 변경 가능합니다. (e.g 삭제 될 수도 있습니다.)

+ +
var a = 1;
+b = 2;
+
+delete this.a; // strict 모드에서는 TypeError를 출력합니다. 그렇지 않으면 자동적으로 실패합니다.
+delete this.b;
+
+console.log(a, b); // ReferenceError를 출력합니다.
+// 'b' 프로퍼티는 삭제되었고, 어디에도 존재하지 않습니다.
+ +

이러한 세가지 다른점 때문에, 변수 선언 오류는 예기치않은 결과로 이어질 가능성이 높습니다.  그러므로 함수 또는 전역 범위인지 여부와 상관없이, 항상 변수를 선언 하는 것을 추천합니다. 그리고 ECMAScript 5 안에 strict mode, 선언되지 않은 변수에 할당하면 오류를 출력합니다.

+ +

var 호이스팅(hoisting)

+ +

변수 선언들 (그리고 일반적인 선언)은 어느 코드가 실행 되기 전에 처리하기 때문에, 코드 안에서 어디서든 변수 선언은  최상위에 선언한 것과 동등합니다. 이것은 변수가 선언되기 전에 사용 될 수 있다는 것을 의미합니다. 변수 선언이 함수 또는 전역 코드의 상단에 이동하는 것과 같은 행동을 "호이스팅(hoisting)"이라고 불립니다.

+ +
bla = 2
+var bla;
+// ...
+
+// 위 선언을 다음과 같이 암묵적으로 이해하면 됩니다:
+
+var bla;
+bla = 2;
+
+ +

이러한 이유로, 그들의 범위(전역 코드의 상단 그리고 함수 코드의 상단) 상단에 변수를 항상 선언하기를 권장합니다. 그러면 변수는 함수 범위 (지역)이 되며, 스코프 체인으로 해결될 것이 분명합니다.

+ +

예제

+ +

두 변수들의 선언 및 초기화

+ +
var a = 0, b = 0;
+
+ +

단일 문자열 값으로 두 변수들 할당

+ +
var a = "A";
+var b = a;
+
+// 다음과 같음:
+
+var a, b = a = "A";
+
+ +

순서에 유의:

+ +
var x = y, y = 'A';
+console.log(x + y); // undefinedA
+
+ +

여기, x와 y는 어떠한 코드 실행하기 전에 선언되었다, 할당은 후에 발생하였다. "x = y"가 실행될 때, y는 존재하여 ReferenceError를 출력하진 않고 값은 'undefined' 입니다. 그래서, x는 undefined 값이 할당 됩니다. 그리고나서, y는 'A' 값이 할당 됩니다. 결과적으로, 첫번째 줄 이후에, x === undefined && y === 'A', 이와 같은 결과가 됩니다.

+ +

다수의 변수들의 초기화

+ +
var x = 0;
+
+function f(){
+  var x = y = 1; // x는 지역변수로 선언됩니다. y는 아닙니다!
+}
+f();
+
+console.log(x, y); // 0, 1
+// x는 예상대로 전역이다
+// y leaked outside of the function, though! 
+ +

암묵적인 전역변수와 외부 함수 범위

+ +

암묵적인 전역변수가 될 것으로 보이는 변수는 함수 범위 밖에서 변수들을 참조할 수 있다.

+ +
var x = 0;  // x는 전역으로 선언되었고, 0으로 할당됩니다.
+
+console.log(typeof z); // undefined, z는 아직 존재하지 않습니다.
+
+function a() { // a 함수를 호출했을 때,
+  var y = 2;   // y는 함수 a에서 지역변수로 선언되었으며, 2로 할당됩니다.
+
+  console.log(x, y);   // 0 2
+
+  function b() {       // b 함수를 호출하였을때,
+    x = 3;  // 존재하는 전역 x값에 3을 할당, 새로운 전역 var 변수를 만들지 않습니다.
+    y = 4;  // 존재하는 외부 y값에 4를 할당, 새로운 전역 var 변수를 만들지 않습니다.
+    z = 5;  // 새로운 전역 z 변수를 생성하고 5를 할당 합니다.
+  }         // (strict mode에서는 ReferenceError를 출력합니다.)
+
+  b();     // 호출되는 b는 전역 변수로 z를 생성합니다.
+  console.log(x, y, z);  // 3 4 5
+}
+
+a();                   // 호출되는 a는 또한 b를 호출합니다.
+console.log(x, z);     // 3 5
+console.log(typeof y); // undefined y는 function a에서 지역 변수입니다.
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-12.2', 'var statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-variable-statement', 'variable statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-variable-statement', 'variable statement')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{Compat("javascript.statements.var")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/reference/statements/while/index.html b/files/ko/web/javascript/reference/statements/while/index.html new file mode 100644 index 0000000000..5509404ed6 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/while/index.html @@ -0,0 +1,142 @@ +--- +title: while +slug: Web/JavaScript/Reference/Statements/while +tags: + - 반복문 + - 자바스크립트 +translation_of: Web/JavaScript/Reference/Statements/while +--- +
{{jsSidebar("Statements")}}
+ +

while문은 조건문이 참일 때 실행되는 반복문이다. 조건은 문장안이 실행되기 전에 참, 거짓을 판단한다.

+ +

문법

+ +
while (condition)
+  statement
+
+ +
+
조건
+
반복이 시작되기 전에 조건문은 참,거짓을 판단받게 된다. 만약 조건문이 참이라면, while문 안의 문장들이 실행된다. 거짓이라면, 문장은 그냥 while 반복문 후로 넘어간다.
+
문장
+
조건문이 참일 때만 while문 속의 문장들이 실행된다. 반복문 속에 여러개의 문장을 사용하고 싶다면 중괄호 { } 를 통해 문장들을 하나로 묶어야 한다.
+
+ +

예제

+ +

다음의 while문은 n이 3보다 작을 때까지 반복한다.

+ +
var n = 0;
+var x = 0;
+
+while (n < 3) {
+  n++;
+  x += n;
+}
+ +

반복을 살펴보면, n을 x에 계속 더하게 된다. 그러므로 x와 n 변수는 다음의 값을 갖는다.

+ + + +

세번째 반복후, n<3 이라는 초건은 더 이상 참이아니가 되므로 반복은 종료된다

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-while-statement', 'while statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-while-statement', 'while statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.6.2', 'while statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.6.2', 'while statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.6.1', 'while statement')}}{{Spec2('ES1')}}Initial definition
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/statements/with/index.html b/files/ko/web/javascript/reference/statements/with/index.html new file mode 100644 index 0000000000..30940cc297 --- /dev/null +++ b/files/ko/web/javascript/reference/statements/with/index.html @@ -0,0 +1,127 @@ +--- +title: with +slug: Web/JavaScript/Reference/Statements/with +translation_of: Web/JavaScript/Reference/Statements/with +--- +
Use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues. See the "Ambiguity Contra" paragraph in the "Description" section below for details.
+ +
{{jsSidebar("Statements")}}
+ +

with statement 는 명령문의 범위 체인을 확장합니다.

+ +

Syntax

+ +
with (expression)
+  statement
+
+ +
+
expression
+
명령문을 평가할 때 사용되는 범위 체인에 지정된 표현식을 추가합니다. 표현식을 중괄호로 감싸는 것은 필수입니다.
+
statement
+
모든 구문을 말합니다. 여러개의 명령문을 실행하려면 블록명령문 ({...})을 사용하여 해당 명령문을 그룹화 하세요.
+
+ +

Description

+ +

JavaScript는 규정되지 않은 이름을 포함하는 스크립트 또는 함수의 실행 컨텍스트와 연관된 범위 체인을 검색하여 규정되지 않은 이름을 찾습니다. 'with'문은 해당 개체를 평가하는 동안 이 개체를 해당 범위 체인의 머리글에 추가합니다. 본문에 사용된 규정되지 않은 이름이 범위 체인의 속성과 일치하는 경우 이름은 속성과 속성이 포함 된 개체에 바인딩 됩니다. 그렇지 않으면, {{jsxref("ReferenceError")}} 가 발생됩니다.

+ +
with 를 사용하는 것은 권장하지 않으며, ECMAScript 5 strict mode에서는 금지되어 있습니다. 임시 변수에 액세스 하려는 속성이 있는 객체를 할당하는 것이 좋습니다.
+ +

Performance pro & contra

+ +

Pro: with 구문은 성능저하 없이 긴 객체 참조를 반복해야할 필요를 줄여서 파일 크기를 감소 시킬 수 있습니다. 'with'에 필요한 스코프 체인 변경은 연산 비용이 들지 않습니다. 'with'를 사용하면 반복되는 객체 참조를 파싱하는 인터프리터가 해소됩니다. 하지만 대게의 경우에 이 이점은 임시변수를 사용하여 원하는 객체에 대한 참조를 저장함으로써 얻을 수 있습니다.

+ +

Contra: The with statement forces the specified object to be searched first for all name lookups. Therefore all identifiers that aren't members of the specified object will be found more slowly in a 'with' block. Where performance is important, 'with' should only be used to encompass code blocks that access members of the specified object.

+ +

Ambiguity contra

+ +

Contra: The with statement makes it hard for a human reader or JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. So given this example:

+ +
function f(x, o) {
+  with (o) {
+    console.log(x);
+  }
+}
+ +

Only when f is called is x either found or not, and if found, either in o or (if no such property exists) in f's activation object, where x names the first formal argument. If you forget to define x in the object you pass as the second argument, or if there's some similar bug or confusion, you won't get an error -- just unexpected results.

+ +

Contra: Code using with may not be forward compatible, especially when used with something other than a plain object. Consider this example:

+ +
+
function f(foo, values) {
+  with (foo) {
+    console.log(values);
+  }
+}
+
+ +

If you call f([1,2,3], obj) in an ECMAScript 5 environment, then the values reference inside the with statement will resolve to obj. However, ECMAScript 6 introduces a values property on {{jsxref("Array.prototype")}} (so that it will be available on every array). So, in a JavaScript environment that supports ECMAScript 6, the values reference inside the with statement could resolve to [1,2,3].values. However, in this particular example, {{jsxref("Array.prototype")}} has been defined with values in its {{jsxref("Symbol.unscopables")}} object. If it were not, one can see how this would be a difficult issue to debug.

+
+ +

Examples

+ +

Using with

+ +

The following with statement specifies that the Math object is the default object. The statements following the with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript assumes the Math object for these references.

+ +
var a, x, y;
+var r = 10;
+
+with (Math) {
+  a = PI * r * r;
+  x = r * cos(PI);
+  y = r * sin(PI / 2);
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-with-statement', 'with statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-with-statement', 'with statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.10', 'with statement')}}{{Spec2('ES5.1')}}Now forbidden in strict mode.
{{SpecName('ES3', '#sec-12.10', 'with statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.10', 'with statement')}}{{Spec2('ES1')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.with")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/strict_mode/index.html b/files/ko/web/javascript/reference/strict_mode/index.html new file mode 100644 index 0000000000..50cac47a52 --- /dev/null +++ b/files/ko/web/javascript/reference/strict_mode/index.html @@ -0,0 +1,383 @@ +--- +title: Strict mode +slug: Web/JavaScript/Reference/Strict_mode +tags: + - ECMAScript 5 + - JavaScript + - 엄격모드 +translation_of: Web/JavaScript/Reference/Strict_mode +--- +
{{JsSidebar("More")}}
+ +
가끔 엄격하지 않은 기본값을 "느슨한 모드(sloppy mode)"라고 부르기도 합니다. 공식적인 용어는 아니지만 혹시 모르니 알아두세요.
+ +
ECMAScript 5 에서 소개된 JavaScript 의 엄격모드는 JavaScript 의 제한된 버전을 선택하여 암묵적인 "느슨한 모드(sloppy mode)" 를 해제하기 위한 방법입니다. 엄격 모드는 단지 부분적인 것이 아니며, 이것은 고의적으로 일반 코드와 다른 시멘틱을 가지고 있습니다. 엄격모드를 지원하지 않는 브라우저에서는 엄격 모드의 코드가 다른 방식으로 동작할 것입니다, 그 때문에 엄격 모드가 적절하게 적용된 피쳐 테스트 없이 엄격 모드에 의존하면 안됩니다. 엄격 모드의 코드와 비-엄격 모드의 코드는 공존할 수 있으며, 때문에 스크립트의 엄격 모드를 취사 선택하는 것이 점진적으로 가능하게 되었습니다.
+ +
+ +

엄격 모드는 평범한 JavaScript 시멘틱스에 몇가지 변경이 일어나게 합니다.

+ +
    +
  1. 기존에는 조용히 무시되던 에러들을 throwing합니다.
  2. +
  3. JavaScript 엔진의 최적화 작업을 어렵게 만드는 실수들을 바로잡습니다. 가끔씩 엄격 모드의 코드는 비-엄격 모드의 동일한 코드보다 더 빨리 작동하도록 만들어집니다.
  4. +
  5. 엄격 모드는 ECMAScript의 차기 버전들에서 정의 될 문법을 금지합니다.
  6. +
+ +

코드를 JavaScript의 변형이 제한된 환경에서 동작하도록 하고 싶다면, 엄격 모드로의 변환(transitioning to strict mode)을 참고하세요.

+ +

엄격모드 적용하기

+ +

엄격모드는 전체 스크립트 또는 부분 함수에 적용가능합니다. 단, {} 괄호로 묶여진 블럭문에는 적용되지 않습니다. 컨텍스트와 같은곳에 적용을 시도하면 동작하지 않습니다. eval 코드, Function 코드, 이벤트 핸들러 속성, {{domxref("WindowTimers.setTimeout()")}} 과 연관된 함수들에 전달된 문자열이 전체 스크립트이며 여기에서 엄격모드가 예상대로 동작합니다. 

+ +

스크립트 엄격 모드

+ +

엄격모드를 전체 스크립트에 적용하기 위해, 정확한 구문 "use strict";(또는 'use strict';) 을 다른 구문 작성 전에 삽입합니다.

+ +
// 전체 스크립트 엄격 모드 구문
+'use strict';
+var v = "Hi!  I'm a strict mode script!";
+
+ +

이 구문은 이미 유명한 웹사이트에서 문제를 일으킨 전적이 있습니다. 상충되지 않는 스크립트들 끼리 맹목적인 연결이 불가능하기 때문입니다. 엄격 모드의 스크립트와 비-엄격 모드의 스크립트의 연결은 심사숙고 하시기를 바랍니다. 이렇게 되면 전체 연결은 엄격으로 보입니다! 엄격 모드에 다른 엄격모드 들을 결합하는 것은 괜찮습니다. 그리고, 비-엄격 스크립트 사이의 결합도 괜찮습니다. 분명한건, 스크립트를 결합하는 것이 절대 이상적인 것이 아니라는 것이지만, 그래야 한다면 함수를 기준으로 엄격모드 사용을 고려하시기 바랍니다.

+ +

또한 함수 내부의 전체 스크립트 내용에 접근할 수 있으며, 엄격모드를 사용하는 외부 함수를 가질 수 있습니다. 이는 결합 문제를 없애주기도 하지만, 이것이 스코프 바깥에 위치한 어떤 전역 변수든 확실하게 밖으로 추출할 수 있음을 의미합니다 . 

+ +

함수에 strict mode 적용

+ +

마찬가지로, 함수에 strict mode를 적용하기 위해, 함수 본문 처음에 다음의 구문을 넣습니다. "use strict"; (또는 'use strict';).

+ +
function strict() {
+  // 함수-레벨 strict mode 문법
+  'use strict';
+  function nested() { return "And so am I!"; }
+  return "Hi!  I'm a strict mode function!  " + nested();
+}
+function notStrict() { return "I'm not strict."; }
+
+ +

모듈에 strict mode 적용

+ +

ECMAScript 2015 는 JavaScript 모듈을 소개했습니다. 따라서, 이는 엄격 모드를 적용할 수 있는 3번 째 방법입니다. JavaScript 모듈의 전체 컨텐츠는 엄격 모드 시작을 위한 구문 없이도 자동으로 엄격모드입니다.

+ +
function strict() {
+    // 모듈이기때문에 기본적으로 엄격합니다
+}
+export default strict;
+
+ +

엄격한 모드 변경

+ +

엄격한 모드는 구문과 런타임 동작을 모두 변경합니다.
+ 일반적으로 이러한 유형의 변화가 발생합니다: 변환 실수를 오류로 해석하거나(문법 오류 또는 런타임에 오류 발생), 특정 이름의 특정 용도에 대한 특정 변수를 계산하는 방법을 단순화하며,  eval 과 arguments 를 단순화하고,"안전한 "자바 스크립트를 작성하도록 돕고, 미래 ECMAScript의 진화에 대비합니다.

+ +

실수를 에러로 바꾸는 것

+ +

엄격한 모드는 일부 이전에 허용되었던 실수를 오류로 바꿔 놓습니다. 자바 스크립트는 초보 개발자에게 쉬운 것이 되도록 설계되었으며, 때로는 오류를 일으킬만한  동작을 에러없이 시행합니다. 때때로 이것은 즉각적인 문제를 해결하지만, 때때로 이것은 더 심각한 문제를 만들어 냅니다. 엄격한 모드는 이러한 실수를 오류로 처리해서 그것을 발견하고 즉시 고칠 수 있도록 합니다.

+ +

첫째로, 엄격모드는 실수로 글로벌 변수를 생성하는 것을 불가능하게 만듭니다. 일반적인 JavaScript에서 변수를 잘못 입력하면 전역 객체에 대한 새 속성이 만들어지고 그대로 "동작" (미래의 오류가 발생할 수 있음: modern 자바 스크립트처럼) 합니다. 전역 변수를 생성하는 할당은 엄격 모드에선 오류를 발생시킵니다.

+ +
"use strict";
+                       // 전역 변수 mistypedVariable 이 존재한다고 가정
+mistypedVaraible = 17; // 변수의 오타때문에 이 라인에서 ReferenceError 를 발생시킴
+
+ +

둘째로, 엄격모드는 예외를 발생시키는 실패를 조용히 넘어가는 대신 작업을 만듭니다. 예를 들어, NaN 은 쓸 수 없는 전역 변수입니다. NaN 에 할당하는 일반적인 코드는 아무 것도 하지 않습니다. 개발자도 아무런 실패 피드백을 받지 않습니다. 엄격 모드에서 NaN 에 할당하는 것은 예외를 발생시킵니다. 일반 코드에서 조용히 넘어가는 모든 실패에 대해 (쓸 수 없는 전역 또는 프로퍼티에 할당, getter-only 프로퍼티에 할당, 확장 불가 객체에 새 프로퍼티 할당) 엄격 모드에서는 예외를 발생시킵니다.

+ +
"use strict";
+
+// 쓸 수 없는 프로퍼티에 할당
+var undefined = 5; // TypeError 발생
+var Infinity = 5; // TypeError 발생
+
+// 쓸 수 없는 프로퍼티에 할당
+var obj1 = {};
+Object.defineProperty(obj1, "x", { value: 42, writable: false });
+obj1.x = 9; // TypeError 발생
+
+// getter-only 프로퍼티에 할당
+var obj2 = { get x() { return 17; } };
+obj2.x = 5; // TypeError 발생
+
+// 확장 불가 객체에 새 프로퍼티 할당
+var fixed = {};
+Object.preventExtensions(fixed);
+fixed.newProp = "ohai"; // TypeError 발생
+
+ +

셋째로, 엄격 모드는 삭제할 수 없는 프로퍼티를 삭제하려할 때 예외를 발생시킵니다(시도가 어떤 효과도 없을 때).

+ +
"use strict";
+delete Object.prototype; // TypeError 발생
+
+ +

넷째로, Gecko 34 이전의 엄격모드는 객체 리터럴의 모든 프로퍼티의 이름이 유니크해도록 요구합니다. 일반 코드는 프로퍼티의 값이 나중에 정해진 프로퍼티 이름으로 중복할 것입니다. 하지만 마지막 인스턴스 만 변경했기 때문에 코드를 수정하여 마지막 인스턴스를 변경하는 것 이외의 속성 값을 변경하면 복제는 버그의 벡터가됩니다. 엄격모드에서는 프로퍼티 이름을 중복하는 것은 구문 에러입니다.

+ +
+

ECMAScript 2015부터는 에러가 아닙니다. ({{bug(1041128)}}).

+
+ +
"use strict";
+var o = { p: 1, p: 2 }; // !!! 구문 에러
+
+ +

다섯째로, 엄격모드는 유니크한 함수 파라미터 이름을 요구합니다. 일반 코드에서는 마지막으로 중복된 인수가 이전에 지정된 인수를 숨깁니다. 이러한 이전의 인수들은 arguments[i] 를 통해 여전히 남아 있을 수 있으므로, 완전히 접근 불가한 것이 아닙니다. 여전히, 이런 숨김 처리는 이치에 맞지 않으며 원했던 것이 아닐 수 있습니다(예를 들면 오타를 숨길 수도 있습니다). 따라서 엄격 모드에서는 중복 인수명은 구문 에러입니다.

+ +
function sum(a, a, c){ // !!! 구문 에러
+  "use strict";
+  return a + b + c; // 코드가 실행되면 잘못된 것임
+}
+
+ +

여섯째로, ECMAScript 5 에서의 엄격 모드는 8진 구문을 금지합니다. 8진 구문은 ES5의 문법이 아니지만, 모든 브라우저에서 앞에 0을 붙여 지원됩니다(0644 === 420 와 "\045" === "%"). ECMAScript 2015 에서는 접두사 "0o"를 붙여 8진수를 지원합니다.

+ +
var a = 0o10; // ES6: 8진수
+ +

초보 개발자들은 가끔 앞에 붙은 0 이 무의미하다고 생각하여, 이를 정렬용으로 사용합니다 — 하지만 이는 숫자의 의미를 바꿔버립니다! 이 8진수 문법은 거의 무용하며 잘못 사용될 수 있으므로 엄격모드에서 이 구문은 에러입니다.

+ +
"use strict";
+var sum = 015 + // !!! 구문 에러
+          197 +
+          142;
+
+ +

일곱째로, ECMAScript 6 의 엄격모드는 {{Glossary("primitive")}} 값에 프로퍼티를 설정하는 것을 금지합니다. 엄격모드가 아닐 때에는 프로퍼티 설정이 간단하게 무시되지만(no-op), 엄격모드에서는 {{jsxref("TypeError")}} 를 발생시킵니다.

+ +
(function() {
+"use strict";
+
+false.true = "";         // TypeError
+(14).sailing = "home";   // TypeError
+"with".you = "far away"; // TypeError
+
+})();
+ +

변수 사용 단순화

+ +

엄격모드는 코드상의 변수 이름을 특정 변수 정의로 매핑하는 방법을 단순화합니다. 많은 컴파일러 최적화는 변수 X 가 어떤 위치에 저장되어 있는지를 말해주는 능력에 의존하고 있습니다. 이는 자바스크립트 코드를 완전히 최적화하는데 중요합니다. 자바스크립트는 때때로 이름을 코드상의 변수 정의로 기본 매핑하는 것을 런타임때까지 실행이 불가하게합니다. 엄격모드는 이것이 발생하는 대부분의 경우를 제거하여 컴파일러가 엄격모드 코드를 더 잘 최적화 할 수 있게합니다.

+ +

첫째로, 엄격모드는 with 를 사용하지 못하게합니다. with 사용의 문제는 런타임중에 블록안의 모든 이름이 전달된 객체의 프로퍼티나 인근 (또는 심지어 전역) 스코프 내의 변수로 매핑될 수도 있다는 것입니다. 이는 사전에 아는 것이 불가합니다. 엄격 모드는 with 를 구문 에러로 만들어, with 의 이름이 런타임에 알 수 없는 위치를 참조하지 않도록합니다.

+ +
"use strict";
+var x = 17;
+with (obj) // !!! 구문 에러
+{
+  // 엄격모드가 아니라면, 이는 var x 가 되어야 하나요,
+  // obj.x 가 되어야 하나요?
+  // 일반적으로는 코드를 실행하지 않고 이를 말하는 것은 불가하므로,
+  // 이름을 최적화 할 수 없습니다.
+  x;
+}
+
+ +

이름이 짧은 변수에 객체를 할당한 후, 변수에 해당하는 프로퍼티에 접근하는 간단한 대안은 with 를 대체할 준비가 되었습니다.

+ +

둘째로, 엄격모드 코드의 eval 은 새로운 변수를 주위 스코프에 추가하지 않습니다. 일반적인 코드에서 eval("var x;") 는 변수 x 를 주위 함수나 전역 스코프에 추가합니다. 이는, 일반적으로 eval 호출을 포함하는 함수에서 인수나 지역 변수를 참조하지 않는 모든 이름은 런타임에 특정 정의에 반드시 매핑되어야 함을 의미합니다(eval 이 외부 변수를 숨기는 새로운 변수를 추가했기 때문입니다). 엄격모드에서 eval 은 evaluated 된 코드에서만 변수를 생성하므로, 외부 변수나 일부 로컬 변수에 참조하는지에 영향을 주지 않습니다.

+ +
var x = 17;
+var evalX = eval("'use strict'; var x = 42; x");
+console.assert(x === 17);
+console.assert(evalX === 42);
+
+ +

이와 관련해서, eval 함수가 엄격모드 코드 내에서 eval(...) 형태의 표현으로 적용되었다면, 코드는 엄격모드 코드로 evaluated 됩니다. 코드는 명시적으로 엄격모드를 적용할 수 있지만, 필수적인 것은 아닙니다.

+ +
function strict1(str){
+  "use strict";
+  return eval(str); // str 은 엄격모드 코드로 다뤄짐
+}
+function strict2(f, str){
+  "use strict";
+  return f(str); // eval(...) 이 아님:
+                 // str 은 엄격모드를 적용한 경우에만 엄격함
+}
+function nonstrict(str){
+  return eval(str); // str 은 엄격모드를 적용한 경우에만 엄격함
+}
+
+strict1("'엄격모드 코드!'");
+strict1("'use strict'; '엄격모드 코드!'");
+strict2(eval, "'느슨한 코드.'");
+strict2(eval, "'use strict'; '엄격모드 코드!'");
+nonstrict("'느슨한 코드.'");
+nonstrict("'use strict'; '엄격모드 코드!'");
+
+ +

따라서 엄격모드 eval 코드 내의 이름은 엄격모드 코드 내의 이름이 eval 의 결과로 evaluated 되지 않은 것과 동일하게 동작합니다.

+ +

셋째로, 엄격모드는 일반 이름을 제거하는 것을 금지합니다. 엄격 모드에서 delete name 은 구문 에러입니다.

+ +
"use strict";
+
+var x;
+delete x; // !!! 구문 에러
+
+eval("var y; delete y;"); // !!! syntax error
+ +

evalarguments 를 더 간단하게 하기

+ +

엄격모드는 argumentsevel 을 덜 기괴하고 마법적으로 만듭니다. 둘은 일반 코드에서 상당히 많은 마법적인 동작들을 갖고 있습니다: 바인딩을 추가하거나 삭제하고 바인딩 값을 변경하기위한 eval, 명명된 인수를 앨리어스하는 인덱싱된 프로퍼티 arguments. 엄격모드는 ECMAScript 의 미래 버전까지는 모든 수정이 이루지지는 않겠지만 evalarguments 를 키워드로 다루기 위한 훌륭한 큰 걸음을 내딛었습니다.

+ +

첫째로, 변수명 eval 과 arguments 는 언어 문법에 바운드되거나 할당될 수 없습니다. 다음 시도들은 모두 구문 에러입니다.

+ +
"use strict";
+eval = 17;
+arguments++;
+++eval;
+var obj = { set p(arguments) { } };
+var eval;
+try { } catch (arguments) { }
+function x(eval) { }
+function arguments() { }
+var y = function eval() { };
+var f = new Function("arguments", "'use strict'; return 17;");
+
+ +

둘째로, 엄격모드 코드는 arguments 객체가 생성한 프로퍼티를 앨리어스하지 않습니다. 함수의 첫 번째 인수가 arg 인 일반 코드에서는 arg 를 설정하는 것은 arguments[0] 를 설정하기도 하며, 그 반대도 그렇습니다(인수가 제공되지 않거나, arguments[0] 이 삭제된 경우는 제외). 엄격모드 함수의 arguments 객체는 함수가 호출될 때 원본 인수들을 저장합니다. arguments[i] 는 명명된 인수에 해당하는 값을 추적하지 않으며, 명명된 인수도 arguments[i] 에 해당하는 값을 추적하지 않습니다.

+ +
function f(a){
+  "use strict";
+  a = 42;
+  return [a, arguments[0]];
+}
+var pair = f(17);
+console.assert(pair[0] === 42);
+console.assert(pair[1] === 17);
+
+ +

셋째로, arguments.callee 는 더 이상 지원되지 않습니다. 일반 코드의 arguments.callee 는 바깥 함수를 참조합니다. 이런 유즈 케이스는 중요하지 않습니다. 간단히 바깥 함수의 이름을 사용하면됩니다. 더욱이, arguments.callee 는 인라인 함수와 같은 최적화를 상당히 방해하므로, arguments.callee 가 접근하는 함수는 인라인이 아닌 함수를 참조하도록 제공해야 했습니다. 엄격모드 함수의 arguments.callee 는 삭제할 수 없는 프로퍼티이며, 설정이나 반환할때 에러를 발생합니다.

+ +
"use strict";
+var f = function() { return arguments.callee; };
+f(); // TypeError
+
+ +

JavaScript "보안"

+ +

엄격모드는 "보안된"  자바스크립트를 작성하기 쉽게 해줍니다. 일부 웹사이트들은 사용자가 다른 사용자들을 대신하여 웹사이트에서 실행시키는자바스크립트를 작성하는 방법을 제공합니다. 브라우저에서 자바스크립트는 사용자의 개인정보에 접근할수 있기 때문에, 자바스크립트는 금지된 기능에 대한  검열을 하기위해 반드시 실행전에 부분적으로 변경되어야 합니다. 자바스크립트의 유연성으로 인해 많은 런타임 체크없이 이것을 수행하는것은 사실상 불가능합니다. 특정 언어의 기능들이 너무 광범위하여 런타임 검사 수행은 상당한 성능비용이 생깁니다. 엄격모드의 작은 수정과 사용자가 제출한 자바스크립트가 엄격모드가 되면 특정 방식으로 호출되므로 런타임 검사의 필요성이 크게 줄어 듭니다.  

+ +

첫째, 엄격모드에서는 this 로  함수에 전달된 값은 강제로 객체가 되지 않습니다 (a.k.a. "boxed"). 보통 함수의 경우, this 는 언제나 객체입니다: 객체값 this  와 함께 호출된 경우 제공된 객체이거나 ; 부울값,  문자 또는 숫자 this  로 호출된 경우 그 값은 Boxed 입니다; 또는 undefined 또는 null this 로 호출되면 전역객체입니다. (특정된 this 명세를 위해서는 call, apply, 또는 bind 를 사용하십시요) 자동 박싱은 성능 비용뿐 아니라 전역 객체가 브라우저에 노출되는것은 보안상 위험합니다. 전역객체들은 자바스크립트 환경의 "보안"  기능에 접근하는것을 제공하기때문에 제한되어야 합니다. 따라서 엄격모드의 함수는, 정의된  this  는 박스드 객체가 되지 않으며, 정의되지 않은경우 this 는 undefined 가 됩니다:

+ +
"use strict";
+function fun() { return this; }
+console.assert(fun() === undefined);
+console.assert(fun.call(2) === 2);
+console.assert(fun.apply(null) === null);
+console.assert(fun.call(undefined) === undefined);
+console.assert(fun.bind(true)() === true);
+
+ +

즉, 브라우저에서 엄격모드의 함수내 에서는 더 이상 window 객체를  this 를 통해 참조할 수 없습니다.

+ +

둘째로, 엄격모드에서는 ECMAScript의 일반적으로 구현된 확장을 통해 자바스크립트 스택을 "걷는"것이 불가능합니다. 이러한 일반적인 확장 코드는,  함수 fun 이 호출되는 중간에, fun.caller 는 가장 최근에 fun 을 호출한 함수이고 fun.arguments 는 fun을 호출하기 위한   입니다. "권한있는"함수와 (잠재적으로 보안되지 않은) 인수에 접근을 허용하기때문에 두가지 확장 모두 자바스크립트의 "보안" 문제가 됩니다. fun 이 엄격모드인경우, both fun.caller 와 fun.arguments 모두 설정 또는 검색될때 삭제 불가능한 속성이 됩니다.

+ +
function restricted()
+{
+  "use strict";
+  restricted.caller;    // throws a TypeError
+  restricted.arguments; // throws a TypeError
+}
+function privilegedInvoker()
+{
+  return restricted();
+}
+privilegedInvoker();
+
+ +

셋째, 엄격모드의 인수 는 더이상 해당 함수의 호출 변수에 대한 접근을 제공하지 않습니다. 일부 이전 ECMAScript에서  arguments.caller  해당 함수에  별명이 지정된 객체였습니다.  이것은 함수의 추상화를 통해 권한이 있는 값을 숨길수 있는 기능을  차단하여 보안의 위협이 됩니다; 이것은 또한 대부분의 최적화를  배제시킵니다. 이러한 이유로 최신 브라우저들은 이를 구현하지 않습니다. 하지만 이것들의 이전 기능들 때문에, 엄격모드함수에서  arguments.caller  설정이나 검색시 삭제 불가능한 요소가 됩니다:

+ +
"use strict";
+function fun(a, b)
+{
+  "use strict";
+  var v = 12;
+  return arguments.caller; //TypeError 가 발생.
+}
+fun(1, 2); // doesn't expose v (or a or b)
+
+ +

미래의 ECMAScript 버전을 위한 준비

+ +

새롭게 선보일 ECMAScript 버전은 새로운 구문을 소개할 것이고, ECMAScript5에서의 엄격 모드는 변환을 쉽게 하기 위해 몇 가지의 제한을 적용할 것으로 예상되고 있습니다. 만약 이 변화들이 엄격 모드에서의 제한을 기반으로 한다면, 더 바꾸기 쉬워질 것입니다.

+ +

첫번째로, 엄격 모드에서의 식별자 후보들은 예약어가 됩니다. 이 예약어들은 implements, interface, let, package, private, protected, public, staticyield입니다. 그럼, 엄격 모드에서는 이 예약어와 똑같은 이름을 사용하거나, 변수명 또는 아규먼트명으로도 사용할 수 없습니다.  

+ +
function package(protected){ // !!!
+  "use strict";
+  var implements; // !!!
+
+  interface: // !!!
+  while (true){
+    break interface; // !!!
+  }
+
+  function private() { } // !!!
+}
+function fun(static) { 'use strict'; } // !!!
+
+
+ +

Mozilla의 특별 지시 두 가지 : 먼저, 코드가 JavaScript 1.7 또는 그보다 높고 (예를 들어, 크롬 코드 또는 <script type=""> 를 바로 사용할 때) 엄격 모드의 코드라면,  let 와 yield는 처음 소개되었을 때의 그 기능을 가진다. 그러나 웹에서의 엄격 모드 코드는, <script src=""><script>...</script>로 로딩되지, let/yield를 식별자로 사용할 수가 없을 것이다. 그리고 나서는, ES5 가 class, enum, export, extends, import, and super 와 같은 예약어들을 무조건 리저브함에도 불구하고, 먼저 Firefox 5 Mozilla 는 그것들을 엄격 모드에서만 리저브한다.

+ +

다음은, 엄격 모드는 스크립트나 함수의 탑 레벨이 아닌 곳에서의 함수 내용 정의를 제한합니다. (strict mode prohibits function statements not at the top level of a script or function). 브라우저에서 일반적인 코드는 함수 내용 정의가 "어디에서든" 허용됩니다. 이것은 ES5의 부분이 아닙니다!(심지어 ES3도 아니다.) 이건 다른 브라우저에서 공존할 수 없는 시멘틱의 확장입니다. 앞으로의 ECMAScript 에디션은 바라건대, 스크립트나 함수의 탑 레벨이 아닌 곳에서의 함수 내용 정의를 위해, 새로운 시멘틱을 명시할 것입니다. 엄격 모드에서 이러한 함수 정의를 금지하는 것(Prohibiting such function statements in strict mode)은 앞으로 출시될 ECMAScript의 사양을 위한 "준비"입니다.  :

+ +
"use strict";
+if (true){
+  function f() { } // !!! syntax error
+  f();
+}
+
+for (var i = 0; i < 5; i++){
+  function f2() { } // !!! syntax error
+  f2();
+}
+
+function baz(){ // kosher
+  function eit() { } // also kosher
+}
+
+ +

이 규제는 엄밀히 말하면 엄격 모드가 아닌데, 저런 함수 표현식들은 기본 ECMAScript5의 확장이기 때문입니다. 그러나 이것이 ECMAScript 협회가 권장하는 방식이며, 브라우저들이 이를 지원할 것입니다. 

+ +

브라우저에서의 엄격 모드

+ +

현재 주류의 브라우저들은 엄격 모드를 지원하고 있습니다. 하지만, 아직도 현실에서 사용되는 수 많은 브라우저의 버전들은 엄격 모드를 부분적으로만 지원하거나(Browser versions used in the wild that only have partial support for strict mode), 아예 지원을 하지 않고 있기 때문에, 맹목적으로 여기에 의지할 수는 없습니다. (예를 들면, Internet Explorer 10 버전 이하!) 엄격 모드는 시멘틱을 바꿉니다. 이 변화들에 의지하는 것은 실수와 엄격 모드를 지원하지 않는 브라우저의 에러를 야기할 것입니다. 엄격 모드를 사용하는 데에 주의하는 것을 익히세요, 그리고 피쳐 테스트로 엄격 모드를 사용하기에 적절한 부분인지 확인하고 보완하세요. 마지막으로, 엄격 모드를 지원하는 브라우저와 그렇지 않은 브라우저에서 작성한 코드의 테스트를 확실히 하도록 하세요. 

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-10.1.1', 'Strict Mode Code')}}{{Spec2('ES5.1')}}초기 정의. 참조 : Strict mode restriction and exceptions
{{SpecName('ES6', '#sec-strict-mode-code', 'Strict Mode Code')}}{{Spec2('ES6')}}Strict mode restriction and exceptions
{{SpecName('ESDraft', '#sec-strict-mode-code', 'Strict Mode Code')}}{{Spec2('ESDraft')}}Strict mode restriction and exceptions
+ +

함께 보기

+ + diff --git a/files/ko/web/javascript/reference/strict_mode/transitioning_to_strict_mode/index.html b/files/ko/web/javascript/reference/strict_mode/transitioning_to_strict_mode/index.html new file mode 100644 index 0000000000..bc45f85cac --- /dev/null +++ b/files/ko/web/javascript/reference/strict_mode/transitioning_to_strict_mode/index.html @@ -0,0 +1,137 @@ +--- +title: Transitioning to strict mode(엄격모드로 전환) +slug: Web/JavaScript/Reference/Strict_mode/Transitioning_to_strict_mode +translation_of: Web/JavaScript/Reference/Strict_mode/Transitioning_to_strict_mode +--- +
{{jsSidebar("More")}}
+ +
ECMAScript 5에서 strict mode이 도입이 되었다. 이제는 모든 주요 브라우저에서 사용이 가능하다(IE10 포함) 웹 브라우저가 엄격한 코드를 해석하도록 만들어준다. (소스 코드의 맨 위에 'use strict'를 추가하는 것만으로),  기존 코드 기반을 엄격 모드로 전환하는 것은 좀 더 많은 작업을 한다.
+ +
 
+ +
이 글은 개발자의 안내서에 초점이 맞춰져있다.
+ +

Gradual transition

+ +

Strict 모드는 점진적으로 전환 할 수 있도록 설계되었다. 개별 파일을 개별적으로 변경하거나 코드를 엄격 모드에서 함수 단위로 전환 할 수도 있다.

+ +

strict 와 non-strict의 차이점

+ +

Syntax errors

+ +

'use strict'; 를 추가하게 되면, 아래의 경우에는 스크립트가 실행되기 전에{{jsxref("SyntaxError")}} 에러를 던진다.

+ + + +

우리들의 명백한 에러나 나쁜 실수들이 드러나기 때문에 이러한 에러들은 좋다. 이러한 것들은 코드가 실행되기 전에 실행이 된다.

+ +

New runtime errors

+ +

JavaScript는 컨테스트에서 조용한 실패에 익숙해져 있다. Strict mode는 이 같은 경우에는 던졌다. 만약 너의 코드베이스에 이 같은 경우가 포함되어있다면, 잘못된 것이 있는지 확인하기 위해 테스트가 필요할 것이다. 다시 한번, 함수 세분화된 단계에서 발생할 수 있다.

+ +

값을 선언되지 않은 변수로 설정하기

+ +
function f(x) {
+  'use strict';
+  var a = 12;
+  b = a + x * 35; // error!
+}
+f(42);
+
+ +

이것은 예상된 효과가 드문 전역객체의 변수를 변경하는 데 사용된다. 만약에 정말로 전역객체의 변수를 부여하고 싶다면, 그것을 인수, 그것을 argument로 넘기고 property로 명시적 할당을 한다.

+ +
var global = this; // in the top-level context, "this" always
+                   // refers to the global object
+function f(x) {
+  'use strict';
+  var a = 12;
+  global.b = a + x * 35;
+}
+f(42);
+
+ +

구성할 수 없는 속성을 삭제하려고 한다.

+ +
'use strict';
+delete Object.prototype; // error!
+
+ +

비-엄격모드에서는 조용한 실패였으나 사용자의 기대에는 맞지 않다.

+ +

중독 된 인수 및 함수 속성

+ +

엄격모드에서 arguments.callee, arguments.caller, anyFunction.caller, or anyFunction.arguments 접근하려고 하면 에러를 던진다. 합법적인 사용 사례는 다음과 같은 함수를 다시 사용하는 것이다 : 

+ +
// example taken from vanillajs: http://vanilla-js.com/
+var s = document.getElementById('thing').style;
+s.opacity = 1;
+(function() {
+  if ((s.opacity-=.1) < 0)
+    s.display = 'none';
+  else
+    setTimeout(arguments.callee, 40);
+})();
+ +

이것을다음과 같이 재 작성할 수 있다 :

+ +
'use strict';
+var s = document.getElementById('thing').style;
+s.opacity = 1;
+(function fadeOut() { // name the function
+  if((s.opacity-=.1) < 0)
+    s.display = 'none';
+  else
+    setTimeout(fadeOut, 40); // use the name of the function
+})();
+ +

문법적 차이

+ +

매우 미묘한 차이점들이 있다. 테스트 단위가 이런 종류의 미묘한 차이를 잡지 못할 수 있다. 이러한 차이점이 너의 코드의 의미에 영향을 주지 않도록, 코드 기반을 신중하게 검토해야 할 것이다. 다행히도,이 세심한 검토는 함수 세분성을 점차적으로 줄일 수 있다.

+ +

함수내부에서 불리는 this

+ +

f() 라는 함수가 있을 때, this 값은 당연히 전역객체이다.  stict mode에서는 undefined 이다. 값은 원시값이고, 함수가 call 나 apply 화 함께 불리게 된다면 값은 이것은 하나의 객체이다.(또는  undefined , null 인 전역객체). stict mode에서, 값은 변환이나 대체없이 직접 전달된다.

+ +

arguments 명명 된 함수 인수를 별명으로 지정하지 않습니다.

+ +

비-엄격모드에서, arguments객체의 값을 수정하면 해당 명명 된 인수가 수정된다. 이로 인해 자바 스크립트 엔진에 대한 최적화가 복잡해지고 코드를 읽기 / 이해하기가 더 어려워졌다. 엄격모드에서, arguments 객체는 명명 된 인수와 동일한 값으로 만들어지고 초기화되지만 arguments 객체 또는 명명 된 인수에 대한 변경 사항은 서로 반영되지 않는다.

+ +

eval바꾸기

+ +

엄격모드에서, eval 은 그것이 불린 범위안에서 새로운 변수를 만들지 않는다.  또한 물론 엄격모드에서, 문자열은 엄격모드 규칙으로 평가된다. 아무 문제가 없는지 확인하기 위해서는 철저한 테스트를 수행해야 한다. 정말로 필요하지 않다면 eval을 사용하지 않는 것이 실용적인 해결책이 될 수 있다.

+ +

Strictness-neutral code

+ +

A potential "downside" of moving strict code to strict mode is that the semantics may be different in legacy browsers which do not implement strict mode. In some rare occasions (like bad concatenation or minification), your code also may not run in the mode you wrote and tested it in. Here are the rules to make your code strictness-neutral:

+ +
    +
  1. 코드를 엄격하게 작성하고 (위의 "New runtime errors" 섹션의) 엄격한 오류가 발생하지 않았는지 확인하십시오.
  2. +
  3. semantic 차이점으로 부터 멀리하라 +
      +
    1. eval: 당신이 하는 일을 안다면, 그것을 사용해라
    2. +
    3. arguments: 함수의 첫 번째 줄로 이름을 통해 항상 함수 인수에 액세스하거나 인수 객체의 복사본을 수행합니다 :
      + var args = Array.prototype.slice.call(arguments)
    4. +
    5. this:  this 당신이 만든 대상을 가리킬 때 사용해라
    6. +
    +
  4. +
+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/template_literals/index.html b/files/ko/web/javascript/reference/template_literals/index.html new file mode 100644 index 0000000000..3eaf2beb13 --- /dev/null +++ b/files/ko/web/javascript/reference/template_literals/index.html @@ -0,0 +1,254 @@ +--- +title: Template literals +slug: Web/JavaScript/Reference/Template_literals +tags: + - Template +translation_of: Web/JavaScript/Reference/Template_literals +--- +
{{JsSidebar("More")}}
+ +

템플릿 리터럴은 내장된 표현식을 허용하는 문자열 리터럴입니다. 여러 줄로 이뤄진 문자열과 문자 보간기능을 사용할 수 있습니다. 이전 버전의 ES2015사양 명세에서는 "template strings" (템플릿 문자열) 라고 불려 왔습니다.

+ +

Syntax

+ +
`string text`
+
+`string text line 1
+ string text line 2`
+
+`string text ${expression} string text`
+
+tag `string text ${expression} string text`
+
+ +

Description

+ +

템플릿 리터럴은 이중 따옴표 나 작은 따옴표 대신 백틱(` `) (grave accent) 을 이용합니다.  템플릿 리터럴은 또한 플레이스 홀더를 이용하여 표현식을 넣을 수 있는데, 이는 $와 중괄호( $ {expression} ) 로 표기할 수 있습니다. 플레이스 홀더 안에서의 표현식과 그 사이의 텍스트는 함께 함수로 전달됩니다. 기본 함수는 단순히 해당 부분을 단일 문자열로 연결시켜 줍니다. 템플릿 리터럴 앞에 어떠한 표현식이 있다면(여기에서는 태그), 템플릿 리터럴은 "태그가 지정된 템플릿"이라고 불리게 됩니다. 이 때, 태그 표현식 (주로 함수)이 처리된 템플릿 리터럴과 함께 호출되면, 출력하기 전에 조작할 수 있습니다. 템플릿 리터럴 안에서 백틱 문자를 사용하려면 백틱 앞에 백슬러쉬(\)를 넣으십시오.

+ +
`\`` === "`" // --> true
+ +

Multi-line strings

+ +

source 내에 삽입되는 newline characters(\n)은 template literal의 일부가 됩니다.

+ +

일반 string 들을 사용하여, multi-line strings 들을 얻기 위해서는 아래와 같은 문법을 사용해야 할 것입니다.

+ +
console.log("string text line 1\n"+
+"string text line 2");
+// "string text line 1
+// string text line 2"
+ +

같은 효과를 template literal을 통해 얻기 위해서는, 아래와 같이 적을 수 있습니다.

+ +
console.log(`string text line 1
+string text line 2`);
+// "string text line 1
+// string text line 2"
+ +

Expression interpolation(표현식 삽입법)

+ +

표현식(expression)을 일반 문자열(normal strings)에 삽입하기 위해서, 당신은 다음의 문법을 사용할 수 있을 것입니다.

+ +
var a = 5;
+var b = 10;
+console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
+// "Fifteen is 15 and
+// not 20."
+ +

template literals을 이용하면, 이를 더욱 읽기 쉽도록 다음과 같은 문법 설탕(syntactic sugar) 을 활용할 수 있습니다.

+ +
var a = 5;
+var b = 10;
+console.log(`Fifteen is ${a + b} and
+not ${2 * a + b}.`);
+// "Fifteen is 15 and
+// not 20."
+ + + +

Nesting templates

+ +

특정한 경우 템플릿을 중첩하는 것이 구성 가능한 문자열을 읽는 읽기 가장 쉬운 방법입니다. 백 스페이스 템플릿 내에서 템플릿 내의 자리 표시자${}에 내부 백틱을 사용하는 것이 쉽습니다. 예를 들어, 조건 a가 참이면:이 템플릿을 문자 그대로 반환합니다.

+ +

In ES5:

+ +
var classes = 'header'
+classes += (isLargeScreen() ?
+   '' : item.isCollapsed ?
+     ' icon-expander' : ' icon-collapser');
+ +

ES2015에서 중첩(nesting)없이 템플릿 리터럴 사용한 경우:

+ +
const classes = `header ${ isLargeScreen() ? '' :
+    (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`;
+ +

ES2015에서 중첩된(nested) 템플릿 리터럴을 사용한 경우:

+ +
const classes = `header ${ isLargeScreen() ? '' :
+ `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;
+ + + +

Tagged templates

+ +

template literals 의 더욱 발전된 한 형태는 tagged templates 입니다. 태그를 사용하면 템플릿 리터럴을 함수로 파싱 할 수 있습니다. 태그 함수의 첫 번째 인수는 문자열 값의 배열을 포함합니다. 나머지 인수는 표현식과 관련됩니다. 결국 함수는 조작 된 문자열을 반환 할 수 있습니다 (또는 다음 예제에서 설명하는 것과 완전히 다른 결과를 반환 할 수 있습니다). function 이름은 원하는 어떤 것이든 가능합니다.

+ +
var person = 'Mike';
+var age = 28;
+
+function myTag(strings, personExp, ageExp) {
+
+  var str0 = strings[0]; // "that "
+  var str1 = strings[1]; // " is a "
+
+  // 사실 이 예제의 string에서 표현식이 두 개 삽입되었으므로
+  // ${age} 뒤에는 ''인 string이 존재하여
+  // 기술적으로 strings 배열의 크기는 3이 됩니다.
+  // 하지만 빈 string이므로 무시하겠습니다.
+  // var str2 = strings[2];
+
+  var ageStr;
+  if (ageExp > 99){
+    ageStr = 'centenarian';
+  } else {
+    ageStr = 'youngster';
+  }
+
+  // 심지어 이 함수내에서도 template literal을 반환할 수 있습니다.
+  return str0 + personExp + str1 + ageStr;
+
+}
+
+var output = myTag`that ${ person } is a ${ age }`;
+
+console.log(output);
+// that Mike is a youngster
+ +

다음 예시에서 보여지듯이, Tag function 들은 string 을 반환할 필요는 없습니다.

+ +
function template(strings, ...keys) {
+  return (function(...values) {
+    var dict = values[values.length - 1] || {};
+    var result = [strings[0]];
+    keys.forEach(function(key, i) {
+      var value = Number.isInteger(key) ? values[key] : dict[key];
+      result.push(value, strings[i + 1]);
+    });
+    return result.join('');
+  });
+}
+
+var t1Closure = template`${0}${1}${0}!`;
+t1Closure('Y', 'A');  // "YAY!"
+var t2Closure = template`${0} ${'foo'}!`;
+t2Closure('Hello', {foo: 'World'});  // "Hello World!"
+
+ +

Raw strings

+ +

태그 지정된 템플릿의 첫 번째 함수 인수에서 사용할 수있는 특별한 raw property을 사용하면  escape sequences 처리하지 않고 원시 문자열을 입력 한대로 액세스 할 수 있습니다.

+ +
function tag(strings) {
+  console.log(strings.raw[0]);
+}
+
+tag`string text line 1 \n string text line 2`;
+// logs "string text line 1 \n string text line 2" ,
+// including the two characters '\' and 'n'
+ +

추가로, default template function 과 string 병합으로 생성될 것 같은 raw string 을 생성하기 위한 {{jsxref("String.raw()")}} method가 존재합니다.

+ +
var str = String.raw`Hi\n${2+3}!`;
+// "Hi\n5!"
+
+str.length;
+// 6
+
+str.split('').join(',');
+// "H,i,\,n,5,!"
+ + + +

Tagged templates and escape sequences

+ +

ES2016 behavior

+ +

ECMAScript 2016에서 tagged templates은 다음 escape sequences의 규칙을 따릅니다.

+ + + +

이는 다음과 같은 tagged template이 문제가 된다는 것을 의미하는데, ECMAScript문법에 따라, parser는 유효한 유니 코드 탈출 시퀀스가 있는지 확인하지만 형식이 잘못되었기 때문에 오류가 발생합니다.

+ +
latex`\unicode`
+// Throws in older ECMAScript versions (ES2016 and earlier)
+// SyntaxError: malformed Unicode character escape sequence
+ +

ES2018 revision of illegal escape sequences

+ +

Tagged templates은 다른 escapes sequences가 일반적으로 사용되는 언어 (예 : DSLs 또는 LaTeX)의 임베딩을 허용해야합니다. ECMAScript proposal Template Literal Revision (4 단계, ECMAScript 2018 표준에 통합됨)은 tagged templates에서 ECMAScript escape sequences의 구문 제한을 제거합니다.

+ +

그러나 illegal escape sequences는 여전히 "cooked"라고 표현되어야합니다. "cooked"배열의 {{jsxref ( "undefined")}} 요소로 나타납니다 :

+ +
function latex(str) {
+ return { "cooked": str[0], "raw": str.raw[0] }
+}
+
+latex`\unicode`
+
+// { cooked: undefined, raw: "\\unicode" }
+ +

escape sequence 제한은 tagged templates에만 적용되며 untagged template literals에는 적용되지 않습니다.

+ +
+

let bad = `bad escape sequence: \unicode`;

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-template-literals', 'Template Literals')}}{{Spec2('ES2015')}}Initial definition. Defined in several section of the specification: Template LiteralsTagged Templates
{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}{{Spec2('ESDraft')}}Defined in several section of the specification: Template LiteralsTagged Templates
Template Literal RevisionStage 4 draftDrops escape sequence restriction from tagged templates
+ +

Browser compatibility

+ + + +

{{Compat("javascript.grammar.template_literals")}}

+ +

See also

+ + diff --git a/files/ko/web/javascript/reference/trailing_commas/index.html b/files/ko/web/javascript/reference/trailing_commas/index.html new file mode 100644 index 0000000000..aeaded7640 --- /dev/null +++ b/files/ko/web/javascript/reference/trailing_commas/index.html @@ -0,0 +1,185 @@ +--- +title: Trailing commas +slug: Web/JavaScript/Reference/Trailing_commas +tags: + - Comma + - ECMAScript + - ECMAScript2017 + - ECMAScript5 + - JavaScript + - Language feature + - Syntax + - Trailing comma + - 구문 + - 자바스크립트 + - 콤마 + - 트레일링 콤마 +translation_of: Web/JavaScript/Reference/Trailing_commas +--- +
{{JsSidebar("More")}}
+ +

Trailing commas ("final commas"라고도 불립니다)는 새로운 엘리먼트나 매개변수, 속성을 JavaScript 코드에 추가할 때 유용합니다. 새로운 속성을 추가할 때, 마지막 줄에 trailing comma가 있다면 그 줄을 수정 없이 그대로 복사해 쓸 수 있습니다. 이외에도 버전 관리 이력이 간단해지고 코드 편집이 더 편해진다는 장점이 있습니다.

+ +

JavaScript는 초기부터 배열 리터럴에 trailing comma를 허용했으며, ECMAScript 5부터는 객체 리터럴, ECMAScript 2017부터는 함수의 매개변수에도 허용하기 시작했습니다.

+ +

그러나 {{Glossary("JSON")}}에서는 trailing comma를 허용하지 않습니다.

+ +

리터럴에서의 trailing comma

+ +

배열

+ +

JavaScript는 배열에 나타나는 trailing comma를 무시합니다.

+ +
var arr = [
+  1,
+  2,
+  3,
+];
+
+arr; // [1, 2, 3]
+arr.length; // 3
+ +

trailing comma가 여러 개 있을 경우 빈 슬롯("구멍")이 생깁니다. 구멍이 있는 배열을 성기다sparse고 합니다(조밀한dense 배열에는 구멍이 없습니다). {{jsxref("Array.prototype.forEach()")}}나 {{jsxref("Array.prototype.map()")}}을 이용해 배열을 순회할 때는 빈 슬롯을 무시합니다.

+ +
var arr = [1, 2, 3,,,];
+arr.length; // 5
+
+ +

객체

+ +

ECMAScript 5부터는 객체 리터럴에도 trailing comma를 사용할 수 있습니다.

+ +
var object = {
+  foo: "bar",
+  baz: "qwerty",
+  age: 42,
+};
+ +

함수에서의 trailing comma

+ +

ECMAScript 2017에서는 함수의 매개변수 목록에 trailing comma를 허용합니다.

+ +

매개변수 정의

+ +

아래의 두 함수 정의는 모두 유효하며, 서로 같습니다. Trailing comma는 함수 정의의 length 속성이나 arguments 객체에 영향을 주지 않습니다.

+ +
function f(p) {}
+function f(p,) {}
+
+(p) => {};
+(p,) => {};
+
+ +

Trailing comma는 클래스나 객체의 메소드 정의에도 사용할 수 있습니다.

+ +
class C {
+  one(a,) {},
+  two(a, b,) {},
+}
+
+var obj = {
+  one(a,) {},
+  two(a, b,) {},
+};
+
+ +

함수 호출

+ +

아래의 두 함수 호출은 모두 유효하며, 서로 같습니다.

+ +
f(p);
+f(p,);
+
+Math.max(10, 20);
+Math.max(10, 20,);
+
+ +

잘못된 trailing comma

+ +

함수의 매개변수 정의나 호출에 쉼표만 있을 경우 {{Jsxref("SyntaxError")}}가 발생합니다. 또한, rest 매개변수를 사용할 때는 trailing comma를 사용할 수 없습니다.

+ +
function f(,) {} // SyntaxError: missing formal parameter
+(,) => {};       // SyntaxError: expected expression, got ','
+f(,)             // SyntaxError: expected expression, got ','
+
+function f(...p,) {} // SyntaxError: parameter after rest parameter
+(...p,) => {}        // SyntaxError: expected closing parenthesis, got ','
+
+ +

구조 분해 할당에서의 trailing comma

+ +

구조 분해 할당의 좌변에도 trailing comma를 사용할 수 있습니다.

+ +
// Trailing comma가 있는 배열 구조 분해
+[a, b,] = [1, 2];
+
+// Trailing comma가 있는 객체 구조 분해
+var o = {
+  p: 42,
+  q: true,
+};
+var {p, q,} = o;
+
+ +

Rest 원소가 있을 경우 역시 {{jsxref("SyntaxError")}}가 발생합니다.

+ +
var [a, ...b,] = [1, 2, 3];
+// SyntaxError: rest element may not have a trailing comma
+ +

JSON에서의 trailing comma

+ +

객체 안에서의 trailing comma는 ECMAScript 5에 와서야 추가되었습니다. JSON은 ES5 이전의 JavaScript 문법을 기초로 하므로 JSON에서는 trailing comma를 사용할 수 없습니다.

+ +

아래의 두 줄 모두 SyntaxError를 발생합니다.

+ +
JSON.parse('[1, 2, 3, 4, ]');
+JSON.parse('{"foo" : 1, }');
+// SyntaxError JSON.parse: unexpected character
+// at line 1 column 14 of the JSON data
+
+ +

JSON을 올바르게 파싱하려면 trailing comma를 제거해야 합니다.

+ +
JSON.parse('[1, 2, 3, 4 ]');
+JSON.parse('{"foo" : 1 }');
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + +
명세상태비고
{{SpecName('ES5.1')}}{{Spec2('ES5.1')}}객체 리터럴 trailing comma 추가
{{SpecName('ES6')}}{{Spec2('ES6')}}변화 없음
{{SpecName('ESDraft')}}{{Spec2('ESDraft')}}ES2017에서 함수 trailing comma 추가
+ +

브라우저 호환성

+ +
+ + +

{{Compat("javascript.grammar.trailing_commas")}}

+
+ +

같이 보기

+ + diff --git a/files/ko/web/javascript/typed_arrays/index.html b/files/ko/web/javascript/typed_arrays/index.html new file mode 100644 index 0000000000..814ae7c885 --- /dev/null +++ b/files/ko/web/javascript/typed_arrays/index.html @@ -0,0 +1,222 @@ +--- +title: JavaScript 형식화 배열 +slug: Web/JavaScript/Typed_arrays +tags: + - Guide + - JavaScript +translation_of: Web/JavaScript/Typed_arrays +--- +
{{JsSidebar("Advanced")}}
+ +

JavaScript 형식화 배열(typed array)은 배열같은 객체이고 원시(raw) 이진 데이터에 액세스하기 위한 메커니즘을 제공합니다. 이미 아시다시피, {{jsxref("Array")}} 객체는 동적으로 늘었다 줄고 어떤 JavaScript 값이든 가질 수 있습니다. JavaScript 엔진은 이러한 배열이 빨라지도록 최적화를 수행합니다. 그러나, audio 및 video 조작과 같은 기능 추가, WebSocket을 사용한 원시 데이터에 액세스 등 웹 어플리케이션이 점점 더 강력해짐에 따라, 빠르고 쉽게 형식화 배열의 원시 이진 데이터를 조작할 수 있게 하는 것이 JavaScript 코드에 도움이 될 때가 있음이 분명해 졌습니다.

+ +

그러나, 형식화 배열은 보통 배열과 혼동되지는 않습니다, 형식화 배열에 {{jsxref("Array.isArray()")}} 호출은 false를 반환하기에. 게다가, 보통 배열에 이용할 수 있는 모든 메서드가 형식화 배열에 의해 지원되지는 않습니다(가령 push 및 pop).

+ +

버퍼 및 뷰: 형식화 배열 구조

+ +

최대 유연성 및 효율을 달성하기 위해, JavaScript 형식화 배열은 구현을 버퍼로 나눕니다. 버퍼 ({{jsxref("ArrayBuffer")}} 객체에 의해 구현됨)는 데이터 부분(chunk, 덩어리)을 나타내는 객체입니다; 이야기 할 형식이 없으며, 그 콘텐츠에 액세스하기 위한 메커니즘을 제공하지 않습니다. 버퍼에 포함된 메모리에 액세스하기 위해, 뷰를 사용할 필요가 있습니다. 뷰는 문맥(context, 즉 데이터 형, 시작 오프셋 및 요소 수)을 제공해 데이터를 실제 형식화 배열로 바꿉니다.

+ +

Typed arrays in an ArrayBuffer

+ +

ArrayBuffer

+ +

{{jsxref("ArrayBuffer")}}는 일반 고정 길이 이진 데이터 버퍼를 나타내는 데 사용되는 데이터 형입니다. ArrayBuffer 콘텐츠를 직접 조작할 수는 없습니다; 대신에, 형식화 배열 뷰 또는 특정 형식으로 버퍼를 나타내는 {{jsxref("DataView")}}를 만들어 버퍼의 콘텐츠를 읽고 쓰기 위해 사용합니다.

+ +

형식화 배열 뷰

+ +

형식화 배열 뷰는 자체 설명형 이름이 있으며 Int8, Uint32, Float64 등과 같은 모든 일반 숫자 형을 위한 뷰를 제공합니다. 특별한 형식화 배열 뷰가 하나 있습니다, Uint8ClampedArray. 값은 0에서 255 사이로 단속(제한)합니다. 예를 들어, 이는 Canvas 데이터 처리에 유용합니다.

+ +

{{page("/ko/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_객체")}}

+ +

DataView

+ +

{{jsxref("DataView")}}는 버퍼에 임의 데이터를 읽고 쓰기 위해 getter/setter API를 제공하는 저레벨 인터페이스입니다. 예를 들어, 서로 다른 유형의 데이터를 처리하는 경우 유용합니다. 형식화 배열 뷰는 플랫폼의 본디(native) 바이트 순서(byte-order, {{Glossary("Endianness")}} 참조)에 속합니다. DataView로 바이트 순서를 제어할 수 있습니다. 기본으로 big-endian이고 getter/setter 메서드로 little-endian으로 설정될 수 있습니다.

+ +

형식화 배열을 사용하는 웹 API

+ +
+
FileReader.prototype.readAsArrayBuffer()
+
FileReader.prototype.readAsArrayBuffer() 메서드는 지정된 Blob 또는 File의 콘텐츠를 읽기 시작합니다.
+
XMLHttpRequest.prototype.send()
+
XMLHttpRequest 인스턴스의 send() 메서드는 이제 형식화 배열 및 인수로 {{jsxref("ArrayBuffer")}} 객체를 지원합니다.
+
ImageData.data
+
0에서 255까지 정수값으로 RGBA 순 데이터를 포함하는 1차원 배열을 나타내는 {{jsxref("Uint8ClampedArray")}}입니다.
+
+ +

+ +

버퍼와 뷰 사용하기

+ +

우선, 여기서 16바이트 고정 길이로 버퍼를 만들어야 합니다:

+ +
var buffer = new ArrayBuffer(16);
+
+ +

이 시점에서, 바이트가 모두 0으로 미리 초기화된 메모리 덩어리가 있습니다. 그렇지만 이거 가지고 할 수 있는 게 많지 않습니다. 실제 16바이트 길이인지 확인할 수 있고 대략 그런 정도입니다:

+ +
if (buffer.byteLength === 16) {
+  console.log("Yes, it's 16 bytes.");
+} else {
+  console.log("Oh no, it's the wrong size!");
+}
+
+ +

정말 이 버퍼로 작업할 수 있기 전에, 뷰를 만들어야 합니다. 32비트 부호있는 정수 배열로 버퍼의 데이터를 다루는 뷰를 만듭시다:

+ +
var int32View = new Int32Array(buffer);
+
+ +

이제 보통 배열처럼 배열 내 필드에 액세스할 수 있습니다:

+ +
for (var i = 0; i < int32View.length; i++) {
+  int32View[i] = i * 2;
+}
+
+ +

이는 배열의 4항목을 값 0, 2, 4 및 6으로 채웁니다 (4항목이 각각 4바이트에 총 16바이트가 됩니다).

+ +

같은 데이터에 여러 뷰

+ +

상황은 당신이 같은 데이터에 여러 뷰를 만들 수 있음을 고려하는 경우 정말 흥미로워지기 시작합니다. 예를 들어, 위 코드가 주어지면 다음과 같이 계속할 수 있습니다:

+ +
var int16View = new Int16Array(buffer);
+
+for (var i = 0; i < int16View.length; i++) {
+  console.log("Entry " + i + ": " + int16View[i]);
+}
+
+ +

여기서 우리는 기존 32비트 뷰와 같은 버퍼를 공유하는 16비트 정수 뷰를 만들고 16비트 정수로 버퍼 내 모든 값을 출력합니다. 이제 우리는 출력 0, 0, 2, 0, 4, 0, 6, 0을 얻습니다.

+ +

그렇지만 한 단계 더 앞으로 갈 수 있습니다. 다음을 생각해 보세요:

+ +
int16View[0] = 32;
+console.log("Entry 0 in the 32-bit array is now " + int32View[0]);
+
+ +

이로부터 출력은 "Entry 0 in the 32-bit array is now 32"입니다. 즉, 두 배열은 확실히 그저 같은 데이터 버퍼 상의 뷰입니다, 버퍼를 서로 다른 형식으로 다루는. 모든 뷰 유형으로 이를 할 수 있습니다.

+ +

복잡한 데이터 구조(체)와 작업하기

+ +

단일 버퍼를 서로 다른 형인 여러 뷰(버퍼 내 서로 다른 오프셋에서 시작하는)와 결합시켜, 여러 데이터 형을 포함하는 데이터 객체와 상호 작용할 수 있습니다. 예를 들어, 이는 WebGL, 데이터 파일 또는 js-ctypes를 쓰는 동안 사용해야 하는 C 구조체에서 복잡한 데이터 구조와 상호 작용케 합니다.

+ +

이 C 구조체를 생각해 보세요:

+ +
struct someStruct {
+  unsigned long id;
+  char username[16];
+  float amountDue;
+};
+ +

이 같은 형식으로 데이터를 포함하는 버퍼에 액세스할 수 있습니다:

+ +
var buffer = new ArrayBuffer(24);
+
+// ... 버퍼 내의 데이터를 읽어들임 ...
+
+var idView = new Uint32Array(buffer, 0, 1);
+var usernameView = new Uint8Array(buffer, 4, 16);
+var amountDueView = new Float32Array(buffer, 20, 1);
+ +

그런 뒤, 예를 들어 amountDueView[0]로 지불할 요금(amount due)을 액세스할 수 있습니다.

+ +
주의: C 구조체에서 데이터 구조 정렬은 플랫폼에 의존합니다. 이러한 패딩(padding) 차이에 대해 조심하고 고려하세요.
+ +

보통 배열로 변환

+ +

형식화 배열을 처리한 뒤, 때때로 {{jsxref("Array")}} 프로토타입의 도움을 받기 위해 보통 배열로 다시 변환하는 게 유용합니다. 이는 {{jsxref("Array.from")}} 또는 Array.from이 지원되지 않는 경우 다음 코드를 사용하여 수행할 수 있습니다.

+ +
var typedArray = new Uint8Array([1, 2, 3, 4]),
+    normalArray = Array.prototype.slice.call(typedArray);
+normalArray.length === 4;
+normalArray.constructor === Array;
+
+ +

스펙

+ + + + + + + + + + + + + + + + + + + + + + + + +
스펙상태설명
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}ECMAScript 6로 대체됨.
{{SpecName('ES6', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ES6')}}ECMA 표준에서 초기 정의.
{{SpecName('ESDraft', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ESDraft')}} 
+ +

브라우저 호환성

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7.0{{ CompatGeckoDesktop("2") }}1011.65.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.0{{CompatVersionUnknown}}{{ CompatGeckoMobile("2") }}1011.64.2
+
+ +

참조

+ + diff --git "a/files/ko/web/javascript/\354\211\230/index.html" "b/files/ko/web/javascript/\354\211\230/index.html" new file mode 100644 index 0000000000..718fa8bdc2 --- /dev/null +++ "b/files/ko/web/javascript/\354\211\230/index.html" @@ -0,0 +1,40 @@ +--- +title: JavaScript 쉘 +slug: Web/JavaScript/쉘 +translation_of: Web/JavaScript/Shells +--- +
{{JsSidebar}}
+ +

여러분은 JavaScript 쉘을 통해 웹페이지 새로고침하지 않고 빠르게 JavaScript 의 코드를 테스트해볼 수 있습니다. 코드를 개발하고 디버깅하는데 매우 유용한 도구입니다.

+ +

독립적으로 사용할 수 있는 JavaScript 쉘

+ +

아래의 Javascript 쉘은 펄과 파이썬과 같이 독립적인 환경을 제공합니다.

+ + + +

JavaScript 쉘 리스트

+ +

아래는 Mozilla에서 사용할 수 있는 JavaScript Shell입니다.

+ + diff --git "a/files/ko/web/javascript/\354\213\234\354\236\221\355\225\230\352\270\260/index.html" "b/files/ko/web/javascript/\354\213\234\354\236\221\355\225\230\352\270\260/index.html" new file mode 100644 index 0000000000..cfe47e1ec5 --- /dev/null +++ "b/files/ko/web/javascript/\354\213\234\354\236\221\355\225\230\352\270\260/index.html" @@ -0,0 +1,327 @@ +--- +title: 시작하기 (자바스크립트 튜토리얼) +slug: Web/JavaScript/시작하기 +translation_of: Learn/Getting_started_with_the_web/JavaScript_basics +--- +

왜 자바스크립트인가?

+

자바스크립트는 종종 오해할 수 있는 강력하고 복잡한 컴퓨터 언어이다. 사용자가 쉽게 데이터를 입력하고 결과를 볼 수 있게 어플리케이션을 빠르게 개발 할 수 있다.

+

 웹브라우저를 중심으로 또한 ECMAScript로 알려진 자바스크립트의 주요 장점은 이와 같이 브라우저를 지원하는 모든 플랫폼에 동일한 결과를 만들 수 있다. 이 페이지의 예제는 구글 맵스처럼 맥 OS와 윈도우, 리눅스에서 실행한다. 수많은 자바스크립트 라이브러리의 최근 성장과 함께 AJax 어플리케이션을 개발하거나 이벤트 처리하기, 에니메이션 만들기, DOM 엘리먼트 선택하기, 도큐먼트 탐색하기가 이제 더욱 쉬워졌다. 다양한 소유권의 이익에 의해 추진된 다른 기술의 과대 광고와는 달리 자바스크립트는 모두 무료이면서 보편적으로 채택된 클라이언트 사이드 프로그래밍 언어이면서 정말이지 유일한 크로스 플래폼이다.

+

당신이 이미 알아야 하는 것

+

자바스크립트는 프로그래밍을 같이 시작하기 위해 매우 쉬운 언어이다. 시작하기 위해서  당신이 필요한 모든 것은 텍스트 에디터와  웹브라우저이다.  

+

이 문서의 범위를 벗어나는 자바스크립트와 함께 개발되고 통합 할 수 있는 다른 기술은 많이 있다. 첫날부터 구글맵스과 같이 완전한 어플리케이션을 만들 것이라고 기대하지 마라!

+

시작하기

+

자바스크립트로 시작하기는 매우 쉽다. 당신은 복잡한 개발 프로그램 설치가 필요가 없다. 컴파일러를 사용하거나 프로그램 만들기, 쉘을 어떻게 사용하는지 알 필요가 없다. 자바스크립트는 당신의 웹 브라우저에서 해석 된다. 당신이 해야 할 모든 일은 텍스트 파일에 당신의 프로그램을 저장하고 당신의 웹브라우저를 연다. 단지 그 것이다!

+

자바스크립트는 입문 컴퓨터 언어로서 최고의 프로그래밍 언어이다. 새로운 학생에게  즉시 피드백 할 수 있게 하고 그들이 아마도 그들의 실생활에 유용한 것을 발견할 수 있는 도구들에 관한 것을 그들에게 가르친다. 이것은 전용 소프트웨어 개발자를 위해 정말 유용한 C, C++, JAVA 와는 뚜렷하게  대조적이다. 

+

브라우저 호환성 이슈들

+

다른 브라우저에서 사용이 가능한 어떤 기능 중에는 차이가 있다. Mozilla, Chrome, Microsoft IE, Apple Safari, Opera에서 가동하는 것에 따라 변동될 수 있다. 이런 변동사항을 문서화 하려고 한다.  사용 가능한 다양한 크로스 플랫폼 자바스크립트 API 사용하여 이런 이슈들을 완하시킬 수 있다. 이런 API는 공통 기능으로 제공하고 이 브라우저의  변동된 것을 숨긴다. 

+

예제를 시도하는 방법

+

아래의 예제들은  몇가지 샘플 코드를 가지고 있다. 이 예제들을 시도하는 방법은 여러가지가 있다. 만약 당신이 이미 당신의 웹사이트를 가지고 있다면 당신은 당신의 웹사이트에 새로운 웹 페이지로써 이 예제들을 저장할 수 있어야 한다.

+

만약 당신이 당신의 웹사이트를 가지고 있지 않다면 당신의 컴퓨터에 파일로써 이 예제들을 저장할 수 있고 당신이 현재 사용하고 있는 웹브라우저를 통해 예제들을 열 수 있다. 자바스크립트는 이런 이유로 시작하려는 프로그래머가 사용하기 매운 쉬운 언어이다. 당신은 컴파일러 또는 개발 환경이 필요하지 않다. 그리고 당신과 당신의 브라우저가 시작하기 위해서 필요한 모든 것이다!

+

예제 : 마우스 클릭 잡기

+

이벤트 핸들링(이벤트 타입들, 핸들러 등록, 전파 등)의 특성은 이 간단한 예제들을 완전히 적용하기에는 너무 광범위하다. 그런데 이 예제는 자바스크립트 이벤트 시스템에 대한 조금의 탐구도 없이 마우스 클릭을 잡기를 설명할 수 없다. 이 예제는 자바스크립트 이벤트에 관해 전체 자세한 내용을 가볍게 스쳐 지나 갈 것이고 만약 당신이 여기 설명된 기본 기능의 범위를 넘어서고 싶다면 자바스크립트 이벤트 시스템에 관해 더 자세히 읽어야 함을 명심하라.

+

'마우스'이벤트들은 사용자 동작에 반응한 웹브라우저에 의해 발생된 전체 이벤트의  집합이다.다음은 사용자의 마우스 동작에 대한 응답으로 방출되는 이벤트의 목록이다.

+ +

인라인 이벤트 핸들러, HTML의 최신버전에서 주의할 것은 다시 말하면 하나가 태그 애트리뷰트들로써 추가 되었다는 것은 모두 소문자 이고 스크립트의 이벤트 핸들러가 항상 모든 소문자이어야 하는 것을 예상된다.

+

이벤트 핸들러를 등록하려는 이러한 이벤트들을 캡처하기 위해 가장 간단한 방법은 HTML을 사용하여 당신의 엘리먼트의 애트리뷰트들로서 개별적인 이벤트들을 지정하는 것이다.

+

예제:

+
  <span onclick="alert('Hello World!');">Click Here</span>
+

당신이 실행하기 원하는 자바스크립트 코드를 애트리뷰트 값으로서 그때마다 처리할 수 있다. 또는 당신은 HTML 페이지안에 <script> 블록에 정의되어진 함수를 호출 할 수 있다 :

+
<script>
+  function clickHandler() {
+     alert("Hello, World!");
+  }
+</script>
+<span onclick="clickHandler();">Click Here</span>
+

또한 발생된 이벤트 객체는 캡처하거나 참조할 수 있으며 객체가 이벤트를 받거나 이벤트 타입 그리고 마우스가 클릭됐을 때 그러한 이벤트에 관한 특성을 접근하는 무언가 개발하는 것을  제공할 수 있다. 인라인 예제를 다시 사용 하라:

+
<script>
+  function clickHandler(event) {
+    var eType = event.type;
+    /* 다음은 호환성을 위한 것이다. */
+    /* Moz는 이벤트 객체의 target 프로퍼티로 채운다. */
+    /* IE는 srcElement 프로퍼티로 채운다.*/
+    var eTarget = event.target || event.srcElement;
+
+    alert( "Captured Event (type=" + eType + ", target=" + eTarget );
+  }
+</script>
+<span onclick="clickHandler(event);">Click Here</span>
+

당신의 HTML안에 이벤트를 수신 등록 이외에 당신은 당신의 자바스크립트에 의해 생성된 어떠한 HTML엘리먼트 객체의 똑같은 이름으로 애트리뷰트들을 마찬가지로 설정할 수 있다. 아래의 예는 span 객체를 인스터트화하고 페이지의 body에  추가하고 mouse-over, mouse-out, mouse-down, mouse-up 이벤트들을 수신하기위해 span 객체를 등록한다. 

+
<body></body>
+<script>
+  function mouseeventHandler(event) {
+    /*다음은 호환성을 위한 것이다. */
+    /* IE는 기본적으로 이벤트 객체를 전달하지 않는다. */
+    if (!event) event = window.event;
+
+    /* 미리 이벤트 타입과 타켓 얻기 */
+    var eType = event.type;
+    var eTarget = event.target || event.srcElement;
+    alert(eType +' event on element with id: '+ eTarget.id);
+  }
+
+ function onloadHandler() {
+   /*  페이지의 body 엘리먼트를 참조하여 얻기 */
+   var body = document.body;
+   /* 클릭되기 위한 span 엘리먼트 생성하기 */
+   var span = document.createElement('span');
+   span.id = 'ExampleSpan';
+   span.appendChild(document.createTextNode ('Click Here!'));
+
+   /* 특정 마우스 이벤트를 받기 위해 spna 객체 등록하기 - 이벤트들의 소문자에 유의하라 그러나 당신이 그것을 치환하기 위한 이름의 선택은 자유다.
+   */
+   span.onmousedown = mouseeventHandler;
+   span.onmouseup = mouseeventHandler;
+   span.onmouseover = mouseeventHandler;
+   span.onmouseout = mouseeventHandler;
+
+   /* 페이지에 span 보여주기 */
+   body.appendChild(span);
+}
+
+window.onload = onloadHandler; // 우리가 핸들러를 치환한 이후에는 우리는 함수 이름 뒤에 ()을 붙여서는 안된다.
+</script>
+

예제: 키보드 이벤트 잡기

+

위의 예제인 "마우스 이벤트 잡기"와 유사하게 키보드 이벤트 잡기는 자바스크립트 이벤트 시스템 탐험에 의존한다. 키보드 이벤트들은 어떤 키든 키보드에서 사용될 때마다 발생한다.

+

키보드 동작에 반응하여 방출 가능한 키보드 이벤트 목록들은 마으스로 사용 가능한 것보다 상당히 작다. 

+ +

keypress 이벤트는 키를 눌렀을 때의 Unicode값이 keycode나 charCode 프로퍼티에 둘다 저장되어 있다. 만약 키가  문자로 생성되어 눌러졌을때 (예를 들어 'a') charCode는 문자의 경우를 반영하여 문자의 코드를 설정한다.(즉, charCode은 Shift 키를 누르고 있는지 여부를 고려한다)그렇지 않으면, 누른 키의 코드가 keyCode에 저장된다.

+

키보드 이벤트들을 캡쳐하기 위한 가장 간단한 방법은 당신의 엘리먼트를 애트리뷰트들로써 개별적인 이벤트들을 지정한 HTML안에 이벤트 핸들러들을 다시 저장하는 것이다.

+

예:

+
  <input type="text" onkeypress="alert ('Hello World!');">
+
+

마우스 이벤트들과 마찬가지로 당신이 실행하기 원하는 자바스크립트 코드는 그때마다 처리할 수 있다. 또는 당신은 HTML 페이지안에 <script> 블록에 정의되어진 함수를 호출 할 수 있다 :

+
<script>
+  function keypressHandler() {
+    alert ("Hello, World!");
+  }
+</script>
+
+<input onkeypress="keypressHandler();" />
+
+

타겟을 참조하거나 이벤트를 캡쳐 하는 것은 (즉, 눌러진 실제 키) 마우스 이벤트를 비슷한 방법으로 이룰 수 있다.

+

 <script type="text/javascript">

+
  function keypressHandler(evt) {
+      var eType = evt.type; // 이벤트 타입으로써 "keypress"를 반환할 것이다.
+
+   /*  여기에 우리는 which 나 다른 keyCode로 반환되는 모질라 기반으로 된 브라우저를 크로스 브라우저 방법으로 사용할 필요가 있다. 조건 연산자 또는 삼항식이 좋은 방법이다.
+      var keyCode = evt.which?evt.which:evt.keyCode;
+      var eCode = 'keyCode is ' + keyCode;
+      var eChar = 'charCode is ' + .fromCharCode(keyCode); // 또는 evt.charCode
+      alert ("Captured Event (type=" + eType + ", key Unicode value=" + eCode + ", ASCII value=" + eChar + ")");
+   }
+</script>
+<input onkeypress="keypressHandler(event);" />
+

페이지로 부터 어떤 키 이벤트를  캡처하기 위해서는 문서 레벨에서 이벤트를 등록하거나 함수안에서 처리하여 마칠 수 있다. 

+
<script>
+  document.onkeypress = keypressHandler;
+  document.onkeydown = keypressHandler;
+  document.onkeyup = keypressHandler;
+</script>
+

여기에 키 이벤트 처리하기 보여주는 완벽한 예제가 있다.

+
<!DOCTYPE html>
+<html>
+<head>
+  <script>
+    var metaChar = false;
+    var exampleKey = 16;
+    function keyEvent(event) {
+      var key = event.keyCode || event.which; // alternative to ternary - if there is no keyCode, use which
+      var keychar = String.fromCharCode(key);
+      if (key == exampleKey) {
+        metaChar = true;
+      }
+      if (key != exampleKey) {
+         if (metaChar) {
+            alert("Combination of metaKey + " + keychar)
+            metaChar = false;
+         } else {
+           alert("Key pressed " + key);
+         }
+      }
+    }
+    function metaKeyUp(event) {
+      var key = event.keyCode || event.which;
+      if (key == exampleKey) { metaChar = false; }
+    }
+  </script>
+</head>
+<body onkeydown="keyEvent(event)" onkeyup="metaKeyUp(event)">
+    Try pressing any key!
+</body>
+</html>
+

브라우저 버그들과 이상한 점

+

키 이벤트를 통해서 사용 가능하게 만들어진 두개의 프로퍼티들은 keycode와 charCode이다. 단순한 용어로 keyCode는 사용자에 의해 눌러진 실제 키보드 키를 의미하는데 반하여 charCode는 키의 ASCII 값을 반환한다. 이 두 값들은 반드시 동일하지 않을 수 있다. 예를 들어 소문자 'a'와 대문자 'A'는 같은 keyCode를 가지고 있다. 왜냐하면 사용자는 같은 키를 누르기 때문이다. 하지만 다른 charCode를 가지는 것은 왜냐하면 결과 문자가 다르기 때문이다.

+

charCode가 해석되는 브라우저의 방법은 일관되게 적용되는 방법이 아니다. 예를 들어  Internet Explorer 와 Opera는 charCode를 지원하지 않는다. 그런데 그들은 keyCode안에 문자 정보를 준다. onkeypress만 아니라 onkeydown 와 onkeyup의 keyCode가  키 정보를 가지고 있다. Firefox 는 "which",  문자를 구별하기 위해 다른 단어를 사용한다. 

+

더 나아가 키 이벤트들을 다루는 것에 관해서는  Keyboard Events에 대한 Mozilla 문서를 참조하시오.

+

{{ draft() }}

+

예제: 이미지 주변에 드래그하기

+

다음 예제는 페이지 근처의 firefox의 이미지를 이동할 수 있다.

+
<!DOCTYPE html>
+<html>
+<head>
+<style>
+img { position: absolute; }
+</style>
+
+<script>
+window.onload = function() {
+
+  movMeId = document.getElementById("ImgMov");
+  movMeId.style.top = "80px";
+  movMeId.style.left = "80px";
+
+  document.onmousedown = coordinates;
+  document.onmouseup = mouseup;
+
+  function coordinates(e) {
+    if (e == null) { e = window.event;}
+
+    // e.srcElement은 IE에서 타겟 엘리먼트로 가지고 있고 반면 e.target은 firefox에서 타겟 엘리먼트로 가지고 있다.
+// 두 프로퍼티들은 이벤트가 일어난 HTML 엘리먼트를 반환한다.
+    var sender = (typeof( window.event ) != "undefined" ) ? e.srcElement : e.target;
+
+    if (sender.id=="ImgMov") {
+      mouseover = true;
+      pleft = parseInt(movMeId.style.left);
+      ptop = parseInt(movMeId.style.top);
+      xcoor = e.clientX;
+      ycoor = e.clientY;
+      document.onmousemove = moveImage;
+      return false;
+    }
+    return false;
+  }
+
+  function moveImage(e) {
+    if (e == null) { e = window.event; }
+    movMeId.style.left = pleft+e.clientX-xcoor+"px";
+    movMeId.style.top = ptop+e.clientY-ycoor+"px";
+    return false;
+  }
+
+  function mouseup(e) {
+    document.onmousemove = null;
+  }
+}
+</script>
+</head>
+
+<body>
+  <img id="ImgMov" src="http://placehold.it/100x100&text=JS" width="64" height="64">
+  <p>Drag and drop around the image in this page.</p>
+</body>
+
+</html>
+

예제: 크기 조정하기

+
+

이미지 크기 조정하는 예제(실제 이미지가 크기가 조정되는 것이 아니고,  이미지의 랜더링만 되는 것이다.)

+
  <!DOCTYPE html>
+  <html>
+    <head>
+      <style>
+        #resizeImage {
+          margin-left: 100px;
+        }
+      </style>
+      <script>
+      window.onload = function() {
+
+        var resizeId = document.getElementById("resizeImage");
+        var resizeStartCoordsX,
+            resizeStartCoordsY,
+            resizeEndCoordsX,
+            resizeEndCoordsY;
+
+        var resizeEndCoords;
+        var resizing = false;
+
+        document.onmousedown = coordinatesMousedown;
+        document.onmouseup = coordinatesMouseup;
+
+        function coordinatesMousedown(e) {
+          if (e == null) {
+            e = window.event;
+          }
+
+          var element = (typeof( window.event ) != 'undefined' ) ? e.srcElement : e.target;
+
+          if (element.id == "resizeImage") {
+            resizing = true;
+            resizeStartCoordsX = e.clientX;
+            resizeStartCoordsY = e.clientY;
+          }
+          return false;
+        }
+
+        function coordinatesMouseup(e) {
+          if (e == null) {
+            e = window.event;
+          }
+
+          if (resizing === true) {
+            var currentImageWidth = parseInt(resizeId.width);
+            var currentImageHeight = parseInt(resizeId.height);
+
+            resizeEndCoordsX = e.clientX;
+            resizeEndCoordsY = e.clientY;
+
+            resizeId.style.height = currentImageHeight - (resizeStartCoordsY - resizeEndCoordsY) + 'px';
+            resizeId.style.width = currentImageWidth - (resizeStartCoordsX - resizeEndCoordsX) + 'px';
+
+            resizing = false;
+          }
+          return false;
+        }
+      }
+      </script>
+    </head>
+
+    <body>
+      <img id="resizeImage" src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Mozilla_Firefox_3.5_logo_256.png"
+width="64" height="64">
+      <p>Click on the image and drag for resizing.</p>
+    </body>
+
+  </html>
+
+

예제: 라인 그리기

+
<!DOCTYPE html>
+<html>
+<head>
+<script>
+function linedraw(ax,ay,bx,by)
+{
+    if(ay>by)
+    {
+        bx=ax+bx;
+        ax=bx-ax;
+        bx=bx-ax;
+        by=ay+by;
+        ay=by-ay;
+        by=by-ay;
+    }
+    var calc=Math.atan((ay-by)/(bx-ax));
+    calc=calc*180/Math.PI;
+    var length=Math.sqrt((ax-bx)*(ax-bx)+(ay-by)*(ay-by));
+    document.body.innerHTML += "<div id='line' style='height:" + length + "px;width:1px;background-color:black;position:absolute;top:" + (ay) + "px;left:" + (ax) + "px;transform:rotate(" + calc + "deg);-ms-transform:rotate(" + calc + "deg);transform-origin:0% 0%;-moz-transform:rotate(" + calc + "deg);-moz-transform-origin:0% 0%;-webkit-transform:rotate(" + calc  + "deg);-webkit-transform-origin:0% 0%;-o-transform:rotate(" + calc + "deg);-o-transform-origin:0% 0%;'></div>"
+}
+</script>
+</head>
+<body onload="linedraw(200,400,500,900);"> <!--당신의 좌표 교체하기 -->
+</body>
+</html>
+

 

diff --git "a/files/ko/web/javascript/\354\226\270\354\226\264_\353\246\254\354\206\214\354\212\244/index.html" "b/files/ko/web/javascript/\354\226\270\354\226\264_\353\246\254\354\206\214\354\212\244/index.html" new file mode 100644 index 0000000000..5743a54e24 --- /dev/null +++ "b/files/ko/web/javascript/\354\226\270\354\226\264_\353\246\254\354\206\214\354\212\244/index.html" @@ -0,0 +1,155 @@ +--- +title: 자바스크립트 언어 자료 +slug: Web/JavaScript/언어_리소스 +tags: + - Advanced + - 자바스크립트 +translation_of: Web/JavaScript/Language_Resources +--- +
{{JsSidebar}}
+ +

ECMAScript자바스크립트의 토대를 구성하는 스크립트 언어입니다. ECMAScript는 ECMA International 표준화 기구에 의해서 ECMA-262 및 ECMA-402 스펙에서 표준화되었습니다. 다음은 현재까지 승인됐거나 작업 중인 ECMAScript 표준입니다:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
이름링크출시 날짜설명
현재판
ECMA-262 10th EditionWorking draft2019ECMAScript 2019 (제 10판), 명세 작업 중
ECMA-262 9th EditionPDFHTML
+ Working draftrepository
2018ECMAScript 2018 (제 9판)
ECMA-402 5th EditionWorking draft, repository2018ECMAScript 2018 국제화 API 표준
폐기(Obsolete)/역사판
ECMA-262 (ES 1)PDFJune 1997ECMAScript 표준 원본.
ECMA-262 (ES 2)PDFAugust 1998ECMAScript 표준 제2판; 또한 ISO 표준 16262.
ECMA-262 (ES 3)PDFDecember 1999ECMAScript 표준 제3판; JavaScript 1.5에 해당.
+ errata 참조
ECMA-262 (ES 5)PDFDecember 2009ECMAScript 제5판
+ ES5 errata 및 ECMAScript 5 support in Mozilla 참조
ECMA-357PDFJune 2004ECMAScript for XML (E4X).
+ E4X errata 참조.
ECMA-357 Edition 2PDFDecember 2005ECMAScript for XML (E4X).
ECMA-262 (ES 5.1)PDF, HTMLJune 2011이 판은 국제화 표준 ISO/IEC 16262:2011 제3판과 완전히 정렬됨.
+ ES5 errata 수정 포함, 새로운 기능은 없음.
ECMA-402 1.0PDF, HTMLDecember 2012ECMAScript 국제화 API 1.0.
ECMA-262 2015 (ES 6)PDF, HTMLJune 2015ECMAScript 2015 (제6판).
ECMA-402 2.0PDFJune 2015ECMAScript 국제화 API 2.0.
ECMA-262 2016 (ES 7)HTMLJune 2016ECMAScript 2016 (제7판).
ECMA-402 3.0HTMLJune 2016ECMAScript 국제화 API 3.0. 나중(올해 6월)에 승인될.
ECMA-262 2017 (ES 8)HTMLJune 2017ECMAScript 2017 (제8판).
ECMA-402 4th EditionHTMLJune 2017ECMAScript 국제화 API 4.0.
+ +

ECMAScript의 역사에 대한 자세한 정보는 Wikipedia ECMAScript entry를 살펴보세요.

+ +

여러분은 코드네임 "Harmony"로 불리우는 ECMAScript의 다음 개정에 참여하거나 그냥 진행상황을 확인할 수도 있습니다.  또한 ECMAScript 국제화 API 스펙도 공개 위키와 ecmascript.org 에 연결된 es-discuss mailing list에서도 확인할 수 있습니다.

+ +

구현

+ + + +

관련 항목

+ + -- cgit v1.2.3-54-g00ecf