From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../aria/aria_live_regions/index.html | 259 -- files/vi/web/accessibility/aria/index.html | 136 - files/vi/web/accessibility/index.html | 76 - files/vi/web/api/audiocontext/index.html | 305 -- .../baseaudiocontext/createoscillator/index.html | 119 - files/vi/web/api/canvas_api/index.html | 129 - files/vi/web/api/childnode/index.html | 78 - files/vi/web/api/childnode/remove/index.html | 97 - files/vi/web/api/document_object_model/index.html | 387 --- .../document_object_model/introduction/index.html | 223 -- files/vi/web/api/eventsource/index.html | 127 - files/vi/web/api/eventsource/url/index.html | 59 - files/vi/web/api/fetch_api/index.html | 100 - files/vi/web/api/file/index.html | 99 - files/vi/web/api/geolocation_api/index.html | 244 -- .../api/htmlcanvaselement/getcontext/index.html | 140 - files/vi/web/api/htmlcanvaselement/index.html | 114 - files/vi/web/api/htmlelement/index.html | 268 -- files/vi/web/api/htmlformelement/index.html | 246 -- files/vi/web/api/htmlformelement/reset/index.html | 28 - .../api/htmlorforeignelement/dataset/index.html | 140 - files/vi/web/api/index.html | 34 - files/vi/web/api/navigator/geolocation/index.html | 53 - files/vi/web/api/navigator/index.html | 186 -- files/vi/web/api/navigator/sendbeacon/index.html | 105 - files/vi/web/api/node/index.html | 373 --- files/vi/web/api/node/insertbefore/index.html | 166 -- files/vi/web/api/node/parentelement/index.html | 50 - files/vi/web/api/node/parentnode/index.html | 63 - files/vi/web/api/notification/index.html | 408 --- files/vi/web/api/touch_events/index.html | 340 --- .../index.html | 61 - files/vi/web/api/url_api/index.html | 122 - files/vi/web/api/webrtc_api/index.html | 233 -- files/vi/web/api/webrtc_api/protocols/index.html | 57 - files/vi/web/api/websockets_api/index.html | 253 -- .../writing_a_websocket_server_in_java/index.html | 217 -- files/vi/web/api/window/index.html | 729 ----- files/vi/web/api/window/load_event/index.html | 125 - files/vi/web/api/window/prompt/index.html | 86 - files/vi/web/css/_colon_first-child/index.html | 126 - files/vi/web/css/_colon_focus-within/index.html | 88 - files/vi/web/css/_colon_focus/index.html | 96 - files/vi/web/css/_colon_last-of-type/index.html | 129 - files/vi/web/css/backdrop-filter/index.html | 146 - files/vi/web/css/background-color/index.html | 157 - files/vi/web/css/content/index.html | 296 -- files/vi/web/css/css_box_alignment/index.html | 245 -- files/vi/web/css/css_box_model/index.html | 115 - .../introduction_to_the_css_box_model/index.html | 78 - .../basic_concepts_of_grid_layout/index.html | 764 ----- files/vi/web/css/css_grid_layout/index.html | 243 -- files/vi/web/css/css_transitions/index.html | 121 - .../using_css_transitions/index.html | 1139 -------- files/vi/web/css/filter-function/index.html | 68 - files/vi/web/css/flex-basis/index.html | 206 -- files/vi/web/css/flex-wrap/index.html | 173 -- files/vi/web/css/flex/index.html | 347 --- files/vi/web/css/index.html | 114 - files/vi/web/css/length/index.html | 324 --- files/vi/web/css/perspective/index.html | 289 -- files/vi/web/css/transform-function/index.html | 160 - .../transform-function/perspective()/index.html | 153 - files/vi/web/css/universal_selectors/index.html | 101 - files/vi/web/css/url()/index.html | 31 - files/vi/web/events/index.html | 3078 -------------------- files/vi/web/guide/api/index.html | 23 - files/vi/web/guide/html/html5/index.html | 173 -- files/vi/web/guide/index.html | 72 - files/vi/web/html/element/center/index.html | 55 - files/vi/web/html/element/dialog/index.html | 163 -- files/vi/web/html/element/em/index.html | 122 - files/vi/web/html/element/header/index.html | 142 - files/vi/web/html/element/html/index.html | 109 - files/vi/web/html/element/index.html | 86 - files/vi/web/html/element/meta/index.html | 441 --- files/vi/web/html/element/span/index.html | 122 - files/vi/web/html/index.html | 78 - .../headers/content-security-policy/index.html | 258 -- .../content-security-policy/style-src/index.html | 167 -- files/vi/web/http/headers/index.html | 362 --- files/vi/web/http/index.html | 84 - files/vi/web/index.html | 100 - .../a_re-introduction_to_javascript/index.html | 950 ------ files/vi/web/javascript/closures/index.html | 452 --- files/vi/web/javascript/data_structures/index.html | 285 -- .../control_flow_and_error_handling/index.html | 405 --- .../guide/details_of_the_object_model/index.html | 742 ----- .../guide/expressions_and_operators/index.html | 920 ------ files/vi/web/javascript/guide/functions/index.html | 668 ----- .../javascript/guide/grammar_and_types/index.html | 711 ----- files/vi/web/javascript/guide/index.html | 124 - .../web/javascript/guide/introduction/index.html | 138 - .../guide/iterators_and_generators/index.html | 187 -- .../javascript/guide/keyed_collections/index.html | 153 - .../guide/loops_and_iteration/index.html | 348 --- .../javascript/guide/numbers_and_dates/index.html | 385 --- .../guide/regular_expressions/index.html | 666 ----- .../javascript/guide/text_formatting/index.html | 250 -- .../web/javascript/guide/using_promises/index.html | 329 --- .../guide/working_with_objects/index.html | 500 ---- files/vi/web/javascript/index.html | 110 - .../vi/web/javascript/memory_management/index.html | 183 -- .../reference/classes/constructor/index.html | 127 - .../reference/classes/extends/index.html | 108 - .../vi/web/javascript/reference/classes/index.html | 410 --- .../vi/web/javascript/reference/errors/index.html | 31 - .../missing_semicolon_before_statement/index.html | 67 - .../errors/more_arguments_needed/index.html | 45 - .../reference/errors/not_a_function/index.html | 84 - .../reference/errors/too_much_recursion/index.html | 55 - .../reference/functions/arguments/index.html | 234 -- .../reference/functions/arrow_functions/index.html | 426 --- .../functions/default_parameters/index.html | 198 -- .../web/javascript/reference/functions/index.html | 657 ----- .../global_objects/array/concat/index.html | 150 - .../global_objects/array/copywithin/index.html | 170 -- .../global_objects/array/entries/index.html | 82 - .../global_objects/array/every/index.html | 236 -- .../reference/global_objects/array/fill/index.html | 149 - .../global_objects/array/filter/index.html | 232 -- .../reference/global_objects/array/find/index.html | 226 -- .../global_objects/array/findindex/index.html | 207 -- .../reference/global_objects/array/flat/index.html | 179 -- .../global_objects/array/foreach/index.html | 303 -- .../reference/global_objects/array/from/index.html | 228 -- .../global_objects/array/includes/index.html | 135 - .../reference/global_objects/array/index.html | 433 --- .../global_objects/array/indexof/index.html | 228 -- .../global_objects/array/isarray/index.html | 130 - .../reference/global_objects/array/join/index.html | 113 - .../reference/global_objects/array/map/index.html | 316 -- .../reference/global_objects/array/of/index.html | 92 - .../reference/global_objects/array/pop/index.html | 96 - .../reference/global_objects/array/push/index.html | 136 - .../global_objects/array/reduce/index.html | 553 ---- .../global_objects/array/reduceright/index.html | 347 --- .../global_objects/array/reverse/index.html | 124 - .../global_objects/array/shift/index.html | 141 - .../global_objects/array/slice/index.html | 249 -- .../reference/global_objects/array/some/index.html | 206 -- .../reference/global_objects/array/sort/index.html | 248 -- .../global_objects/array/splice/index.html | 161 - .../global_objects/array/tolocalestring/index.html | 167 -- .../global_objects/array/tostring/index.html | 75 - .../global_objects/array/unshift/index.html | 119 - .../global_objects/array/values/index.html | 113 - .../global_objects/arraybuffer/index.html | 141 - .../reference/global_objects/date/index.html | 260 -- .../reference/global_objects/date/parse/index.html | 202 -- .../reference/global_objects/error/index.html | 241 -- .../global_objects/function/call/index.html | 148 - .../reference/global_objects/function/index.html | 150 - .../global_objects/function/tosource/index.html | 65 - .../reference/global_objects/generator/index.html | 130 - .../javascript/reference/global_objects/index.html | 203 -- .../reference/global_objects/infinity/index.html | 81 - .../reference/global_objects/isfinite/index.html | 97 - .../reference/global_objects/json/index.html | 132 - .../reference/global_objects/map/index.html | 263 -- .../reference/global_objects/math/abs/index.html | 108 - .../reference/global_objects/math/ceil/index.html | 172 -- .../reference/global_objects/math/floor/index.html | 132 - .../reference/global_objects/math/index.html | 196 -- .../reference/global_objects/math/sqrt/index.html | 101 - .../reference/global_objects/nan/index.html | 97 - .../reference/global_objects/number/index.html | 216 -- .../global_objects/number/isfinite/index.html | 88 - .../global_objects/number/isinteger/index.html | 88 - .../global_objects/number/isnan/index.html | 99 - .../global_objects/number/issafeinteger/index.html | 94 - .../number/max_safe_integer/index.html | 71 - .../number/min_safe_integer/index.html | 61 - .../reference/global_objects/number/nan/index.html | 63 - .../number/negative_infinity/index.html | 96 - .../number/positive_infinity/index.html | 96 - .../global_objects/object/assign/index.html | 259 -- .../object/defineproperties/index.html | 228 -- .../object/defineproperty/index.html | 483 --- .../object/getownpropertynames/index.html | 156 - .../reference/global_objects/object/index.html | 213 -- .../global_objects/object/tostring/index.html | 128 - .../global_objects/object/valueof/index.html | 108 - .../global_objects/promise/all/index.html | 121 - .../global_objects/promise/catch/index.html | 136 - .../global_objects/promise/finally/index.html | 95 - .../reference/global_objects/promise/index.html | 317 -- .../global_objects/regexp/exec/index.html | 194 -- .../reference/global_objects/regexp/index.html | 618 ---- .../reference/global_objects/string/index.html | 405 --- .../global_objects/string/match/index.html | 160 - .../global_objects/string/normalize/index.html | 146 - .../global_objects/string/repeat/index.html | 118 - .../global_objects/string/replace/index.html | 233 -- .../global_objects/string/slice/index.html | 138 - .../global_objects/string/startswith/index.html | 128 - .../global_objects/string/substr/index.html | 121 - .../global_objects/string/substring/index.html | 195 -- .../reference/global_objects/weakmap/index.html | 138 - files/vi/web/javascript/reference/index.html | 50 - .../reference/iteration_protocols/index.html | 383 --- .../operators/conditional_operator/index.html | 119 - .../reference/operators/delete/index.html | 292 -- .../reference/operators/function/index.html | 175 -- .../web/javascript/reference/operators/index.html | 298 -- .../operators/operator_precedence/index.html | 477 --- .../reference/operators/super/index.html | 226 -- .../javascript/reference/operators/this/index.html | 382 --- .../reference/operators/typeof/index.html | 271 -- .../reference/statements/async_function/index.html | 255 -- .../reference/statements/continue/index.html | 135 - .../reference/statements/do...while/index.html | 98 - .../reference/statements/export/index.html | 186 -- .../reference/statements/for...of/index.html | 318 -- .../javascript/reference/statements/for/index.html | 137 - .../reference/statements/function_star_/index.html | 208 -- .../web/javascript/reference/statements/index.html | 143 - .../reference/statements/throw/index.html | 193 -- .../reference/template_literals/index.html | 238 -- files/vi/web/reference/api/index.html | 59 - files/vi/web/reference/index.html | 29 - files/vi/web/svg/index.html | 94 - files/vi/web/svg/tutorial/index.html | 59 - files/vi/web/svg/tutorial/svg_image_tag/index.html | 32 - files/vi/web/tutorials/index.html | 238 -- 225 files changed, 49495 deletions(-) delete mode 100644 files/vi/web/accessibility/aria/aria_live_regions/index.html delete mode 100644 files/vi/web/accessibility/aria/index.html delete mode 100644 files/vi/web/accessibility/index.html delete mode 100644 files/vi/web/api/audiocontext/index.html delete mode 100644 files/vi/web/api/baseaudiocontext/createoscillator/index.html delete mode 100644 files/vi/web/api/canvas_api/index.html delete mode 100644 files/vi/web/api/childnode/index.html delete mode 100644 files/vi/web/api/childnode/remove/index.html delete mode 100644 files/vi/web/api/document_object_model/index.html delete mode 100644 files/vi/web/api/document_object_model/introduction/index.html delete mode 100644 files/vi/web/api/eventsource/index.html delete mode 100644 files/vi/web/api/eventsource/url/index.html delete mode 100644 files/vi/web/api/fetch_api/index.html delete mode 100644 files/vi/web/api/file/index.html delete mode 100644 files/vi/web/api/geolocation_api/index.html delete mode 100644 files/vi/web/api/htmlcanvaselement/getcontext/index.html delete mode 100644 files/vi/web/api/htmlcanvaselement/index.html delete mode 100644 files/vi/web/api/htmlelement/index.html delete mode 100644 files/vi/web/api/htmlformelement/index.html delete mode 100644 files/vi/web/api/htmlformelement/reset/index.html delete mode 100644 files/vi/web/api/htmlorforeignelement/dataset/index.html delete mode 100644 files/vi/web/api/index.html delete mode 100644 files/vi/web/api/navigator/geolocation/index.html delete mode 100644 files/vi/web/api/navigator/index.html delete mode 100644 files/vi/web/api/navigator/sendbeacon/index.html delete mode 100644 files/vi/web/api/node/index.html delete mode 100644 files/vi/web/api/node/insertbefore/index.html delete mode 100644 files/vi/web/api/node/parentelement/index.html delete mode 100644 files/vi/web/api/node/parentnode/index.html delete mode 100644 files/vi/web/api/notification/index.html delete mode 100644 files/vi/web/api/touch_events/index.html delete mode 100644 files/vi/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html delete mode 100644 files/vi/web/api/url_api/index.html delete mode 100644 files/vi/web/api/webrtc_api/index.html delete mode 100644 files/vi/web/api/webrtc_api/protocols/index.html delete mode 100644 files/vi/web/api/websockets_api/index.html delete mode 100644 files/vi/web/api/websockets_api/writing_a_websocket_server_in_java/index.html delete mode 100644 files/vi/web/api/window/index.html delete mode 100644 files/vi/web/api/window/load_event/index.html delete mode 100644 files/vi/web/api/window/prompt/index.html delete mode 100644 files/vi/web/css/_colon_first-child/index.html delete mode 100644 files/vi/web/css/_colon_focus-within/index.html delete mode 100644 files/vi/web/css/_colon_focus/index.html delete mode 100644 files/vi/web/css/_colon_last-of-type/index.html delete mode 100644 files/vi/web/css/backdrop-filter/index.html delete mode 100644 files/vi/web/css/background-color/index.html delete mode 100644 files/vi/web/css/content/index.html delete mode 100644 files/vi/web/css/css_box_alignment/index.html delete mode 100644 files/vi/web/css/css_box_model/index.html delete mode 100644 files/vi/web/css/css_box_model/introduction_to_the_css_box_model/index.html delete mode 100644 files/vi/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html delete mode 100644 files/vi/web/css/css_grid_layout/index.html delete mode 100644 files/vi/web/css/css_transitions/index.html delete mode 100644 files/vi/web/css/css_transitions/using_css_transitions/index.html delete mode 100644 files/vi/web/css/filter-function/index.html delete mode 100644 files/vi/web/css/flex-basis/index.html delete mode 100644 files/vi/web/css/flex-wrap/index.html delete mode 100644 files/vi/web/css/flex/index.html delete mode 100644 files/vi/web/css/index.html delete mode 100644 files/vi/web/css/length/index.html delete mode 100644 files/vi/web/css/perspective/index.html delete mode 100644 files/vi/web/css/transform-function/index.html delete mode 100644 files/vi/web/css/transform-function/perspective()/index.html delete mode 100644 files/vi/web/css/universal_selectors/index.html delete mode 100644 files/vi/web/css/url()/index.html delete mode 100644 files/vi/web/events/index.html delete mode 100644 files/vi/web/guide/api/index.html delete mode 100644 files/vi/web/guide/html/html5/index.html delete mode 100644 files/vi/web/guide/index.html delete mode 100644 files/vi/web/html/element/center/index.html delete mode 100644 files/vi/web/html/element/dialog/index.html delete mode 100644 files/vi/web/html/element/em/index.html delete mode 100644 files/vi/web/html/element/header/index.html delete mode 100644 files/vi/web/html/element/html/index.html delete mode 100644 files/vi/web/html/element/index.html delete mode 100644 files/vi/web/html/element/meta/index.html delete mode 100644 files/vi/web/html/element/span/index.html delete mode 100644 files/vi/web/html/index.html delete mode 100644 files/vi/web/http/headers/content-security-policy/index.html delete mode 100644 files/vi/web/http/headers/content-security-policy/style-src/index.html delete mode 100644 files/vi/web/http/headers/index.html delete mode 100644 files/vi/web/http/index.html delete mode 100644 files/vi/web/index.html delete mode 100644 files/vi/web/javascript/a_re-introduction_to_javascript/index.html delete mode 100644 files/vi/web/javascript/closures/index.html delete mode 100644 files/vi/web/javascript/data_structures/index.html delete mode 100644 files/vi/web/javascript/guide/control_flow_and_error_handling/index.html delete mode 100644 files/vi/web/javascript/guide/details_of_the_object_model/index.html delete mode 100644 files/vi/web/javascript/guide/expressions_and_operators/index.html delete mode 100644 files/vi/web/javascript/guide/functions/index.html delete mode 100644 files/vi/web/javascript/guide/grammar_and_types/index.html delete mode 100644 files/vi/web/javascript/guide/index.html delete mode 100644 files/vi/web/javascript/guide/introduction/index.html delete mode 100644 files/vi/web/javascript/guide/iterators_and_generators/index.html delete mode 100644 files/vi/web/javascript/guide/keyed_collections/index.html delete mode 100644 files/vi/web/javascript/guide/loops_and_iteration/index.html delete mode 100644 files/vi/web/javascript/guide/numbers_and_dates/index.html delete mode 100644 files/vi/web/javascript/guide/regular_expressions/index.html delete mode 100644 files/vi/web/javascript/guide/text_formatting/index.html delete mode 100644 files/vi/web/javascript/guide/using_promises/index.html delete mode 100644 files/vi/web/javascript/guide/working_with_objects/index.html delete mode 100644 files/vi/web/javascript/index.html delete mode 100644 files/vi/web/javascript/memory_management/index.html delete mode 100644 files/vi/web/javascript/reference/classes/constructor/index.html delete mode 100644 files/vi/web/javascript/reference/classes/extends/index.html delete mode 100644 files/vi/web/javascript/reference/classes/index.html delete mode 100644 files/vi/web/javascript/reference/errors/index.html delete mode 100644 files/vi/web/javascript/reference/errors/missing_semicolon_before_statement/index.html delete mode 100644 files/vi/web/javascript/reference/errors/more_arguments_needed/index.html delete mode 100644 files/vi/web/javascript/reference/errors/not_a_function/index.html delete mode 100644 files/vi/web/javascript/reference/errors/too_much_recursion/index.html delete mode 100644 files/vi/web/javascript/reference/functions/arguments/index.html delete mode 100644 files/vi/web/javascript/reference/functions/arrow_functions/index.html delete mode 100644 files/vi/web/javascript/reference/functions/default_parameters/index.html delete mode 100644 files/vi/web/javascript/reference/functions/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/concat/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/copywithin/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/entries/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/every/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/fill/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/filter/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/find/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/findindex/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/flat/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/foreach/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/from/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/includes/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/indexof/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/isarray/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/join/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/map/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/of/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/pop/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/push/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/reduce/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/reduceright/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/reverse/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/shift/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/slice/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/some/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/sort/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/splice/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/tolocalestring/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/tostring/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/unshift/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/values/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/arraybuffer/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/date/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/date/parse/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/error/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/function/call/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/function/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/function/tosource/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/generator/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/infinity/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/isfinite/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/json/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/map/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/math/abs/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/math/ceil/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/math/floor/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/math/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/math/sqrt/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/nan/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/isfinite/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/isinteger/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/isnan/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/issafeinteger/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/max_safe_integer/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/min_safe_integer/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/nan/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/negative_infinity/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/positive_infinity/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/assign/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/tostring/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/valueof/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/promise/all/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/promise/catch/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/promise/finally/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/promise/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/regexp/exec/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/regexp/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/match/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/normalize/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/repeat/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/replace/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/slice/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/startswith/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/substr/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/substring/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/weakmap/index.html delete mode 100644 files/vi/web/javascript/reference/index.html delete mode 100644 files/vi/web/javascript/reference/iteration_protocols/index.html delete mode 100644 files/vi/web/javascript/reference/operators/conditional_operator/index.html delete mode 100644 files/vi/web/javascript/reference/operators/delete/index.html delete mode 100644 files/vi/web/javascript/reference/operators/function/index.html delete mode 100644 files/vi/web/javascript/reference/operators/index.html delete mode 100644 files/vi/web/javascript/reference/operators/operator_precedence/index.html delete mode 100644 files/vi/web/javascript/reference/operators/super/index.html delete mode 100644 files/vi/web/javascript/reference/operators/this/index.html delete mode 100644 files/vi/web/javascript/reference/operators/typeof/index.html delete mode 100644 files/vi/web/javascript/reference/statements/async_function/index.html delete mode 100644 files/vi/web/javascript/reference/statements/continue/index.html delete mode 100644 files/vi/web/javascript/reference/statements/do...while/index.html delete mode 100644 files/vi/web/javascript/reference/statements/export/index.html delete mode 100644 files/vi/web/javascript/reference/statements/for...of/index.html delete mode 100644 files/vi/web/javascript/reference/statements/for/index.html delete mode 100644 files/vi/web/javascript/reference/statements/function_star_/index.html delete mode 100644 files/vi/web/javascript/reference/statements/index.html delete mode 100644 files/vi/web/javascript/reference/statements/throw/index.html delete mode 100644 files/vi/web/javascript/reference/template_literals/index.html delete mode 100644 files/vi/web/reference/api/index.html delete mode 100644 files/vi/web/reference/index.html delete mode 100644 files/vi/web/svg/index.html delete mode 100644 files/vi/web/svg/tutorial/index.html delete mode 100644 files/vi/web/svg/tutorial/svg_image_tag/index.html delete mode 100644 files/vi/web/tutorials/index.html (limited to 'files/vi/web') diff --git a/files/vi/web/accessibility/aria/aria_live_regions/index.html b/files/vi/web/accessibility/aria/aria_live_regions/index.html deleted file mode 100644 index bbeee0897f..0000000000 --- a/files/vi/web/accessibility/aria/aria_live_regions/index.html +++ /dev/null @@ -1,259 +0,0 @@ ---- -title: ARIA live regions -slug: Web/Accessibility/ARIA/ARIA_Live_Regions -translation_of: Web/Accessibility/ARIA/ARIA_Live_Regions ---- -

Sử dụng JavaScript, nó có thể thay đổi vài phần trong trang web mà không yêu cầu tải lại trang — lấy ví dụ, để cập nhật danh sách kết quả tìm kiếm ngay lập tức, hoặc để hiển thị một cảnh báo hay thông báo mà không bắt người dùng phải tương tác. Mặc dù những thay đổi này có thể nhìn thấy đối với người dùng, nó lại có thể không rõ ràng với những người cần sự hỗ trợ của công nghệ trợ năng. ARIA live regions giúp xử lý điều này bằng việc cung cấp một cách để lập trình các thay đổi nội dung động có thể được nhận diện bởi các công nghệ trợ năng.

- -
-

Lưu ý: Các công nghệ trợ năng sẽ thông báo các thay đổi trong nội dung của một khu vực trực tiếp. Khu vực trực tiếp trước hết phải hiện diện (và thường trống), để trình duyệt và công nghệ hỗ trợ nhận thức được điều đó. Mọi thay đổi sau đó sẽ được thông báo.

- -

Đơn giản chỉ cần thêm vào thuộc tính aria-live hoặc thuộc tính chuyên biệt role (như là role="alert") trong markup ban đầu chưa có hoạt động.

- -

Dynamically adding an element with an aria-live attribute or specialized role to the document also won't result in any announcement by assistive technologies (as, at that point, the browser/assistive technologies are not aware of the live region yet, so cannot monitor it for changes).

- -

Always make sure that the live region is present in the document first, and only then dynamically add/change any content.

-
- -

Simple live regions

- -

Dynamic content which updates without a page reload is generally either a region or a widget. Simple content changes which are not interactive should be marked as live regions. Below is a list of each related ARIA live region property with a description.

- -
    -
  1. aria-live: The aria-live=POLITENESS_SETTING is used to set the priority with which screen reader should treat updates to live regions - the possible settings are: off, polite or assertive. The default setting is off. This attribute is by far the most important.
  2. -
  3. -

    aria-controls: The aria-controls=[IDLIST] is used to associate a control with the regions that it controls. Regions are identified just like an id in a div, and multiple regions can be associated with a control using a space, e.g. aria-controls="myRegionID1 myRegionsID2".

    - -
    Not known if the aria-controls aspect of live regions is implemented in current ATs, or which. Needs research.
    -
  4. -
- -

Normally, only aria-live="polite" is used. Any region which receives updates that are important for the user to receive, but not so rapid as to be annoying, should receive this attribute. The screen reader will speak changes whenever the user is idle.

- -

For regions which are not important, or would be annoying because of rapid updates or other reasons, silence them with aria-live="off".

- - - -

A website specializing in providing information about planets provides a dropdown box. When a planet is selected from the dropdown, a region on the page is updated with information about the selected planet.

- -

HTML

- -
<fieldset>
-  <legend>Planet information</legend>
-  <label for="planetsSelect">Planet:</label>
-  <select id="planetsSelect" aria-controls="planetInfo">
-    <option value="">Select a planet&hellip;</option>
-    <option value="mercury">Mercury</option>
-    <option value="venus">Venus</option>
-    <option value="earth">Earth</option>
-    <option value="mars">Mars</option>
-  </select>
-  <button id="renderPlanetInfoButton">Go</button>
-</fieldset>
-
-<div role="region" id="planetInfo" aria-live="polite">
-  <h2 id="planetTitle">No planet selected</h2>
-  <p id="planetDescription">Select a planet to view its description</p>
-</div>
-
-<p><small>Information courtesy <a href="https://en.wikipedia.org/wiki/Solar_System#Inner_Solar_System">Wikipedia</a></small></p>
-
- -

JavaScript

- -
const PLANETS_INFO = {
-  mercury: {
-    title: 'Mercury',
-    description: 'Mercury is the smallest and innermost planet in the Solar System. It is named after the Roman deity Mercury, the messenger to the gods.'
-  },
-
-  venus: {
-    title: "Venus",
-    description: 'Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty.'
-  },
-
-  earth: {
-    title: "Earth",
-    description: 'Earth is the third planet from the Sun and the only object in the Universe known to harbor life.'
-  },
-
-  mars: {
-    title: "Mars",
-    description: 'Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System after Mercury. In English, Mars carries a name of the Roman god of war, and is often referred to as the "Red Planet".'
-  }
-};
-
-function renderPlanetInfo(planet) {
-  const planetTitle = document.querySelector('#planetTitle');
-  const planetDescription = document.querySelector('#planetDescription');
-
-  if (planet in PLANETS_INFO) {
-    planetTitle.textContent = PLANETS_INFO[planet].title;
-    planetDescription.textContent = PLANETS_INFO[planet].description;
-  } else {
-    planetTitle.textContent = 'No planet selected';
-    planetDescription.textContent = 'Select a planet to view its description';
-  }
-}
-
-const renderPlanetInfoButton = document.querySelector('#renderPlanetInfoButton');
-
-renderPlanetInfoButton.addEventListener('click', event => {
-  const planetsSelect = document.querySelector('#planetsSelect');
-  const selectedPlanet = planetsSelect.options[planetsSelect.selectedIndex].value;
-
-  renderPlanetInfo(selectedPlanet);
-});
-
- -

{{EmbedLiveSample('Dropdown_box_updates_useful_onscreen_information', '', 350)}}

- -

As the user selects a new planet, the information in the live region will be announced. Because the live region has aria-live="polite", the screen reader will wait until the user pauses before announcing the update. Thus, moving down in the list and selecting another planet will not announce updates in the live region. Updates in the live region will only be announced for the planet finally chosen.

- -

Here is a screenshot of VoiceOver on Mac announcing the update (via subtitles) to the live region:

- -

A screenshot of VoiceOver on Mac announcing the update to a live region. Subtitles are shown in the picture.

- -

Preferring specialized live region roles

- -

In the following well-known predefined cases it is better to use a specific provided "live region role":

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
RoleDescriptionCompatibility Notes
logChat, error, game or other type of logTo maximize compatibility, add a redundant aria-live="polite" when using this role.
statusA status bar or area of the screen that provides an updated status of some kind. Screen reader users have a special command to read the current status.To maximize compatibility, add a redundant aria-live="polite" when using this role.
alertError or warning message that flashes on the screen. Alerts are particularly important for client side validation notices to users. (TBD: link to ARIA form tutorial with aria info)To maximize compatibility, some people recommend adding a redundant aria-live="assertive" when using this role. However, adding both aria-live and role="alert" causes double speaking issues in VoiceOver on iOS.
progressbarA hybrid between a widget and a live region. Use this with aria-valuemin, aria-valuenow and aria-valuemax. (TBD: add more info here).
marqueefor text which scrolls, such as a stock ticker.
timeror any kind of timer or clock, such as a countdown timer or stopwatch readout.
- -

Advanced live regions

- -

(TBD: more granular information on the support of the individual attributes with combinations of OS/Browser/AT).

- -

General support for Live Regions was added to JAWS on version 10.0. In Windows Eyes supports Live Regions since version 8.0 "for use outside of Browse Mode for Microsoft Internet Explorer and Mozilla Firefox". NVDA added some basic support for Live Regions for Mozilla Firefox back in 2008 and was improved in 2010 and 2014. In 2015, basic support was also added for Internet Explorer (MSHTML).

- -

The Paciello Group has some information about the state of the support of Live Regions (2014). Paul J. Adam has researched the support of Aria-Atomic and Aria-Relevant in particular. 

- -
    -
  1. aria-atomic: The aria-atomic=BOOLEAN is used to set whether or not the screen reader should always present the live region as a whole, even if only part of the region changes. The possible settings are: false or true. The default setting is false.
  2. -
  3. aria-relevant: The aria-relevant=[LIST_OF_CHANGES] is used to set what types of changes are relevant to a live region. The possible settings are one or more of: additions, removalstext, all. The default setting is: additions text.
  4. -
  5. aria-labelledby: The aria-labelledby=[IDLIST] is used to associate a region with its labels, similar to aria-controls but instead associating labels to the region. and label identifiers are separated with a space.
  6. -
  7. aria-describedby: The aria-describedby=[IDLIST] is used to associate a region with its descriptions, similar to aria-controls but instead associating descriptions to the region and description identifiers are separated with a space.
  8. -
- -

Advanced use case: Clock

- -

As an illustration of aria-atomic, consider a site with a simple clock, showing hours and minutes. The clock is updated each minute, with the new remaining time simply overwriting the current content.

- -
<div id="clock" role="timer" aria-live="polite"></div>
-
- -
/* basic JavaScript to update the clock */
-
-setInterval(function() {
-  var now = new Date();
-  document.getElementById('clock').innerHTML = "Time: " + now.getHours() + ":" + ("0"+now.getMinutes()).substr(-2);
-}, 60000);
-
- -

The first time the function executes, the entirety of the string that is added will be announced. On subsequent calls, only the parts of the content that changed compared to the previous content will be announced. For instance, when the clock changes from "17:33" to "17:34", assistive technologies will only announce "4", which won't be very useful to users.

- -

One way around this would be to first clear the contents of the live region, and then inject the new content. However, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates.

- -

aria-atomic="true" ensures that each time the live region is updated, the entirety of the content is announced in full (e.g. "Time: 17:34").

- -
<div id="clock" role="timer" aria-live="polite" aria-atomic="true"></div>
-
- -
-

Note: As observed, setting/updating the innerHTML again would cause the whole text to be read again, whether or not you set aria-atomic="true", so the above Clock example does not work as expected.

-
- -

A working example of a simple year control for better understanding:

- -
<div id="date-input">
-  <label>Year:
-    <input type="text" id="year" value="1990" onblur="change(event)"/>
-  </label>
-</div>
-
-<div id="date-output" aria-live="polite">
-  The set year is:
-  <span id="year-output">1990</span>
-</div>
- -

- -
function change(event) {
-  var yearOut = document.getElementById("year-output");
-  switch (event.target.id) {
-    case "year":
-      yearOut.innerHTML = event.target.value;
-      break;
-   default:
-      return;
-  }
-};
- -

- -

Without aria-atomic="true" the screenreader announces only the changed value of year.

- -

With aria-atomic="true", the screenreader announces "The set year is: changedvalue"

- -

Advanced use case: Roster

- -

A chat site would like to display a list of users currently logged in. Display a list of users where a user's log-in and log-out status will be reflected dynamically (without a page reload).

- -
<ul id="roster" aria-live="polite" aria-relevant="additions removals">
-	<!-- use JavaScript to add remove users here-->
-</ul>
-
- -

Breakdown of ARIA live properties:

- - - -

See also

- - diff --git a/files/vi/web/accessibility/aria/index.html b/files/vi/web/accessibility/aria/index.html deleted file mode 100644 index b7587c76b0..0000000000 --- a/files/vi/web/accessibility/aria/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: ARIA -slug: Web/Accessibility/ARIA -tags: - - ARIA - - Accessibility - - HTML - - NeedsTranslation - - TopicStub -translation_of: Web/Accessibility/ARIA ---- -

Accessible Rich Internet Applications (ARIA) is a set of attributes that define ways to make web content and web applications (especially those developed with JavaScript) more accessible to people with disabilities.

- -

It supplements HTML so that interactions and widgets commonly used in applications can be passed to assistive technologies when there is not otherwise a mechanism. For example, ARIA enables accessible navigation landmarks in HTML4, JavaScript widgets, form hints and error messages, live content updates, and more. 

- -
-

Many of these widgets were later incorporated into HTML5, and developers should prefer using the correct semantic HTML element over using ARIA, if such an element exists. For instance, native elements have built-in keyboard accessibility, roles and states. However, if you choose to use ARIA, you are responsible for mimicking (the equivalent) browser behaviour in script.

-
- -

Here's the markup for a progress bar widget:

- -
<div id="percent-loaded" role="progressbar" aria-valuenow="75"
-     aria-valuemin="0" aria-valuemax="100">
-</div>
-
- -

This progress bar is built using a <div>, which has no meaning. Unfortunately, there isn't a more semantic tag available to developers in HTML 4, so we need to include ARIA roles and properties. These are specified by adding attributes to the element. In this example, the role="progressbar" attribute informs the browser that this element is actually a JavaScript-powered progress bar widget. The aria-valuemin and aria-valuemax attributes specify the minimum and maximum values for the progress bar, and the aria-valuenow describes the current state of it and therefore must be kept updated with JavaScript.

- -

Along with placing them directly in the markup, ARIA attributes can be added to the element and updated dynamically using JavaScript code like this:

- -
// Find the progress bar <div> in the DOM.
- var progressBar = document.getElementById("percent-loaded");
-
-// Set its ARIA roles and states,
-// so that assistive technologies know what kind of widget it is.
- progressBar.setAttribute("role", "progressbar");
- progressBar.setAttribute("aria-valuemin", 0);
- progressBar.setAttribute("aria-valuemax", 100);
-
-// Create a function that can be called at any time to update
-// the value of the progress bar.
- function updateProgress(percentComplete) {
-   progressBar.setAttribute("aria-valuenow", percentComplete);
- }
- -
-

Note that ARIA was invented after HTML4, so does not validate in HTML4 or its XHTML variants. However, the accessibility gains it provides far outweigh any technical invalidity.

- -

In HTML5, all ARIA attributes validate. The new landmark elements (<main>, <header>, <nav> etc) have built-in ARIA roles, so there is no need to duplicate them.

-
- -

Support

- -

Like any other web technology, there are varying degrees of support for ARIA. Support is based on the operating system and browser being used, as well as the kind of assistive technology interfacing with it. In addition, the version of the operating system, browser, and assistive technology are contributing factors. Older software versions may not support certain ARIA roles, have only partial support, or misreport its functionality.

- -

It is also important to acknowledge that some people who rely on assistive technology are reluctant to upgrade their software, for fear of losing the ability to interact with their computer and browser. Because of this, it is important to use semantic HTML elements whenever possible, as semantic HTML has far better support for assistive technology.

- -

It is also important to test your authored ARIA with actual assistive technology. Much as how browser emulators and simulators are not an effective solution for testing full support, proxy assistive technology solutions aren't sufficient to fully guarantee functionality.

- -
-
-
-

Tutorials

- -
-
Introduction to ARIA
-
A quick introduction to making dynamic content accessible with ARIA. See also the classic ARIA intro by Gez Lemon, from 2008.
-
Videos of screen readers using ARIA
-
See both real and simplified examples from around the web, including "before" and "after" ARIA videos.
-
Using ARIA
-
A practical guide for developers. It suggests what ARIA attributes to use on HTML elements. Suggestions are based on implementation realities.
-
- -

Simple ARIA enhancements

- -
-
Enhancing page navigation with ARIA landmarks
-
A nice intro to using ARIA landmarks to improve web page navigation for screen reader users. See also, ARIA landmark implementation notes and examples on real sites (updated as of July 2011).
-
Improving form accessibility
-
ARIA is not just for dynamic content! Learn how to improve accessibility of HTML forms using additional ARIA attributes.
-
- -

ARIA for Scripted Widgets

- -
-
Writing keyboard-navigable JavaScript widgets
-
Built-in elements like <input>, <button> etc have built-in keyboard accessibility. If you 'fake' these with <div>s and ARIA, you must ensure your widgets are keyboard accessible.
-
Live regions
-
Live regions provide suggestions to screen readers about how to handle changes to the contents of a page.
-
Using ARIA Live Regions to announce content changes
-
A quick summary of live regions, by the makers of JAWS screen reader software. Live regions are also supported by NVDA with Firefox, and VoiceOver with Safari.
-
-
- -
-

References

- -
-
ARIA Roles
-
Reference pages covering all the WAI-ARIA roles discussed on MDN.
-
- -

Standardization Efforts

- -
-
WAI-ARIA Specification
-
The W3C specification itself.
-
WAI-ARIA Authoring Practices
-
-

The official best practices documents how best to ARIA-ify common widgets and interactions. An excellent resource.

-
-
- -

Videos

- -

Following talks are a great way to understand ARIA:

- -

ARIA, Accessibility APIs and coding like you give a damn! – Léonie Watson

- -

Filing Bugs

- -

File ARIA bugs on browsers, screen readers, and JavaScript libraries.

-
-
-
- - - -

Accessibility, AJAX, JavaScript

- - diff --git a/files/vi/web/accessibility/index.html b/files/vi/web/accessibility/index.html deleted file mode 100644 index 908f9c13c5..0000000000 --- a/files/vi/web/accessibility/index.html +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: Accessibility -slug: Web/Accessibility -tags: - - Accessibility - - Landing - - NeedsTranslation - - TopicStub -translation_of: Web/Accessibility ---- -

Accessibility (often abbreviated to A11y—as in "a" then 11 characters then "y") in Web development means enabling as many people as possible to use Web sites, even when those people's abilities are limited in some way.

- -

For many people, technology makes things easier. For people with disabilities, technology makes things possible. Accessibility means developing content to be as accessible as possible no matter an individual's physical and cognitive abilities and no matter how they access the web.

- -

"The Web is fundamentally designed to work for all people, whatever their hardware, software, language, culture, location, or physical or mental ability. When the Web meets this goal, it is accessible to people with a diverse range of hearing, movement, sight, and cognitive ability." (W3C - Accessibility)

- -
-
-

Key tutorials

- -

The MDN Accessibility Learning Area contains modern, up-to-date tutorials covering accessibility essentials:

- -
-
What is accessibility?
-
This article starts off the module with a good look at what accessibility actually is — this includes what groups of people we need to consider and why, what tools different people use to interact with the Web, and how we can make accessibility part of our web development workflow.
-
HTML: A good basis for accessibility
-
A great deal of web content can be made accessible just by making sure the correct HTML elements are used for the correct purpose at all times. This article looks in detail at how HTML can be used to ensure maximum accessibility.
-
CSS and JavaScript accessibility best practices
-
CSS and JavaScript, when used properly, also have the potential to allow for accessible web experiences ... or they can significantly harm accessibility if misused. This article outlines some CSS and JavaScript best practices that should be considered to ensure even complex content is as accessible as possible.
-
WAI-ARIA basics
-
Following on from the previous article, sometimes making complex UI controls that involve unsemantic HTML and dynamic JavaScript-updated content can be difficult. WAI-ARIA is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. Here we'll show how to use it at a basic level to improve accessibility.
-
Accessible multimedia
-
Another category of content that can create accessibility problems is multimedia — video, audio, and image content need to be given proper textual alternatives so they can be understood by assistive technologies and their users. This article shows how.
-
Mobile accessibility
-
With web access on mobile devices being so popular, and popular platforms such as iOS and Android having fully-fledged accessibility tools, it is important to consider the accessibility of your web content on these platforms. This article looks at mobile-specific accessibility considerations.
-
-
- -
-

Other documentation

- -
-
Understanding the Web Content Accessibility Guidelines
-
-

This set of articles provides quick explanations to help you understand the steps that need to be taken to conform to the recommendations outlined in the W3C Web Content Accessibility Guidelines 2.0 (WCAG 2.0 or just WCAG, for the purposes of this writing).

-
-
Keyboard-navigable JavaScript widgets
-
Until now, web developers who want to make their styled <div> and <span> based widgets accessible have lacked the proper techniques. Keyboard accessibility is part of the minimum accessibility requirements which a developer should be aware of.
-
ARIA
-
A collection of articles to learn how to use ARIA to make your HTML documents more accessible.
-
Assistive technology (AT) development
-
A collection of articles intended for AT developers
-
Mobile accessibility checklist
-
This document provides a concise checklist of accessibility requirements for mobile app developers.
-
Cognitive accessibility
-
When creating web content, be aware of how you can ensure that it is accessible to people cognitive impairments.
-
Accessibility for seizure disorders
-
Some types of visual web content can induce seizures in people with certain brain disorders. Understand the types of content that can be problematic, and find tools and strategies to help you avoid them.
-
-
- -

View all articles about Accessibility...

-
-
- -

See also

- - - - diff --git a/files/vi/web/api/audiocontext/index.html b/files/vi/web/api/audiocontext/index.html deleted file mode 100644 index da175915e4..0000000000 --- a/files/vi/web/api/audiocontext/index.html +++ /dev/null @@ -1,305 +0,0 @@ ---- -title: AudioContext -slug: Web/API/AudioContext -tags: - - API - - Audio - - AudioContext - - Interface - - NeedsTranslation - - Reference - - TopicStub - - Web Audio API - - sound -translation_of: Web/API/AudioContext ---- -

{{APIRef("Web Audio API")}}

- -
-

The AudioContext interface represents an audio-processing graph built from audio modules linked together, each represented by an {{domxref("AudioNode")}}. An audio context controls both the creation of the nodes it contains and the execution of the audio processing, or decoding. You need to create an AudioContext before you do anything else, as everything happens inside a context.

-
- -

An AudioContext can be a target of events, therefore it implements the {{domxref("EventTarget")}} interface.

- -

{{InheritanceDiagram}}

- -

Constructor

- -
-
{{domxref("AudioContext.AudioContext", "AudioContext()")}}
-
Creates and returns a new AudioContext object.
-
- -

Properties

- -
-
{{domxref("AudioContext.currentTime")}} {{readonlyInline}}
-
Returns a double representing an ever-increasing hardware time in seconds used for scheduling. It starts at 0.
-
{{domxref("AudioContext.destination")}} {{readonlyInline}}
-
Returns an {{domxref("AudioDestinationNode")}} representing the final destination of all audio in the context. It can be thought of as the audio-rendering device.
-
{{domxref("AudioContext.listener")}} {{readonlyInline}}
-
Returns the {{domxref("AudioListener")}} object, used for 3D spatialization.
-
{{domxref("AudioContext.sampleRate")}} {{readonlyInline}}
-
Returns a float representing the sample rate (in samples per second) used by all nodes in this context. The sample-rate of an {{domxref("AudioContext")}} cannot be changed.
-
{{domxref("AudioContext.state")}} {{readonlyInline}}
-
Returns the current state of the AudioContext.
-
{{domxref("AudioContext.mozAudioChannelType")}} {{ non-standard_inline() }} {{readonlyInline}}
-
Used to return the audio channel that the sound playing in an {{domxref("AudioContext")}} will play in, on a Firefox OS device.
-
- -

Event handlers

- -
-
{{domxref("AudioContext.onstatechange")}}
-
An event handler that runs when an event of type {{event("statechange")}} has fired. This occurs when the AudioContext's state changes, due to the calling of one of the state change methods ({{domxref("AudioContext.suspend")}}, {{domxref("AudioContext.resume")}}, or {{domxref("AudioContext.close")}}).
-
- -

Methods

- -

Also implements methods from the interface {{domxref("EventTarget")}}.

- -
-
{{domxref("AudioContext.close()")}}
-
Closes the audio context, releasing any system audio resources that it uses.
-
{{domxref("AudioContext.createBuffer()")}}
-
Creates a new, empty {{ domxref("AudioBuffer") }} object, which can then be populated by data and played via an {{ domxref("AudioBufferSourceNode") }}.
-
{{domxref("AudioContext.createConstantSource()")}}
-
Creates a {{domxref("ConstantSourceNode")}} object, which is an audio source that continuously outputs a monaural (one-channel) sound signal whose samples all have the same value.
-
{{domxref("AudioContext.createBufferSource()")}}
-
Creates an {{domxref("AudioBufferSourceNode")}}, which can be used to play and manipulate audio data contained within an {{ domxref("AudioBuffer") }} object. {{ domxref("AudioBuffer") }}s are created using {{domxref("AudioContext.createBuffer")}} or returned by {{domxref("AudioContext.decodeAudioData")}} when it successfully decodes an audio track.
-
{{domxref("AudioContext.createMediaElementSource()")}}
-
Creates a {{domxref("MediaElementAudioSourceNode")}} associated with an {{domxref("HTMLMediaElement")}}. This can be used to play and manipulate audio from {{HTMLElement("video")}} or {{HTMLElement("audio")}} elements.
-
{{domxref("AudioContext.createMediaStreamSource()")}}
-
Creates a {{domxref("MediaStreamAudioSourceNode")}} associated with a {{domxref("MediaStream")}} representing an audio stream which may come from the local computer microphone or other sources.
-
{{domxref("AudioContext.createMediaStreamDestination()")}}
-
Creates a {{domxref("MediaStreamAudioDestinationNode")}} associated with a {{domxref("MediaStream")}} representing an audio stream which may be stored in a local file or sent to another computer.
-
{{domxref("AudioContext.createScriptProcessor()")}}
-
Creates a {{domxref("ScriptProcessorNode")}}, which can be used for direct audio processing via JavaScript.
-
{{domxref("AudioContext.createStereoPanner()")}}
-
Creates a {{domxref("StereoPannerNode")}}, which can be used to apply stereo panning to an audio source.
-
{{domxref("AudioContext.createAnalyser()")}}
-
Creates an {{domxref("AnalyserNode")}}, which can be used to expose audio time and frequency data and for example to create data visualisations.
-
{{domxref("AudioContext.createBiquadFilter()")}}
-
Creates a {{domxref("BiquadFilterNode")}}, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc.
-
{{domxref("AudioContext.createChannelMerger()")}}
-
Creates a {{domxref("ChannelMergerNode")}}, which is used to combine channels from multiple audio streams into a single audio stream.
-
{{domxref("AudioContext.createChannelSplitter()")}}
-
Creates a {{domxref("ChannelSplitterNode")}}, which is used to access the individual channels of an audio stream and process them separately.
-
{{domxref("AudioContext.createConvolver()")}}
-
Creates a {{domxref("ConvolverNode")}}, which can be used to apply convolution effects to your audio graph, for example a reverberation effect.
-
{{domxref("AudioContext.createDelay()")}}
-
Creates a {{domxref("DelayNode")}}, which is used to delay the incoming audio signal by a certain amount. This node is also useful to create feedback loops in a Web Audio API graph.
-
{{domxref("AudioContext.createDynamicsCompressor()")}}
-
Creates a {{domxref("DynamicsCompressorNode")}}, which can be used to apply acoustic compression to an audio signal.
-
{{domxref("AudioContext.createGain()")}}
-
Creates a {{domxref("GainNode")}}, which can be used to control the overall volume of the audio graph.
-
{{domxref("AudioContext.createIIRFilter()")}}
-
Creates an {{domxref("IIRFilterNode")}}, which represents a second order filter configurable as several different common filter types.
-
{{domxref("AudioContext.createOscillator()")}}
-
Creates an {{domxref("OscillatorNode")}}, a source representing a periodic waveform. It basically generates a tone.
-
{{domxref("AudioContext.createPanner()")}}
-
Creates a {{domxref("PannerNode")}}, which is used to spatialise an incoming audio stream in 3D space.
-
{{domxref("AudioContext.createPeriodicWave()")}}
-
Creates a {{domxref("PeriodicWave")}}, used to define a periodic waveform that can be used to determine the output of an {{ domxref("OscillatorNode") }}.
-
{{domxref("AudioContext.createWaveShaper()")}}
-
Creates a {{domxref("WaveShaperNode")}}, which is used to implement non-linear distortion effects.
-
{{domxref("AudioContext.createAudioWorker()")}}
-
Creates an {{domxref("AudioWorkerNode")}}, which can interact with a web worker thread to generate, process, or analyse audio directly. This was added to the spec on August 29 2014, and is not implemented in any browser yet.
-
{{domxref("AudioContext.decodeAudioData()")}}
-
Asynchronously decodes audio file data contained in an {{domxref("ArrayBuffer")}}. In this case, the ArrayBuffer is usually loaded from an {{domxref("XMLHttpRequest")}}'s response attribute after setting the responseType to arraybuffer. This method only works on complete files, not fragments of audio files.
-
{{domxref("AudioContext.getOutputTimestamp()")}}
-
Returns a new AudioTimestamp containing two correlated context's audio stream position values: the AudioTimestamp.contextTime member contains the time of the sample frame which is currently being rendered by the audio output device (i.e., output audio stream position), in the same units and origin as context's {{domxref("AudioContext.currentTime")}}; the AudioTimestamp.performanceTime member contains the time estimating the moment when the sample frame corresponding to the stored contextTime value was rendered by the audio output device, in the same units and origin as {{domxref("performance.now()")}}.
-
{{domxref("AudioContext.resume()")}}
-
Resumes the progression of time in an audio context that has previously been suspended.
-
{{domxref("AudioContext.suspend()")}}
-
Suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing CPU/battery usage in the process.
-
- -

Obsolete methods

- -
-
{{domxref("AudioContext.createJavaScriptNode()")}}
-
Creates a {{domxref("JavaScriptNode")}}, used for direct audio processing via JavaScript. This method is obsolete, and has been replaced by {{domxref("AudioContext.createScriptProcessor()")}}.
-
{{domxref("AudioContext.createWaveTable()")}}
-
Creates a {{domxref("WaveTableNode")}}, used to define a periodic waveform. This method is obsolete, and has been replaced by {{domxref("AudioContext.createPeriodicWave()")}}.
-
- -

Examples

- -

Basic audio context declaration:

- -
var audioCtx = new AudioContext();
- -

Cross browser variant:

- -
var AudioContext = window.AudioContext || window.webkitAudioContext;
-var audioCtx = new AudioContext();
-
-var oscillatorNode = audioCtx.createOscillator();
-var gainNode = audioCtx.createGain();
-var finish = audioCtx.destination;
-// etc.
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-audiocontext-interface', 'AudioContext')}}{{Spec2('Web Audio API')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}
- 35
{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22
6.0{{property_prefix("webkit")}}
createStereoPanner(){{CompatChrome(42.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(37.0)}} {{CompatNo}}{{CompatNo}}{{CompatNo}}
onstatechange, state, suspend(), resume(){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(40.0)}}{{CompatNo}}{{CompatNo}}{{CompatSafari(8.0)}}
createConstantSource(){{CompatChrome(56.0)}}{{CompatNo}}{{CompatGeckoDesktop(52)}}{{CompatNo}}{{CompatOpera(43)}}{{CompatNo}}
Unprefixed{{CompatVersionUnknown}}{{CompatVersionUnknown}}    
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(37.0)}} 2.2{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
createStereoPanner(){{CompatChrome(42.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
onstatechange, state, suspend(), resume(){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
createConstantSource(){{CompatChrome(56.0)}}{{CompatNo}}{{CompatGeckoMobile(52)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(56.0)}}
Unprefixed{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(43)}}{{CompatUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/vi/web/api/baseaudiocontext/createoscillator/index.html b/files/vi/web/api/baseaudiocontext/createoscillator/index.html deleted file mode 100644 index 1cef402134..0000000000 --- a/files/vi/web/api/baseaudiocontext/createoscillator/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: AudioContext.createOscillator() -slug: Web/API/BaseAudioContext/createOscillator -translation_of: Web/API/BaseAudioContext/createOscillator -original_slug: Web/API/AudioContext/createOscillator ---- -

{{ APIRef("Web Audio API") }}

- -
-

Phương thức createOscillator() của giao thức {{ domxref("AudioContext") }} tạo một cái {{ domxref("OscillatorNode") }} (nút máy dao động). Tức là ta cái nguồn từ dạng sóng.

-
- -

Cú pháp

- -
var audioCtx = new AudioContext();
-var oscillator = audioCtx.createOscillator();
- -

Trả về

- -

Một cái {{domxref("OscillatorNode")}}.

- -

Ví dụ

- -

Ví dụ này trình bày sử dụng đơn giản của một cái AudioContext để tạo một cái OsillatorNode. Để biết thêm thông tin, xem biểu hiện, và trang {{domxref("OscillatorNode")}} của chúng tôi

- -

Ví dụ này trình bày sử dụng đơn giản của một cái AudioContext để tạo một cái OsillatorNode. Để biết thêm thông tin, xem biểu hiện Violent Theremin (app.js); và trang {{ domxref("OscillatorNode") }} của chúng tôi.

- -
// create web audio api context
-var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
-
-// create Oscillator node
-var oscillator = audioCtx.createOscillator();
-
-oscillator.type = 'square';
-oscillator.frequency.value = 3000; // Hz
-oscillator.connect(audioCtx.destination);
-oscillator.start();
- -

Quy cách

- - - - - - - - - - - - - - -
Quy cáchĐịa vịChú thích
{{SpecName('Web Audio API', '#widl-AudioContext-createOscillator-OscillatorNode', 'createOscillator')}}{{Spec2('Web Audio API')}} 
- -

Tương thích trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
Đặc trưngChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc trưngAndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

Xem thêm

- - diff --git a/files/vi/web/api/canvas_api/index.html b/files/vi/web/api/canvas_api/index.html deleted file mode 100644 index dc582ea7ce..0000000000 --- a/files/vi/web/api/canvas_api/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Canvas API -slug: Web/API/Canvas_API -translation_of: Web/API/Canvas_API ---- -
{{CanvasSidebar}}
- -

Canvas API cung cấp phương tiện để vẽ đồ họa thông qua JavaScript và HTML {{HtmlElement("canvas")}} thuộc tính. Nó có thể được sử dụng cho hình động, đồ họa game, trực quan hóa dữ liệu, xử lí ảnh và video trong thời gian thực.

- -

Canvas API tập trung vào đồ họa 2D. WebGL API, nó cũng sử dụng <canvas> , để vẽ đồ họa 2D và 3D.

- -

Ví dụ đơn giản

- -

This simple example draws a green rectangle onto a canvas.

- -

HTML

- -
<canvas id="canvas"></canvas>
-
- -

JavaScript

- -

The {{domxref("Document.getElementById()")}} method gets a reference to the HTML <canvas> element. Next, the {{domxref("HTMLCanvasElement.getContext()")}} method gets that element's context—the thing onto which the drawing will be rendered.

- -

The actual drawing is done using the {{domxref("CanvasRenderingContext2D")}} interface. The {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} property makes the rectangle green. The {{domxref("CanvasRenderingContext2D.fillRect()", "fillRect()")}} method places its top-left corner at (10, 10), and gives it a size of 150 units wide by 100 tall.

- -
const canvas = document.getElementById('canvas');
-const ctx = canvas.getContext('2d');
-
-ctx.fillStyle = 'green';
-ctx.fillRect(10, 10, 150, 100);
-
- -

Result

- -

{{ EmbedLiveSample('Basic_example', 700, 180) }}

- -

Reference

- -
- -
- -
-

Note: The interfaces related to the WebGLRenderingContext are referenced under WebGL.

-
- -

{{domxref("CanvasCaptureMediaStream")}} is a related interface.

- -

Guides and tutorials

- -
-
Canvas tutorial
-
A comprehensive tutorial covering both the basic usage of the Canvas API and its advanced features.
-
HTML5 Canvas Deep Dive
-
A hands-on, book-length introduction to the Canvas API and WebGL.
-
Canvas Handbook
-
A handy reference for the Canvas API.
-
Demo: A basic ray-caster
-
A demo of ray-tracing animation using canvas.
-
Manipulating video using canvas
-
Combining {{HTMLElement("video")}} and {{HTMLElement("canvas")}} to manipulate video data in real time.
-
- -

Libraries

- -

The Canvas API is extremely powerful, but not always simple to use. The libraries listed below can make the creation of canvas-based projects faster and easier.

- - - -
-

Note: See the WebGL API for 2D and 3D libaries that use WebGL.

-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#2dcontext', 'the 2D rendering context')}}{{Spec2('HTML WHATWG')}}
- -

Browser compatibility

- -

Mozilla applications gained support for <canvas> starting with Gecko 1.8 (Firefox 1.5). The element was originally introduced by Apple for the OS X Dashboard and Safari. Internet Explorer supports <canvas> from version 9 onwards; for earlier versions of IE, a page can effectively add support for <canvas> by including a script from Google's Explorer Canvas project. Google Chrome and Opera 9 also support <canvas>.

- -

See also

- - diff --git a/files/vi/web/api/childnode/index.html b/files/vi/web/api/childnode/index.html deleted file mode 100644 index ff71a15d51..0000000000 --- a/files/vi/web/api/childnode/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: ChildNode -slug: Web/API/ChildNode -tags: - - API - - DOM - - Experimental - - Interface - - NeedsTranslation - - Node - - TopicStub -translation_of: Web/API/ChildNode ---- -
{{APIRef("DOM")}}
- -

The ChildNode interface contains methods that are particular to {{domxref("Node")}} objects that can have a parent.

- -

ChildNode is a raw interface and no object of this type can be created; it is implemented by {{domxref("Element")}}, {{domxref("DocumentType")}}, and {{domxref("CharacterData")}} objects.

- -

Properties

- -

There are neither inherited, nor specific properties.

- -

Methods

- -

There are no inherited methods.

- -
-
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
-
Removes this ChildNode from the children list of its parent.
-
{{domxref("ChildNode.before()")}} {{experimental_inline}}
-
Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this ChildNode's parent, just before this ChildNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
-
{{domxref("ChildNode.after()")}} {{experimental_inline}}
-
Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this ChildNode's parent, just after this ChildNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
-
{{domxref("ChildNode.replaceWith()")}} {{experimental_inline}}
-
Replaces this ChildNode in the children list of its parent with a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-childnode', 'ChildNode')}}{{Spec2('DOM WHATWG')}}Split the ElementTraversal interface in {{domxref("ParentNode")}} and ChildNode. previousElementSibling and nextElementSibling are now defined on the latter. The {{domxref("CharacterData")}} and {{domxref("DocumentType")}} implemented the new interfaces. Added the remove(), before(), after() and replaceWith() methods.
{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}{{Spec2('Element Traversal')}}Added the initial definition of its properties to the ElementTraversal pure interface and use it on {{domxref("Element")}}.
- -

Polyfill

- -

External on github: childNode.js

- -

Browser compatibility

- - - -

{{Compat("api.ChildNode")}}

- -

See also

- - diff --git a/files/vi/web/api/childnode/remove/index.html b/files/vi/web/api/childnode/remove/index.html deleted file mode 100644 index 3c0fde3e18..0000000000 --- a/files/vi/web/api/childnode/remove/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: ChildNode.remove() -slug: Web/API/ChildNode/remove -tags: - - API - - ChildNode - - DOM - - Phương Thức - - Đang thử nghiệm -translation_of: Web/API/ChildNode/remove ---- -
{{APIRef("DOM")}}
- -

Phương thức ChildNode.remove() dùng để loại bỏ chính đối tượng gọi nó ra khỏi cây cấu trúc.

- -

Cú pháp

- -
node.remove();
-
- -

Ví dụ

- -

Cách dùng remove()

- -
<div id="div-01">Đây là div-01</div>
-<div id="div-02">Đây là div-02</div>
-<div id="div-03">Đây là div-03</div>
-
- -
var el = document.getElementById('div-02');
-el.remove(); // Gỡ bỏ div có id là 'div-02'
-
- -

ChildNode.remove() is unscopable

- -

The remove() method is not scoped into the with statement. See {{jsxref("Symbol.unscopables")}} for more information.

- -
with(node) {
-  remove();
-}
-// ReferenceError: remove is not defined 
- -

Giải pháp thay thế

- -

Ta có thể thay thế phương thức remove() bằng đoạn mã sau để chạy trên Internet Explorer 9 và những đời sau này:

- -
// Nguồn: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
-(function (arr) {
-  arr.forEach(function (item) {
-    if (item.hasOwnProperty('remove')) {
-      return;
-    }
-    Object.defineProperty(item, 'remove', {
-      configurable: true,
-      enumerable: true,
-      writable: true,
-      value: function remove() {
-        if (this.parentNode !== null)
-          this.parentNode.removeChild(this);
-      }
-    });
-  });
-})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('DOM WHATWG', '#dom-childnode-remove', 'ChildNode.remove')}}{{Spec2('DOM WHATWG')}}Lần đầu được định nghĩa.
- -

Tính tương thích trên trình duyệt

- -
- - -

{{Compat("api.ChildNode.remove")}}

-
- -

Xem thêm

- - diff --git a/files/vi/web/api/document_object_model/index.html b/files/vi/web/api/document_object_model/index.html deleted file mode 100644 index d00ed4aeea..0000000000 --- a/files/vi/web/api/document_object_model/index.html +++ /dev/null @@ -1,387 +0,0 @@ ---- -title: Document Object Model (DOM) -slug: Web/API/Document_Object_Model -tags: - - API - - DOM - - DOM Reference - - Intermediate - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/API/Document_Object_Model ---- -

{{DefaultAPISidebar("DOM")}}

- -

The Document Object Model (DOM) is a programming interface for HTML, XML and SVG documents. It provides a structured representation of the document as a tree. The DOM defines methods that allow access to the tree, so that they can change the document structure, style and content. The DOM provides a representation of the document as a structured group of nodes and objects, possessing various properties and methods. Nodes can also have event handlers attached to them, and once an event is triggered, the event handlers get executed. Essentially, it connects web pages to scripts or programming languages.

- -

Although the DOM is often accessed using JavaScript, it is not a part of the JavaScript language. It can also be accessed by other languages.

- -

An introduction to the DOM is available.

- -

DOM interfaces

- -
- -
- -

Obsolete DOM interfaces

- -

The Document Object Model has been highly simplified. To achieve this, the following interfaces present in the different DOM level 3 or earlier specification have been removed. It is still not very clear whether some may be reintroduced or not, but for the time being they have to be considered as obsolete and should be avoided:

- -
- -
- -

HTML interfaces

- -

A document containing HTML is described using the {{domxref("HTMLDocument")}} interface. Note that the HTML specification also extends the {{domxref("Document")}} interface.

- -

An HTMLDocument object also gives access to various features of browsers  like the tab or the window, in which a page is drawn using the {{domxref("Window")}} interface, the {{domxref("window.style", "Style")}} associated to it (usually CSS), the history of the browser relative to the context, {{domxref("window.history", "History")}}. Eventually, {{domxref("Selection")}} is done on the document.

- -

HTML element interfaces

- -
- -
- -

Other interfaces

- -
- -
- -

Obsolete HTML interfaces

- -
- -
- -

SVG interfaces

- -

SVG element interfaces

- -
- -
- -

SVG data type interfaces

- -

Here are the DOM API for data types used in the definitions of SVG properties and attributes.

- -
-

Note: Starting in {{Gecko("5.0")}}, the following SVG-related DOM interfaces representing lists of objects are now indexable and can be accessed ; in addition, they have a length property indicating the number of items in the lists: {{domxref("SVGLengthList")}}, {{domxref("SVGNumberList")}}, {{domxref("SVGPathSegList")}}, and {{domxref("SVGPointList")}}.

-
- -

Static type

- -
- -
- -

Animated type

- -
- -
- - - -
- -
- -

Other SVG interfaces

- -
- -
- -

See also

- - diff --git a/files/vi/web/api/document_object_model/introduction/index.html b/files/vi/web/api/document_object_model/introduction/index.html deleted file mode 100644 index 7a1ef163ee..0000000000 --- a/files/vi/web/api/document_object_model/introduction/index.html +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: Introduction to the DOM -slug: Web/API/Document_Object_Model/Introduction -translation_of: Web/API/Document_Object_Model/Introduction ---- -

Phần này cung cấp một giới thiệu khái niệm ngắn gọn về DOM: nó là gì, nó cung cấp cấu trúc cho HTML và XML như thế nào, bạn có thể truy cập nó thế nào, và API này trình bày thông tin và các ví dụ tham khảo.

- -

DOM là gì?

- -

The Document Object Model (DOM) là một giao diện lập trình cho tài liệu HTML và XML. Nó cung cấp đại diện cấu trúc của tài liệu và nó xác định con đường mà cấu trúc có thể được truy cập từ các chương trình để chúng có thể thay đổi cấu trúc, phong cách và nội dung tài liệu. DOM cung cấp một sự trình bày của tài liệu như một nhóm cấu trúc của các nút và đối tượng mà có các thuộc tính và phương thức. Về cơ bản, nó kết nối các trang web tới các đoạn mã hay các ngôn ngữ lập trình.

- -

Một trang Web là một tài liệu. Tài liệu này có thể hoặc là được hiển thị trong cửa sổ trình duyệt hoặc là như mã nguồn HTML. Nhưng nó cùng là tài liệu trong cả hai trường hợp. The Document Object Model (DOM) cung cấp cách khác để hiển thị, lưu trữ và thao tác cùng tài liệu. DOM là một đại diện hướng đối tượng hoàn toàn của trang web, và nó có thể được chỉnh sửa với một ngôn ngữ kịch bản như JavaScript.

- -

Các tiêu chuẩn W3C DOM và WHATWG DOM tạo thành nền tảng của DOM được thực hiện trong hầu hết các trình duyệt hiện đại . Nhiều trình duyệt cung cấp các mở rộng bên ngoài chuẩn, nên phải cẩn thận khi sử dụng chúng trên web nơi các tài liệu có thể được truy cập bởi các trình duyệt khác nhau với các DOM khác nhau.

- -

Ví dụ, DOM chuẩn quy định rằng phương thức getElementsByTagName trong code bên dưới phải trả về một danh sách của tất cả phần tử <p> trong tài liệu:

- -
var paragraphs = document.getElementsByTagName("P");
-// paragraphs[0] is the first <p> element
-// paragraphs[1] is the second <p> element, etc.
-alert(paragraphs[0].nodeName);
-
- -

Tất cả các thuộc tính, phương thức và sự kiện được sử dụng để thao tác và tạo ra các trang web được tổ chức dưới dạng các đối tượng (objects) (vd: đối tượng document đại diện cho trang tài liệu, đối tượng table kế thừa từ HTMLTableElement, một DOM interface đặc thù, cho phép truy cập HTML tables, v.v...). Phần này sẽ giới thiệu từng đối tượng DOM, được kế thừa trong các trình duyệt chạy trên nền Gecko.

- -

DOM and JavaScript

- -

The short example above, like nearly all of the examples in this reference, is JavaScript. That is to say, it's written in JavaScript, but it uses the DOM to access the document and its elements. The DOM is not a programming language, but without it, the JavaScript language wouldn't have any model or notion of web pages, HTML documents, XML documents, and their component parts (e.g. elements). Every element in a document—the document as a whole, the head, tables within the document, table headers, text within the table cells—is part of the document object model for that document, so they can all be accessed and manipulated using the DOM and a scripting language like JavaScript.

- -

In the beginning, JavaScript and the DOM were tightly intertwined, but eventually they evolved into separate entities. The page content is stored in the DOM and may be accessed and manipulated via JavaScript, so that we may write this approximative equation:

- -

API (HTML or XML page) = DOM + JS (scripting language)

- -

The DOM was designed to be independent of any particular programming language, making the structural representation of the document available from a single, consistent API. Though we focus exclusively on JavaScript in this reference documentation, implementations of the DOM can be built for any language, as this Python example demonstrates:

- -
# Python DOM example
-import xml.dom.minidom as m
-doc = m.parse("C:\\Projects\\Py\\chap1.xml");
-doc.nodeName # DOM property of document object;
-p_list = doc.getElementsByTagName("para");
-
- -

For more information on what technologies are involved in writing JavaScript on the web, see JavaScript technologies overview.

- -

How Do I Access the DOM?

- -

You don't have to do anything special to begin using the DOM. Different browsers have different implementations of the DOM, and these implementations exhibit varying degrees of conformance to the actual DOM standard (a subject we try to avoid in this documentation), but every web browser uses some document object model to make web pages accessible to script.

- -

When you create a script–whether it's inline in a <script> element or included in the web page by means of a script loading instruction–you can immediately begin using the API for the document or window elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page. Your DOM programming may be something as simple as the following, which displays an alert message by using the alert() function from the window object, or it may use more sophisticated DOM methods to actually create new content, as in the longer example below.

- -
<body onload="window.alert('Welcome to my home page!');">
-
- -

Aside from the <script> element in which the JavaScript is defined, this JavaScript sets a function to run when the document is loaded (and when the whole DOM is available for use). This function creates a new H1 element, adds text to that element, and then adds the H1 to the tree for this document:

- -
<html>
-  <head>
-    <script>
-       // run this function when the document is loaded
-       window.onload = function() {
-
-         // create a couple of elements in an otherwise empty HTML page
-         var heading = document.createElement("h1");
-         var heading_text = document.createTextNode("Big Head!");
-         heading.appendChild(heading_text);
-         document.body.appendChild(heading);
-      }
-    </script>
-  </head>
-  <body>
-  </body>
-</html>
-
- -

Important Data Types

- -

This reference tries to describe the various objects and types in as simple a way as possible. But there are a number of different data types being passed around the API that you should be aware of. For the sake of simplicity, syntax examples in this API reference typically refer to nodes as elements, to arrays of nodes as nodeLists (or simply elements), and to attribute nodes simply as attributes.

- -

The following table briefly describes these data types.

- - - - - - - - - - - - - - - - - - - - - - - - -
documentWhen a member returns an object of type document (e.g., the ownerDocument property of an element returns the document to which it belongs), this object is the root document object itself. The DOM document Reference chapter describes the document object.
elementelement refers to an element or a node of type element returned by a member of the DOM API. Rather than saying, for example, that the document.createElement() method returns an object reference to a node, we just say that this method returns the element that has just been created in the DOM. element objects implement the DOM Element interface and also the more basic Node interface, both of which are included together in this reference.
nodeListA nodeList is an array of elements, like the kind that is returned by the method document.getElementsByTagName(). Items in a nodeList are accessed by index in either of two ways: -
    -
  • list.item(1)
  • -
  • list[1]
  • -
- These two are equivalent. In the first, item() is the single method on the nodeList object. The latter uses the typical array syntax to fetch the second item in the list.
attributeWhen an attribute is returned by a member (e.g., by the createAttribute() method), it is an object reference that exposes a special (albeit small) interface for attributes. Attributes are nodes in the DOM just like elements are, though you may rarely use them as such.
namedNodeMapA namedNodeMap is like an array, but the items are accessed by name or index, though this latter case is merely a convenience for enumeration, as they are in no particular order in the list. A namedNodeMap has an item() method for this purpose, and you can also add and remove items from a namedNodeMap.
- -

DOM interfaces

- -

This guide is about the objects and the actual things you can use to manipulate the DOM hierarchy. There are many points where understanding how these work can be confusing. For example, the object representing the HTML form element gets its name property from the HTMLFormElement interface but its className property from the HTMLElement interface proper. In both cases, the property you want is simply in that form object.

- -

But the relationship between objects and the interfaces that they implement in the DOM can be confusing, and so this section attempts to say a little something about the actual interfaces in the DOM specification and how they are made available.

- -

Interfaces and Objects

- -

Many objects borrow from several different interfaces. The table object, for example, implements a specialized HTML Table Element Interface, which includes such methods as createCaption and insertRow. But since it's also an HTML element, table implements the Element interface described in the DOM element Reference chapter. And finally, since an HTML element is also, as far as the DOM is concerned, a node in the tree of nodes that make up the object model for an HTML or XML page, the table element also implements the more basic Node interface, from which Element derives.

- -

When you get a reference to a table object, as in the following example, you routinely use all three of these interfaces interchangeably on the object, perhaps without knowing it.

- -
var table = document.getElementById("table");
-var tableAttrs = table.attributes; // Node/Element interface
-for (var i = 0; i < tableAttrs.length; i++) {
-  // HTMLTableElement interface: border attribute
-  if(tableAttrs[i].nodeName.toLowerCase() == "border")
-    table.border = "1";
-}
-// HTMLTableElement interface: summary attribute
-table.summary = "note: increased border";
-
- -

Core Interfaces in the DOM

- -

This section lists some of the most commonly-used interfaces in the DOM. The idea is not to describe what these APIs do here but to give you an idea of the sorts of methods and properties you will see very often as you use the DOM. These common APIs are used in the longer examples in the DOM Examples chapter at the end of this book.

- -

Document and window objects are the objects whose interfaces you generally use most often in DOM programming. In simple terms, the window object represents something like the browser, and the document object is the root of the document itself. Element inherits from the generic Node interface, and together these two interfaces provide many of the methods and properties you use on individual elements. These elements may also have specific interfaces for dealing with the kind of data those elements hold, as in the table object example in the previous section.

- -

The following is a brief list of common APIs in web and XML page scripting using the DOM.

- - - -

Testing the DOM API

- -

This document provides samples for every interface that you can use in your own web development. In some cases, the samples are complete HTML pages, with the DOM access in a <script> element, the interface (e.g, buttons) necessary to fire up the script in a form, and the HTML elements upon which the DOM operates listed as well. When this is the case, you can cut and paste the example into a new HTML document, save it, and run the example from the browser.

- -

There are some cases, however, when the examples are more concise. To run examples that only demonstrate the basic relationship of the interface to the HTML elements, you may want to set up a test page in which interfaces can be easily accessed from scripts. The following very simple web page provides a <script> element in the header in which you can place functions that test the interface, a few HTML elements with attributes that you can retrieve, set, or otherwise manipulate, and the web user interface necessary to call those functions from the browser.

- -

You can use this test page or create a similar one to test the DOM interfaces you are interested in and see how they work on the browser platform. You can update the contents of the test() function as needed, create more buttons, or add elements as necessary.

- -
<html>
-  <head>
-    <title>DOM Tests</title>
-    <script type="application/javascript">
-    function setBodyAttr(attr, value){
-      if (document.body) eval('document.body.'+attr+'="'+value+'"');
-      else notSupported();
-    }
-    </script>
-  </head>
-  <body>
-    <div style="margin: .5in; height: 400;">
-      <p><b><tt>text</tt></b></p>
-      <form>
-        <select onChange="setBodyAttr('text',
-        this.options[this.selectedIndex].value);">
-          <option value="black">black
-          <option value="darkblue">darkblue
-        </select>
-        <p><b><tt>bgColor</tt></b></p>
-        <select onChange="setBodyAttr('bgColor',
-        this.options[this.selectedIndex].value);">
-          <option value="white">white
-          <option value="lightgrey">gray
-        </select>
-        <p><b><tt>link</tt></b></p>
-        <select onChange="setBodyAttr('link',
-        this.options[this.selectedIndex].value);">
-          <option value="blue">blue
-          <option value="green">green
-        </select>  <small>
-        <a href="http://www.brownhen.com/dom_api_top.html" id="sample">
-        (sample link)</a></small><br>
-      </form>
-      <form>
-        <input type="button" value="version" onclick="ver()" />
-      </form>
-    </div>
-  </body>
-</html>
-
- -

To test a lot of interfaces in a single page-for example, a "suite" of properties that affect the colors of a web page-you can create a similar test page with a whole console of buttons, textfields, and other HTML elements. The following screenshot gives you some idea of how interfaces can be grouped together for testing.

- -
-
Figure 0.1 Sample DOM Test Page
-Image:DOM_Ref_Introduction_to_the_DOM.gif
- -

In this example, the dropdown menus dynamically update such DOM-accessible aspects of the web page as its background color (bgColor), the color of the hyperlinks (aLink), and color of the text (text). However you design your test pages, testing the interfaces as you read about them is an important part of learning how to use the DOM effectively.

- - - - diff --git a/files/vi/web/api/eventsource/index.html b/files/vi/web/api/eventsource/index.html deleted file mode 100644 index 36a35382dd..0000000000 --- a/files/vi/web/api/eventsource/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: EventSource -slug: Web/API/EventSource -tags: - - API - - Communications - - EventSource - - Interface - - NeedsTranslation - - Reference - - Server Sent Events - - Server-sent events - - TopicStub - - messaging -translation_of: Web/API/EventSource ---- -
{{APIRef("Server Sent Events")}}
- -

The EventSource interface is web content's interface to server-sent events. An EventSource instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format. The connection remains open until closed by calling {{domxref("EventSource.close()")}}.

- -

Once the connection is opened, incoming messages from the server are delivered to your code in the form of {{event("message")}} events.

- -

Unlike WebSockets, server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). That makes them an excellent choice when there's no need to send data from the client to the server in message form. For example, EventSource is a useful approach for handling things like social media status updates, news feeds, or delivering data into a client-side storage mechanism like IndexedDB or web storage.

- -

Constructor

- -
-
{{domxref("EventSource.EventSource", "EventSource()")}}
-
Creates a new EventSource to handle receiving server-sent events from a specified URL, optionally in credentials mode.
-
- -

Properties

- -

This interface also inherits properties from its parent, {{domxref("EventTarget")}}.

- -
-
{{domxref("EventSource.readyState")}} {{readonlyinline}}
-
A number representing the state of the connection. Possible values are CONNECTING (0), OPEN (1), or CLOSED (2).
-
{{domxref("EventSource.url")}} {{readonlyinline}}
-
A {{domxref("DOMString")}} representing the URL of the source.
-
{{domxref("EventSource.withCredentials")}} {{readonlyinline}}
-
A {{domxref("Boolean")}} indicating whether the EventSource object was instantiated with cross-origin (CORS) credentials set (true), or not (false, the default).
-
- -

Event handlers

- -
-
{{domxref("EventSource.onerror")}}
-
Is an {{domxref("EventHandler")}} called when an error occurs and the {{domxref("EventSource/error_event", "error")}} event is dispatched on an EventSource object.
-
{{domxref("EventSource.onmessage")}}
-
Is an {{domxref("EventHandler")}} called when a {{domxref("EventSource/message_event", "message")}} event is received, that is when a message is coming from the source.
-
{{domxref("EventSource.onopen")}}
-
Is an {{domxref("EventHandler")}} called when an {{domxref("EventSource/open_event", "open")}} event is received, that is when the connection was just opened.
-
- -

Methods

- -

This interface also inherits methods from its parent, {{domxref("EventTarget")}}.

- -
-
{{domxref("EventSource.close()")}}
-
Closes the connection, if any, and sets the readyState attribute to CLOSED. If the connection is already closed, the method does nothing.
-
- -

Events

- -
-
{{domxref("EventSource/error_event", "error")}}
-
Fired when a connection to an event source failed to open.
-
{{domxref("EventSource/message_event", "message")}}
-
Fired when data is received from an event source.
-
{{domxref("EventSource/open_event", "open")}}
-
Fired when a connection to an event source has opened.
-
- -

Examples

- -

In this basic example, an EventSource is created to receive events from the server; a page with the name sse.php is responsible for generating the events.

- -
var evtSource = new EventSource('sse.php');
-var eventList = document.querySelector('ul');
-
-evtSource.onmessage = function(e) {
-  var newElement = document.createElement("li");
-
-  newElement.textContent = "message: " + e.data;
-  eventList.appendChild(newElement);
-}
- -

Each received event causes our EventSource object's onmessage event handler to be run. It, in turn, creates a new {{HTMLElement("li")}} element and writes the message's data into it, then appends the new element to the list element already in the document.

- -
-

Note: You can find a full example on GitHub — see Simple SSE demo using PHP.

-
- -

Specifications

- - - - - - - - - - - - -
SpecificationStatus
{{SpecName('HTML WHATWG', "comms.html#the-eventsource-interface", "EventSource")}}{{Spec2('HTML WHATWG')}}
- - - -

Browser compatibility

- -
- - -

{{Compat("api.EventSource")}}

-
- -

See also

- - diff --git a/files/vi/web/api/eventsource/url/index.html b/files/vi/web/api/eventsource/url/index.html deleted file mode 100644 index 2af6554db0..0000000000 --- a/files/vi/web/api/eventsource/url/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: EventSource.url -slug: Web/API/EventSource/url -translation_of: Web/API/EventSource/url ---- -
{{APIRef('WebSockets API')}}
- -

url là thuộc tính chỉ đọc của giao diện {{domxref("EventSource")}} trả về {{domxref("DOMString")}} đại diện cho URL của nguồn.

- -

Cú pháp

- -
var myUrl = eventSource.url;
- -

Giá trị

- -

{{domxref("DOMString")}} đại diện cho URL của nguồn.

- -

Ví dụ

- -
var evtSource = new EventSource('sse.php');
-console.log(evtSource.url);
- -
-

Ghi chú: bạn có thể xem ví dụ đầy đủ trên GitHub — xem Simple SSE demo using PHP.

-
- -

Thông số kĩ thuật

- - - - - - - - - - - - - - -
Thông số kĩ thuậtTrạng tháiChú thích
{{SpecName('HTML WHATWG', "comms.html#dom-eventsource-url", "url")}}{{Spec2('HTML WHATWG')}}Định nghĩa ban đầu
- - - -

Trình duyệt tương thích

- -
- - -

{{Compat("api.EventSource.url")}}

-
- -

Liên quan

- - diff --git a/files/vi/web/api/fetch_api/index.html b/files/vi/web/api/fetch_api/index.html deleted file mode 100644 index cc728a4eb1..0000000000 --- a/files/vi/web/api/fetch_api/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Fetch API -slug: Web/API/Fetch_API -translation_of: Web/API/Fetch_API ---- -
{{DefaultAPISidebar("Fetch API")}}
- -

The Fetch API cung cấp giao diện để tìm nạp tài nguyên (bao gồm thông qua mạng). It will seem familiar to anyone who has used {{DOMxRef("XMLHttpRequest")}}, but the new API provides a more powerful and flexible feature set.

- -

Concepts and usage

- -

Fetch cung cấp một định nghĩa chung về các đối tượng {{DOMxRef("Request")}} and {{DOMxRef("Response")}} (và mọi thứ khác liên quan đến các request network). Điều này cho phép chúng được sử dụng ở bất cứ nơi nào cần chúng trong tương lai, cho dù đó là service workers, Cache API, và những thứ tương tự khác mà có khả năng xử lý hoặc sửa đổi các request và responses, hoặc bất kỳ trường hợp nào mà yêu cầu bạn tự tạo ra responses trong chương trình của chính mình.

- -

Nó cũng cung cấp một định nghĩa cho các khái niệm liên quan như CORS and the HTTP Header, thay thế các định nghĩa riêng biệt của chúng ở nơi khác.

- -

Để thực hiện một request và tìm nạp tài nguyên, use the {{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}} method. Nó được triển khai trong nhiều interfaces, đặc biệt là {{DOMxRef("Window")}} và {{DOMxRef("WorkerGlobalScope")}}. Điều này làm cho nó có sẵn trong hầu hết mọi ngữ cảnh mà bạn có thể muốn tìm nạp tài nguyên.

- -

The fetch() method có một đối số bắt buộc, đó chính là đường dẫn đến tài nguyên bạn tìm nạp. Nó returns a {{DOMxRef("Promise")}} thứ mà sẽ giải quyết và đưa ra một {{DOMxRef("Response")}} cho request đó, bất kể là thành công hay thất bại. Bạn có thể tùy chỉnh việc truyền một đối tượng tùy chỉnh init như là một đối số thữ hai (see {{DOMxRef("Request")}}).

- -

Cho đến khi một {{DOMxRef("Response")}} được truy xuất, có một số methods có sẵn để xác định nội dung body là gì và cách nó được xử lý như thế nào. (see {{DOMxRef("Body")}}).

- -

Bạn có thể tạo ra một request và response trực tiếp bằng cách sử dụng {{DOMxRef("Request.Request", "Request()")}} và {{DOMxRef("Response.Response", "Response()")}} constructors, nhưng cách làm này là không phổ biến. Thay vào đó, những thứ này có thể được tạo ra bằng cách là kết quả trả về của các hành động API khác (ví dụ, {{DOMxRef("FetchEvent.respondWith()")}} from service workers).

- -

Differences from jQuery

- -

The fetch khác với jQuery.ajax() in ba điểm chính sau:

- - - -
-

Note: Tìm hiểu thêm về cách sử dụng Fetch API tại Using Fetch, và học các khái niệm tại  Fetch basic concepts.

-
- -

Huỷ bỏ fetch

- -

Browsers have started to add experimental support for the {{DOMxRef("AbortController")}} and {{DOMxRef("AbortSignal")}} interfaces (aka The Abort API), which allow operations like Fetch and XHR to be aborted if they have not already completed. See the interface pages for more details.

- -

Fetch Interfaces

- -
-
{{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}}
-
The fetch() method được sử dụng để tìm nạp tài nguyên.
-
{{DOMxRef("Headers")}}
-
Đại diện cho các response/request headers, cho phép bạn truy vấn chúng and thực hiện các hành động khác nhau phụ thuộc vào các kết quả..
-
{{DOMxRef("Request")}}
-
Đại điện cho một request tài nguyên.
-
{{DOMxRef("Response")}}
-
Đại điện cho một Response của một Request.
-
- -

Fetch mixin

- -
-
{{DOMxRef("Body")}}
-
Cung cấp các methods liên quan đến body của response/request, cho phép bạn khai báo kiểu nội dung của chúng và cách chúng được xử lý.
-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("Fetch")}}{{Spec2("Fetch")}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

- -

See also

- - diff --git a/files/vi/web/api/file/index.html b/files/vi/web/api/file/index.html deleted file mode 100644 index 3722df4e46..0000000000 --- a/files/vi/web/api/file/index.html +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: File -slug: Web/API/File -tags: - - API - - File API - - Interface - - Reference - - Web -translation_of: Web/API/File ---- -
{{APIRef}}
- -

File cung cấp thông tin về các tệp và cho phép Javascript truy cập nội dung của chúng.

- -

File thường được lấy từ một {{DOMxRef("FileList")}} đối tượng trả về như là kết quả của người dùng chọn files sử dụng phần tử {{HTMLElement("input")}}, từ thao tác kéo và thả đối tượng {{DOMxRef("DataTransfer")}}, hoặc là từ mozGetAsFile() API trên một {{DOMxRef("HTMLCanvasElement")}}.

- -

Đối tượng file là một loại {{DOMxRef("Blob")}}, và có thể sử dụng trong mọi hoàn cảnh mà Blob có thể sử dụng. Cụ thể, {{DOMxRef("FileReader")}}, {{DOMxRef("URL.createObjectURL()")}}, {{DOMxRef("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}}, và {{DOMxRef("XMLHttpRequest", "", "send()")}} chấp nhận cả Blobs và Files.

- -

Đọc Using files from web applications để biết thêm thông tin và ví dụ.

- -

{{InheritanceDiagram}}

- -

Constructor

- -
-
{{DOMxRef("File.File", "File()")}}
-
Trả về một constructed File mới.
-
- -

Thuộc tính

- -
-
{{DOMxRef("File.lastModified")}} {{ReadOnlyInline}}
-
Trả về thời gian sửa đổi cuối cùng của file, tính bằng mili giây kể từ kỉ nguyên UNIX (January 1st, 1970 at Midnight).
-
{{DOMxRef("File.lastModifiedDate")}} {{Deprecated_Inline}} {{ReadOnlyInline}}
-
Returns the last modified {{JSxRef("Date")}} of the file referenced by the File object.
-
{{DOMxRef("File.name")}}{{ReadOnlyInline}}
-
Trả về tên của tệp referenced by the File object.
-
{{DOMxRef("File.webkitRelativePath")}} {{Non-standard_Inline}} {{ReadOnlyInline}}
-
Trả về đường dẫn (URL) của {{DOMxRef("File")}} có liên quan.
-
- -

File bổ sung {{DOMxRef("Blob")}}, Vì vậy, nó cũng có các thuộc tính có sẵn:

- -
-
{{DOMxRef("File.size")}} {{ReadOnlyInline}}
-
Trả về kích thước của file (tính bằng bytes)
-
{{DOMxRef("File.type")}} {{ReadOnlyInline}}
-
Trả về thể loại MIME của file file.
-
- -

Phương thức

- -

File không có phương thức nào, nhưng nó thừa kế từ {{DOMxRef("Blob")}}:

- -
-
{{DOMxRef("Blob.slice()", "Blob.slice([start[, end[, contentType]]])")}}
-
Trả về một đối tượng Blob mới có nội dung trong phạm vi bytes chỉ định của Blob
-
{{DOMxRef("Blob.stream()")}}
-
Chuyển đổi file thành {{DOMxRef("ReadableStream")}} vì vậy có thể sử dụng để đọc nội dung file.
-
{{DOMxRef("Blob.text()")}}
-
Chuyển đổi file thành stream và đọc nó để hoàn thành. Nó trả về một promise có thể giải quyết với {{DOMxRef("USVString")}} (text).
-
{{DOMxRef("Blob.arrayBuffer()")}}
-
Chuyển đổi file thành stream và đọc nó để hoàn thành. Nó trả về một promise có thể giải quyết với {{DOMxRef("ArrayBuffer")}}.
-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('File API', "#file-section", "The File interface")}}{{Spec2('File API')}}Initial definition.
- -

Browser compatibility

- - - -

{{Compat("api.File")}}

- -

Xem thêm

- - diff --git a/files/vi/web/api/geolocation_api/index.html b/files/vi/web/api/geolocation_api/index.html deleted file mode 100644 index 0286a06249..0000000000 --- a/files/vi/web/api/geolocation_api/index.html +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Geolocation API -slug: Web/API/Geolocation_API -translation_of: Web/API/Geolocation_API ---- -

{{securecontext_header}} {{APIRef("API định vị địa lý")}}

- -

Các API Định vị cho phép người dùng để cung cấp vị trí của họ vào các ứng dụng web nếu họ mong muốn. Vì lý do riêng tư, người dùng được yêu cầu cho phép báo cáo thông tin vị trí.

- -

Đối tượng định vị địa lý

- -

Các Định vị API được công bố thông qua {{domxref( "navigator.geolocation")}} đối tượng.

- -

Nếu đối tượng tồn tại, dịch vụ định vị địa lý có sẵn. Do đó, bạn có thể kiểm tra sự hiện diện của vị trí địa lý:

- -
if ("geolocation" in navigator) {
-  / * định vị địa lý có sẵn * /
-} else {
-  / * định vị địa lý KHÔNG có sẵn * /
-}
-
- -
-

Lưu ý: Trên Firefox 24 và các phiên bản cũ hơn, "geolocation" in navigatorluôn được trả về truengay cả khi API bị tắt. Điều này đã được sửa với Firefox 25 để tuân thủ thông số kỹ thuật. ({{bug(884921)}}).

-
- -

Lấy vị trí hiện tại

- -

Để có được vị trí hiện tại của người dùng, bạn có thể gọi phương thức {{domxref("geolocation.getCurrentPosition()", "getCurrentPosition()")}}. Điều này bắt đầu một yêu cầu không đồng bộ để phát hiện vị trí của người dùng và truy vấn phần cứng định vị để có được thông tin cập nhật. Khi vị trí được xác định, chức năng gọi lại được xác định sẽ được thực thi. Bạn có thể tùy chọn cung cấp chức năng gọi lại thứ hai để được thực thi nếu xảy ra lỗi. Tham số thứ ba, tùy chọn, là một đối tượng tùy chọn trong đó bạn có thể đặt tuổi tối đa của vị trí được trả về, thời gian chờ yêu cầu và nếu bạn muốn độ chính xác cao cho vị trí.

- -
-

Lưu ý: Theo mặc định, {{domxref("Geolocation.getCurrentPosition ()", "getCurrentPosition()")}} cố gắng trả lời nhanh nhất có thể với kết quả chính xác thấp. Nó rất hữu ích nếu bạn cần một câu trả lời nhanh bất kể độ chính xác. Chẳng hạn, các thiết bị có GPS có thể mất một phút hoặc hơn để sửa lỗi GPS, do đó, dữ liệu kém chính xác hơn(vị trí IP hoặc wifi) có thể được trả về {{domxref("Geolocation.getCurrentPosition()", "getCurrentPosition() ")}}.

-
- -
navigator.geolocation.getCurrentPosition(function(position) {
-  do_something(location.coords.latitude, location.coords.longitude);
-});
- -

Ví dụ trên sẽ khiến do_something()hàm thực thi khi lấy được vị trí.

- -

Xem vị trí hiện tại

- -

Nếu dữ liệu vị trí thay đổi (theo chuyển động của thiết bị hoặc nếu có thông tin địa lý chính xác hơn), bạn có thể thiết lập chức năng gọi lại được gọi với thông tin vị trí được cập nhật đó. Điều này được thực hiện bằng cách sử dụng hàm {{domxref("Geolocation.watchPocation ()", "watchPosition()")}}, có cùng tham số đầu vào như {{domxref("Geolocation.getCurrentPosition()", "getCurrentPosition() ")}}. Chức năng gọi lại được gọi nhiều lần, cho phép trình duyệt cập nhật vị trí của bạn khi bạn di chuyển hoặc cung cấp vị trí chính xác hơn vì các kỹ thuật khác nhau được sử dụng để định vị địa lý cho bạn. Hàm gọi lại lỗi, là tùy chọn giống như đối với {{domxref("Geolocation.getCurrentPosition()", "getCurrentPosition()")}}, có thể được gọi lặp lại.

- -
-

Lưu ý: Bạn có thể sử dụng {{domxref("Geolocation.watchPosition()", "watchPosition()")}} mà không cần một cuộc gọi {{domxref("Geolocation.getCienPocation ()", "getCienPocation ()")}}.

-
- -
var watchID = navigator.geolocation.watchPosition(function(location) {
-  do_something(location.coords.latitude, location.coords.longitude);
-});
- -

Phương thức {{domxref("Geolocation.watchPosition()", "watchPosition()")}} trả về số ID có thể được sử dụng để xác định duy nhất trình theo dõi vị trí được yêu cầu; bạn sử dụng giá trị này song song với phương thức {{domxref("Geolocation.clearWatch()", "clearWatch()")}} để dừng xem vị trí của người dùng.

- -
navigator.geolocation.clearWatch(watchID);
-
- -

Phản ứng tinh chỉnh

- -

Both {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("Geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional PositionOptions object.

- -

{{page("/en-US/docs/DOM/navigator.geolocation.getCurrentPosition","PositionOptions")}}

- -

A call to {{domxref("Geolocation.watchPosition()","watchPosition")}} could look like:

- -
function geo_success(position) {
-  do_something(position.coords.latitude, position.coords.longitude);
-}
-
-function geo_error() {
-  alert("Sorry, no position available.");
-}
-
-var geo_options = {
-  enableHighAccuracy: true,
-  maximumAge        : 30000,
-  timeout           : 27000
-};
-
-var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
- -

Describing a position

- -

The user's location is described using a {{domxref("Position")}} object referencing a {{domxref("Coordinates")}} object.

- -

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Position")}}

- -

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Coordinates")}}

- -

Handling errors

- -

The error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a PositionError object as its first parameter.

- -
function errorCallback(error) {
-  alert('ERROR(' + error.code + '): ' + error.message);
-};
-
- -

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","PositionError")}}

- -

Geolocation Live Example

- - - -

HTML Content

- -
<button id = "find-me">Show my location</button><br/>
-<p id = "status"></p>
-<a id = "map-link" target="_blank"></a>
-
- -

JavaScript Content

- -
function geoFindMe() {
-
-  const status = document.querySelector('#status');
-  const mapLink = document.querySelector('#map-link');
-
-  mapLink.href = '';
-  mapLink.textContent = '';
-
-  function success(position) {
-    const latitude  = position.coords.latitude;
-    const longitude = position.coords.longitude;
-
-    status.textContent = '';
-    mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
-    mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
-  }
-
-  function error() {
-    status.textContent = 'Unable to retrieve your location';
-  }
-
-  if (!navigator.geolocation) {
-    status.textContent = 'Geolocation is not supported by your browser';
-  } else {
-    status.textContent = 'Locating…';
-    navigator.geolocation.getCurrentPosition(success, error);
-  }
-
-}
-
-document.querySelector('#find-me').addEventListener('click', geoFindMe);
-
- -

Live Result

- -

{{EmbedLiveSample('Geolocation_Live_Example', 350, 150, "", "", "", "geolocation")}}

- -

Prompting for permission

- -

Any add-on hosted on addons.mozilla.org which makes use of geolocation data must explicitly request permission before doing so. The following function will request permission in a manner similar to the automatic prompt displayed for web pages. The user's response will be saved in the preference specified by the pref parameter, if applicable. The function provided in the callback parameter will be called with a boolean value indicating the user's response. If true, the add-on may access geolocation data.

- -
function prompt(window, pref, message, callback) {
-    let branch = Components.classes["@mozilla.org/preferences-service;1"]
-                           .getService(Components.interfaces.nsIPrefBranch);
-
-    if (branch.getPrefType(pref) === branch.PREF_STRING) {
-        switch (branch.getCharPref(pref)) {
-        case "always":
-            return callback(true);
-        case "never":
-            return callback(false);
-        }
-    }
-
-    let done = false;
-
-    function remember(value, result) {
-        return function() {
-            done = true;
-            branch.setCharPref(pref, value);
-            callback(result);
-        }
-    }
-
-    let self = window.PopupNotifications.show(
-        window.gBrowser.selectedBrowser,
-        "geolocation",
-        message,
-        "geo-notification-icon",
-        {
-            label: "Share Location",
-            accessKey: "S",
-            callback: function(notification) {
-                done = true;
-                callback(true);
-            }
-        }, [
-            {
-                label: "Always Share",
-                accessKey: "A",
-                callback: remember("always", true)
-            },
-            {
-                label: "Never Share",
-                accessKey: "N",
-                callback: remember("never", false)
-            }
-        ], {
-            eventCallback: function(event) {
-                if (event === "dismissed") {
-                    if (!done) callback(false);
-                    done = true;
-                    window.PopupNotifications.remove(self);
-                }
-            },
-            persistWhileVisible: true
-        });
-}
-
-prompt(window,
-       "extensions.foo-addon.allowGeolocation",
-       "Foo Add-on wants to know your location.",
-       function callback(allowed) { alert(allowed); });
-
- -

Browser compatibility

- -

{{Compat("api.Geolocation")}}

- -

khả dụng

- -

Vì định vị dựa trên WiFi thường được cung cấp bởi Google, API định vị vanilla có thể không khả dụng ở Trung Quốc. Bạn có thể sử dụng các nhà cung cấp bên thứ ba địa phương như Baidu , Autonavi hoặc Tencent . Các dịch vụ này sử dụng địa chỉ IP của người dùng và / hoặc ứng dụng cục bộ để cung cấp định vị nâng cao.

- -

Xem thêm

- - diff --git a/files/vi/web/api/htmlcanvaselement/getcontext/index.html b/files/vi/web/api/htmlcanvaselement/getcontext/index.html deleted file mode 100644 index b2478fba5d..0000000000 --- a/files/vi/web/api/htmlcanvaselement/getcontext/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: HTMLCanvasElement.getContext() -slug: Web/API/HTMLCanvasElement/getContext -tags: - - TV -translation_of: Web/API/HTMLCanvasElement/getContext ---- -
{{APIRef("Canvas API")}}
- -

The HTMLCanvasElement.getContext() method returns a drawing context on the canvas, or {{jsxref("null")}} if the context identifier is not supported.

- -

Later calls to this method on the same canvas element return the same drawing context instance as was returned the last time the method was invoked with the same contextType argument. To get a different drawing context object you need to pass a different contextType or call the method on a different canvas element. 

- -

Syntax

- -
var ctx = canvas.getContext(contextType);
-var ctx = canvas.getContext(contextType, contextAttributes);
-
- -

Parameters

- -
-
contextType
-
Is a {{domxref("DOMString")}} containing the context identifier defining the drawing context associated to the canvas. Possible values are: -
    -
  • "2d", leading to the creation of a {{domxref("CanvasRenderingContext2D")}} object representing a two-dimensional rendering context.
  • -
  • "webgl" (or "experimental-webgl") which will create a {{domxref("WebGLRenderingContext")}} object representing a three-dimensional rendering context. This context is only available on browsers that implement WebGL version 1 (OpenGL ES 2.0).
  • -
  • "webgl2" which will create a {{domxref("WebGL2RenderingContext")}} object representing a three-dimensional rendering context. This context is only available on browsers that implement WebGL version 2 (OpenGL ES 3.0). {{experimental_inline}}
  • -
  • "bitmaprenderer" which will create an {{domxref("ImageBitmapRenderingContext")}} which only provides functionality to replace the content of the canvas with a given {{domxref("ImageBitmap")}}.
  • -
- -
-

Note: The identifier "experimental-webgl" is used in new implementations of WebGL. These implementations have either not reached test suite conformance, or the graphics drivers on the platform are not yet stable. The Khronos Group certifies WebGL implementations under certain conformance rules.

-
-
-
contextAttributes
-
-

You can use several context attributes when creating your rendering context, for example:

- -
const gl = canvas.getContext('webgl', {
-  antialias: false,
-  depth: false
-});
- 2d context attributes: - -
    -
  • alpha: Boolean that indicates if the canvas contains an alpha channel. If set to false, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images.
  • -
  • {{non-standard_inline}} (Gecko only) willReadFrequently: Boolean that indicates whether or not a lot of read-back operations are planned. This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}} frequently. This option is only available, if the flag gfx.canvas.willReadFrequently.enable is set to true (which, by default, is only the case for B2G/Firefox OS).
  • -
  • {{non-standard_inline}} (Blink only) storage: String that indicates which storage is used ("persistent" by default).
  • -
- WebGL context attributes: - -
    -
  • alpha: Boolean that indicates if the canvas contains an alpha buffer.
  • -
  • antialias: Boolean that indicates whether or not to perform anti-aliasing.
  • -
  • depth: Boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits.
  • -
  • failIfMajorPerformanceCaveat: Boolean that indicates if a context will be created if the system performance is low.
  • -
  • powerPreference: A hint to the user agent indicating what configuration of GPU is suitable for the WebGL context. Possible values are: -
      -
    • "default": Let the user agent decide which GPU configuration is most suitable. This is the default value.
    • -
    • "high-performance": Prioritizes rendering performance over power consumption.
    • -
    • "low-power": Prioritizes power saving over rendering performance.
    • -
    -
  • -
  • premultipliedAlpha: Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha.
  • -
  • preserveDrawingBuffer: If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author.
  • -
  • stencil: Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits.
  • -
-
-
- -

Return value

- -

A {{domxref("RenderingContext")}} which is either a

- - - -

If the contextType doesn't match a possible drawing context, null is returned.

- -

Examples

- -

Given this {{HTMLElement("canvas")}} element:

- -
<canvas id="canvas" width="300" height="300"></canvas>
-
- -

You can get a 2d context of the canvas with the following code:

- -
var canvas = document.getElementById('canvas');
-var ctx = canvas.getContext('2d');
-console.log(ctx); // CanvasRenderingContext2D { ... }
-
- -

Now you have the 2D rendering context for a canvas and you can draw within it.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "semantics-scripting.html#dom-htmlcanvaselement-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
- -

Browser compatibility

- - - -

{{Compat("api.HTMLCanvasElement.getContext")}}

- -

See also

- - diff --git a/files/vi/web/api/htmlcanvaselement/index.html b/files/vi/web/api/htmlcanvaselement/index.html deleted file mode 100644 index 50b2592322..0000000000 --- a/files/vi/web/api/htmlcanvaselement/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: HTMLCanvasElement -slug: Web/API/HTMLCanvasElement -tags: - - API - - Canvas - - HTML DOM - - Interface - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/API/HTMLCanvasElement ---- -
-
{{APIRef("Canvas API")}}
-
- -

The HTMLCanvasElement interface provides properties and methods for manipulating the layout and presentation of {{HtmlElement("canvas")}} elements. The HTMLCanvasElement interface also inherits the properties and methods of the {{domxref("HTMLElement")}} interface.

- -

{{InheritanceDiagram(600, 120)}}

- -

Properties

- -

Inherits properties from its parent, {{domxref("HTMLElement")}}.

- -
-
{{domxref("HTMLCanvasElement.height")}}
-
Is a positive integer reflecting the {{htmlattrxref("height", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 150 is used.
-
{{domxref("HTMLCanvasElement.width")}}
-
Is a positive integer reflecting the {{htmlattrxref("width", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 300 is used.
-
{{domxref("HTMLCanvasElement.mozOpaque")}} {{non-standard_inline}} {{deprecated_inline}}
-
Is a {{jsxref("Boolean")}} reflecting the {{htmlattrxref("moz-opaque", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element. It lets the canvas know whether or not translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized. This is only supported in Mozilla-based browsers; use the standardized {{domxref("HTMLCanvasElement.getContext()", "canvas.getContext('2d', { alpha: false })")}} instead.
-
{{domxref("HTMLCanvasElement.mozPrintCallback")}}{{non-standard_inline}}
-
Is a function that is Initially null. Web content can set this to a JavaScript function that will be called when the canvas is to be redrawn while the page is being printed. When called, the callback is passed a "printState" object that implements the MozCanvasPrintState interface. The callback can get the context to draw to from the printState object and must then call done() on it when finished. The purpose of mozPrintCallback is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. See this blog post.
-
- -

Methods

- -

Inherits methods from its parent, {{domxref("HTMLElement")}}.

- -
-
{{domxref("HTMLCanvasElement.captureStream()")}} {{experimental_inline}}
-
Returns a {{domxref("CanvasCaptureMediaStream")}} that is a real-time video capture of the surface of the canvas.
-
{{domxref("HTMLCanvasElement.getContext()")}}
-
Returns a drawing context on the canvas, or null if the context ID is not supported. A drawing context lets you draw on the canvas. Calling getContext with "2d" returns a {{domxref("CanvasRenderingContext2D")}} object, whereas calling it with "webgl" (or "experimental-webgl") returns a {{domxref("WebGLRenderingContext")}} object. This context is only available on browsers that implement WebGL.
-
{{domxref("HTMLCanvasElement.toDataURL()")}}
-
Returns a data-URL containing a representation of the image in the format specified by the type parameter (defaults to png). The returned image is in a resolution of 96dpi.
-
{{domxref("HTMLCanvasElement.toBlob()")}}
-
Creates a {{domxref("Blob")}} object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.
-
{{domxref("HTMLCanvasElement.transferControlToOffscreen()")}} {{experimental_inline}}
-
Transfers control to an {{domxref("OffscreenCanvas")}} object, either on the main thread or on a worker.
-
{{domxref("HTMLCanvasElement.mozGetAsFile()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Returns a {{domxref("File")}} object representing the image contained in the canvas; this file is a memory-based file, with the specified name. If type is not specified, the image type is image/png.
-
- -

Events

- -

Listen to these events using addEventListener().

- -
-
webglcontextcreationerror
-
Fired if the user agent is unable to create a WebGLRenderingContext or WebGL2RenderingContext context.
-
webglcontextlost
-
Fired if the user agent detects that the drawing buffer associated with a WebGLRenderingContext or WebGL2RenderingContext object has been lost.
-
webglcontextrestored
-
Fired if the user agent restores the drawing buffer for a WebGLRenderingContext or WebGL2RenderingContext object.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Media Capture DOM Elements', '#html-media-element-media-capture-extensions', 'HTMLCanvasElement')}}{{Spec2('Media Capture DOM Elements')}}Adds the method captureStream().
{{SpecName('HTML WHATWG', "#htmlcanvaselement", "HTMLCanvasElement")}}{{Spec2('HTML WHATWG')}}The method getContext() now returns a {{domxref("RenderingContext")}} rather than an opaque object.
- The transferControlToOffscreen()method has been added.
{{SpecName('HTML5.1', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5 W3C')}}Initial definition.
- -

Browser compatibility

- -
- - -

{{Compat("api.HTMLCanvasElement")}}

-
- -

See also

- - diff --git a/files/vi/web/api/htmlelement/index.html b/files/vi/web/api/htmlelement/index.html deleted file mode 100644 index 1a625a2a5b..0000000000 --- a/files/vi/web/api/htmlelement/index.html +++ /dev/null @@ -1,268 +0,0 @@ ---- -title: HTMLElement -slug: Web/API/HTMLElement -tags: - - API - - HTML DOM - - Interface -translation_of: Web/API/HTMLElement ---- -
{{ APIRef("HTML DOM") }}
- -

Interface HTMLElement đại diện cho mọi phần tử HTML. Một vài phần tử sử dụng trực tiếp interface này, một vài phần tử khác lại sử dụng nó thông qua các lớp khác kế thừa nó.

- -

{{InheritanceDiagram}}

- -

Các thuộc tính

- -

Được kế thừa từ {{domxref("Element")}}, và sử dụng chúng từ {{domxref("GlobalEventHandlers")}} và {{domxref("TouchEventHandlers")}}.

- -
-
{{domxref("HTMLElement.accessKey")}}
-
Là một {{domxref("DOMString")}} trả về từ khoá truy cập được gán cho phần tử.
-
{{domxref("HTMLElement.accessKeyLabel")}} {{readonlyInline}}
-
Trả về một {{domxref("DOMString")}} chứa các từ khoá truy cập đã được gán của phần tử.
-
{{domxref("HTMLElement.contentEditable")}}
-
Là một {{domxref("DOMString")}}, nếu giá trị là "true", ta có thể chỉnh sửa phần tử này và ngược lại nếu giá trị là "false".
-
{{domxref("HTMLElement.isContentEditable")}} {{readonlyInline}}
-
Trả về giá trị {{domxref("Boolean")}} cho biết nội dung của phần tử có được phép chỉnh sửa hay không.
-
{{domxref("HTMLElement.contextMenu")}} {{deprecated_inline}}
-
Là một {{domxref("HTMLMenuElement")}} trả về một menu tóm lược liên kết các phần tử. Giá trị có thể là null.
-
{{domxref("HTMLElement.dataset")}} {{readonlyInline}}
-
Trả về một {{domxref("DOMStringMap")}} cho phép ta thao tác với các thuộc tính dữ liệu tùy biến của phần tử (data-*) .
-
{{domxref("HTMLElement.dir")}}
-
Là một {{domxref("DOMString")}}, tương tự với thuộc tính global dir, đại diện cho hướng hiển thị của phần tử. Các giá trị cho phép là "ltr", "rtl", và "auto".
-
{{domxref("HTMLElement.draggable")}}
-
Có kiểu {{jsxref("Boolean")}} cho ta biết phần tử có thể được kéo (drag) hay không.
-
{{domxref("HTMLElement.dropzone")}} {{readonlyInline}}
-
Trả về một {{domxref("DOMSettableTokenList")}} tương tự với thuộc tính global dropzone mô tả hành vi của phần tử liên quan đến hành động thả (drop).
-
{{domxref("HTMLElement.hidden")}}
-
Có kiểu {{jsxref("Boolean")}} cho ta biết phần tử có ẩn hay không.
-
{{domxref("HTMLElement.inert")}}
-
Có kiểu {{jsxref("Boolean")}} cho ta biết user agent must act as though the given node is absent đối với các sự kiện tương tác của người dùng, tìm kiếm văn bản trong trang, và lựa chọn văn bản.
-
{{domxref("HTMLElement.innerText")}}
-
Trả về nội dung văn bản được "render" từ một node và phần tử con của nó. Điều này tương tự với việc người dùng bôi đen văn bản và sao chép chúng.
-
{{domxref("HTMLElement.itemScope")}} {{experimental_inline}}
-
Có kiểu {{jsxref("Boolean")}} cho biết scope của item.
-
{{domxref("HTMLElement.itemType")}} {{readonlyInline}}{{experimental_inline}}
-
Trả về một {{domxref("DOMSettableTokenList")}}…
-
{{domxref("HTMLElement.itemId")}} {{experimental_inline}}
-
Là một {{domxref("DOMString")}} cho biết ID của item.
-
{{domxref("HTMLElement.itemRef")}} {{readonlyInline}}{{experimental_inline}}
-
Là một {{domxref("DOMSettableTokenList")}}…
-
{{domxref("HTMLElement.itemProp")}} {{readonlyInline}}{{experimental_inline}}
-
Trả về một {{domxref("DOMSettableTokenList")}}…
-
{{domxref("HTMLElement.itemValue")}} {{experimental_inline}}
-
Trả về một {{jsxref("Object")}} cho biết giá trị của item.
-
{{domxref("HTMLElement.lang")}}
-
Là một {{domxref("DOMString")}} cho biết ngôn ngữ của thuộc tính của một phần tử, của văn bản và của nội dung phần tử đó.
-
{{domxref("HTMLElement.noModule")}}
-
Có kiểu {{jsxref("Boolean")}} cho biết rằng việc nhúng đoạn script có thể được thực thi bởi user agent (có hỗ trợ module scripts) hay không.
-
{{domxref("HTMLElement.nonce")}}
-
Returns the cryptographic number used once that is used by Content Security Policy to determine whether a given fetch will be allowed to proceed.
-
{{domxref("HTMLElement.offsetHeight")}} {{readonlyInline}}{{experimental_inline}}
-
Returns a double containing the height of an element, relative to the layout.
-
{{domxref("HTMLElement.offsetLeft")}}{{readonlyInline}}{{experimental_inline}}
-
Returns a double, the distance from this element's left border to its offsetParent's left border.
-
{{domxref("HTMLElement.offsetParent")}}{{readonlyInline}}{{experimental_inline}}
-
Returns a {{domxref("Element")}} that is the element from which all offset calculations are currently computed.
-
{{domxref("HTMLElement.offsetTop")}}{{readonlyInline}}{{experimental_inline}}
-
Returns a double, the distance from this element's top border to its offsetParent's top border.
-
{{domxref("HTMLElement.offsetWidth")}}{{readonlyInline}}{{experimental_inline}}
-
Returns a double containing the width of an element, relative to the layout.
-
{{domxref("HTMLElement.properties")}} {{readonlyInline}}{{experimental_inline}}
-
Returns a {{domxref("HTMLPropertiesCollection")}}…
-
{{domxref("HTMLElement.spellcheck")}}{{ gecko_minversion_inline("1.9")}}
-
Is a {{jsxref("Boolean")}} that controls spell-checking. It is present on all HTML elements, though it doesn't have an effect on all of them.
-
{{domxref("HTMLElement.style")}}
-
Is a {{domxref("CSSStyleDeclaration")}}, an object representing the declarations of an element's style attributes.
-
{{domxref("HTMLElement.tabIndex")}}
-
Is a long representing the position of the element in the tabbing order.
-
{{domxref("HTMLElement.title")}}
-
Is a {{domxref("DOMString")}} containing the text that appears in a popup box when mouse is over the element.
-
{{domxref("HTMLElement.translate")}} {{experimental_inline}}
-
Is a {{jsxref("Boolean")}} representing the translation.
-
- -

Event handlers

- -

Most event handler properties, of the form onXYZ, are defined on the {{domxref("GlobalEventHandlers")}} or {{domxref("TouchEventHandlers")}} interfaces and implemented by HTMLElement. In addition, the following handlers are specific to HTMLElement.

- -
-
{{ domxref("HTMLElement.oncopy") }} {{ non-standard_inline() }}
-
Returns the event handling code for the copy event ({{bug("280959")}}).
-
{{ domxref("HTMLElement.oncut") }} {{ non-standard_inline() }}
-
Returns the event handling code for the cut event ({{bug("280959")}}).
-
{{ domxref("HTMLElement.onpaste") }} {{ non-standard_inline() }}
-
Returns the event handling code for the paste event ({{bug("280959")}}).
-
{{domxref("TouchEventHandlers.ontouchstart")}} {{non-standard_inline}}
-
Returns the event handling code for the {{event("touchstart")}} event.
-
{{domxref("TouchEventHandlers.ontouchend")}} {{non-standard_inline}}
-
Returns the event handling code for the {{event("touchend")}} event.
-
{{domxref("TouchEventHandlers.ontouchmove")}} {{non-standard_inline}}
-
Returns the event handling code for the {{event("touchmove")}} event.
-
{{domxref("TouchEventHandlers.ontouchenter")}} {{non-standard_inline}}
-
Returns the event handling code for the {{event("touchenter")}} event.
-
{{domxref("TouchEventHandlers.ontouchleave")}} {{non-standard_inline}}
-
Returns the event handling code for the {{event("touchleave")}} event.
-
{{domxref("TouchEventHandlers.ontouchcancel")}} {{non-standard_inline}}
-
Returns the event handling code for the {{event("touchcancel")}} event.
-
- -

Các phương thức

- -

Được kế thừa từ {{domxref("Element")}}.

- -
-
{{domxref("HTMLElement.blur()")}}
-
Bỏ truy cập phần tử hiện tại.
-
{{domxref("HTMLElement.click()")}}
-
Gửi một sự kiện click chuột đến phần tử.
-
{{domxref("HTMLElement.focus()")}}
-
Truy cập đến phần tử hiện tại (truy cập bằng cách click vào phần tử hoặc nhấn phím Tab để di chuyển đến).
-
{{domxref("HTMLElement.forceSpellCheck()")}} {{experimental_inline}}
-
Kiểm tra chính tả nội dung của phần tử.
-
- -

Các sự kiện

- -

Bắt các sự kiện bằng cách sự dụng phương thức addEventListener() hoặc bằng cách gán một thuộc tính sự sự kiện on_tên_sự_kiện dựa trên interface này.

- -
-
invalid
-
Được gọi khi một phần tử không thỏa điều kiện khi đang xác minh (validation) thông tin.
- Dùng tương tự với thuộc tính oninvalid.
-
- -

Các sự kiện animation

- -
-
animationcancel
-
Được gọi khi một animation dừng đột ngột.
- Dùng tương tự với thuộc tính onanimationcancel.
-
animationend
-
Được gọi khi một animation kết thúc.
- Dùng tương tự với thuộc tính onanimationend.
-
animationiteration
-
Được gọi khi một vòng lặp animation kết thúc.
- Dùng tương tự với thuộc tính onanimationiteration.
-
animationstart
-
Fired when an animation starts.
- Dùng tương tự với thuộc tính onanimationstart.
-
- -

Các sự kiện input

- -
-
beforeinput
-
Được gọi khi giá trị của một phần tử {{HTMLElement("input")}}, {{HTMLElement("select")}}, hoặc {{HTMLElement("textarea")}} sắp được chỉnh sửa.
-
input
-
Được gọi khi giá trị của một phần tử {{HTMLElement("input")}}, {{HTMLElement("select")}}, hoặc {{HTMLElement("textarea")}} đã được chỉnh sửa.
- Dùng tương tự với thuộc tính oninput.
-
- -

Pointer events

- -
-
gotpointercapture
-
Fired when an element captures a pointer using setPointerCapture().
- Also available via the ongotpointercapture property.
-
lostpointercapture
-
Fired when a captured pointer is released.
- Also available via the onlostpointercapture property.
-
pointercancel
-
Fired when a pointer event is canceled.
- Also available via the onpointercancel property.
-
pointerdown
-
Fired when a pointer becomes active.
- Also available via the onpointerdown property.
-
pointerenter
-
Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants.
- Also available via the onpointerenter property.
-
pointerleave
-
Fired when a pointer is moved out of the hit test boundaries of an element.
- Also available via the onpointerleave property.
-
pointermove
-
Fired when a pointer changes coordinates.
- Also available via the onpointermove property.
-
pointerout
-
Fired when a pointer is moved out of the hit test boundaries of an element (among other reasons).
- Also available via the onpointerout property.
-
pointerover
-
Fired when a pointer is moved into an element's hit test boundaries.
- Also available via the onpointerover property.
-
pointerup
-
Fired when a pointer is no longer active.
- Also available via the onpointerup property.
-
- -

Các sự kiện transition

- -
-
transitioncancel
-
Được gọi khi một CSS transition bị hủy.
- Dùng tương tự với thuộc tính ontransitioncancel.
-
transitionend
-
Được gọi khi một CSS transition hoàn thành.
- Dùng tương tự với thuộc tính ontransitionend.
-
transitionrun
-
Được gọi khi một CSS transition được tạo ra đầu tiên.
- Dùng tương tự với thuộc tính ontransitionrun.
-
transitionstart
-
Được gọi khi một CSS transition thực sự bắt đầu.
- Dùng tương tự với thuộc tính ontransitionstart.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSSOM View', '#extensions-to-the-htmlelement-interface', 'HTMLElement')}}{{Spec2('CSSOM View')}}Added the following properties: offsetParent, offsetTop, offsetLeft, offsetWidth, and offsetHeight.
{{SpecName('HTML WHATWG', 'elements.html#htmlelement', 'HTMLElement')}}{{Spec2('HTML WHATWG')}}Added the following properties: translate, itemScope, itemType, itemId, itemRef, itemProp, properties, and itemValue.
- Added the following method: forceSpellcheck().
- Moved the onXYZ attributes to the {{domxref("GlobalEventHandlers")}} interface and added an inheritance from it.
{{SpecName('HTML5 W3C', 'dom.html#htmlelement', 'HTMLElement')}}{{Spec2('HTML5 W3C')}}Added the following properties: dataset, hidden, tabindex, accessKey, accessKeyLabel, draggable, dropzone, contentEditable, isContentEditable, contextMenu, spellcheck, commandType, commandLabel, commandIcon, commandHidden, commandDisabled, commandChecked, style, and all the onXYZ properties.
- Moved the id and className properties to the {{domxref("Element")}} interface.
{{SpecName('DOM2 HTML', 'html.html#ID-011100101', 'HTMLElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName('DOM2 HTML')}}
{{SpecName('DOM1', 'level-one-html.html#ID-011100101', 'HTMLElement')}}{{Spec2('DOM1')}}Initial definition.
- -

Khả năng tương thích của trình duyệt

- - - -

{{Compat("api.HTMLElement")}}

- -

Xem thêm

- - diff --git a/files/vi/web/api/htmlformelement/index.html b/files/vi/web/api/htmlformelement/index.html deleted file mode 100644 index d80fb120a2..0000000000 --- a/files/vi/web/api/htmlformelement/index.html +++ /dev/null @@ -1,246 +0,0 @@ ---- -title: HTMLFormElement -slug: Web/API/HTMLFormElement -tags: - - API - - DOM - - Form Element - - Forms - - HTML - - HTML DOM - - HTML Form Element - - HTML forms - - HTMLFormElement - - Interface - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/API/HTMLFormElement ---- -
{{APIRef("HTML DOM")}}
- -

The {{domxref("HTMLFormElement")}} interface represents a {{HTMLElement("form")}} element in the DOM; it allows access to and in some cases modification of aspects of the form, as well as access to its component elements.

- -

{{InheritanceDiagram(600,120)}}

- -

Properties

- -

This interface also inherits properties from its parent, {{domxref("HTMLElement")}}.

- -
-
{{domxref("HTMLFormElement.elements")}} {{ReadOnlyInline}}
-
A {{domxref("HTMLFormControlsCollection")}} holding all form controls belonging to this form element.
-
{{domxref("HTMLFormElement.length")}}{{ReadOnlyInline}}
-
A long reflecting  the number of controls in the form.
-
{{domxref("HTMLFormElement.name")}}
-
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("name", "form") }} HTML attribute, containing the name of the form.
-
{{domxref("HTMLFormElement.method")}}
-
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("method", "form") }} HTML attribute, indicating the HTTP method used to submit the form. Only specified values can be set.
-
{{domxref("HTMLFormElement.target")}}
-
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("target", "form") }} HTML attribute, indicating where to display the results received from submitting the form.
-
{{domxref("HTMLFormElement.action")}}
-
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("action", "form") }} HTML attribute, containing the URI of a program that processes the information submitted by the form.
-
{{domxref("HTMLFormElement.encoding")}} or {{domxref("HTMLFormElement.enctype")}}
-
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("enctype", "form") }} HTML attribute, indicating the type of content that is used to transmit the form to the server. Only specified values can be set. The two properties are synonyms.
-
{{domxref("HTMLFormElement.acceptCharset")}}
-
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("accept-charset", "form") }} HTML attribute, representing the character encoding that the server accepts.
-
{{domxref("HTMLFormElement.autocomplete")}}
-
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("autocomplete", "form") }} HTML attribute, indicating whether the controls in this form can have their values automatically populated by the browser.
-
{{domxref("HTMLFormElement.noValidate")}}
-
A {{jsxref("Boolean")}} reflecting the value of the form's  {{ htmlattrxref("novalidate", "form") }} HTML attribute, indicating whether the form should not be validated.
-
- -

Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's {{ htmlattrxref("action", "form") }} HTML attribute).

- -

Methods

- -

This interface also inherits methods from its parent, {{domxref("HTMLElement")}}.

- -
-
{{domxref("HTMLFormElement.submit()")}}
-
Submits the form to the server.
-
{{domxref("HTMLFormElement.reset()")}}
-
Resets the form to its initial state.
-
{{domxref("HTMLFormElement.checkValidity()")}}
-
Returns true if the element's child controls are subject to constraint validation and satisfy those contraints; returns false if some controls do not satisfy their constraints. Fires an event named {{event("invalid")}} at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to false.
-
{{domxref("HTMLFormElement.reportValidity()")}}
-
Returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable {{Event("invalid")}} events are fired for each invalid child and validation problems are reported to the user.
-
{{domxref("HTMLFormElement.requestAutocomplete()")}} {{obsolete_inline}}
-
Triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not off or on. The form will receive an event once the user has finished with the interface, the event will either be {{event("autocomplete")}} when the fields have been filled or {{event("autocompleteerror")}} when there was a problem. This method has been removed from Chrome and Firefox — see {{bug(1270740)}} for background information on why.
-
- -

Events

- -

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

- -
-
reset
-
The reset event fires when a form is reset.
- Also available via the onreset property.
-
submit
-
The submit event fires when a form is submitted.
- Also available via the onsubmit property.
-
- -

Usage notes

- -

Obtaining a form element object

- -

To obtain an HTMLFormElement object, you can use a CSS selector with {{domxref("ParentNode.querySelector", "querySelector()")}}, or you can get a list of all of the forms in the document using its {{domxref("Document.forms", "forms")}} property.

- -

{{domxref("Document.forms")}} returns an array of HTMLFormElement objects listing each of the forms on the page. You can then use any of the following syntaxes to get an individual form:

- -
-
document.forms[index]
-
Returns the form at the specified index into the array of forms.
-
document.forms[id]
-
Returns the form whose ID is id.
-
document.forms[name]
-
Returns the form whose {{domxref("Element.name", "name")}} attribute's value is name.
-
- -

Accessing the form's elements

- -

You can access the list of the form's data-containing elements by examining the form's {{domxref("HTMLFormElement.elements", "elements")}} property. This returns an {{domxref("HTMLFormControlsCollection")}} listing all of the form's user data entry elements, both those which are descendants of the <form> and those which are made members of the form using their form attributes.

- -

Elements that are considered form controls

- -

The elements which are included by HTMLFormElement.elements and HTMLFormElement.length are:

- - - -

No other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms.

- -

Examples

- -

Creating a new form element, modifying its attributes, then submitting it:

- -
var f = document.createElement("form");// Create a form
-document.body.appendChild(f);          // Add it to the document body
-f.action = "/cgi-bin/some.cgi";        // Add action and method attributes
-f.method = "POST";
-f.submit();                            // Call the form's submit method
-
- -

Extract information from a form element and set some of its attributes:

- -
<form name="formA" action="/cgi-bin/test" method="post">
- <p>Press "Info" for form details, or "Set" to change those details.</p>
- <p>
-  <button type="button" onclick="getFormInfo();">Info</button>
-  <button type="button" onclick="setFormInfo(this.form);">Set</button>
-  <button type="reset">Reset</button>
- </p>
-
- <textarea id="form-info" rows="15" cols="20"></textarea>
-</form>
-
-<script>
-  function getFormInfo(){
-    // Get a reference to the form via its name
-    var f = document.forms["formA"];
-    // The form properties we're interested in
-    var properties = [ 'elements', 'length', 'name', 'charset', 'action', 'acceptCharset', 'action', 'enctype', 'method', 'target' ];
-    // Iterate over the properties, turning them into a string that we can display to the user
-    var info = properties.map(function(property) { return property + ": " + f[property] }).join("\n");
-
-    // Set the form's <textarea> to display the form's properties
-    document.forms["formA"].elements['form-info'].value = info;
-  }
-
-  function setFormInfo(f){ // Argument should be a form element reference.
-    f.action = "a-different-url.cgi";
-    f.name   = "a-different-name";
-  }
-</script>
-
- -

Submit a form into a new window:

- -
<!doctype html>
-<html>
-<head>
-<meta charset="utf-8">
-<title>Example new-window form submission</title>
-</head>
-<body>
-
-<form action="test.php" target="_blank">
-  <p><label>First name: <input type="text" name="firstname"></label></p>
-  <p><label>Last name: <input type="text" name="lastname"></label></p>
-  <p><label><input type="password" name="pwd"></label></p>
-
-  <fieldset>
-   <legend>Pet preference</legend>
-    <p><label><input type="radio" name="pet" value="cat"> Cat</label></p>
-    <p><label><input type="radio" name="pet" value="dog"> Dog</label></p>
-  </fieldset>
-
-  <fieldset>
-    <legend>Owned vehicles</legend>
-
-    <p><label><input type="checkbox" name="vehicle" value="Bike">I have a bike</label></p>
-    <p><label><input type="checkbox" name="vehicle" value="Car">I have a car</label></p>
-  </fieldset>
-
-  <p><button>Submit</button></p>
-</form>
-
-</body>
-</html>
- -

Submitting forms and uploading files using XMLHttpRequest

- -

If you want to know how to serialize and submit a form using the {{domxref("XMLHttpRequest")}} API, please read this paragraph.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmlformelement", "HTMLFormElement")}}{{Spec2('HTML WHATWG')}}The following method has been added: requestAutocomplete().
{{SpecName('HTML5 W3C', "forms.html#the-form-element", "HTMLFormElement")}}{{Spec2('HTML5 W3C')}}The elements properties returns an {{domxref("HTMLFormControlsCollection")}} instead of a raw {{domxref("HTMLCollection")}}. This is mainly a technical change. The following method has been added: checkValidity(). The following properties have been added: autocomplete, noValidate, and encoding.
{{SpecName('DOM2 HTML', 'html.html#ID-40002357', 'HTMLFormElement')}}{{Spec2('DOM2 HTML')}}No change
{{SpecName('DOM1', 'level-one-html.html#ID-40002357', 'HTMLFormElement')}}{{Spec2('DOM1')}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("api.HTMLFormElement")}}

- -

See also

- - diff --git a/files/vi/web/api/htmlformelement/reset/index.html b/files/vi/web/api/htmlformelement/reset/index.html deleted file mode 100644 index dc68298cab..0000000000 --- a/files/vi/web/api/htmlformelement/reset/index.html +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: HTMLFormElement.reset() -slug: Web/API/HTMLFormElement/reset -translation_of: Web/API/HTMLFormElement/reset ---- -
{{APIRef("HTML DOM")}}
- -

Phương thức HTMLFormEuity.reset () khôi phục các giá trị mặc định của thành phần biểu mẫu. Phương pháp này thực hiện tương tự như nhấp vào nút đặt lại của biểu mẫu

- -

Nếu một điều khiển biểu mẫu (chẳng hạn như nút đặt lại) có tên hoặc id của thiết lập lại, nó sẽ che dấu phương thức đặt lại của biểu mẫu. Nó không thiết lập lại các thuộc tính khác trong đầu vào, chẳng hạn như bị vô hiệu hóa.

- -

Syntax

- -
HTMLFormElement.reset()
-
- -

Example

- -
document.getElementById('myform').reset();
-
- -

Specification

- -

Browser compatibility

- - - -

{{Compat("api.HTMLFormElement.reset")}}

diff --git a/files/vi/web/api/htmlorforeignelement/dataset/index.html b/files/vi/web/api/htmlorforeignelement/dataset/index.html deleted file mode 100644 index ad2617ab56..0000000000 --- a/files/vi/web/api/htmlorforeignelement/dataset/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: HTMLElement.dataset -slug: Web/API/HTMLOrForeignElement/dataset -tags: - - API - - HTML DOM - - HTMLElement - - Tham khảo - - Thuộc tính - - dataset -translation_of: Web/API/HTMLOrForeignElement/dataset -original_slug: Web/API/HTMLElement/dataset ---- -
{{ APIRef("HTML DOM") }}
- -

The dataset property on the {{domxref("HTMLElement")}} interface provides read/write access to all the custom data attributes (data-*) set on the element. This access is available both in HTML and within the DOM.  It is a map of DOMString, one entry for each custom data attribute.  Note that the dataset property itself can be read, but not directly written.  Instead, all writes must be to the individual properties within the dataset, which in turn represent the data attributes.   Note also that an HTML data-attribute and its corresponding DOM dataset.property do not share the same name, but they are always similar:

- - - -

In addition to the information below, you'll find a how-to guide for using HTML data attributes in our article Using data attributes.

- -

Chuyển đổi tên

- -

Từ dash-style (kiểu-gạch-nối) sang camelCase (bướuLạcĐà): Tên thuộc tính dữ liệu tùy biến được chuyển đổi thành khóa cho {{ domxref("DOMStringMap") }} dự trên quy định sau:

- - - -

Từ camelCase (bướuLạcĐà) sang dash-style (kiểu-gạch-nối): Cách chuyển đổi ngược lại, dò theo khóa để tìm ra tên thuộc tính, bằng quy định sau:

- - - -

Việc có rằng buộc trong quy định trên nhằm đảm bảo việc chuyển đổi có thể đảo ngược cho nhau.

- -

Ví dụ, thuộc tính có tên data-abc-def sẽ có khóa tương ứng abcDef.

- - - -

Truy cập giá trị

- - - -

Loại giá trị

- - - -

Cú pháp

- - - -

Ví dụ

- -
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>
- -
const el = document.querySelector('#user');
-
-// el.id == 'user'
-// el.dataset.id === '1234567890'
-// el.dataset.user === 'johndoe'
-// el.dataset.dateOfBirth === ''
-
-// gán dữ liệu cho thuộc tính data
-el.dataset.dateOfBirth = '1960-10-03';
-// Kết quả: el.dataset.dateOfBirth === 1960-10-03
-
-delete el.dataset.dateOfBirth;
-// Kết quả: el.dataset.dateOfBirth === undefined
-
-// 'someDataAttr' in el.dataset === false
-el.dataset.someDataAttr = 'mydata';
-// Kết quả: 'someDataAttr' in el.dataset === true
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('HTML WHATWG', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML WHATWG')}}No change from latest snapshot, {{SpecName('HTML5.1')}}
{{SpecName('HTML5.1', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName('HTML WHATWG')}}, no change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5 W3C')}}Snapshot of  {{SpecName('HTML WHATWG')}}, initial definition.
- -

Tính tương thích trên trình duyệt

- - - -

{{Compat("api.HTMLElement.dataset")}}

- -

Xem thêm

- - diff --git a/files/vi/web/api/index.html b/files/vi/web/api/index.html deleted file mode 100644 index 71e6573815..0000000000 --- a/files/vi/web/api/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Web API Interfaces -slug: Web/API -tags: - - API - - Apps - - JavaScript - - NeedsTranslation - - Reference - - TopicStub - - Web -translation_of: Web/API ---- -

Có rất nhiều API tốt khi viết Web bằng Javascript. Dưới đây là danh sách những interfaces (những kiểu object) mà bạn có thể sử dụng khi phát triển Web app hay Website.

- -

Web APIs thường được viết bởi JavaScript, nhưng không phải luôn là như vậy.

- -

Đặc tả

- -

Đây là danh sách tất cả những API sẵn có.

- -
{{ListGroups}}
- -

Interfaces

- -

Đây là danh sách tất cả những interfaces (những kiểu object) sẵn có.

- -
{{APIListAlpha}}
- -

Xem thêm

- - diff --git a/files/vi/web/api/navigator/geolocation/index.html b/files/vi/web/api/navigator/geolocation/index.html deleted file mode 100644 index 4881071171..0000000000 --- a/files/vi/web/api/navigator/geolocation/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Navigator.geolocation -slug: Web/API/Navigator/geolocation -tags: - - API - - Bất động sản - - Geolocation API - - Tham khảo -translation_of: Web/API/Navigator/geolocation ---- -
{{securecontext_header}}{{APIRef("Geolocation API")}}
- -

Navigator.geolocation với đặc tính chỉ cho đọc trả lại một đối tượng {{domxref("Geolocation")}} cho phép trang web truy cập thông tin địa điểm của thiết bị. Việc này cho phép trang web hoặc phần mềm đưa ra đề nghị chào hàng dựa trên vị trí của người dùng.

- -
-

Ghi chú: Vì lý do bảo mật, khi một trang web cố gắng truy cập vị trí, người dùng sẽ được thông báo và hỏi cấp yêu cầu cho phép. Hãy cẩn thận vì mỗi trình duyệt web có chính sách và phương pháp khác nhau.

-
- -

Syntax

- -
geo = navigator.geolocation
-
- -

Specifications

- - - - - - - - - - - - - - - - -
Chi tiết kỹ thuậtTình trạngGhi chú
{{SpecName('Geolocation', '#navi-geo', 'Navigator.geolocation')}}{{Spec2('Geolocation')}}Initial definition
- -

Tương thích vơi trình duyệt

- - - -

{{Compat("api.Navigator.geolocation")}}

- -

Xem thêm

- - diff --git a/files/vi/web/api/navigator/index.html b/files/vi/web/api/navigator/index.html deleted file mode 100644 index e9ab7a7b29..0000000000 --- a/files/vi/web/api/navigator/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: Navigator -slug: Web/API/Navigator -tags: - - API - - DOM4 - - Interface - - Navigator - - NeedsTranslation - - Reference - - TopicStub - - Web - - Web Performance -translation_of: Web/API/Navigator ---- -
{{APIRef("DOM4")}}
- -

The Navigator interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.

- -

A Navigator object can be retrieved using the read-only {{domxref("window.navigator")}} property.

- -

Properties

- -

Doesn't inherit any properties, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorLanguage")}}, {{domxref("NavigatorOnLine")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorStorage")}}, {{domxref("NavigatorStorageUtils")}}, {{domxref("NavigatorConcurrentHardware")}}, {{domxref("NavigatorPlugins")}}, and {{domxref("NavigatorUserMedia")}}.

- -

Standard

- -
-
{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}
-
Returns an array containing every {{domxref("VRDisplay")}} object that is currently presenting ({{domxref("VRDisplay.ispresenting")}} is true).
-
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}
-
Returns the internal "code" name of the current browser. Do not rely on this property to return the correct value.
-
{{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}
-
Returns a {{domxref("DOMString")}} with the official name of the browser. Do not rely on this property to return the correct value.
-
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}
-
Returns the version of the browser as a {{domxref("DOMString")}}. Do not rely on this property to return the correct value.
-
{{domxref("Navigator.battery")}} {{readonlyInline}}
-
Returns a {{domxref("BatteryManager")}} object you can use to get information about the battery charging status.
-
{{domxref("Navigator.connection")}} {{readonlyInline}}{{experimental_inline}}
-
Provides a {{domxref("NetworkInformation")}} object containing information about the network connection of a device.
-
{{domxref("Navigator.cookieEnabled")}} {{readonlyinline}}
-
Returns false if setting a cookie will be ignored and true otherwise.
-
{{domxref("Navigator.geolocation")}} {{readonlyInline}}
-
Returns a {{domxref("Geolocation")}} object allowing accessing the location of the device.
-
{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}
-
Returns the number of logical processor cores available.
-
{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}
-
Returns a {{domxref("Boolean")}} flag indicating whether the host browser is Java-enabled or not.
-
{{domxref('Navigator.keyboard')}} {{readonlyinline}} {{experimental_inline}}
-
Returns a {{domxref('Keyboard')}} object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.
-
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
-
Returns a {{domxref("DOMString")}} representing the preferred language of the user, usually the language of the browser UI. The null value is returned when this is unknown.
-
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
-
Returns an array of {{domxref("DOMString")}} representing the languages known to the user, by order of preference.
-
{{domxref("Navigator.locks")}} {{readonlyinline}}{{experimental_inline}}
-
Returns a {{domxref("LockManager")}} object which provides methods for requesting a new {{domxref('Lock')}} object and querying for an existing {{domxref('Lock')}} object
-
{{domxref("Navigator.mediaCapabilities")}} {{readonlyinline}}{{experimental_inline}}
-
Returns a {{domxref("MediaCapabilities")}} object that can expose information about the decoding and encoding capabilities for a given format and output capabilities.
-
{{domxref("Navigator.maxTouchPoints")}} {{readonlyInline}}
-
Returns the maximum number of simultaneous touch contact points are supported by the current device.
-
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
-
Returns an {{domxref("MimeTypeArray")}} listing the MIME types supported by the browser.
-
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
-
Returns a {{domxref("Boolean")}} indicating whether the browser is working online.
-
{{domxref("Navigator.oscpu")}}
-
Returns a string that represents the current operating system.
-
{{domxref("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}
-
Returns a {{domxref("Permissions")}} object that can be used to query and update permission status of APIs covered by the Permissions API.
-
{{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}
-
Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.
-
{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
-
Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.
-
{{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}
-
Always returns 'Gecko', on any browser. This property is kept only for compatibility purpose.
-
{{domxref("Navigator.serviceWorker")}} {{readonlyInline}}
-
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
-
{{domxref("NavigatorStorage.storage")}} {{readonlyinline}}
-
Returns the singleton {{domxref('StorageManager')}} object used for managing persistence permissions and estimating available storage on a site-by-site/app-by-app basis.
-
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
-
Returns the user agent string for the current browser.
-
{{domxref("Navigator.webdriver")}} {{readonlyInline}} {{experimental_inline}}
-
Indicates whether the user agent is controlled by automation.
-
- -

Non-standard

- -
-
{{domxref("Navigator.buildID")}} {{non-standard_inline}}
-
Returns the build identifier of the browser. In modern browsers this property now returns a fixed timestamp as a privacy measure, e.g. 20181001000000 in Firefox 64 onwards.
-
{{domxref("Navigator.credentials")}} {{non-standard_inline}}
-
Returns the {{domxref("CredentialsContainer")}} interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. 
-
{{domxref("Navigator.deviceMemory")}} {{readonlyInline}} {{non-standard_inline}}
-
Returns the amount of device memory in gigabytes. This value is an approximation given by rounding to the nearest power of 2 and dividing that number by 1024.
-
{{domxref("Navigator.doNotTrack")}} {{non-standard_inline}}
-
Reports the value of the user's do-not-track preference. When this value is "yes", your web site or application should not track the user.
-
{{domxref("Navigator.mediaDevices")}} {{non-standard_inline}}
-
Returns a reference to a {{domxref("MediaDevices")}} object which can then be used to get information about available media devices ({{domxref("MediaDevices.enumerateDevices()")}}), find out what constrainable properties are supported for media on the user's computer and user agent ({{domxref("MediaDevices.getSupportedConstraints()")}}), and to request access to media using {{domxref("MediaDevices.getUserMedia()")}}.
-
{{domxref("Navigator.mozNotification")}} {{obsolete_inline}} {{deprecated_inline("22")}} {{non-standard_inline}}
- {{domxref("Navigator.webkitNotification")}} {{obsolete_inline}}
-
Returns a {{domxref("navigator.mozNotification", "notification")}} object you can use to deliver notifications to the user from your web application.
-
{{domxref("Navigator.mozSocial")}} {{non-standard_inline}}
-
The Object, returned by the navigator.mozSocial property, is available within the social media provider's panel to provide functionality it may need.
-
{{domxref("Navigator.presentation")}} {{non-standard_inline}}
-
Returns a reference to the {{domxref("Presentation")}} API.
-
{{domxref("Navigator.productSub")}} {{non-standard_inline}}
-
Returns the build number of the current browser (e.g., "20060909").
-
{{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}
-
Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
-
{{domxref("Navigator.standalone")}} {{non-standard_inline}}
-
Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.
-
{{domxref("Navigator.storageQuota")}} {{readonlyinline}} {{experimental_inline}}
-
Returns a {{domxref('StorageQuota')}} interface which provides means to query and request storage usage and quota information.
-
{{domxref("Navigator.vendor")}} {{non-standard_inline}}
-
Returns the vendor name of the current browser (e.g., "Netscape6").
-
{{domxref("Navigator.vendorSub")}} {{non-standard_inline}}
-
Returns the vendor version number (e.g. "6.1").
-
{{domxref("Navigator.webkitPointer")}} {{non-standard_inline}}
-
Returns a PointerLock object for the Mouse Lock API.
-
- -

Methods

- -

Doesn't inherit any method, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorUserMedia")}}, and {{domxref("NavigatorStorageUtils")}}.

- -

Standard

- -
-
{{domxref("Navigator.canShare()")}} {{experimental_inline}}
-
Returns true if a call to Navigator.share() would succeed.
-
{{domxref("Navigator.getVRDisplays()")}} {{experimental_inline}}
-
Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer.
-
{{domxref("Navigator.getUserMedia", "Navigator.getUserMedia()")}} {{experimental_inline}}
-
After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.
-
{{domxref("Navigator.registerContentHandler()")}} {{Obsolete_inline(59)}}
-
Allows web sites to register themselves as a possible handler for a given MIME type.
-
{{domxref("Navigator.registerProtocolHandler()")}}
-
Allows web sites to register themselves as a possible handler for a given protocol.
-
{{domxref("Navigator.requestMediaKeySystemAccess()")}} {{experimental_inline}}
-
Returns a {{jsxref("Promise")}} for a MediaKeySystemAccess object.
-
{{domxref("Navigator.sendBeacon()")}}{{experimental_inline}}
-
Used to asynchronously transfer a small amount of data using {{Glossary("HTTP")}} from the User Agent to a web server.
-
{{domxref("Navigator.share()")}}{{experimental_inline}}
-
Invokes the native sharing mechanism of the current platform.
-
{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline("1.7.8")}} {{obsolete_inline("9.0")}} {{experimental_inline}}
-
Returns false. JavaScript taint/untaint functions removed in JavaScript 1.2.
-
{{domxref("Navigator.vibrate()")}} {{gecko_minversion_inline("11.0")}}
-
Causes vibration on devices with support for it. Does nothing if vibration support isn't available.
-
- -

Non-standard

- -
-

Firefox OS devices adds more non-standard methods. You can consult them on the Firefox OS Navigator extensions article.

-
- -
-
{{domxref("Navigator.mozIsLocallyAvailable()")}} {{non-standard_inline}}
-
Lets code check to see if the document at a given URI is available without using the network.
-
{{domxref("Navigator.mozPay()")}} {{non-standard_inline}}
-
Allows in-app payment.
-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#the-navigator-object', 'the Navigator object')}}{{Spec2('HTML WHATWG')}}
- -

Browser compatibility

- - - -
{{Compat("api.Navigator")}}
diff --git a/files/vi/web/api/navigator/sendbeacon/index.html b/files/vi/web/api/navigator/sendbeacon/index.html deleted file mode 100644 index 1a48443fc9..0000000000 --- a/files/vi/web/api/navigator/sendbeacon/index.html +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Navigator.sendBeacon() -slug: Web/API/Navigator/sendBeacon -tags: - - API - - Beacon - - Navigator - - sendBeacon - - web perfomance -translation_of: Web/API/Navigator/sendBeacon -original_slug: Web/API/Navigator/sendBeacon-vi ---- -
Phương thức navigator.sendBeacon() gửi {{glossary("Asynchronous", "bất đồng bộ")}} 1 lượng nhỏ dữ liệu đến máy chủ (web server) thông qua giao thức {{Glossary("HTTP")}} .
- -

Cú pháp

- -
navigator.sendBeacon(url, data);
-
- -

Tham Số

- -
-
url
-
Đường dẫn để nhận dữ liệu (Tạo request). Có thể là đường dẫn tuyệt đối hoặc tương đối.
-
data
-
Một đối tượng chứa dữ liệu để gửi đi có thể là 1 {{domxref("ArrayBuffer")}}, {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, {{domxref("DOMString")}}, {{domxref("FormData")}}, hoặc {{domxref("URLSearchParams")}}.
-
- -

Giá trị trả về

- -

Phương thức sendBeacon() trả về true nếu như {{glossary("user agent")}} (tác nhân người dùng hay web browser) xếp dữ liệu (data) để gửi đi thành công. Nếu không, sẽ trả về false.

- -

Mô tả

- -

Phương thức này dùng cho phân tích và chuẩn đoán cần gửi dữ liệu về máy chủ trước thời điểm đóng trang, nếu như gửi sớm hơn, có thể sẽ bị thiếu thông tin cần thu thập. Ví dụ, đường dẫn nào người dùng nhấn vào trước khi chuyển đến trang khác và đóng trang.

- -

Việc đảm bảo rằng dữ liệu được gửi đi trong khi đóng trang (unload) trước đây thường rất khó để thực hiện, bởi user agents (web browser) luôn bỏ qua những {{domxref("XMLHttpRequest")}} bất đồng bộ được chạy trong sự kiện {{domxref("Window/unload_event", "unload")}}.

- -

Trước đây, người ta thường làm trễ thời gian tải lại trang đủ lâu để gửi được dữ liệu đi bằng 1 số cách sau:

- - - -

Tất cả những phương thức đó đều chặn quá trình tải lại trang, làm chậm việc chuyển đến trang tiếp theo. Trang tiếp theo không thể làm gì để ngăn chặn việc này, vì vậy trang mới sẽ có vẻ chậm đi, mặc dù đó là lỗi từ trang trước.

- -

Ví dụ sau đây là 1 đoạn code mẫu để gửi dữ liệu về server bằng 1 XMLHttpRequest đồng bộ trong khi xử lý unload. Điều này làm trễ việc tải trang tiếp theo.

- -
window.addEventListener("unload", function logData() {
-  var xhr = new XMLHttpRequest();
-  xhr.open("POST", "/log", false); // tham số thứ 3 là `false` để gửi request bất đồng bộ
-  xhr.send(analyticsData);
-});
-
- -

Đây là những gì sendBeacon() thay thế. Với phương thức sendBeacon(), dữ liệu sẽ được gửi đi bất đồng bộ, User Agent (trình duyệt) có thể làm thế mà không tạo trễ khi tải lại trang hoặc chuyển đến trang tiếp theo. Điều này giải quyết tất cả vấn đề với việc gửi các dữ liệu phân tích:

- - - -

Ví dụ sau đây là 1 đoạn code mẫu để gửi dữ liệu về server sử dụng phương thức sendBeacon().

- -
window.addEventListener("unload", function logData() {
-  navigator.sendBeacon("/log", analyticsData);
-});
-
- -

sendBeacon tạo 1 HTTP request với phương thức POST, kèm theo tất cả cookies liên quan khi được gọi.

- -

Tài liệu chi tiết

- - - - - - - - - - - - - - - - -
Tài liệuTrạng tháiBình luận
{{SpecName('Beacon', '#sendbeacon-method', 'sendBeacon()')}}{{Spec2('Beacon')}}Định nghĩa đầu tiên
- -

Tương thích với trình duyệt

- - - -

{{Compat("api.Navigator.sendBeacon")}}

- -

Xem thêm

- - diff --git a/files/vi/web/api/node/index.html b/files/vi/web/api/node/index.html deleted file mode 100644 index cf1f7cbe1f..0000000000 --- a/files/vi/web/api/node/index.html +++ /dev/null @@ -1,373 +0,0 @@ ---- -title: Node -slug: Web/API/Node -tags: - - API - - DOM - - DOM Reference - - NeedsTranslation - - Reference - - TopicStub - - WebAPI -translation_of: Web/API/Node ---- -
{{APIRef("DOM")}}
- -

A Node is an interface from which a number of DOM types inherit, and allows these various types to be treated (or tested) similarly.

- -

The following interfaces all inherit from Node its methods and properties: {{domxref("Document")}}, {{domxref("Element")}}, {{domxref("CharacterData")}} (which {{domxref("Text")}}, {{domxref("Comment")}}, and {{domxref("CDATASection")}} inherit), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}

- -

These interfaces may return null in particular cases where the methods and properties are not relevant. They may throw an exception - for example when adding children to a node type for which no children can exist.

- -

Properties

- -

Inherits properties from its parents {{domxref("EventTarget")}}.[1]

- -
-
{{domxref("Node.baseURI")}} {{readonlyInline}}
-
Returns a {{domxref("DOMString")}} representing the base URL. The concept of base URL changes from one language to another; in HTML, it corresponds to the protocol, the domain name and the directory structure, that is all until the last '/'.
-
{{domxref("Node.baseURIObject")}} {{Non-standard_inline()}}
-
(Not available to web content.) The read-only {{ Interface("nsIURI") }} object representing the base URI for the element.
-
{{domxref("Node.childNodes")}} {{readonlyInline}}
-
Returns a live {{domxref("NodeList")}} containing all the children of this node. {{domxref("NodeList")}} being live means that if the children of the Node change, the {{domxref("NodeList")}} object is automatically updated.
-
{{domxref("Node.firstChild")}} {{readonlyInline}}
-
Returns a {{domxref("Node")}} representing the first direct child node of the node, or null if the node has no child.
-
{{domxref("Node.lastChild")}} {{readonlyInline}}
-
Returns a {{domxref("Node")}} representing the last direct child node of the node, or null if the node has no child.
-
{{domxref("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}
-
Returns a {{domxref("DOMString")}} representing the local part of the qualified name of an element. In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML. {{ gecko_minversion_inline("1.9.2") }}
- Though recent specifications require localName to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
-
{{domxref("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}
-
The namespace URI of this node, or null if it is no namespace. In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the http://www.w3.org/1999/xhtml namespace in both HTML and XML trees. {{ gecko_minversion_inline("1.9.2") }}
- Though recent specifications require namespaceURI to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
-
{{domxref("Node.nextSibling")}} {{readonlyInline}}
-
Returns a {{domxref("Node")}} representing the next node in the tree, or null if there isn't such node.
-
{{domxref("Node.nodeName")}} {{readonlyInline}}
-
Returns a {{domxref("DOMString")}} containing the name of the Node. The structure of the name will differ with the name type. E.g. An {{domxref("HTMLElement")}} will contain the name of the corresponding tag, like 'audio' for an {{domxref("HTMLAudioElement")}}, a {{domxref("Text")}} node will have the '#text' string, or a {{domxref("Document")}} node will have the '#document' string.
-
{{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}
-
A {{ Interface("nsIPrincipal") }} representing the node principal.
-
{{domxref("Node.nodeType")}}{{readonlyInline}}
-
Returns an unsigned short representing the type of the node. Possible values are: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameValue
ELEMENT_NODE1
ATTRIBUTE_NODE {{deprecated_inline()}}2
TEXT_NODE3
CDATA_SECTION_NODE {{deprecated_inline()}}4
ENTITY_REFERENCE_NODE {{deprecated_inline()}}5
ENTITY_NODE {{deprecated_inline()}}6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE {{deprecated_inline()}}12
-
-
{{domxref("Node.nodeValue")}}
-
Is a {{domxref("DOMString")}} representing the value of an object. For most Node types, this returns null and any set operation is ignored. For nodes of type TEXT_NODE ({{domxref("Text")}} objects), COMMENT_NODE ({{domxref("Comment")}} objects), and PROCESSING_INSTRUCTION_NODE ({{domxref("ProcessingInstruction")}} objects), the value corresponds to the text data contained in the object.
-
{{domxref("Node.ownerDocument")}} {{readonlyInline}}
-
Returns the {{domxref("Document")}} that this node belongs to. If no document is associated with it, returns null.
-
{{domxref("Node.parentNode")}} {{readonlyInline}}
-
Returns a {{domxref("Node")}} that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns null.
-
{{domxref("Node.parentElement")}} {{readonlyInline}}
-
Returns an {{domxref("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{domxref("Element")}}, this property returns null.
-
{{domxref("Node.prefix")}} {{obsolete_inline}}{{readonlyInline}}
-
Is a {{domxref("DOMString")}} representing the namespace prefix of the node, or null if no prefix is specified.
- Though recent specifications require prefix to be defined on the {{domxref("Element")}} interface, Gecko-based browsers still implement it on the {{domxref("Node")}} interface.
-
{{domxref("Node.previousSibling")}} {{readonlyInline}}
-
Returns a {{domxref("Node")}} representing the previous node in the tree, or null if there isn't such node.
-
{{domxref("Node.textContent")}}
-
Is a {{domxref("DOMString")}} representing the textual content of an element and all its descendants.
-
- -

Methods

- -

Inherits methods from its parents {{domxref("EventTarget")}}.[1]

- -
-
{{domxref("Node.appendChild()")}}
-
Insert a {{domxref("Node")}} as the last child node of this element.
-
{{domxref("Node.cloneNode()")}}
-
Clone a {{domxref("Node")}}, and optionally, all of its contents. By default, it clones the content of the node.
-
{{domxref("Node.compareDocumentPosition()")}}
-
 
-
{{domxref("Node.contains()")}}
-
 
-
{{domxref("Node.getFeature()")}} {{obsolete_inline}}
-
...
-
{{domxref("Node.getUserData()")}} {{obsolete_inline}}
-
Allows a user to get some {{domxref("DOMUserData")}} from the node.
-
{{domxref("Node.hasAttributes()")}} {{obsolete_inline}}
-
Returns a {{domxref("Boolean")}} indicating if the element has any attributes, or not.
-
{{domxref("Node.hasChildNodes()")}}
-
Returns a {{domxref("Boolean")}} indicating if the element has any child nodes, or not.
-
{{domxref("Node.insertBefore()")}}
-
Inserts the first {{domxref("Node")}} given in a parameter immediately before the second, child of this element, {{domxref("Node")}}.
-
{{domxref("Node.isDefaultNamespace()")}}
-
 
-
{{domxref("Node.isEqualNode()")}}
-
 
-
{{domxref("Node.isSameNode()")}} {{obsolete_inline}}
-
 
-
{{domxref("Node.isSupported()")}} {{obsolete_inline}}
-
Returns a Boolean flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node.
-
{{domxref("Node.lookupPrefix()")}}
-
 
-
{{domxref("Node.lookupNamespaceURI()")}}
-
 
-
{{domxref("Node.normalize()")}}
-
Clean up all the text nodes under this element (merge adjacent, remove empty).
-
{{domxref("Node.removeChild()")}}
-
Removes a child node from the current element, which must be a child of the current node.
-
{{domxref("Node.replaceChild()")}}
-
Replaces one child {{domxref("Node")}} of the current one with the second one given in parameter.
-
{{domxref("Node.setUserData()")}} {{obsolete_inline}}
-
Allows a user to attach, or remove, {{domxref("DOMUserData")}} to the node.
-
 
-
- -

Examples

- -

Browse all child nodes

- -

The following function recursively cycles all child nodes of a node and executes a callback function upon them (and upon the parent node itself).

- -
function DOMComb (oParent, oCallback) {
-  if (oParent.hasChildNodes()) {
-    for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) {
-      DOMComb(oNode, oCallback);
-    }
-  }
-  oCallback.call(oParent);
-}
- -

Syntax

- -
DOMComb(parentNode, callbackFunction);
- -

Description

- -

Recursively cycle all child nodes of parentNode and parentNode itself and execute the callbackFunction upon them as this objects.

- -

Parameters

- -
-
parentNode
-
The parent node (Node Object).
-
callbackFunction
-
The callback function (Function).
-
- -

Sample usage

- -

The following example send to the console.log the text content of the body:

- -
function printContent () {
-  if (this.nodeValue) { console.log(this.nodeValue); }
-}
-
-onload = function () {
-  DOMComb(document.body, printContent);
-};
- -

Remove all children nested within a node

- -
Element.prototype.removeAll = function () {
-  while (this.firstChild) { this.removeChild(this.firstChild); }
-  return this;
-};
- -

Sample usage

- -
/* ... an alternative to document.body.innerHTML = "" ... */
-document.body.removeAll();
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removed the following properties: attributes, namespaceURI, prefix, and localName.
- Removed the following methods: isSupported(), hasAttributes(), isSameNode(), getFeature(), setUserData(), and getUserData().
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM3 Core')}}The methods insertBefore(), replaceChild(), removeChild(), and appendChild() returns one more kind of error (NOT_SUPPORTED_ERR) if called on a {{domxref("Document")}}.
- The normalize() method has been modified so that {{domxref("Text")}} node can also be normalized if the proper {{domxref("DOMConfiguration")}} flag is set.
- Added the following methods: compareDocumentPosition(), isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), and getUserData().
- Added the following properties: baseURI and textContent.
{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM2 Core')}}The ownerDocument property was slightly modified so that {{domxref("DocumentFragment")}} also returns null.
- Added the following properties: namespaceURI, prefix, and localName.
- Added the following methods: normalize(), isSupported() and hasAttributes().
{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}{{Spec2('DOM1')}}Initial definition.
- -

 

- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.
- Removed in {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
getUserData(), setUserData() and hasAttributes() {{deprecated_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
- Removed in {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSameNode() {{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("9.0")}}.
- Removed in {{CompatGeckoDesktop("10.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSupported() {{obsolete_inline}}{{CompatUnknown}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
- Removed in {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
attributes{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("21.0")}}.
- Moved to {{domxref("Element")}} in {{CompatGeckoDesktop("22.0")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Supported from {{CompatGeckoDesktop("1.0")}} to {{CompatGeckoDesktop("6.0")}}.
- Removed in {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
-
- -

[1] Webkit and Blink incorrectly do not make Node inherit from {{domxref("EventTarget")}}.

diff --git a/files/vi/web/api/node/insertbefore/index.html b/files/vi/web/api/node/insertbefore/index.html deleted file mode 100644 index f60a35f3e7..0000000000 --- a/files/vi/web/api/node/insertbefore/index.html +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: Node.insertBefore() -slug: Web/API/Node/insertBefore -translation_of: Web/API/Node/insertBefore ---- -
{{APIRef("DOM")}}
- -

Phương thức Node.insertBefore()  chèn một nút trước nút tài liệu tham khảo như một đối tượng con của một đối tượng gốc (đối tượng bố mẹ) cụ thể . Nếu đối tượng con đã cho là một tham chiếu tới tới một đối tượng node đang tồn tại trong tài liệu  , insertBefore() chuyển nó từ vị trí hiện tại  tới vị trí mới (không có yêu cầu nào phải xoá cái nút từ node gốc của nó trước khi thêm nó vào mấy nút khác).

- -

Vậy có nghĩa là một node thì không thể đồng thời ở tại hai điểm của tài liệu . Vậy, nếu node đã có nguồn gốc của nó rồi thì đối tượng node  sẽ bị chuyển đi trước tiên rồi sau đó bị chèn vào ở vị trí mới . {{domxref("Node.cloneNode()")}} có thể được sử dụng để tạo một bản sao của đối tượng  node trước khi thêm nó vào dưới phần tử gốc mới. Hãy lưu ý rằng những bản sao được tạo nên cùng cloneNode() sẽ không được tự động đồng bộ hoá.

- -

Nếu tài liệu ttham chiếu node là null thì node cụ thể được thêm vào đuôi của danh sách tập con của đối tượng node gốc.

- -

Nếu đối tượng  con đã cho là một {{domxref("DocumentFragment")}} thì toàn bộ nội dung của DocumentFragment  sẽ được chuyển đến danh sách tập con của đối tượng gốc cụ thể.

- -

Cú pháp

- -
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
-
- - - -

Nếu referenceNode là null thì newNode isẽ được chèn vào đuôi của danh sách các đối tượng tập con nodes .

- -
-

referenceNode  không phải  là một tham số  có thể tuỳ chọn -- bạn phải đưa ra một Node hoặc  null. Việc cung cấp nó thất bại hoặc đưa ra những giá trị không hợp lệ có thể sẽ behave  differently( hành xử khác nhau) trong mỗi phiên bản công cụ tìm kiếm khác nhau.

-
- -

Return value

- -

Giá trị được trả về sẽ là một phần tử con trừ khi newNode là một {{domxref("DocumentFragment")}}, trong trường hợp {{domxref("DocumentFragment")}} rỗng được trả về.

- -

Ví dụ

- -

Example 1

- -
<div id="parentElement">
-   <span id="childElement">foo bar</span>
-</div>
-
-<script>
-// Create the new node to insert
-var newNode = document.createElement("span");
-
-// Get a reference to the parent node
-var parentDiv = document.getElementById("childElement").parentNode;
-
-// Begin test case [ 1 ] : Exist a childElement --> All working correctly
-var sp2 = document.getElementById("childElement");
-parentDiv.insertBefore(newNode, sp2);
-// End test case [ 1 ]
-
-// Begin test case [ 2 ] : childElement is of Type undefined
-var sp2 = undefined; // Not exist a node of id "childElement"
-parentDiv.insertBefore(newNode, sp2); // Implicit dynamic cast to type Node
-// End test case [ 2 ]
-
-// Begin test case [ 3 ] : childElement is of Type "undefined" ( string )
-var sp2 = "undefined"; // Not exist a node of id "childElement"
-parentDiv.insertBefore(newNode, sp2); // Generate "Type Error: Invalid Argument"
-// End test case [ 3 ]
-</script>
-
- -

Example 2

- -
<div id="parentElement">
-  <span id="childElement">foo bar</span>
-</div>
-
-<script>
-// Create a new, plain <span> element
-var sp1 = document.createElement("span");
-
-// Get a reference to the element, before we want to insert the element
-var sp2 = document.getElementById("childElement");
-// Get a reference to the parent element
-var parentDiv = sp2.parentNode;
-
-// Insert the new element into the DOM before sp2
-parentDiv.insertBefore(sp1, sp2);
-</script>
- -

Không hề có phương thức  insertAfter() nào cả. Nó có thể được mô phỏng bởi phương thức  insertBefore cùng với {{domxref("Node.nextSibling")}}.

- -

Trong ví dụ trước, sp1 đã chèn được vào sau  sp2 bằng cách dùng :

- -
parentDiv.insertBefore(sp1, sp2.nextSibling);
- -

Nếu sp2 không có đối tượng anh em nào tiếp nữa , thì nó hẳn phải là đối tượng con cuối cùng — sp2.nextSibling trả về null, và sp1 sẽ được chèn vào cuối cùng của danh sách tập node con (ngay sau sp2).

- -

Example 3

- -

Chèn một phần tử vào phần tử con đứng đầu bằng cách dùng đặc tính firstChild.

- -
// Get a reference to the element in which we want to insert a new node
-var parentElement = document.getElementById('parentElement');
-// Get a reference to the first child
-var theFirstChild = parentElement.firstChild;
-
-// Create a new element
-var newElement = document.createElement("div");
-
-// Insert the new element before the first child
-parentElement.insertBefore(newElement, theFirstChild);
- -

Khi phần tử không có con cả (đối tượng con đầu tiên) thì  firstChild là null. Phần tử vẫn được thêm vào bố mẹ đối tượng gốc, sau con út (đối tượng con cuối cùng). Bởi bố mẹ không có con cả nên nó cũng không có con út luôn. Như vậy, phần tử mới sẽ là phần tử duy nhất sau việc chia cắt.

- -

Khả năng tương thích của công cụ tìm kiếm

- - - -

{{Compat("api.Node.insertBefore")}}

- -

Chi tiết

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM WHATWG')}}Fixes errors in the insertion algorithm
{{SpecName('DOM4','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM4')}}Describes the algorithm in more detail
{{SpecName('DOM3 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM3 Core')}}No notable changes
{{SpecName('DOM2 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM2 Core')}}No notable changes
{{SpecName('DOM1','level-one-core.html#method-insertBefore','Node.insertBefore')}}{{Spec2('DOM1')}}Introduced
- -

Xem thêm

- - diff --git a/files/vi/web/api/node/parentelement/index.html b/files/vi/web/api/node/parentelement/index.html deleted file mode 100644 index 7e1e081325..0000000000 --- a/files/vi/web/api/node/parentelement/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Node.parentElement -slug: Web/API/Node/parentElement -tags: - - API - - Cần tương thích trình duyệt - - Mô hình Đối tượng Văn bản - - Nút - - Thuộc tính -translation_of: Web/API/Node/parentElement ---- -
-
{{APIRef("DOM")}}
-
- -

Thuộc tính chỉ-đọc Node.parentElement trả về cha của nút DOM {{domxref("Element")}}, hoặcnull nếu nút không có cha hoặc cha của nó không là {{domxref("Element")}} DOM.

- -

Cú pháp

- -
parentElement = node.parentElement
- -

parentElement là thành phần cha của nút hiện tại. Nó luôn luôn là một đối tượng {{domxref("Element")}} DOM, hoặc null.

- -

Ví dụ

- -
if (node.parentElement) {
-    node.parentElement.style.color = "red";
-}
- -

Tương thích trình duyệt

- -

Trên một vài trình duyệt, thuộc tính parentElement chỉ được xác định trên những nút mà chính nó là một {{domxref("Element")}}. Đặc biệt, nó không xác định trên các nút văn bản.

- -
- - -

{{Compat("api.Node.parentElement")}}

-
- -

Thông số

- - - -

Xem thêm

- - diff --git a/files/vi/web/api/node/parentnode/index.html b/files/vi/web/api/node/parentnode/index.html deleted file mode 100644 index a93e4d8ac9..0000000000 --- a/files/vi/web/api/node/parentnode/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Node.parentNode -slug: Web/API/Node/parentNode -tags: - - API - - Gecko - - Mô hình Đối tượng Tài liệu - - Thuộc tính -translation_of: Web/API/Node/parentNode ---- -
-
{{APIRef("DOM")}}
-
- -

 

- -

Thuộc tính chỉ-đọc Node.parentNode trả về cha của một nút xác định trong DOM.

- -

Cú pháp

- -
parentNode = node.parentNode
-
- -

parentNode là cha của nút hiện tại. Cha của một phần tử là một nút Element,một nút Document, hoặc một nút DocumentFragment.

- -

Ví dụ

- -
if (node.parentNode) {
-  // loại bỏ một nút khỏi cây, trừ khi
-  // nó không nằm trong cây
-  node.parentNode.removeChild(node);
-}
- -

Chú ý

- -

Các nodes Document và DocumentFragment có thể không có cha, vì vậy parentNode có thể luôn trả về giá trị null.

- -

Nó cũng trả về null nếu nút vừa được tạo và chưa được đính vào cây.

- -

Tương thích trình duyệt

- - - -

{{Compat("api.Node.parentNode")}}

- -

Thông số

- - - -

Xem thêm

- - diff --git a/files/vi/web/api/notification/index.html b/files/vi/web/api/notification/index.html deleted file mode 100644 index 829159b490..0000000000 --- a/files/vi/web/api/notification/index.html +++ /dev/null @@ -1,408 +0,0 @@ ---- -title: Notification -slug: Web/API/notification -translation_of: Web/API/Notification ---- -

{{APIRef("Web Notifications")}}

- -

The Notification interface of the Notifications API is used to configure and display desktop notifications to the user.

- -

{{AvailableInWorkers}}

- -

Hàm khởi tạo

- -
-
{{domxref("Notification.Notification", "Notification()")}}
-
Creates a new instance of the {{domxref('Notification')}} object.
-
- -

Properties

- -

Static properties

- -

These properties are available only on the Notification object itself.

- -
-
{{domxref("Notification.permission")}} {{readonlyinline}}
-
A string representing the current permission to display notifications. Possible value are: denied (the user refuses to have notifications displayed), granted (the user accepts having notifications displayed), or default (the user choice is unknown and therefore the browser will act as if the value were denied).
-
- -

Instance properties

- -

These properties are available only on instances of the Notification object.

- -
-
{{domxref("Notification.title")}} {{readonlyinline}}
-
The title of the notification as specified in the options parameter of the constructor.
-
{{domxref("Notification.dir")}} {{readonlyinline}}
-
The text direction of the notification as specified in the options parameter of the constructor.
-
{{domxref("Notification.lang")}} {{readonlyinline}}
-
The language code of the notification as specified in the options parameter of the constructor.
-
{{domxref("Notification.body")}} {{readonlyinline}}
-
The body string of the notification as specified in the options parameter of the constructor.
-
{{domxref("Notification.tag")}} {{readonlyinline}}
-
The ID of the notification (if any) as specified in the options parameter of the constructor.
-
{{domxref("Notification.icon")}} {{readonlyinline}}
-
The URL of the image used as an icon of the notification as specified in the options parameter of the constructor.
-
{{domxref("Notification.data")}} {{readonlyinline}}
-
Returns a structured clone of the notification’s data.
-
{{domxref("Notification.requireInteraction")}} {{readonlyinline}}
-
A {{jsxref("Boolean")}} indicating that on devices with sufficiently large screens, a notification should remain active until the user clicks or dismisses it.
-
{{domxref("Notification.silent")}} {{readonlyinline}}
-
Specifies whether the notification should be silent, i.e. no sounds or vibrations should be issued, regardless of the device settings.
-
{{domxref("Notification.timestamp")}} {{readonlyinline}}
-
Specifies the time at which a notification is created or applicable (past, present, or future).
-
- -

Unsupported properties

- -

The following properties are listed in the most up-to-date spec, but are not supported in any browsers yet. It is advisable to keep checking back regularly to see if the status of these has updated, and let us know if you find any out of date information.

- -
-
{{domxref("Notification.noscreen")}} {{readonlyinline}}
-
Specifies whether the notification firing should enable the device's screen or not.
-
{{domxref("Notification.renotify")}} {{readonlyinline}}
-
Specifies whether the user should be notified after a new notification replaces an old one.
-
{{domxref("Notification.sound")}} {{readonlyinline}}
-
Specifies a sound resource to play when the notification fires, in place of the default system notification sound.
-
{{domxref("Notification.sticky")}} {{readonlyinline}}
-
Specifies whether the notification should be 'sticky', i.e. not easily clearable by the user.
-
{{domxref("Notification.vibrate")}} {{readonlyinline}}
-
Specifies a vibration pattern for devices with vibration hardware to emit.
-
- -

Event handlers

- -
-
{{domxref("Notification.onclick")}}
-
A handler for the {{event("click")}} event. It is triggered each time the user clicks on the notification.
-
{{domxref("Notification.onerror")}}
-
A handler for the {{event("error")}} event. It is triggered each time the notification encounters an error.
-
- -

Obsolete handlers

- -

The following event handlers are still supported as listed in the {{anch("browser compatibility")}} section below, but are no longer listed in the current spec. I is safe therefore to assume they are obsolete, and may stop working in future browser versions.

- -
-
{{domxref("Notification.onclose")}}
-
A handler for the {{event("close")}} event. It is triggered when the user closes the notification.
-
{{domxref("Notification.onshow")}}
-
A handler for the {{event("show")}} event. It is triggered when the notification is displayed.
-
- -

Methods

- -

Static methods

- -

These methods are available only on the Notification object itself.

- -
-
{{domxref("Notification.requestPermission()")}}
-
Requests permission from the user to display notifications.
-
- -

Instance methods

- -

These properties are available only on an instance of the Notification object or through its prototype. The Notification object also inherits from the {{domxref("EventTarget")}} interface.

- -
-
{{domxref("Notification.close()")}}
-
Programmatically closes a notification.
-
- -

Example

- -

Assume this basic HTML:

- -
<button onclick="notifyMe()">Notify me!</button>
- -

It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.

- -
function notifyMe() {
-  // Let's check if the browser supports notifications
-  if (!("Notification" in window)) {
-    alert("This browser does not support desktop notification");
-  }
-
-  // Let's check whether notification permissions have already been granted
-  else if (Notification.permission === "granted") {
-    // If it's okay let's create a notification
-    var notification = new Notification("Hi there!");
-  }
-
-  // Otherwise, we need to ask the user for permission
-  else if (Notification.permission !== 'denied') {
-    Notification.requestPermission(function (permission) {
-      // If the user accepts, let's create a notification
-      if (permission === "granted") {
-        var notification = new Notification("Hi there!");
-      }
-    });
-  }
-
-  // At last, if the user has denied notifications, and you
-  // want to be respectful there is no need to bother them any more.
-}
- -

{{EmbedLiveSample('Example', '100%', 30)}}

- -

In many cases, you don't need to be this verbose. For example, in our Emogotchi demo (see source code), we simply run {{domxref("Notification.requestPermission")}} regardless to make sure we can get permission to send notifications (this uses the newer promise-based method syntax):

- -
Notification.requestPermission().then(function(result) {
-  console.log(result);
-});
- -

Then we run a simple spawnNotification() function when we want to fire a notification — this is passed arguments to specify the body, icon and title we want, then it creates the necessary options object and fires the notification using the {{domxref("Notification.Notification","Notification()")}} constructor.

- -
function spawnNotification(theBody,theIcon,theTitle) {
-  var options = {
-      body: theBody,
-      icon: theIcon
-  }
-  var n = new Notification(theTitle,options);
-}
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{property_prefix("webkit")}}[1]
- 22
4.0 {{property_prefix("moz")}}[2]
- 22
{{CompatNo}}256[3]
icon5{{property_prefix("webkit")}}[1]
- 22
4.0 {{property_prefix("moz")}}[2]
- 22
{{CompatNo}}25{{CompatNo}}
Available in workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
silent{{CompatChrome(43.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
noscreen, sticky{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
sound{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
renotify{{CompatChrome(50.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Promise-based Notification.requestPermission(){{CompatUnknown}}{{CompatGeckoDesktop("47.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}} -

{{CompatVersionUnknown}}

-
4.0{{property_prefix("moz")}}[2]
- 22
1.0.1{{property_prefix("moz")}}[2]
- 1.2
{{CompatNo}}{{CompatUnknown}}{{CompatNo}} -

{{CompatVersionUnknown}}

-
icon{{CompatUnknown}}{{CompatVersionUnknown}}4.0{{property_prefix("moz")}}[2]
- 22
1.0.1{{property_prefix("moz")}}[2]
- 1.2
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
Available in workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
silent{{CompatNo}}{{CompatChrome(43.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(43.0)}}
noscreen, sticky{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
sound{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
renotify{{CompatNo}}{{CompatChrome(50.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Promise-based Notification.requestPermission(){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("47.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Before Chrome 22, the support for notification followed an old prefixed version of the specification and used the {{domxref("window.navigator.webkitNotifications","navigator.webkitNotifications")}} object to instantiate a new notification.

- -

Before Chrome 32, {{domxref("Notification.permission")}} was not supported.

- -

Before Chrome 42, service worker additions were not supported.

- -

Starting in Chrome 49, notifications do not work in incognito mode.

- -

[2] Prior to Firefox 22 (Firefox OS <1.2), the instantiation of a new notification must be done with the {{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} object through its createNotification method.

- -

Prior to Firefox 22 (Firefox OS <1.2), the Notification was displayed when calling the show method and supported only the click and close events.

- -

Nick Desaulniers wrote a Notification shim to cover both newer and older implementations.

- -

One particular Firefox OS issue is that you can pass a path to an icon to use in the notification, but if the app is packaged you cannot use a relative path like /my_icon.png. You also can't use window.location.origin + "/my_icon.png" because window.location.origin is null in packaged apps. The manifest origin field fixes this, but it is only available in Firefox OS 1.1+. A potential solution for supporting Firefox OS <1.1 is to pass an absolute URL to an externally hosted version of the icon. This is less than ideal as the notification is displayed immediately without the icon, then the icon is fetched, but it works on all versions of Firefox OS.

- -

When using notifications  in a Firefox OS app, be sure to add the desktop-notification permission in your manifest file. Notifications can be used at any permission level, hosted or above: "permissions": { "desktop-notification": {} }

- -

[3] Safari started to support notification with Safari 6, but only on Mac OSX 10.8+ (Mountain Lion).

- -

See also

- - diff --git a/files/vi/web/api/touch_events/index.html b/files/vi/web/api/touch_events/index.html deleted file mode 100644 index f723a4f971..0000000000 --- a/files/vi/web/api/touch_events/index.html +++ /dev/null @@ -1,340 +0,0 @@ ---- -title: Touch events -slug: Web/API/Touch_events -tags: - - Advanced - - DOM - - Event - - Guide - - Mobile - - NeedsTranslation - - Overview - - TopicStub - - touch -translation_of: Web/API/Touch_events ---- -
{{DefaultAPISidebar("Touch Events")}}
- -

In order to provide quality support for touch-based user interfaces, touch events offer the ability to interpret finger (or stylus) activity on touch screens or trackpads.

- -

The touch events interfaces are relatively low-level APIs that can be used to support application specific multi-touch interactions such as a two-finger gesture. A multi-touch interaction starts when a finger (or stylus) first touches the contact surface. Other fingers may subsequently touch the surface and optionally move across the touch surface. The interaction ends when the fingers are removed from the surface. During this interaction, an application receives touch events during the start, move and end phases.

- -

Touch events are similar to mouse events except they support simultaneous touches and at different locations on the touch surface. The {{domxref("TouchEvent")}} interface encapsulates all of the touch points that are currently active. The {{domxref("Touch")}} interface, which represents a single touch point, includes information such as the position of the touch point relative to the browser viewport.

- -

Definitions

- -
-
Surface
-
The touch-sensitive surface. This may be a screen or trackpad.
-
- -
-
Touch point
-
A point of contact with the surface. This may be a finger (or elbow, ear, nose, whatever, but typically a finger) or stylus.
-
- -

Interfaces

- -
-
{{domxref("TouchEvent")}}
-
Represents an event that occurs when the state of touches on the surface changes.
-
{{domxref("Touch")}}
-
Represents a single point of contact between the user and the touch surface.
-
{{domxref("TouchList")}}
-
Represents a group of touches; this is used when the user has, for example, multiple fingers on the surface at the same time.
-
- -

Example

- -

This example tracks multiple touch points at a time, allowing the user to draw in a {{HTMLElement("canvas")}} with more than one finger at a time. It will only work on a browser that supports touch events.

- -
Note: The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method.
- -

Create a canvas

- -
<canvas id="canvas" width="600" height="600" style="border:solid black 1px;">
-  Your browser does not support canvas element.
-</canvas>
-<br>
-<button onclick="startup()">Initialize</button>
-<br>
-Log: <pre id="log" style="border: 1px solid #ccc;"></pre>
-
- -

Setting up the event handlers

- -

When the page loads, the startup() function shown below should be called by our {{HTMLElement("body")}} element's onload attribute (but in the example we use a button to trigger it, due to limitations of the MDN live example system).

- -
function startup() {
-  var el = document.getElementsByTagName("canvas")[0];
-  el.addEventListener("touchstart", handleStart, false);
-  el.addEventListener("touchend", handleEnd, false);
-  el.addEventListener("touchcancel", handleCancel, false);
-  el.addEventListener("touchmove", handleMove, false);
-  console.log("initialized.");
-}
-
- -

This simply sets up all the event listeners for our {{HTMLElement("canvas")}} element so we can handle the touch events as they occur.

- -

Tracking new touches

- -

We'll keep track of the touches in-progress.

- -
var ongoingTouches = [];
-
- -

When a {{event("touchstart")}} event occurs, indicating that a new touch on the surface has occurred, the handleStart() function below is called.

- -
function handleStart(evt) {
-  evt.preventDefault();
-  console.log("touchstart.");
-  var el = document.getElementsByTagName("canvas")[0];
-  var ctx = el.getContext("2d");
-  var touches = evt.changedTouches;
-
-  for (var i = 0; i < touches.length; i++) {
-    console.log("touchstart:" + i + "...");
-    ongoingTouches.push(copyTouch(touches[i]));
-    var color = colorForTouch(touches[i]);
-    ctx.beginPath();
-    ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 * Math.PI, false);  // a circle at the start
-    ctx.fillStyle = color;
-    ctx.fill();
-    console.log("touchstart:" + i + ".");
-  }
-}
-
- -

This calls {{domxref("event.preventDefault()")}} to keep the browser from continuing to process the touch event (this also prevents a mouse event from also being delivered). Then we get the context and pull the list of changed touch points out of the event's {{domxref("TouchEvent.changedTouches")}} property.

- -

After that, we iterate over all the {{domxref("Touch")}} objects in the list, pushing them onto an array of active touch points and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4 pixel radius circle will show up neatly.

- -

Drawing as the touches move

- -

Each time one or more fingers moves, a {{event("touchmove")}} event is delivered, resulting in our handleMove() function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch.

- -
function handleMove(evt) {
-  evt.preventDefault();
-  var el = document.getElementsByTagName("canvas")[0];
-  var ctx = el.getContext("2d");
-  var touches = evt.changedTouches;
-
-  for (var i = 0; i < touches.length; i++) {
-    var color = colorForTouch(touches[i]);
-    var idx = ongoingTouchIndexById(touches[i].identifier);
-
-    if (idx >= 0) {
-      console.log("continuing touch "+idx);
-      ctx.beginPath();
-      console.log("ctx.moveTo(" + ongoingTouches[idx].pageX + ", " + ongoingTouches[idx].pageY + ");");
-      ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
-      console.log("ctx.lineTo(" + touches[i].pageX + ", " + touches[i].pageY + ");");
-      ctx.lineTo(touches[i].pageX, touches[i].pageY);
-      ctx.lineWidth = 4;
-      ctx.strokeStyle = color;
-      ctx.stroke();
-
-      ongoingTouches.splice(idx, 1, copyTouch(touches[i]));  // swap in the new touch record
-      console.log(".");
-    } else {
-      console.log("can't figure out which touch to continue");
-    }
-  }
-}
-
- -

This iterates over the changed touches as well, but it looks in our cached touch information array for the previous information about each touch in order to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's {{domxref("Touch.identifier")}} property. This property is a unique integer for each touch, and remains consistent for each event during the duration of each finger's contact with the surface.

- -

This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together.

- -

After drawing the line, we call Array.splice() to replace the previous information about the touch point with the current information in the ongoingTouches array.

- -

Handling the end of a touch

- -

When the user lifts a finger off the surface, a {{event("touchend")}} event is sent. We handle this by calling the handleEnd() function below. Its job is to draw the last line segment for each touch that ended and remove the touch point from the ongoing touch list.

- -
function handleEnd(evt) {
-  evt.preventDefault();
-  log("touchend");
-  var el = document.getElementsByTagName("canvas")[0];
-  var ctx = el.getContext("2d");
-  var touches = evt.changedTouches;
-
-  for (var i = 0; i < touches.length; i++) {
-    var color = colorForTouch(touches[i]);
-    var idx = ongoingTouchIndexById(touches[i].identifier);
-
-    if (idx >= 0) {
-      ctx.lineWidth = 4;
-      ctx.fillStyle = color;
-      ctx.beginPath();
-      ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
-      ctx.lineTo(touches[i].pageX, touches[i].pageY);
-      ctx.fillRect(touches[i].pageX - 4, touches[i].pageY - 4, 8, 8);  // and a square at the end
-      ongoingTouches.splice(idx, 1);  // remove it; we're done
-    } else {
-      console.log("can't figure out which touch to end");
-    }
-  }
-}
-
- -

This is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call Array.splice(), we simply remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touch point.

- -

Handling canceled touches

- -

If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the {{event("touchcancel")}} event is sent, and we call the handleCancel() function below.

- -
function handleCancel(evt) {
-  evt.preventDefault();
-  console.log("touchcancel.");
-  var touches = evt.changedTouches;
-
-  for (var i = 0; i < touches.length; i++) {
-    var idx = ongoingTouchIndexById(touches[i].identifier);
-    ongoingTouches.splice(idx, 1);  // remove it; we're done
-  }
-}
-
- -

Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment.

- -

Convenience functions

- -

This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear.

- -

Selecting a color for each touch

- -

In order to make each touch's drawing look different, the colorForTouch() function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches.

- -
function colorForTouch(touch) {
-  var r = touch.identifier % 16;
-  var g = Math.floor(touch.identifier / 3) % 16;
-  var b = Math.floor(touch.identifier / 7) % 16;
-  r = r.toString(16); // make it a hex digit
-  g = g.toString(16); // make it a hex digit
-  b = b.toString(16); // make it a hex digit
-  var color = "#" + r + g + b;
-  console.log("color for touch with identifier " + touch.identifier + " = " + color);
-  return color;
-}
-
- -

The result from this function is a string that can be used when calling {{HTMLElement("canvas")}} functions to set drawing colors. For example, for a {{domxref("Touch.identifier")}} value of 10, the resulting string is "#aaa".

- -

Copying a touch object

- -

Some browsers (mobile Safari, for one) re-use touch objects between events, so it's best to copy the bits you care about, rather than referencing the entire object.

- -
function copyTouch(touch) {
-  return { identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY };
-}
- -

Finding an ongoing touch

- -

The ongoingTouchIndexById() function below scans through the ongoingTouches array to find the touch matching the given identifier, then returns that touch's index into the array.

- -
function ongoingTouchIndexById(idToFind) {
-  for (var i = 0; i < ongoingTouches.length; i++) {
-    var id = ongoingTouches[i].identifier;
-
-    if (id == idToFind) {
-      return i;
-    }
-  }
-  return -1;    // not found
-}
-
- -

Showing what's going on

- -
function log(msg) {
-  var p = document.getElementById('log');
-  p.innerHTML = msg + "\n" + p.innerHTML;
-}
- -

If your browser supports it, you can {{LiveSampleLink('Example', 'see it live')}}.

- -

jsFiddle example

- -

Additional tips

- -

This section provides additional tips on how to handle touch events in your web application.

- -

Handling clicks

- -

Since calling preventDefault() on a {{event("touchstart")}} or the first {{event("touchmove")}} event of a series prevents the corresponding mouse events from firing, it's common to call preventDefault() on {{event("touchmove")}} rather than {{event("touchstart")}}. That way, mouse events can still fire and things like links will continue to work. Alternatively, some frameworks have taken to refiring touch events as mouse events for this same purpose. (This example is oversimplified and may result in strange behavior. It is only intended as a guide.)

- -
function onTouch(evt) {
-  evt.preventDefault();
-  if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0))
-    return;
-
-  var newEvt = document.createEvent("MouseEvents");
-  var type = null;
-  var touch = null;
-
-  switch (evt.type) {
-    case "touchstart":
-      type = "mousedown";
-      touch = evt.changedTouches[0];
-      break;
-    case "touchmove":
-      type = "mousemove";
-      touch = evt.changedTouches[0];
-      break;
-    case "touchend":
-      type = "mouseup";
-      touch = evt.changedTouches[0];
-      break;
-  }
-
-  newEvt.initMouseEvent(type, true, true, evt.originalTarget.ownerDocument.defaultView, 0,
-    touch.screenX, touch.screenY, touch.clientX, touch.clientY,
-    evt.ctrlKey, evt.altKey, evt.shiftKey, evt.metaKey, 0, null);
-  evt.originalTarget.dispatchEvent(newEvt);
-}
-
- -

Calling preventDefault() only on a second touch

- -

One technique for preventing things like pinchZoom on a page is to call preventDefault() on the second touch in a series. This behavior is not well defined in the touch events spec, and results in different behavior for different browsers (i.e., iOS will prevent zooming but still allow panning with both fingers; Android will allow zooming but not panning; Opera and Firefox currently prevent all panning and zooming.) Currently, it's not recommended to depend on any particular behavior in this case, but rather to depend on meta viewport to prevent zooming.

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Touch Events 2', '#touch-interface', 'Touch')}}{{Spec2('Touch Events 2')}}Added radiusX, radiusY, rotationAngle, force properties
{{SpecName('Touch Events', '#touch-interface', 'Touch')}}{{Spec2('Touch Events')}}Initial definition.
- -

Browser compatibility

- -

Touch

- - - -

{{Compat("api.Touch")}}

- -

Firefox, touch events, and multiprocess (e10s)

- -

In Firefox, touch events are disabled when e10s (electrolysis; multiprocess Firefox) is disabled. e10s is on by default in Firefox, but can end up becoming disabled in certain situations, for example when certain accessibility tools or Firefox add-ons are installed that require e10s to be disabled to work. This means that even on a touchscreen-enabled desktop/laptop, touch events won't be enabled.

- -

You can test whether e10s is disabled by going to about:support and looking at the "Multiprocess Windows" entry in the "Application Basics" section. 1/1 means it is enabled, 0/1 means disabled.

- -

If you want to force e10s to be on — to explicitly re-enable touch events support — you need to go to about:config and create a new Boolean preference browser.tabs.remote.force-enable. Set it to true, restart the browser, and e10s will be enabled regardless of any other settings.

diff --git a/files/vi/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html b/files/vi/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html deleted file mode 100644 index 33ca3f4490..0000000000 --- a/files/vi/web/api/touch_events/supporting_both_touchevent_and_mouseevent/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Supporting both TouchEvent and MouseEvent -slug: Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent -translation_of: Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent ---- -

{{DefaultAPISidebar("Touch Events")}}

- -

{{domxref("Touch_events","touch")}} interface cho phép cung cấp các tương tác với ứng dụng trên thiết bị. Tuy nhiên, sự thật là đa số các web hiện tại được thiết kế để làm việc với trỏ chuột. Thậm chí, khi trình duyệt hổ trợ touch, trình duyệt vẫn phải giả lập sự kiện của chuột.

- -

Event firing

- -

Touch event đưa ra vài yêu cầu cho trình duyệt (xem Interaction with Mouse Events and click để xem chi tiết), lưu ý răng trình duyệt có thể fire cả 2 sự kiện touch và mouse để đáp lại cùng một tương tác của user

- -

Nếu trình duyệt fire cả 2 sự kiện touch và mouse cho cùng tương tác, trình duyệt phải  fire {{event("touchstart")}} trước khi fire sự kiện mouse. Vì vậy, nếu ứng dụng không muốn sử dụng sự kiện mouse trên một element {{domxref("Touch.target","target")}}, chúng ta phải gọi {{domxref("Event.preventDefault()","preventDefault()")}}.

- -

Đây là một snippet code dùng {{event("touchmove")}} event handler và gọi preventDefault().

- -
// touchmove handler
-function process_touchmove(ev) {
-  // Call preventDefault() to prevent any further handling
-  ev.preventDefault();
-}
-
- -

Thứ tự Event

- -

Thứ tự của các sự kiện touch và mouse được định nghĩa như sau:

- - - -

Nếu {{event("touchstart")}}, {{event("touchmove")}} hoặc {{event("touchend")}} được hủy, sẽ không có sự mouse hoặc click nào được fire, thứ tự sẽ là:

- - - -

Community

- - - - - - diff --git a/files/vi/web/api/url_api/index.html b/files/vi/web/api/url_api/index.html deleted file mode 100644 index 71626f5c4a..0000000000 --- a/files/vi/web/api/url_api/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: URL API -slug: Web/API/URL_API -translation_of: Web/API/URL_API ---- -

{{DefaultAPISidebar("URL API")}}

- -

The URL API is a component of the URL standard, which defines what constitutes a valid {{Glossary("URL", "Uniform Resource Locator")}} and the API that accesses and manipulates URLs. The URL standard also defines concepts such as domains, hosts, and IP addresses, and also attempts to describe in a standard way the legacy application/x-www-form-urlencoded {{Glossary("MIME type")}} used to submit web forms' contents as a set of key/value pairs.

- -

Mô hình URL và cách sử dụng

- -

Phần lớn tiêu chuẩn URL được lấy theo định nghĩa của URL cùng cấu trúc và phân tích cú pháp. Nó cũng bao gồm các định nghĩa về các thuật ngữ khác nhau liên quan đến việc đánh địa chỉ các máy tính trên mạng, các thuật toán để phân tích địa chỉ IP và địa chỉ DOM được chỉ định.

- -

Truy cập component URL

- -

Tạo object {{domxref("URL")}} đối với một URL đã cho sẽ phân tích cú pháp URL và cung cấp quyền truy cập nhanh vào các thành phần của nó.

- -
let addr = new URL("https://wiki.developer.mozilla.org/vi/docs/Web/API/URL_API");
-let host = addr.host;
-let path = addr.pathname;
-
- -

Mã trên tạo ra 1 object URL cho bài viết bạn đang đọc, rồi lấy thuộc tính {{domxref("URL.host", "host")}} và {{domxref("URL.pathname", "pathname")}}. Trong tình huống trên, các giá trị tương ứng lần lượt là wiki.developer.mozilla.org/vi/docs/Web/API/URL_API.

- -

Thay đổi URL

- -

Hầu hết các thuộc tính của URL là cố định; bạn có thể viết các giá trị mới cho chúng để thay đổi URL. Ví dụ: để tạo URL mới và đặt tên người dùng:

- -
let myUsername = "someguy";
-let addr = new URL("https://mysite.com/login");
-addr.username = myUsername;
-
- -

Đặt giá trị của {{domxref("URL.username", "username")}} không chỉ thay đổi giá trị của thuộc tính, mà còn thay đổi cả đường dẫn URL. Sau khi thực thi đoạn code, giá trị trả về của {{domxref("URL.href", "addr.href")}} là https://someguy@mysite.com/login. Điều này đúng với mọi thuộc tính có thể ghi.

- -

Truy vấn

- -

Thuộc tính {{domxref("URL.search", "search")}} trong URL chứa các giá trị truy vấn của URL. Lấy ví dụ, nếu đường dẫn URL là https://mysite.com/login?user=someguy&page=news, thì giá trị của thuộc tính search?user=someguy&page=news. Bạn có thể kiểm tra các giá trị của mỗi tham số với {{domxref("URLSearchParams")}} là object của phương thức {{domxref("URLSearchParams.get", "get()")}}:

- -
let addr = new URL("https://mysite.com/login?user=someguy&page=news");
-try {
-  loginUser(addr.searchParams.get("user"));
-  gotoPage(addr.searchParams.get("page"));
-} catch(err) {
-  showErrorMessage(err);
-}
-
- -

Với ví dụ trên, username và trang đích được lấy từ query và chuyển vào trong function được dùng để điều hướng người dùng đăng nhập và chuyển tới trang đích mong muốn.

- -

Other functions within URLSearchParams let you change the value of keys, add and delete keys and their values, and even sort the list of parameters.

- -

URL API interfaces

- -

The URL API is a simple one, with only a couple of interfaces to its name:

- -
- -
- -

Older versions of the specification included an interface called {{domxref("URLUtilsReadOnly")}}, which has since been merged into the {{domxref("WorkerLocation")}} interface.

- -

Ví dụ

- -

If you want to process the parameters included in a URL, you could do it manually, but it's much easier to create a URL object to do it for you. The fillTableWithParameters() function below takes as input a {{domxref("HTMLTableElement")}} object representing a {{HTMLElement("table")}}. Rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value.

- -

Note the call to {{domxref("URLSearchParams.sort()")}} to sort the parameter list before generating the table.

- -
function fillTableWithParameters(tbl) {
-  let url = new URL(document.location.href);
-  url.searchParams.sort();
-  let keys = url.searchParams.keys();
-
-  for (let key of keys) {
-    let val = url.searchParams.get(key);
-    let row = document.createElement("tr");
-    let cell = document.createElement("td");
-    cell.innerText = key;
-    row.appendChild(cell);
-    cell = document.createElement("td");
-    cell.innerText = val;
-    row.appendChild(cell);
-    tbl.appendChild(row);
-  };
-}
- -

A working version of this example can be found on Glitch. Just add parameters to the URL when loading the page to see them in the table. For instance, try https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable.

- -

Quy chuẩn

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('URL')}}{{Spec2('URL')}}WHATWG specification
- -

Tương thích trình duyệt

- -
- - -

{{Compat("api.URL")}}

-
- -

Xem thêm

- - diff --git a/files/vi/web/api/webrtc_api/index.html b/files/vi/web/api/webrtc_api/index.html deleted file mode 100644 index 508df4945f..0000000000 --- a/files/vi/web/api/webrtc_api/index.html +++ /dev/null @@ -1,233 +0,0 @@ ---- -title: WebRTC API -slug: Web/API/WebRTC_API -tags: - - API - - Audio - - Conferencing - - Landing - - Media - - NeedsTranslation - - Networking - - TopicStub - - Video - - WebRTC - - WebRTC API - - streaming -translation_of: Web/API/WebRTC_API ---- -
{{WebRTCSidebar}}
- -

WebRTC (Web Real-Time Communication) is a technology which enables Web applications and sites to capture and optionally stream audio and/or video media, as well as to exchange arbitrary data between browsers without requiring an intermediary. The set of standards that comprise WebRTC makes it possible to share data and perform teleconferencing peer-to-peer, without requiring that the user installs plug-ins or any other third-party software.

- -

WebRTC consists of several interrelated APIs and protocols which work together to achieve this. The documentation you'll find here will help you understand the fundamentals of WebRTC, how to set up and use both data and media connections, and more.

- -

Interoperability

- -

Because implementations of WebRTC are still evolving, and because each browser has different levels of support for codecs and WebRTC features, you should strongly consider making use of the Adapter.js library provided by Google before you begin to write your code.

- -

Adapter.js uses shims and polyfills to smooth over the differences among the WebRTC implementations across the environments supporting it. Adapter.js also handles prefixes and other naming differences to make the entire WebRTC development process easier, with more broadly compatible results. The library is also available as an NPM package.

- -

To learn more about Adapter.js, see Improving compatibility using WebRTC adapter.js.

- -

WebRTC concepts and usage

- -

WebRTC serves multiple purposes; together with the Media Capture and Streams API, they provide powerful multimedia capabilities to the Web, including support for audio and video conferencing, file exchange, screen sharing, identity management, and interfacing with legacy telephone systems including support for sending {{Glossary("DTMF")}} (touch-tone dialing) signals. Connections between peers can be made without requiring any special drivers or plug-ins, and can often be made without any intermediary servers.

- -

Connections between two peers are represented by the {{DOMxRef("RTCPeerConnection")}} interface. Once a connection has been established and opened using RTCPeerConnection, media streams ({{DOMxRef("MediaStream")}}s) and/or data channels ({{DOMxRef("RTCDataChannel")}}s) can be added to the connection.

- -

Media streams can consist of any number of tracks of media information; tracks, which are represented by objects based on the {{DOMxRef("MediaStreamTrack")}} interface, may contain one of a number of types of media data, including audio, video, and text (such as subtitles or even chapter names). Most streams consist of at least one audio track and likely also a video track, and can be used to send and receive both live media or stored media information (such as a streamed movie).

- -

You can also use the connection between two peers to exchange arbitrary binary data using the {{DOMxRef("RTCDataChannel")}} interface. This can be used for back-channel information, metadata exchange, game status packets, file transfers, or even as a primary channel for data transfer.

- -

more details and links to relevant guides and tutorials needed

- -

WebRTC interfaces

- -

Because WebRTC provides interfaces that work together to accomplish a variety of tasks, we have divided up the interfaces in the list below by category. Please see the sidebar for an alphabetical list.

- -

Connection setup and management

- -

These interfaces are used to set up, open, and manage WebRTC connections. Included are interfaces representing peer media connections, data channels, and interfaces used when exchanging information on the capabilities of each peer in order to select the best possible configuration for a two-way media connection..

- -
-
{{DOMxRef("RTCPeerConnection")}}
-
Represents a WebRTC connection between the local computer and a remote peer. It is used to handle efficient streaming of data between the two peers.
-
{{DOMxRef("RTCDataChannel")}}
-
Represents a bi-directional data channel between two peers of a connection.
-
{{DOMxRef("RTCDataChannelEvent")}}
-
Represents events that occur while attaching a {{DOMxRef("RTCDataChannel")}} to a {{DOMxRef("RTCPeerConnection")}}. The only event sent with this interface is {{event("datachannel")}}.
-
{{DOMxRef("RTCSessionDescription")}}
-
Represents the parameters of a session. Each RTCSessionDescription consists of a description {{DOMxRef("RTCSessionDescription.type", "type")}} indicating which part of the offer/answer negotiation process it describes and of the {{Glossary("SDP")}} descriptor of the session.
-
{{DOMxRef("RTCSessionDescriptionCallback")}}
-
The RTCSessionDescriptionCallback is passed into the {{DOMxRef("RTCPeerConnection")}} object when requesting it to create offers or answers.
-
{{DOMxRef("RTCStatsReport")}}
-
Provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by calling {{DOMxRef("RTCPeerConnection.getStats()")}}. Details about using WebRTC statistics can be found in WebRTC Statistics API.
-
{{DOMxRef("RTCIceCandidate")}}
-
Represents a candidate Internet Connectivity Establishment ({{Glossary("ICE")}}) server for establishing an {{DOMxRef("RTCPeerConnection")}}.
-
{{DOMxRef("RTCIceTransport")}}
-
Represents information about an ICE transport.
-
{{DOMxRef("RTCIceServer")}}
-
Defines how to connect to a single ICE server (such as a {{Glossary("STUN")}} or {{Glossary("TURN")}} server).
-
{{DOMxRef("RTCPeerConnectionIceEvent")}}
-
Represents events that occur in relation to ICE candidates with the target, usually an {{DOMxRef("RTCPeerConnection")}}. Only one event is of this type: {{event("icecandidate")}}.
-
{{DOMxRef("RTCRtpSender")}}
-
Manages the encoding and transmission of data for a {{DOMxRef("MediaStreamTrack")}} on an {{DOMxRef("RTCPeerConnection")}}.
-
{{DOMxRef("RTCRtpReceiver")}}
-
Manages the reception and decoding of data for a {{DOMxRef("MediaStreamTrack")}} on an {{DOMxRef("RTCPeerConnection")}}.
-
{{DOMxRef("RTCRtpContributingSource")}}
-
Contains information about a given contributing source (CSRC) including the most recent time a packet that the source contributed was played out.
-
{{DOMxRef("RTCTrackEvent")}}
-
The interface used to represent a {{domxref("RTCPeerConnection.track_event", "track")}} event, which indicates that an {{DOMxRef("RTCRtpReceiver")}} object was added to the {{DOMxRef("RTCPeerConnection")}} object, indicating that a new incoming {{DOMxRef("MediaStreamTrack")}} was created and added to the RTCPeerConnection.
-
{{DOMxRef("RTCConfiguration")}}
-
Used to provide configuration options for an RTCPeerConnection.
-
- -
-
{{DOMxRef("RTCSctpTransport")}}
-
Provides information which describes a Stream Control Transmission Protocol ({{Glossary("SCTP")}}) transport and also provides a way to access the underlying Datagram Transport Layer Security ({{Glossary("DTLS")}}) transport over which SCTP packets for all of an RTCPeerConnection's data channels are sent and received.
-
{{DOMxRef("RTCSctpTransportState")}}
-
Indicates the state of an {{DOMxRef("RTCSctpTransport")}} instance.
-
- -

Identity and security

- -

The WebRTC API includes a number of interfaces which are used  to manage security and identity.

- -
-
{{DOMxRef("RTCIdentityProvider")}}
-
Enables a user agent is able to request that an identity assertion be generated or validated.
-
{{DOMxRef("RTCIdentityAssertion")}}
-
Represents the identity of the remote peer of the current connection. If no peer has yet been set and verified this interface returns null. Once set it can't be changed.
-
{{DOMxRef("RTCIdentityProviderRegistrar")}}
-
Registers an identity provider (idP).
-
{{DOMxRef("RTCIdentityEvent")}}
-
Represents an identity assertion generated by an identity provider (idP). This is usually for an {{DOMxRef("RTCPeerConnection")}}. The only event sent with this type is {{event("identityresult")}}.
-
{{DOMxRef("RTCIdentityErrorEvent")}}
-
Represents an error associated with the identity provider (idP). This is usually for an {{DOMxRef("RTCPeerConnection")}}. Two events are sent with this type: {{event("idpassertionerror")}} and {{event("idpvalidationerror")}}.
-
{{DOMxRef("RTCCertificate")}}
-
Represents a certificate that an {{DOMxRef("RTCPeerConnection")}} uses to authenticate.
-
- -

Telephony

- -

These interfaces are related to interactivity with Public-Switched Telephone Networks (PTSNs).

- -
-
{{DOMxRef("RTCDTMFSender")}}
-
Manages the encoding and transmission of Dual-Tone Multi-Frequency ({{Glossary("DTMF")}}) signaling for an {{DOMxRef("RTCPeerConnection")}}.
-
{{DOMxRef("RTCDTMFToneChangeEvent")}}
-
Used by the {{domxref("RTCDTMFSender.tonechange_event", "tonechange")}} event to indicate that a DTMF tone has either begun or ended. This event does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated).
-
- -

Guides

- -
-
Introduction to WebRTC protocols
-
This article introduces the protocols on top of which the WebRTC API is built.
-
WebRTC connectivity
-
A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.
-
Lifetime of a WebRTC session
-
WebRTC lets you build peer-to-peer communication of arbitrary data, audio, or video—or any combination thereof—into a browser application. In this article, we'll look at the lifetime of a WebRTC session, from establishing the connection all the way through closing the connection when it's no longer needed.
-
Establishing a connection: The perfect negotiation pattern
-
Perfect negotiation is a design pattern which is recommended for your signaling process to follow, which provides transparency in negotiation while allowing both sides to be either the offerer or the answerer, without significant coding needed to differentiate the two.
-
Signaling and two-way video calling
-
A tutorial and example which turns a WebSocket-based chat system created for a previous example and adds support for opening video calls among participants. The chat server's WebSocket connection is used for WebRTC signaling.
-
Codecs used by WebRTC
-
A guide to the codecs which WebRTC requires browsers to support as well as the optional ones supported by various popular browsers. Included is a guide to help you choose the best codecs for your needs.
-
Using WebRTC data channels
-
This guide covers how you can use a peer connection and an associated {{DOMxRef("RTCDataChannel")}} to exchange arbitrary data between two peers.
-
Using DTMF with WebRTC
-
WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the {{DOMxRef("RTCDTMFSender")}} interface. This guide shows how to do so.
-
- -

Tutorials

- -
-
Improving compatibility using WebRTC adapter.js
-
The WebRTC organization provides on GitHub the WebRTC adapter to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.
-
Taking still photos with WebRTC
-
This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it.
-
A simple RTCDataChannel sample
-
The {{DOMxRef("RTCDataChannel")}} interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the WebSocket API, so that the same programming model can be used for each.
-
- -

Resources

- -

Protocols

- -

WebRTC-proper protocols

- - - - - - - -

WebRTC statistics

- - - -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}The initial definition of the API of WebRTC.
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}}The initial definition of the object conveying the stream of media content.
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}}The initial definition on how to obtain stream of content from DOM Elements
- -

In additions to these specifications defining the API needed to use WebRTC, there are several protocols, listed under resources.

- - - - diff --git a/files/vi/web/api/webrtc_api/protocols/index.html b/files/vi/web/api/webrtc_api/protocols/index.html deleted file mode 100644 index 8d3bcb81e4..0000000000 --- a/files/vi/web/api/webrtc_api/protocols/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Introduction to WebRTC protocols -slug: Web/API/WebRTC_API/Protocols -translation_of: Web/API/WebRTC_API/Protocols ---- -
{{WebRTCSidebar}}{{draft}}
- -

Bài viết này giới thiệu các giao thức của WebRTC API được đã được xây dựng.

- -

ICE

- -

Interactive Connectivity Establishment (ICE) là một khuân mẫu cho phép trình duyệt của bạn kết nối với các trình duyệt khác. Có rất nhiều lý do tại sao việc kết nối trực tiếp từ A đến B một cách đơn giản sẽ không làm việc. Nó cần vượt qua firewall cái đã ngăn chặn mở môt cuộc kết nối trực tiếp, nó cung cấp cho bạn một địa chỉ duy nhất, trong hầu hết các trường hợp thiết bị của bạn không có địa chỉ public I, và chuyển tiếp dữ liệu thông qua một server nếu bộ định tuyến (router) của bạn không cho phép bạn kết nối một cách trực tiếp với browser khác. ICE sử dụng STUN hoặc TURN hay cả hai server để hoàn thành việc này như đã mô tả ở trên.

- -

STUN

- -

Session Traversal Utilities for NAT (STUN) (Từ viết tắt trong một từ viết tắt) là một giao thức để phát hiện ra địa chỉ IP pubic của bạn và xác định bất cứ hạn chế nào trong bộ định tuyến (router) của bạn đã ngăn chặn một cuộc kết nối trực tiếp với các browsers.

- -

Client sẽ gửi một yêu cầu tới STUN server thông qua internet, STUN server sẽ phản hồi địa chỉ IP public và client có thể có hoặc không truy cập được phìa sau bộ định tuyến NAT.

- -

An interaction between two users of a WebRTC application involving a STUN server.

- -

NAT

- -

Network Address Translation (NAT) được sử dụng để cung cấp cho thiết bị của bạn một địa chỉ IP public. Một bộ định tuyến (router) sẽ có một đia chỉ IP public và mỗi thiết bị được kết nối đến router sẽ có một đia chỉ IP private. Các requests sẽ được chuyển đổi từ địa chỉ IP private sang địa chỉ IP pubic với một cổng (port) duy nhất. Với cách này bạn không cần một địa chỉ IP public riêng cho từng thiết bị nhưng vẫn có thể được phát hiện trên internet.

- -

Một vài bộ định tuyến (routers) sẽ có những ngăn cản kết nối tới những thiết bị trên network. Điều này có nghĩa là ngay cả việc chúng ta có địa chỉ IP public đã được tìm ra bở STUN server, nhưng không một ai có thể tạo ra một kết nối. Trong tình huốn này chúng ta cần chuyển sang TURN.

- -

TURN

- -

Một vài bộ định tuyến (routers) sử dụng NAT được gọi là 'Symmetric NAT'. Nghĩa là bộ định tuyến (router) chỉ chấp nhận kết nối từ những peer mà bạn đã kết nối trước đó.

- -

Traversal Using Relays around NAT (TURN) có nghĩa là vượt qua hạn chế Symmetric NAT bằng các mở một kết nối với TURN server và truyền tải tất cả thông tin thông qua TURN server. Bạn sẽ tạo một kết nối với một TURN server và nói với tất cả các peer để gửi những gói tin đến server để sau đó nó sẽ chuyển lại cho bạn. Điều này rõ ràng đi kèm với các loại chi phí vì vậy nó chỉ được sử dụng nếu không có lựa chon nào thay thế.

- -

An interaction between two users of a WebRTC application involving STUN and TURN servers.

- -

SDP

- -

Session Description Protocol (SDP) là một tiêu chuẩn mô tả cho những nội dung đa phương tiện của một kết nối như độ phân giản (resolution), định dạn (formats), mã (codecs), mã hóa (encryption), v.v. cho nên tất cả các peers có thể hiểu những loại dữ liệu đang gửi đi. Vì vậy đây là siêu dữ liệu mô tả nội dung chứ không phải chính nội dung đa phương tiện.

- -

Về mặt kỹ thuận, SDP không thực sự là một protocol, nhưng định dạng data được sử dụng để mô tả kết nối chia sẻ đa phương tiện giữa các thiết bị.

- -

Documenting SDP is well outside the scope of this documentation; however, there are a few things worth noting here.

- -

Tài liệu SDP nằm ngoài phạm vi của tài liệu này. Tuy nhiên, có một vài thứ thực sự đáng chú ý ở đây.

- -

Cấu trúc

- -

SDP bao gồm một hay nhiều dòng text UTF-8, mỗi dòng bắt đầu với một kiểu ký tự, theo sau là một ký tự dấu bằng ("="), theo sau nữa là nội dung có cấu trúc bao gồm giá trị hay mô tả mà định dạng của nó phụ thuộc vào kiểu. Những dòng nội dung bắt đầu với một chữ (letter) thường được gọi là "letter-lines". Ví dụ, những dòng cung cấp mô tả đa phương tiện có kiểu "m", vì vậy những dòng của nó được xem như là "m-lines"

- -

Thông tin tham khảo

- -

Để tìm hiểu thêm về SDP, tham khảo những tài liệu hữu ích dưới đây:

- - diff --git a/files/vi/web/api/websockets_api/index.html b/files/vi/web/api/websockets_api/index.html deleted file mode 100644 index e69c174077..0000000000 --- a/files/vi/web/api/websockets_api/index.html +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: The WebSocket API (WebSockets) -slug: Web/API/WebSockets_API -tags: - - API - - Client - - Communication - - NeedsTranslation - - Overview - - Server - - TopicStub - - Two-Way - - WebSocket - - WebSocket API - - WebSockets - - data - - interactive -translation_of: Web/API/WebSockets_API ---- -

{{DefaultAPISidebar("Websockets API")}}

- -

Các WebSocket API là một công nghệ tiên tiến mà nó có thể tạo ra một phiên giao tiếp tương tác hai chiều giữa trình duyệt của người dùng và một máy chủ (server). Với API này, bạn có thể gửi những thông báo tới một máy chủ và nhận những phản hồi (response) hướng sự kiện (event-driven) mà không phải liên tục gửi yêu cầu máy chủ để nhận một câu trả lời.

- -
-

Chú ý: Mặc dù một kết nối Websocket có một số tính năng hơi giống với các socket kiểu Unix chuẩn, Nhưng chúng lại không có liên quan gì với nhau.

-
- -

Giao diện (Interfaces)

- -
-
WebSocket
-
Một giao diện cơ bản cho việc kết nối tới một máy chủ Websocket và sau đó là việc gửi và nhận dữ liệu trên kết nối đó.
-
CloseEvent
-
Sự kiện được gửi đi từ một đối tượng Websocket khi kết nối được đóng lại.
-
MessageEvent
-
Sự kiện được gửi bởi đối tượng Websocket khi một thông điệp được nhận từ một máy chủ.
-
- -

Công cụ

- - - - - - - -

 

- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComments
{{SpecName("HTML WHATWG", "web-sockets.html", "WebSocket API")}}{{Spec2("HTML WHATWG")}} 
WebSocketsCandidate Recommendation 
{{RFC(6455, "The WebSocket Protocol")}}IETF RFC 
- -

 

- -

Xem thêm

- - - -

Khả năng tương thích với các trình duyệt

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Tính năngChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Version -76 support {{obsolete_inline}}6{{CompatNo}}{{CompatGeckoDesktop("2.0")}}{{CompatNo}}11.00 (disabled)5.0.1
Protocol version 7 support {{obsolete_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("6.0")}}
- {{property_prefix("Moz")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
Protocol version 10 support {{obsolete_inline}}14{{CompatNo}}{{CompatGeckoDesktop("7.0")}}
- {{property_prefix("Moz")}}
HTML5 Labs{{CompatUnknown}}{{CompatUnknown}}
Standard - RFC 6455 Support4314{{CompatGeckoDesktop("48.0")}}1012.106.0
Usable in Workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("37.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Version -76 support {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Protocol version 7 support {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Protocol version 8 support (IETF draft 10) {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatGeckoMobile("7.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Standard - RFC 6455 Support4.4(Yes){{CompatGeckoDesktop("11.0")}}{{CompatUnknown}}12.106.0
Usable in Workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Chú ý về Gecko

- -

Việc hỗ trợ Websocket trên Firefox đang được tiếp tục với việc theo dõi sư thay đổi của đặc tả Websocket. Firefox 6 triển khai phiên bản 7 của các giao thức cơ bản, trong khi Firefox 7 triển khai phiên bản 8 (như mô tả bởi IETF draft 10). Firefox di đông đón nhận sự hỗ trợ WebSocket từ phiên bản Firefox di động 7.0.

- -

Gecko 6.0

- -

Trước Gecko 6.0 {{geckoRelease("6.0")}}, Đã có, không chính xác, một đối tượng WebSocket mà một số trang đã nghĩ rằng đó là việc bao hàm các dịch vụ WebSocket không có tiền tố; Đối tượng này vừa được đổi tên thành MozWebSocket.

- -

Gecko 7.0

- -

Bắt đầu từ phiên bản Gecko 7.0 {{geckoRelease("7.0")}}, thông số network.websocket.max-connections được sử dụng để xác định số lượng kết nối websocket tối đa có thể được mở trong một khoảng thời gian nhất định. Giá trị mặc định là 200.

- -

Gecko 8.0

- -

Bắt đầu từ phiên bản Gecko 8.0 {{geckoRelease("8.0")}}, phần mở rộng của luồng deflate-stream tới giao thức WebSocket đã bị vô hiệu hóa, bởi vì nó không còn được dùng trong các bản đặc tả. Điều này giải quyết vấn đề không tương thích giữa một số trang web.

- -

Gecko 11.0

- -

Trước phiên bản Gecko 11.0, Cả thông điệp đến và đi đều bị giới hạn ở kích thức 16MB. Bây giờ chúng có thể lên đến kích thước 2GB. Chú ý, tuy vậy vẫn còn tùy thuộc vào kích thước bộ nhớ (đặc biệt là trên thiết bị di động) làm cho nó chỉ là kích thước lý thuyết không phải là kích thước thực tế. Trong thực tế, việc truyền các dữ liệu kích thước như vậy sẽ thất bại nếu thiết bị không có đủ bộ nhớ.

- -

Ngoài ra, ArrayBuffer hỗ trợ cho việc gửi và nhận dữ liệu nhị phân đã được triển khai.

- -

Kể từ phiên bản Gecko 11.0, API Websocket không còn được thêm tiền tố nữa.

diff --git a/files/vi/web/api/websockets_api/writing_a_websocket_server_in_java/index.html b/files/vi/web/api/websockets_api/writing_a_websocket_server_in_java/index.html deleted file mode 100644 index 6258f6236f..0000000000 --- a/files/vi/web/api/websockets_api/writing_a_websocket_server_in_java/index.html +++ /dev/null @@ -1,217 +0,0 @@ ---- -title: Writing a WebSocket server in Java -slug: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java -tags: - - WebSocket -translation_of: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java ---- -

Giới thiệu

- -

Đây là một ví dụ để cho bạn biết thế nào là  một WebSocket API server sử dụng Oracle Java.
-
- Mặc dù có nhiều ngôn ngữ sercer-side khác nhau bạn có thể sử dụng để tạo một WebSocket server, đây là ví dụ sử dụng Oracle Java code đơn giản.

- -

Sever này phù hợp tiêu chuẩn RFC 6455, vì vậy nó chỉ kết nối từ  Chrome version 16, Firefox 11, IE 10 và cao hơn.

- -

Bước 1:

- -

WebSockets truyền đạt về một TCP (Transmission Control Protocol)  kết nối. Lớp Java's ServerSocket là nằm ở trong gói  java.net.

- -

ServerSocket

- -

Xây dựng:

- -
ServerSocket(int port)
- -

Khi bạn thuyết trình về ServerSocket class, it is bound to the port number you specified by the port argument.

- -

Here's how to implement what we have learnt:

- -
import java.net.ServerSocket;
-import java.net.Socket;
-
-public class Server{
-    public static void main(String[] args){
-        ServerSocket server = new ServerSocket(80);
-
-        System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection...");
-
-        Socket client = server.accept();
-
-        System.out.println("A client connected.");
-    }
-}
- -

Socket

- -

Methods:

- - - -

OutputStream

- -

Methods:

- -
write(byte[] b, int off, int len)
- -

Writes len bytes from the specified byte array starting at offset off to this output stream.

- -

InputStream

- -

Methods:

- -
read(byte[] b, int off, int len)
- -

Reads up to len bytes of data from the input stream into an array of bytes.

- -

Let us extend our example.

- -
Socket client = server.accept();
-
-System.out.println("A client connected.");
-
-InputStream in = client.getInputStream();
-
-OutputStream out = client.getOutputStream();
-
-new Scanner(in, "UTF-8").useDelimiter("\\r\\n\\r\\n").next();
- -

Handshaking

- -

When a client connects to a server, it sends a GET request to upgrade the connection to a WebSocket from a simple HTTP request. This is known as handshaking.

- -
import java.util.Scanner;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-//translate bytes of request to string
-String data = new Scanner(in,"UTF-8").useDelimiter("\\r\\n\\r\\n").next();
-
-Matcher get = Pattern.compile("^GET").matcher(data);
-
-if (get.find()) {
-
-} else {
-
-}
- -

Creating the response is easier than understanding why you must do it in this way.

- -

You must,

- -
    -
  1. Obtain the value of Sec-WebSocket-Key request header without any leading and trailing whitespace
  2. -
  3. Link it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  4. -
  5. Compute SHA-1 and Base64 code of it
  6. -
  7. Write it back as value of Sec-WebSocket-Accept response header as part of a HTTP response.
  8. -
- -
if (get.find()) {
-    Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
-    match.find();
-    byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n"
-            + "Connection: Upgrade\r\n"
-            + "Upgrade: websocket\r\n"
-            + "Sec-WebSocket-Accept: "
-            + DatatypeConverter
-            .printBase64Binary(
-                    MessageDigest
-                    .getInstance("SHA-1")
-                    .digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
-                            .getBytes("UTF-8")))
-            + "\r\n\r\n")
-            .getBytes("UTF-8");
-
-    out.write(response, 0, response.length);
-}
-
- -

Decoding messages

- -

After a successful handshake, client can send messages to the server, but now these are encoded.

- -

If we send "abcdef", we get these bytes:

- - - - - - - - - - - - - - - - - - -
129134167225225210198131130182194135
- -

- 129:

- - - - - - - - - - - - - - - - - - - - -
FIN (Is this the whole message?)RSV1RSV2RSV3Opcode
10000x1=0001
- -

FIN: You can send your message in frames, but now keep things simple.
- Opcode 0x1 means this is a text. Full list of Opcodes

- -

- 134:

- -

If the second byte minus 128 is between 0 and 125, this is the length of the message. If it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (64-bit unsigned integer, the most significant bit MUST be 0) are the length.

- -
-

I can take 128 because the first bit is always 1.

-
- -

- 167, 225, 225 and 210 are the bytes of the key to decode. It changes every time.

- -

- The remaining encoded bytes are the message.

- -

Decoding algorithm

- -

decoded byte = encoded byte XOR (position of encoded byte BITWISE AND 0x3)th byte of key

- -

Ví dụ trên Java:

- -
byte[] decoded = new byte[6];
-byte[] encoded = new byte[] {198, 131, 130, 182, 194, 135};
-byte[] key = byte[4] {167, 225, 225, 210};
-
-for (int i = 0; i < encoded.length; i++) {
-    decoded[i] = (byte)(encoded[i] ^ key[i & 0x3]);
-}
- -

Tài liệu liên quan

- - - -
 
diff --git a/files/vi/web/api/window/index.html b/files/vi/web/api/window/index.html deleted file mode 100644 index cc02cd80a2..0000000000 --- a/files/vi/web/api/window/index.html +++ /dev/null @@ -1,729 +0,0 @@ ---- -title: Window -slug: Web/API/Window -tags: - - API - - Browser - - DOM - - Interface - - JavaScript - - NeedsTranslation - - Reference - - Tab - - TopicStub - - Window - - global - - global scope - - scope -translation_of: Web/API/Window ---- -
{{APIRef("DOM")}}
- -

The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the {{domxref("document.defaultView")}} property.

- -

A global variable, window, representing the window in which the script is running, is exposed to JavaScript code.

- -

The Window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the Window interface is a suitable place to include these items that need to be globally available. Many of these are documented in the JavaScript Reference and the DOM Reference.

- -

In a tabbed browser, each tab is represented by its own Window object; the global window seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as {{Domxref("Window.resizeTo", "resizeTo()")}} and {{Domxref("Window.innerHeight", "innerHeight")}}. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.

- -

{{InheritanceDiagram}}

- -

Constructors

- -

See also the DOM Interfaces.

- -
-
{{domxref("DOMParser")}}
-
DOMParser can parse XML or HTML source stored in a string into a DOM Document. DOMParser is specified in DOM Parsing and Serialization.
-
{{domxref("Window.GeckoActiveXObject")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Image")}}
-
Used for creating an {{domxref("HTMLImageElement")}}.
-
{{domxref("Option")}}
-
Used for creating an {{domxref("HTMLOptionElement")}}
-
{{domxref("Window.QueryInterface")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.StaticRange")}} {{experimental_inline}} {{readonlyinline}}
-
Returns a {{domxref('StaticRange.StaticRange','StaticRange()')}} constructor which creates a {{domxref('StaticRange')}} object.
-
{{domxref("Worker")}}
-
Used for creating a Web worker
-
{{domxref("Window.XMLSerializer")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.XPCNativeWrapper")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.XPCSafeJSObjectWrapper")}}
-
{{todo("NeedsContents")}}
-
- -

Properties

- -

This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from the {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("WindowEventHandlers")}} mixins.

- -

Note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below.

- -
-
{{domxref("Window.closed")}} {{Non-standard_inline}} {{readOnlyInline}}
-
This property indicates whether the current window is closed or not.
-
{{domxref("Window.console")}} {{ReadOnlyInline}}
-
Returns a reference to the console object which provides access to the browser's debugging console.
-
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}} {{ReadOnlyInline}}
-
Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore.
-
{{domxref("Window.controllers")}} {{non-standard_inline}} {{ReadOnlyInline}}
-
Returns the XUL controller objects for the current chrome window.
-
{{domxref("Window.customElements")}} {{ReadOnlyInline}}
-
returns a reference to the {{domxref("CustomElementRegistry")}} object, which can be used to register new custom elements and get information about previously registered custom elements.
-
{{domxref("Window.crypto")}} {{readOnlyInline}}
-
Returns the browser crypto object.
-
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
-
Gets/sets the status bar text for the given window.
-
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}} {{ReadOnlyInline}}
-
Returns the ratio between physical pixels and device independent pixels in the current display.
-
{{domxref("Window.dialogArguments")}} {{ReadOnlyInline}}
-
Gets the arguments passed to the window (if it's a dialog box) at the time {{domxref("window.showModalDialog()")}} was called. This is an {{Interface("nsIArray")}}.
-
{{domxref("Window.directories")}} {{obsolete_inline}}
-
Synonym of {{domxref("window.personalbar")}}
-
{{domxref("Window.document")}} {{ReadOnlyInline}}
-
Returns a reference to the document that the window contains.
-
{{domxref("Window.DOMMatrix")}} {{readOnlyInline}} {{experimental_inline}}
-
Returns a reference to a {{domxref("DOMMatrix")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.
-
{{domxref("Window.DOMMatrixReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
-
Returns a reference to a {{domxref("DOMMatrixReadOnly")}} object, which represents 4x4 matrices, suitable for 2D and 3D operations.
-
{{domxref("Window.DOMPoint")}} {{readOnlyInline}} {{experimental_inline}}
-
Returns a reference to a {{domxref("DOMPoint")}} object, which represents a 2D or 3D point in a coordinate system.
-
{{domxref("Window.DOMPointReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
-
Returns a reference to a {{domxref("DOMPointReadOnly")}} object, which represents a 2D or 3D point in a coordinate system.
-
{{domxref("Window.DOMQuad")}} {{readOnlyInline}} {{experimental_inline}}
-
Returns a reference to a {{domxref("DOMQuad")}} object, which provides represents a quadrilaterial object, that is one having four corners and four sides.
-
{{domxref("Window.DOMRect")}} {{readOnlyInline}} {{experimental_inline}}
-
Returns a reference to a {{domxref("DOMRect")}} object, which represents a rectangle.
-
{{domxref("Window.DOMRectReadOnly")}} {{readOnlyInline}} {{experimental_inline}}
-
Returns a reference to a {{domxref("DOMRectReadOnly")}} object, which represents a rectangle.
-
{{domxref("Window.event")}} {{ReadOnlyInline}}
-
Returns the current event, which is the event currently being handled by the JavaScript code's context, or undefined if no event is currently being handled. The {{domxref("Event")}} object passed directly to event handlers should be used instead whenever possible.
-
{{domxref("Window.frameElement")}} {{readOnlyInline}}
-
Returns the element in which the window is embedded, or null if the window is not embedded.
-
{{domxref("Window.frames")}} {{readOnlyInline}}
-
Returns an array of the subframes in the current window.
-
{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}
-
This property indicates whether the window is displayed in full screen or not.
-
{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}
-
Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.
- Was: Multiple storage objects that are used for storing data across multiple pages.
-
{{domxref("Window.history")}} {{ReadOnlyInline}}
-
Returns a reference to the history object.
-
{{domxref("Window.innerHeight")}} {{readOnlyInline}}
-
Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
-
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
-
Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
-
{{domxref("Window.isSecureContext")}} {{experimental_inline}} {{readOnlyInline}}
-
Indicates whether a context is capable of using features that require secure contexts.
-
{{domxref("Window.length")}} {{readOnlyInline}}
-
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
-
{{domxref("Window.location")}}
-
Gets/sets the location, or current URL, of the window object.
-
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
-
Returns the locationbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.localStorage")}} {{readOnlyInline}} {{gecko_minversion_inline("1.9.1")}}
-
Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
-
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
-
Returns the menubar object, whose visibility can be toggled in the window.
-
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
-
Returns the message manager object for this window.
-
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}
-
The time in milliseconds since epoch at which the current animation cycle began. Use {{domxref("Animation.startTime")}} instead.
-
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}} {{non-standard_inline}} {{gecko_minversion_inline("1.9.2")}}
-
Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.
-
{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}} {{gecko_minversion_inline("1.9.2")}}
-
Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed.
-
{{domxref("Window.mozPaintCount")}} {{non-standard_inline}} {{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}
-
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.
-
{{domxref("Window.name")}}
-
Gets/sets the name of the window.
-
{{domxref("Window.navigator")}} {{readOnlyInline}}
-
Returns a reference to the navigator object.
-
{{domxref("Window.opener")}}
-
Returns a reference to the window that opened this current window.
-
{{domxref("Window.orientation")}} {{non-standard_inline}} {{deprecated_inline}} {{readOnlyInline}}
-
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.
-
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
-
Gets the height of the outside of the browser window.
-
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
-
Gets the width of the outside of the browser window.
-
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
-
An alias for {{domxref("window.scrollX")}}.
-
{{domxref("Window.scrollY","Window.pageYOffset")}} {{readOnlyInline}}
-
An alias for {{domxref("window.scrollY")}}
-
{{domxref("Window.parent")}} {{readOnlyInline}}
-
Returns a reference to the parent of the current window or subframe.
-
{{domxref("Window.performance")}} {{readOnlyInline}}
-
Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.
-
{{domxref("Window.personalbar")}} {{readOnlyInline}}
-
Returns the personalbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}
-
Formerly provided access to install and remove PKCS11 modules.
-
{{domxref("Window.returnValue")}}
-
The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.
-
{{domxref("Window.screen")}} {{readOnlyInline}}
-
Returns a reference to the screen object associated with the window.
-
{{domxref("Window.screenX")}} and {{domxref("Window.screenLeft")}} {{readOnlyInline}}
-
Both properties return the horizontal distance from the left border of the user's browser viewport to the left side of the screen.
-
{{domxref("Window.screenY")}} and {{domxref("Window.screenTop")}} {{readOnlyInline}}
-
Both properties return the vertical distance from the top border of the user's browser viewport to the top side of the screen.
-
{{domxref("Window.scrollbars")}} {{readOnlyInline}}
-
Returns the scrollbars object, whose visibility can be toggled in the window.
-
{{domxref("Window.scrollMaxX")}} {{non-standard_inline}} {{ReadOnlyInline}}
-
The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.
-
{{domxref("Window.scrollMaxY")}} {{non-standard_inline}} {{ReadOnlyInline}}
-
The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).
-
{{domxref("Window.scrollX")}} {{readOnlyInline}}
-
Returns the number of pixels that the document has already been scrolled horizontally.
-
{{domxref("Window.scrollY")}} {{readOnlyInline}}
-
Returns the number of pixels that the document has already been scrolled vertically.
-
{{domxref("Window.self")}} {{ReadOnlyInline}}
-
Returns an object reference to the window object itself.
-
{{domxref("Window.sessionStorage")}}
-
Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
-
{{domxref("Window.sidebar")}} {{non-standard_inline}} {{ReadOnlyInline}}
-
Returns a reference to the window object of the sidebar.
-
{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}
-
Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using Web Speech API speech synthesis functionality.
-
{{domxref("Window.status")}}
-
Gets/sets the text in the statusbar at the bottom of the browser.
-
{{domxref("Window.statusbar")}} {{readOnlyInline}}
-
Returns the statusbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.toolbar")}} {{readOnlyInline}}
-
Returns the toolbar object, whose visibility can be toggled in the window.
-
{{domxref("Window.top")}} {{readOnlyInline}}
-
Returns a reference to the topmost window in the window hierarchy. This property is read only.
-
{{domxref("Window.visualViewport")}} {{readOnlyInline}}
-
Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.
-
{{domxref("Window.window")}} {{ReadOnlyInline}}
-
Returns a reference to the current window.
-
window[0], window[1], etc.
-
Returns a reference to the window object in the frames. See {{domxref("Window.frames")}} for more details.
-
- -

Properties implemented from elsewhere

- -
-
{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}
-
Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.
-
{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}
-
Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.
-
{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}
-
Returns a boolean indicating whether the current context is secure (true) or not (false).
-
{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}
-
Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)
-
- -

Methods

- -

This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("EventTarget")}}.

- -
-
{{domxref("Window.alert()")}}
-
Displays an alert dialog.
-
{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Moves back one in the window history. This method is obsolete; you should instead use {{domxref("History.back", "window.history.back()")}}.
-
{{domxref("Window.blur()")}}
-
Sets focus away from the window.
-
{{domxref("Window.cancelAnimationFrame()")}} {{experimental_inline}}
-
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}.
-
{{domxref("Window.cancelIdleCallback()")}} {{experimental_inline}}
-
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}.
-
{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}
-
Registers the window to capture all events of the specified type.
-
{{domxref("Window.clearImmediate()")}}
-
Cancels the repeated execution set using setImmediate.
-
{{domxref("Window.close()")}}
-
Closes the current window.
-
{{domxref("Window.confirm()")}}
-
Displays a dialog with a message that the user needs to respond to.
-
{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.dispatchEvent()")}}
-
Used to trigger an event.
-
{{domxref("Window.dump()")}} {{Non-standard_inline}}
-
Writes a message to the console.
-
{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.find()")}}
-
Searches for a given string in a window.
-
{{domxref("Window.focus()")}}
-
Sets focus on the current window.
-
{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Moves the window one document forward in the history. This method is obsolete; you should instead use {{domxref("History.forward", "window.history.forward()")}}.
-
{{domxref("Window.getAttention()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Flashes the application icon.
-
{{domxref("Window.getAttentionWithCycleCount()")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.getComputedStyle()")}}
-
Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.
-
{{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_inline}}
-
Gets default computed style for the specified element, ignoring author stylesheets.
-
{{domxref("Window.getSelection()")}}
-
Returns the selection object representing the selected item(s).
-
{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Returns the browser to the home page.
-
{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}
-
Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.
-
{{domxref("Window.maximize()")}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.minimize()")}} (top-level XUL windows only)
-
Minimizes the window.
-
{{domxref("Window.moveBy()")}}
-
Moves the current window by a specified amount.
-
{{domxref("Window.moveTo()")}}
-
Moves the window to the specified coordinates.
-
{{domxref("Window.open()")}}
-
Opens a new window.
-
{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
Opens a new dialog window.
-
{{domxref("Window.postMessage()")}}
-
Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.
-
{{domxref("Window.print()")}}
-
Opens the Print Dialog to print the current document.
-
{{domxref("Window.prompt()")}}
-
Returns the text entered by the user in a prompt dialog.
-
{{domxref("Window.releaseEvents()")}} {{Non-standard_inline}} {{Deprecated_inline}}
-
Releases the window from trapping events of a specific type.
-
{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}
-
Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.
-
{{domxref("Window.requestIdleCallback()")}}  {{experimental_inline}}
-
Enables the scheduling of tasks during a browser's idle periods.
-
{{domxref("Window.resizeBy()")}}
-
Resizes the current window by a certain amount.
-
{{domxref("Window.resizeTo()")}}
-
Dynamically resizes window.
-
{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}
-
{{todo("NeedsContents")}}
-
{{domxref("Window.scroll()")}}
-
Scrolls the window to a particular place in the document.
-
{{domxref("Window.scrollBy()")}}
-
Scrolls the document in the window by the given amount.
-
{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}
-
Scrolls the document by the given number of lines.
-
{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}
-
Scrolls the current document by the specified number of pages.
-
{{domxref("Window.scrollTo()")}}
-
Scrolls to a particular set of coordinates in the document.
-
{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)
-
Changes the cursor for the current window
-
{{domxref("Window.setImmediate()")}}
-
Executes a function after the browser has finished other heavy tasks
-
{{domxref("Window.setResizable()")}} {{Non-standard_inline}}
-
Toggles a user's ability to resize a window.
-
{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}
-
Sizes the window according to its content.
-
{{domxref("Window.stop()")}}
-
This method stops window loading.
-
{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}
-
Updates the state of commands of the current chrome window (UI).
-
- -

Methods implemented from elsewhere

- -
-
{{domxref("EventTarget.addEventListener()")}}
-
Register an event handler to a specific event type on the window.
-
{{domxref("WindowOrWorkerGlobalScope.atob()")}}
-
Decodes a string of data which has been encoded using base-64 encoding.
-
{{domxref("WindowOrWorkerGlobalScope.btoa()")}}
-
Creates a base-64 encoded ASCII string from a string of binary data.
-
{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
-
Cancels the repeated execution set using {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.
-
{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}
-
Cancels the delayed execution set using {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.
-
{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}
-
Accepts a variety of different image sources, and returns a {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh.
-
{{domxref("WindowOrWorkerGlobalScope.fetch()")}}
-
Starts the process of fetching a resource from the network.
-
{{domxref("EventTarget.removeEventListener")}}
-
Removes an event listener from the window.
-
{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
-
Schedules a function to execute every time a given number of milliseconds elapses.
-
{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
-
Schedules a function to execute in a given amount of time.
-
- -

Obsolete methods

- -
-
{{domxref("Window.showModalDialog()")}} {{obsolete_inline}}
-
Displays a modal dialog. This method was removed completely in Chrome 43, and Firefox 55.
-
- -

Event handlers

- -

These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.

- -

This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowEventHandlers")}}.

- -
-

Note: Starting in {{Gecko("9.0")}}, you can now use the syntax if ("onabort" in window) to determine whether or not a given event handler property exists. This is because event handler interfaces have been updated to be proper web IDL interfaces. See DOM event handlers for details.

-
- -
-
{{domxref("Window.onappinstalled")}}
-
Called when the page is installed as a webapp. See {{event('appinstalled')}} event.
-
{{domxref("Window.onbeforeinstallprompt")}}
-
An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.
-
{{domxref("Window.ondevicelight")}}
-
An event handler property for any ambient light levels changes
-
{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}
-
Called if accelerometer detects a change (For mobile devices)
-
{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}
-
Called when the orientation is changed (For mobile devices)
-
{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only
-
An event handler property for any device orientation changes.
-
{{domxref("Window.ondeviceproximity")}}
-
An event handler property for device proximity event
-
{{domxref("Window.ongamepadconnected")}}
-
Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).
-
{{domxref("Window.ongamepaddisconnected")}}
-
Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).
-
{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}
-
An event handler property for the MozBeforePaint event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.
-
{{domxref("Window.onpaint")}}
-
An event handler property for paint events on the window.
-
{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}
-
An event handler for handled {{jsxref("Promise")}} rejection events.
-
{{domxref("Window.onuserproximity")}}
-
An event handler property for user proximity events.
-
{{domxref("Window.onvrdisplayconnect")}}
-
Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).
-
{{domxref("Window.onvrdisplaydisconnect")}}
-
Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).
-
{{domxref("Window.onvrdisplayactivate")}}
-
Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
-
{{domxref("Window.onvrdisplaydeactivate")}}
-
Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
-
{{domxref("Window.onvrdisplayblur")}}
-
Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
-
{{domxref("Window.onvrdisplayfocus")}}
-
Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).
-
{{domxref("Window.onvrdisplaypresentchange")}}
-
represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).
-
- -

Event handlers implemented from elsewhere

- -
-
{{domxref("GlobalEventHandlers.onabort")}}
-
Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress
-
{{domxref("WindowEventHandlers.onafterprint")}}
-
Called when the print dialog box is closed. See {{event("afterprint")}} event.
-
{{domxref("WindowEventHandlers.onbeforeprint")}}
-
Called when the print dialog box is opened. See {{event("beforeprint")}} event.
-
{{domxref("WindowEventHandlers.onbeforeunload")}}
-
An event handler property for before-unload events on the window.
-
{{domxref("GlobalEventHandlers.onblur")}}
-
Called after the window loses focus, such as due to a popup.
-
{{domxref("GlobalEventHandlers.onchange")}}
-
An event handler property for change events on the window.
-
{{domxref("GlobalEventHandlers.onclick")}}
-
Called after the ANY mouse button is pressed & released
-
{{domxref("GlobalEventHandlers.ondblclick")}}
-
Called when a double click is made with ANY mouse button.
-
{{domxref("GlobalEventHandlers.onclose")}}
-
Called after the window is closed
-
{{domxref("GlobalEventHandlers.oncontextmenu")}}
-
Called when the RIGHT mouse button is pressed
-
{{domxref("GlobalEventHandlers.onerror")}}
-
Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.
-
{{domxref("GlobalEventHandlers.onfocus")}}
-
Called after the window receives or regains focus. See {{event("focus")}} events.
-
{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}
-
An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.
-
{{domxref("GlobalEventHandlers.oninput")}}
-
Called when the value of an <input> element changes
-
{{domxref("GlobalEventHandlers.onkeydown")}}
-
Called when you begin pressing ANY key. See {{event("keydown")}} event.
-
{{domxref("GlobalEventHandlers.onkeypress")}}
-
Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.
-
{{domxref("GlobalEventHandlers.onkeyup")}}
-
Called when you finish releasing ANY key. See {{event("keyup")}} event.
-
{{domxref("WindowEventHandlers.onlanguagechange")}}
-
An event handler property for {{event("languagechange")}} events on the window.
-
{{domxref("GlobalEventHandlers.onload")}}
-
Called after all resources and the DOM are fully loaded. WILL NOT get called when the page is loaded from cache, such as with back button.
-
{{domxref("WindowEventHandlers.onmessage")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.
-
{{domxref("GlobalEventHandlers.onmousedown")}}
-
Called when ANY mouse button is pressed.
-
{{domxref("GlobalEventHandlers.onmousemove")}}
-
Called continously when the mouse is moved inside the window.
-
{{domxref("GlobalEventHandlers.onmouseout")}}
-
Called when the pointer leaves the window.
-
{{domxref("GlobalEventHandlers.onmouseover")}}
-
Called when the pointer enters the window
-
{{domxref("GlobalEventHandlers.onmouseup")}}
-
Called when ANY mouse button is released
-
{{domxref("WindowEventHandlers.onoffline")}}
-
Called when network connection is lost. See {{event("offline")}} event.
-
{{domxref("WindowEventHandlers.ononline")}}
-
Called when network connection is established. See {{event("online")}} event.
-
{{domxref("WindowEventHandlers.onpagehide")}}
-
Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.
-
{{domxref("WindowEventHandlers.onpageshow")}}
-
Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.
-
{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
-
Called when a back button is pressed.
-
{{domxref("GlobalEventHandlers.onreset")}}
-
Called when a form is reset
-
{{domxref("GlobalEventHandlers.onresize")}}
-
Called continuously as you are resizing the window.
-
{{domxref("GlobalEventHandlers.onscroll")}}
-
Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked
-
{{domxref("GlobalEventHandlers.onwheel")}}
-
Called when the mouse wheel is rotated around any axis
-
{{domxref("GlobalEventHandlers.onselect")}}
-
Called after text in an input field is selected
-
{{domxref("GlobalEventHandlers.onselectionchange")}}
-
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
-
{{domxref("WindowEventHandlers.onstorage")}}
-
Called when there is a change in session storage or local storage. See {{event("storage")}} event
-
{{domxref("GlobalEventHandlers.onsubmit")}}
-
Called when a form is submitted
-
{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}
-
An event handler for unhandled {{jsxref("Promise")}} rejection events.
-
{{domxref("WindowEventHandlers.onunload")}}
-
Called when the user navigates away from the page.
-
- -

Events

- -

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

- -
-
error
-
Fired when when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.
- Also available via the {{domxref("GlobalEventHandlers/onerror", "onerror")}} property.
-
languagechange
-
Fired at the global scope object when the user's preferred language changes.
- Also available via the onlanguagechange property.
-
orientationchange
-
Fired when the orientation of the device has changed.
- Also available via the onorientationchange property.
-
devicemotion
-
Fired at a regular interval, indicating the amount of physical force of acceleration the device is receiving and the rate of rotation, if available.
-
deviceorientation
-
Fired when fresh data is available from the magnetometer orientation sensor about the current orientation of the device as compared to the Earth coordinate frame.
-
{{domxref("Document/defaultView/resize_event", "resize")}}
-
Fired when the window has been resized.
- Also available via the onresize property.
-
{{domxref("Document/defaultView/storage_event", "storage")}}
-
Fired when a storage area (localStorage or sessionStorage) has been modified in the context of another document.
- Also available via the onstorage property.
-
- -

Animation events

- -
-
animationcancel
-
Fired when an animation unexpectedly aborts.
- Also available via the onanimationcancel property.
-
animationend
-
Fired when an animation has completed normally.
- Also available via the onanimationend property.
-
animationiteration
-
Fired when an animation iteration has completed.
- Also available via the onanimationiteration property.
-
animationstart
-
Fired when an animation starts.
- Also available via the onanimationstart property.
-
- -

Clipboard events

- -
-
clipboardchange
-
Fired when the system clipboard content changes.
-
copy
-
Fired when the user initiates a copy action through the browser's user interface.
- Also available via the oncopy property.
-
cut
-
Fired when the user initiates a cut action through the browser's user interface.
- Also available via the oncut property.
-
paste
-
Fired when the user initiates a paste action through the browser's user interface.
- Also available via the onpaste property.
-
- -

Connection events

- -
-
offline
-
Fired when the browser has lost access to the network and the value of navigator.onLine has switched to false.
- Also available via the {{domxref("WindowEventHandlers.onoffline", "onoffline")}} property.
-
online
-
Fired when the browser has gained access to the network and the value of navigator.onLine has switched to true.
- Also available via the {{domxref("WindowEventHandlers.ononline", "ononline")}} property.
-
- -

Focus events

- -
-
blur
-
Fired when an element has lost focus.
- Also available via the onblur property.
-
focus
-
Fired when an element has gained focus.
- Also available via the onfocus property
-
- -

Gamepad events

- -
-
gamepadconnected
-
Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.
- Also available via the ongamepadconnected property.
-
gamepaddisconnected
-
Fired when the browser detects that a gamepad has been disconnected.
- Also available via the ongamepaddisconnected property
-
- -

History events

- -
-
hashchange
-
Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).
- Also available via the onhashchange property.
-
pagehide
-
Sent when the browser  hides the current document while in the process of switching to displaying in its palce a different document from the session's history. This happens, for example, when the user clicks the Back button or when they click the Forward button to move ahead in session history.
- Also available through the onpagehide event handler property.
-
pageshow
-
Sent when the browser makes the document visible due to navigation tasks, including not only when the page is first loaded, but also situations such as the user navigating back to the page after having navigated to another within the same tab.
- Also available using the onpageshow event handler property.
-
{{domxref("Document/defaultView/popstate_event", "popstate")}}
-
Fired when the active history entry changes.
- Also available using the onpopstate event handler property.
-
- -

Load & unload events

- -
-
beforeunload
-
Fired when the window, the document and its resources are about to be unloaded.
- Also available via the onbeforeunload property.
-
DOMContentLoaded
-
Fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
-
load
-
Fired when the whole page has loaded, including all dependent resources such as stylesheets images.
- Also available via the onload property.
-
unload
-
Fired when the document or a child resource is being unloaded.
- Also available via the onunload property.
-
- -

Manifest events

- -
-
appinstalled
-
Fired when the browser has successfully installed a page as an application.
- Also available via the onappinstalled property.
-
beforeinstallprompt
-
Fired when a user is about to be prompted to install a web application.
- Also available via the onbeforeinstallprompt property.
-
- -

Messaging events

- -
-
message
-
Fired when the window receives a message, for example from a call to Window.postMessage() from another browsing context.
- Also available via the onmessage property.
-
messageerror
-
Fired when a Window object receives a message that can't be deserialized.
- Also available via the onmessageerror property.
-
- - - -
-
afterprint
-
Fired after the associated document has started printing or the print preview has been closed.
- Also available via the onafterprint property.
-
beforeprint
-
Fired when the associated document is about to be printed or previewed for printing.
- Also available via the onbeforeprint property.
-
- -

Promise rejection events

- -
-
rejectionhandled
-
Sent every time a JavaScript {{jsxref("Promise")}} is rejected, regardless of whether or not there is a handler in place to catch the rejection.
- Also available through the onrejectionhandled event handler property.
-
unhandledrejection
-
Sent when a JavaScript {{jsxref("Promise")}} is rejected but there is no handler in place to catch the rejection.
- Also available using the onunhandledrejection event handler property.
-
- -

Transition events

- -
-
transitioncancel
-
Fired when a CSS transition is canceled.
- Also available via the ontransitioncancel property.
-
transitionend
-
Fired when a CSS transition has completed.
- Also available via the ontransitionend property.
-
transitionrun
-
Fired when a CSS transition is first created.
- Also available via the ontransitionrun property.
-
transitionstart
-
Fired when a CSS transition has actually started.
- Also available via the ontransitionstart property.
-
- -

WebVR events

- -
-
vrdisplayactivate
-
Fired when a VR display becomes available to be presented to, for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
- Also available via the onvrdisplayactivate property.
-
vrdisplayblur
-
Fired when presentation to a VR display has been paused for some reason by the browser, OS, or VR hardware.
- Also available via the onvrdisplayblur property.
-
vrdisplayconnect
-
Fired when a compatible VR display is connected to the computer.
- Also available via the onvrdisplayconnect property.
-
vrdisplaydeactivate
-
Fired when a VR display can no longer be presented to, for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
- Also available via the onvrdisplaydeactivate property.
-
vrdisplaydisconnect
-
Fired when a compatible VR display is disconnected from the computer.
- Also available via the onvrdisplaydisconnect property.
-
vrdisplayfocus
-
Fired when presentation to a VR display has resumed after being blurred.
- Also available via the onvrdisplayfocus property.
-
vrdisplaypresentchange
-
fired when the presenting state of a VR display changes — i.e. goes from presenting to not presenting, or vice versa.
- Also available via the onvrdisplaypresentchange property.
-
vrdisplaypointerrestricted
-
Fired when the VR display's pointer input is restricted to consumption via a pointerlocked element.
- Also available via the onvrdisplaypointerrestricted property.
-
vrdisplaypointerunrestricted
-
Fired when the VR display's pointer input is no longer restricted to consumption via a pointerlocked element.
- Also available via the onvrdisplaypointerunrestricted property.
-
- -

Interfaces

- -

See DOM Reference

- -

Browser compatibility

- - - -

{{Compat("api.Window")}}

- -

See also

- - diff --git a/files/vi/web/api/window/load_event/index.html b/files/vi/web/api/window/load_event/index.html deleted file mode 100644 index ec1d576ff4..0000000000 --- a/files/vi/web/api/window/load_event/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: load -slug: Web/API/Window/load_event -tags: - - DOM - - Event - - Sự kiện -translation_of: Web/API/Window/load_event -original_slug: Web/Events/load ---- -

Sự kiện load có hiệu lực (được kích hoạt) khi các tài nguyên của một đối tượng hoặc các tài nguyên phụ thuộc vào đối tượng đó đã được tải nạp hoàn tất.

- -

Các ví dụ

- -

Window

- -
<script>
-  window.addEventListener("load", function(event) {
-    console.log("Tất cả các tài nguyên đã được tải nạp hoàn tất!");
-  });
-</script>
- -

Phần tử script

- -
<script>
-  var script = document.createElement("script");
-  script.addEventListener("load", function(event) {
-    console.log("Script đã được tải nạp xong và thực thi");
-  });
-  script.src = "http://example.com/example.js";
-  script.async = true;
-  document.getElementsByTagName("script")[0].parentNode.appendChild(script);
-</script>
- -

Thông tin cơ bản

- -
-
Specification
-
DOM L3
-
Giao diện
-
UIEvent
-
Bubbles
-
Không
-
Có thể hủy bỏ
-
Không thể
-
Đối tượng
-
Window, Document, Element
-
Hành động mặc địch
-
Không.
-
- -

Các thuộc tính

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thuộc tínhKiểu / LoạiMô tả
target {{readonlyInline}}{{domxref("EventTarget")}}Mục tiêu để áp dụng sự kiện (Đối tượng thuộc cây DOM).
type {{readonlyInline}}{{domxref("DOMString")}}Loại sự kiện
bubbles {{readonlyInline}}{{domxref("Boolean")}}Xác định sự kiện bình thường có bubbles hay không.
cancelable {{readonlyInline}}{{domxref("Boolean")}}Xác định sự kiện liệu có thể hủy bỏ được hay không.
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("Document.defaultView", "document.defaultView")}} (window of the document)
detail {{readonlyInline}}long (float)0.
- -

Các thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - -
Thông sốTrạng tháiDiễn giải
{{SpecName('UI Events', '#event-type-load', 'load')}}{{Spec2('UI Events')}} 
{{SpecName('HTML WHATWG', 'parsing.html#the-end:event-load', 'Load event')}}{{Spec2('HTML WHATWG')}}Liên kết này đưa đến phần giải thích các bước được thực hiện khi quá trình tải nạp tài liệu kết thúc. Sự kiện 'load' cũng được kích hoạt ở nhiều phần tử. Và lưu ý rằng có nhiều chỗ trong Thông số kỹ thuật đề cập đến những thứ mà có thể "Trì hoãn sự kiện load".
- -

Các sự kiện liên quan

- - diff --git a/files/vi/web/api/window/prompt/index.html b/files/vi/web/api/window/prompt/index.html deleted file mode 100644 index 9830f0cb7c..0000000000 --- a/files/vi/web/api/window/prompt/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Window.prompt() -slug: Web/API/Window/prompt -translation_of: Web/API/Window/prompt ---- -
{{ApiRef("Window")}}
- -

Câu lệnh Window.prompt() hiển thị một cửa sổ yêu cầu người dùng nhập liệu vào.

- -

Cú pháp

- -
result = window.prompt(message, default);
-
- -

Các tham số

- -
-
message {{optional_inline}}
-
Là một dòng thông báo hiện ra cho người dùng xem. Có thể bỏ trống không cần nhập.
-
default {{optional_inline}}
-
Là giá trị mặc định hiển thị ở khung nhập liệu. Lưu ý nếu bạn dùng Internet Explorer 7 hoặc 8, nếu không cung cấp tham số này, thì giá trị mặc định sẽ là "undefined"
-
- -

Giá trị trả về

- -

Trả về chuỗi text hoặc null.

- -

Example

- -
let sign = prompt("What's your sign?");
-
-if (sign.toLowerCase() == "scorpio") {
-  alert("Wow! I'm a Scorpio too!");
-}
-
-// Có nhiều cách để sử dụng prompt()
-sign = window.prompt(); // open the blank prompt window
-sign = prompt();       //  open the blank prompt window
-sign = window.prompt('Are you feeling lucky'); // open the window with Text "Are you feeling lucky"
-sign = window.prompt('Are you feeling lucky', 'sure'); // open the window with Text "Are you feeling lucky" and default value "sure"
- -

Khi người dùng ấn OK, giá trị họ nhập vào sẽ là giá trị trả về ở dạng chuỗi text. Nếu họ nhấn OK mà chưa nhập gì thì sẽ trả về chuỗi rỗng. Và nếu họ bấm Cancel thì sẽ trả về null.

- -

Giao diện cửa sổ prompt (trình duyệt Chrome trên OS X):

- -

prompt() dialog in Chrome on OS X

- -

Các lưu ý

- -

Cửa sổ prompt chứa 1 textbox một dòng, 1 nút OK và 1 nút Cancel, và trả về giá trị người dùng nhập vào (có thể rỗng).

- -

The following text is shared between this article, DOM:window.confirm and DOM:window.alert Dialog boxes are modal windows; chúng sẽ ngăn người dùng truy cập vào các nội dung khác của website cho đến khi hoàn thành thao tác với cửa sổ prompt. Chính vì vậy, bạn không nên lạm dụng nó quá mức.

- -

Giá trị trả về là chuỗi text, vì vậy nếu bạn muốn chắc chắn đó là kiểu Number thì hãy ép kiểu nó như ví dụ bên dưới:

- -
const aNumber = Number(window.prompt("Type a number", ""));
- -

Specification

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#dom-prompt', 'prompt()')}}{{Spec2('HTML WHATWG')}}
- -

Browser Compatibility

- - - -

{{Compat("api.Window.prompt")}}

- -

See also

- - diff --git a/files/vi/web/css/_colon_first-child/index.html b/files/vi/web/css/_colon_first-child/index.html deleted file mode 100644 index 2259b90f32..0000000000 --- a/files/vi/web/css/_colon_first-child/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: ':first-child' -slug: 'Web/CSS/:first-child' -translation_of: 'Web/CSS/:first-child' ---- -
{{CSSRef}}
- -

:first-child CSS pseudo-class đại diện cho phần tử đầu tiên trong số các phần tử anh chị em của nó.

- -
/* Chọn thẻ <p> đầu tiên trong số các thẻ anh chị em của nó*/
-p:first-child {
-  color: lime;
-}
- -
-

Note: As originally defined, the selected element had to have a parent. Beginning with Selectors Level 4, this is no longer required.

-
- -

Cú pháp

- -{{csssyntax}} - -

Ví dụ

- -

Ví dụ đơn giản

- -

HTML

- -
<div>
-  <p>This text is selected!</p>
-  <p>This text isn't selected.</p>
-</div>
-
-<div>
-  <h2>This text isn't selected: it's not a `p`.</h2>
-  <p>This text isn't selected.</p>
-</div>
-
- -

CSS

- -
p:first-child {
-  color: lime;
-  background-color: black;
-  padding: 5px;
-}
-
- -

Kết quả

- -

{{EmbedLiveSample('Basic_example', 500, 200)}}

- -

Styling một danh sách

- -

HTML

- -
<ul>
-  <li>Item 1</li>
-  <li>Item 2</li>
-  <li>Item 3
-    <ul>
-      <li>Item 3.1</li>
-      <li>Item 3.2</li>
-      <li>Item 3.3</li>
-    </ul>
-  </li>
-</ul>
- -

CSS

- -
ul li {
-  color: blue;
-}
-
-ul li:first-child {
-  color: red;
-  font-weight: bold;
-}
- -

Result

- -

{{EmbedLiveSample('Styling_a_list')}}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#first-child-pseudo', ':first-child')}}{{Spec2('CSS4 Selectors')}}Matching elements are not required to have a parent.
{{SpecName('CSS3 Selectors', '#first-child-pseudo', ':first-child')}}{{Spec2('CSS3 Selectors')}}No change.
{{SpecName('CSS2.1', 'selector.html#first-child', ':first-child')}}{{Spec2('CSS2.1')}}Initial definition.
- -

Khả năng tương thích của trình duyệt

- - - -

{{Compat("css.selectors.first-child")}}

- -

Xem thêm

- - diff --git a/files/vi/web/css/_colon_focus-within/index.html b/files/vi/web/css/_colon_focus-within/index.html deleted file mode 100644 index 05ea089bb0..0000000000 --- a/files/vi/web/css/_colon_focus-within/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: ':focus-within' -slug: 'Web/CSS/:focus-within' -translation_of: 'Web/CSS/:focus-within' ---- -
{{CSSRef}}
- -

Lớp giả CSS :focus-within đại diện cho thành phần nhận focus hoặc chứa một thành phần nhận focus. Nói cách khác, nó đại diện cho một thành phần mà chính nó khớp bởi một lớp giả {{cssxref(":focus")}} hoặc có một hậu duệ (con cháu) được khớp bởi :focus. (Gồm cả hậu duệ trong shadow trees.)

- -
/* Chọn một <div> khi hậu duệ của nó được focus */
-div:focus-within {
-  background: cyan;
-}
- -

Nó rất hữu dụng, ví dụ chung, để làm nổi bật toàn bộ container {{htmlElement("form")}} khi người dùng focus vào một trong các field {{htmlElement("input")}} của nó.

- -

Cú pháp

- -{{csssyntax}} - -

Ví dụ

- -

Trong ví dụ này, form sẽ nhận kiểu màu đặc biệt khi text input nhận focus.

- -

HTML

- -
<p>Try typing into this form.</p>
-
-<form>
-  <label for="given_name">Given Name:</label>
-  <input id="given_name" type="text">
-  <br>
-  <label for="family_name">Family Name:</label>
-  <input id="family_name" type="text">
-</form>
- -

CSS

- -
form {
-  border: 1px solid;
-  color: gray;
-  padding: 4px;
-}
-
-form:focus-within {
-  background: #ff8;
-  color: black;
-}
-
-input {
-  margin: 4px;
-}
-
- -

Result

- -

{{EmbedLiveSample("Example", 500, 150)}}

- -

Chi tiết

- - - - - - - - - - - - - - - - -
Chi tiếtTình trạngComment
{{SpecName("CSS4 Selectors", "#the-focus-within-pseudo", ":focus-within")}}{{Spec2("CSS4 Selectors")}}Initial definition.
- -

Tương thích Trình duyệt

- - - -

{{Compat("css.selectors.focus-within")}}

- -

Xem cả

- - diff --git a/files/vi/web/css/_colon_focus/index.html b/files/vi/web/css/_colon_focus/index.html deleted file mode 100644 index 88dca6736c..0000000000 --- a/files/vi/web/css/_colon_focus/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: ':focus' -slug: 'Web/CSS/:focus' -translation_of: 'Web/CSS/:focus' ---- -
{{CSSRef}}
- -

Lớp giả  CSS :focus đại diện cho thành phần (như một input form) nhận focus. Nó được kích hoạt khi người dùng kích hoặc tap lên thành phần hoặc chọn nó bằng phím "tab".

- -
/* Chọn bấy kỳ thành phần input nào được focus */
-input:focus {
-  color: red;
-}
- -
-

Chú ý: Lớp giả này chỉ áp dụng với chính thành phần được focus. Sử dụng {{cssxref(":focus-within")}} nếu bạn muốn chọn thành phần chứa một thành phần được focus.

-
- -

Cú pháp

- -{{csssyntax}} - -

Ví dụ

- -

HTML

- -
<input class="red-input" value="I'll be red when focused."><br>
-<input class="blue-input" value="I'll be blue when focused.">
- -

CSS

- -
.red-input:focus {
-  background: yellow;
-  color: red;
-}
-
-.blue-input:focus {
-  background: yellow;
-  color: blue;
-}
- -

Result

- -

{{EmbedLiveSample('Example')}}

- -

Chi tiết

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Chi tiếtTrạng tháiBình luận
{{SpecName('HTML WHATWG', 'scripting.html#selector-focus', ':focus')}}{{Spec2('HTML WHATWG')}}Defines HTML-specific semantics.
{{SpecName('CSS4 Selectors', '#focus-pseudo', ':focus')}}{{Spec2('CSS4 Selectors')}}No change.
{{SpecName('CSS3 Selectors', '#the-user-action-pseudo-classes-hover-act', ':focus')}}{{Spec2('CSS3 Selectors')}}No change.
{{SpecName('CSS2.1', 'selector.html#dynamic-pseudo-classes', ':focus')}}{{Spec2('CSS2.1')}}Initial definition.
- -

Tương thích trình duyệt

- -
- - -

{{Compat("css.selectors.focus")}}

-
- -

 

- -
 
- -

Xem thêm

- - diff --git a/files/vi/web/css/_colon_last-of-type/index.html b/files/vi/web/css/_colon_last-of-type/index.html deleted file mode 100644 index a06987bb03..0000000000 --- a/files/vi/web/css/_colon_last-of-type/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: ':last-of-type' -slug: 'Web/CSS/:last-of-type' -translation_of: 'Web/CSS/:last-of-type' ---- -
{{CSSRef}}
- -

Nội dung tóm tắt

- -

Cú pháp :last-of-type (CSS pseudo-class) đại diện cho phần tử cuối cùng trong danh sách các phần tử con có chung phần tử cha trong phép chọn css.

- -

Syntax

- -{{csssyntax}} - -

Example

- -

Để chỉ định phần tử cuối cùng bên trong thẻ {{HTMLElement("p")}} , bạn có thể sử dụng cú pháp:

- -
p em:last-of-type {
-  color: lime;
-}
-
- -
<p>
-  <em>I'm not lime :(</em>
-  <strong>I'm not lime :(</strong>
-  <em>I'm lime :D</em>
-  <strong>I'm also not lime :(</strong>
-</p>
-
-<p>
-  <em>I'm not lime :(</em>
-  <span><em>I am lime!</em></span>
-  <strong>I'm not lime :(</strong>
-  <em>I'm lime :D</em>
-  <span><em>I am also lime!</em> <strike> I'm not lime </strike></span>
-  <strong>I'm also not lime :(</strong>
-</p>
- -

...hết quả trả về:

- -
{{EmbedLiveSample('Example','100%', '120')}}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#last-of-type-pseudo', ':last-of-type')}}{{Spec2('CSS4 Selectors')}}No change
{{SpecName('CSS3 Selectors', '#last-of-type-pseudo', ':last-of-type')}}{{Spec2('CSS3 Selectors')}}Initial definition
- -

Trình duyệt (browser) tương thích

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}9.09.53.2
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}9.010.03.2
-
- -

Xem thêm

- - diff --git a/files/vi/web/css/backdrop-filter/index.html b/files/vi/web/css/backdrop-filter/index.html deleted file mode 100644 index 87378a1654..0000000000 --- a/files/vi/web/css/backdrop-filter/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: backdrop-filter -slug: Web/CSS/backdrop-filter -tags: - - Bố trí - - Bộ lọc SVG - - CSS - - SVG - - Thuộc tính CSS - - Tài liệu tham khảo - - Web - - 'recipe:css-property' - - Đồ họa -translation_of: Web/CSS/backdrop-filter ---- -
{{CSSRef}}
- -

Thuộc tính CSS backdrop-filter cho phép bạn áp dụng các hiệu ứng đồ họa như làm mờ hoặc chuyển màu cho vùng phía sau một phần tử. Bởi vì nó áp dụng cho mọi thứ phía sau phần tử, để xem hiệu ứng, bạn phải làm cho phần tử hoặc nền của nó ít nhất một phần trong suốt.

- -
/* Giá trị từ khóa */
-backdrop-filter: none;
-
-/* Bộ lọc URL đến SVG */
-backdrop-filter: url(commonfilters.svg#filter);
-
-/* Giá trị <filter-function> */
-backdrop-filter: blur(2px);
-backdrop-filter: brightness(60%);
-backdrop-filter: contrast(40%);
-backdrop-filter: drop-shadow(4px 4px 10px blue);
-backdrop-filter: grayscale(30%);
-backdrop-filter: hue-rotate(120deg);
-backdrop-filter: invert(70%);
-backdrop-filter: opacity(20%);
-backdrop-filter: sepia(90%);
-backdrop-filter: saturate(80%);
-
-/* Nhiều bộ lọc */
-backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);
-
-/* Giá trị chung */
-backdrop-filter: inherit;
-backdrop-filter: initial;
-backdrop-filter: unset;
-
- -

Cú pháp

- -

Giá trị

- -
-
none
-
Không có bộ lọc nào được áp dụng cho phông nền.
-
<filter-function-list>
-
Danh sách được phân tách bằng dấu cách về {{cssxref("<filter-function>")}}s hoặc một bộ lọc SVG sẽ được áp dụng cho phông nền.
-
- -

Định nghĩa hình thức

- -

{{cssinfo}}

- -

Cấu trúc hình thức

- -{{csssyntax}} - -

Ví dụ

- -

CSS

- -
.box {
-  background-color: rgba(255, 255, 255, 0.3);
-  border-radius: 5px;
-  font-family: sans-serif;
-  text-align: center;
-  line-height: 1;
- -webkit-backdrop-filter: blur(10px);
-  backdrop-filter: blur(10px);
-  max-width: 50%;
-  max-height: 50%;
-  padding: 20px 40px;
-}
-
-html,
-body {
-  height: 100%;
-  width: 100%;
-}
-
-body {
-  background-image: url(https://picsum.photos/id/1080/6858/4574), linear-gradient(rgb(219, 166, 166), rgb(0, 0, 172));
-  background-position: center center;
-  background-repeat: no-repeat;
-  background-size: cover;
-}
-
-.container {
-  align-items: center;
-  display: flex;
-  justify-content: center;
-  height: 100%;
-  width: 100%;
-}
- -

HTML

- -
<div class="container">
-  <div class="box">
-    <p>backdrop-filter: blur(10px)</p>
-  </div>
-</div>
-
- -

Kết quả

- -

{{EmbedLiveSample("Examples", 600, 400)}}

- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Filters 2.0', '#BackdropFilterProperty', 'backdrop-filter')}}{{Spec2('Filters 2.0')}}Định nghĩa ban đầu.
- -

Tính tương thích của trình duyệt web

- - - -

{{Compat("css.properties.backdrop-filter")}}

- -

Xem thêm

- - diff --git a/files/vi/web/css/background-color/index.html b/files/vi/web/css/background-color/index.html deleted file mode 100644 index 0a88107eb1..0000000000 --- a/files/vi/web/css/background-color/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: background-color -slug: Web/CSS/background-color -translation_of: Web/CSS/background-color ---- -
{{CSSRef}}
- -

Thuộc tính CSS background-color đặt màu nền của một phần tử.

- -
{{EmbedInteractiveExample("pages/css/background-color.html")}}
- - - -

Cú pháp

- -
/* Giá trị từ khóa */
-background-color: red;
-background-color: indigo;
-
-/* Giá trị Hex (Thập lục phân) */
-background-color: #bbff00;    /* Hoàn toàn mờ đục */
-background-color: #bf0;       /* Fully opaque shorthand */
-background-color: #11ffee00;  /* Hoàn toàn trong suốt */
-background-color: #1fe0;      /* Fully transparent shorthand  */
-background-color: #11ffeeff;  /* Hoàn toàn mờ đục */
-background-color: #1fef;      /* Fully opaque shorthand  */
-
-/* Giá trị RGB */
-background-color: rgb(255, 255, 128);        /* Hoàn toàn mờ đục */
-background-color: rgba(117, 190, 218, 0.5);  /* Trong suốt 50% */
-
-/* Giá trị HSL */
-background-color: hsl(50, 33%, 25%);         /* Hoàn toàn mờ đục */
-background-color: hsla(50, 33%, 25%, 0.75);  /* Trong suốt 75% */
-
-/* Giá trị từ khóa đặc biệt */
-background-color: currentcolor;
-background-color: transparent;
-
-/* Giá trị chung */
-background-color: inherit;
-background-color: initial;
-background-color: unset;
- -

Thuộc tính background-color được chỉ định là một giá trị <color>.

- -

Giá trị

- -
-
{{cssxref("<color>")}}
-
Màu đồng nhất của nền. Nó được hiển thị đằng sau bất kỳ {{cssxref("background-image")}} được chỉ định, mặc dù màu sẽ vẫn hiển thị qua bất kỳ độ trong suốt nào của hình ảnh.
-
- -

Mối quan tâm về khả năng tiếp cận

- -

Điều quan trọng là phải đảm bảo rằng tỷ lệ tương phản giữa màu nền và màu của văn bản được đặt trên nó đủ cao để những người gặp tình trạng thị lực kém có thể đọc được nội dung của trang.

- -

Tỷ lệ tương phản màu được xác định bằng cách so sánh độ chói của văn bản và giá trị màu nền. Để xem Web Content Accessibility Guidelines (WCAG) hiện tại, tỷ lệ 4,5:1 là bắt buộc đối với nội dung văn bản và 3:1 đối với văn bản to, chẳng hạn như tiêu đề. Văn bản to được định nghĩa là 18,66px và đậm hoặc lớn hơn, hoặc 24px hoặc lớn hơn.

- - - -

Định nghĩa hình thức

- -

{{cssinfo}}

- -

Cú pháp hình thức

- -{{csssyntax}} - -

Ví dụ

- -

HTML

- -
<div class="exampleone">
-  Lorem ipsum dolor sit amet, consectetuer
-</div>
-
-<div class="exampletwo">
-  Lorem ipsum dolor sit amet, consectetuer
-</div>
-
-<div class="examplethree">
-  Lorem ipsum dolor sit amet, consectetuer
-</div>
- -

CSS

- -
.exampleone {
-  background-color: teal;
-  color: white;
-}
-
-.exampletwo {
-  background-color: rgb(153,102,153);
-  color: rgb(255,255,204);
-}
-
-.examplethree {
-  background-color: #777799;
-  color: #FFFFFF;
-}
-
- -

Kết quả

- -

{{EmbedLiveSample("Examples", 200, 150)}}

- - - -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtGhi chúPhản hồi
{{SpecName('CSS3 Backgrounds', '#background-color', 'background-color')}}Though technically removing the transparent keyword, this doesn't change anything as it has been incorporated as a true {{cssxref("<color>")}}Backgrounds Level 3 GitHub issues
{{SpecName('CSS2.1', 'colors.html#propdef-background-color', 'background-color')}}
{{SpecName('CSS1', '#background-color', 'background-color')}}Initial definition
- -

Tính tương thích của trình duyệt web

- - - -

{{Compat("css.properties.background-color")}}

- -

Xem thêm

- - diff --git a/files/vi/web/css/content/index.html b/files/vi/web/css/content/index.html deleted file mode 100644 index 61956c11a9..0000000000 --- a/files/vi/web/css/content/index.html +++ /dev/null @@ -1,296 +0,0 @@ ---- -title: content -slug: Web/CSS/content -translation_of: Web/CSS/content ---- -
{{CSSRef}}
- -

The content CSS property replaces an element with a generated value. Objects inserted using the content property are anonymous replaced elements.

- -
/* Keywords that cannot be combined with other values */
-content: normal;
-content: none;
-
-/* <image> values */
-content: url("http://www.example.com/test.png");
-content: linear-gradient(#e66465, #9198e5);
-
-/* alt text for generated content, added in the Level 3 specification */
-content: url("http://www.example.com/test.png") / "This is the alt text";
-
-/* values below can only be applied to generated content using ::before and ::after */
-
-/* <string> value */
-content: "prefix";
-
-/* <counter> values, optionally with <list-style-type> */
-content: counter(chapter_counter);
-content: counter(chapter_counter, upper-roman);
-content: counters(section_counter, ".");
-content: counters(section_counter, ".", decimal-leading-zero);
-
-/* attr() value linked to the HTML attribute value */
-content: attr(value string);
-
-/* Language- and position-dependent keywords */
-content: open-quote;
-content: close-quote;
-content: no-open-quote;
-content: no-close-quote;
-
-/* Except for normal and none, several values can be used simultaneously */
-content: open-quote chapter_counter;
-
-/* Global values */
-content: inherit;
-content: initial;
-content: unset;
-
- -

Syntax

- -

Values

- -
-
none
-
The pseudo-element is not generated.
-
normal
-
Computes to none for the ::before and ::after pseudo-elements.
-
{{cssxref("<string>")}}
-
Specifies the "alt text" for the element. This value can be any number of text characters. Non-Latin characters must be encoded using their Unicode escape sequences: for example, \000A9 represents the copyright symbol.
-
{{cssxref("<image>")}}
-
An {{cssxref("<image>")}}, denoted by the {{cssxref("<url>")}} or {{cssxref("<gradient>")}} data type, or part of the webpage, defined by the {{cssxref("element", "element()")}} function, denoting the content to display.
-
{{cssxref("<counter>")}}
-
The value of a CSS counter, generally a number produced by computations defined by {{cssxref("<counter-reset>")}} and {{cssxref("<counter-increment>")}} properies. It can be displayed using either the {{cssxref("counter")}} or {{cssxref("counters")}} function.
-
-

The {{cssxref("counter")}} function has two forms: 'counter(name)' or 'counter(name, style)'. The generated text is the value of the innermost counter of the given name in scope at the given pseudo-element. It is formatted in the specified {{cssxref("<list-style-type>")}} (decimal by default).

- -

The {{cssxref("counters")}} function also has two forms: 'counters(name, string)' or 'counters(name, string, style)'. The generated text is the value of all counters with the given name in scope at the given pseudo-element, from outermost to innermost, separated by the specified string. The counters are rendered in the indicated {{cssxref("<list-style-type>")}} (decimal by default).

-
-
attr(x)
-
The value of the element's attribute x as a string. If there is no attribute x, an empty string is returned. The case-sensitivity of attribute names depends on the document language.
-
open-quote | close-quote
-
These values are replaced by the appropriate string from the {{cssxref("quotes")}} property.
-
no-open-quote | no-close-quote
-
Introduces no content, but increments (decrements) the level of nesting for quotes.
-
- -

Accessibility concerns

- -

CSS-generated content is not included in the DOM. Because of this, it will not be represented in the accessibility tree and certain assistive technology/browser combinations will not announce it. If the content conveys information that is critical to understanding the page's purpose, it is better to include it in the main document.

- - - -

Formal definition

- -

{{cssinfo}}

- -

Formal syntax

- -{{csssyntax}} - -

Examples

- -

Headings and quotes

- -

This example inserts quotation marks around quotes, and adds the word "Chapter" before headings.

- -

HTML

- -
<h1>5</h1>
-<p>According to Sir Tim Berners-Lee,
-  <q cite="http://www.w3.org/People/Berners-Lee/FAQ.html#Internet">I was
-    lucky enough to invent the Web at the time when the Internet
-    already existed - and had for a decade and a half.</q>
-  We must understand that there is nothing fundamentally wrong
-  with building on the contributions of others.
-</p>
-
-<h1>6</h1>
-<p>According to the Mozilla Manifesto,
-  <q cite="http://www.mozilla.org/en-US/about/manifesto/">Individuals
-    must have the ability to shape the Internet and
-    their own experiences on the Internet.</q>
-  Therefore, we can infer that contributing to the open web
-  can protect our own individual experiences on it.
-</p>
- -

CSS

- -
q {
-  color: blue;
-}
-
-q::before {
-  content: open-quote;
-}
-
-q::after {
-  content: close-quote;
-}
-
-h1::before  {
-  content: "Chapter ";  /* The trailing space creates separation
-                           between the added content and the
-                           rest of the content */
-}
- -

Result

- -

{{EmbedLiveSample('Headings_and_quotes', '100%', 200)}}

- -

Image combined with text

- -

This example inserts an image before the link. If the image is not found, it inserts text instead.

- -

HTML

- -
<a href="http://www.mozilla.org/en-US/">Mozilla Home Page</a>
- -

CSS

- -
a::before {
-  content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico") / " MOZILLA: ";
-  font: x-small Arial, sans-serif;
-  color: gray;
-}
- -

Result

- -

{{EmbedLiveSample('Image_combined_with_text', '100%', 60)}}

- -

Targeting classes

- -

This example inserts additional text after special items in a list.

- -

HTML

- -
<h2>Paperback Best Sellers</h2>
-<ol>
-  <li>Political Thriller</li>
-  <li class="new-entry">Halloween Stories</li>
-  <li>My Biography</li>
-  <li class="new-entry">Vampire Romance</li>
-</ol>
- -

CSS

- -
.new-entry::after {
-  content: " New!";  /* The leading space creates separation
-                        between the added content and the
-                        rest of the content */
-  color: red;
-}
- -

Result

- -

{{EmbedLiveSample('Targeting_classes', '100%', 160)}}

- -

Images and element attributes

- -

This example inserts an image before each link, and adds its id attribute after.

- -

HTML

- -
<ul>
-  <li><a id="moz" href="http://www.mozilla.org/">
-    Mozilla Home Page</a></li>
-  <li><a id="mdn" href="https://developer.mozilla.org/">
-    Mozilla Developer Network</a></li>
-</ul>
- -

CSS

- -
a {
-  text-decoration: none;
-  border-bottom: 3px dotted navy;
-}
-
-a::after {
-  content: " (" attr(id) ")";
-}
-
-#moz::before {
-  content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico");
-}
-
-#mdn::before {
-  content: url("https://mdn.mozillademos.org/files/7691/mdn-favicon16.png");
-}
-
-li {
-  margin: 1em;
-}
-
- -

Result

- -

{{EmbedLiveSample('Images_and_element_attributes', '100%', 160)}}

- -

Element replacement

- -

This example replaces an element's content with an image. You can replace the contents of an element with either a {{cssxref("<url>")}} or an {{cssxref("<image>")}} value. Content added with ::before or ::after will not be generated as the contents of the element have been replaced.

- -

HTML

- -
<div id="replaced">Mozilla</div>
-
- -

CSS

- -
#replaced {
-  content: url("https://mdn.mozillademos.org/files/12668/MDN.svg");
-}
-
-#replaced::after { /* will not show if element replacement is supported */
-  content: " (" attr(id) ")";
-}
- -

Result

- -

{{EmbedLiveSample('Element_replacement', '100%', 200)}}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("CSS3 Content", "#content-property", "content")}}{{Spec2("CSS3 Content")}}Adds support for alt-text
{{SpecName("CSS2.1", "generate.html#content", "content")}}{{Spec2("CSS2.1")}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("css.properties.content")}}

- -

See also

- - diff --git a/files/vi/web/css/css_box_alignment/index.html b/files/vi/web/css/css_box_alignment/index.html deleted file mode 100644 index 1c9bc57018..0000000000 --- a/files/vi/web/css/css_box_alignment/index.html +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: CSS Box Alignment -slug: Web/CSS/CSS_Box_Alignment -translation_of: Web/CSS/CSS_Box_Alignment ---- -
{{CSSRef}}
- -

Mô-đun sắp xếp hộp CSS chỉ định các tính năng CSS liên quan đến căn chỉnh các hộp trong các mô hình bố trí hộp CSS khác nhau: bố trí khối, bố cục bảng, bố cục flex và bố cục lưới. Mô-đun này nhằm mục đích tạo ra một phương thức liên kết nhất quán trên tất cả CSS. Tài liệu này nêu chi tiết các khái niệm chung được tìm thấy trong đặc tả.

- -
-

Lưu ý : Tài liệu cho từng phương pháp bố cục sẽ nêu chi tiết cách áp dụng Sắp xếp hộp ở đó.

-
- -

Phương thức căn chỉnh cũ hơn

- -

CSS theo truyền thống có khả năng liên kết rất hạn chế. Chúng tôi đã có thể căn chỉnh văn bản bằng cách sử dụng {{cssxref ("text-align")}}, các khối trung tâm sử dụng tự động {{cssxref ("margin")}} s và trong bảng hoặc khối nội tuyến bằng cách sử dụng {{cssxref("vertical-align")}}. Việc căn chỉnh văn bản hiện được bao phủ bởi các mô-đun Văn bản Nội tuyếnCSS , và lần đầu tiên trong Căn chỉnh Hộp, chúng tôi có khả năng căn chỉnh ngang và dọc hoàn toàn.

- -

Nếu ban đầu bạn học Flexbox thì bạn có thể xem xét các thuộc tính này là một phần của đặc tả Flexbox, và một số thuộc tính thực sự được liệt kê trong Cấp 1 của Flexbox. Tuy nhiên, đặc điểm kỹ thuật lưu ý rằng đặc tả của Alignment Box nên được nhắc đến vì nó có thể bổ sung thêm các khả năng so với những gì hiện có trong Flexbox.

- -

Ví dụ cơ bản

- -

Các ví dụ sau đây minh họa cách một số Thuộc tính sắp xếp hộp được áp dụng trong GridFlexbox .

- -

Ví dụ căn chỉnh bố cục lưới CSS

- -

Trong ví dụ này bằng cách sử dụng Grid Layout, có thêm không gian trong vùng chứa lưới sau khi đặt các bản nhạc có chiều rộng cố định trên trục nội tuyến (chính). Không gian này được phân phối bằng {{cssxref ("justify-content")}}. Trên trục (chéo), sự liên kết của các mục bên trong vùng lưới của chúng được điều khiển bằng {{cssxref ("align-items")}}. Mục đầu tiên ghi đè align-itemsgiá trị được đặt trên nhóm bằng cách đặt {{cssxref ("align-self")}} thành center.

- -

{{EmbedGHLiveSample ("css-example / box-alignment / overview / grid-align-items.html", '100%', 500)}}

- -

Ví dụ liên kết Flexbox

- -

Trong ví dụ này, ba mục flex được căn chỉnh trên trục chính sử dụng justify-contentvà trên Trục chéo sử dụng align-items. Mục đầu tiên ghi đè align-itemstập hợp trên nhóm bằng cách đặt align-selfthành center.

- -

{{EmbedGHLiveSample ("css-example / box-alignment / overview / flex-align-items.html", '100%', 500)}}

- -

Khái niệm và thuật ngữ chính

- -

Đặc tả chi tiết một số thuật ngữ liên kết để giúp dễ dàng thảo luận các thuộc tính căn chỉnh bên ngoài việc thực hiện chúng trong một phương pháp bố cục cụ thể. Ngoài ra còn có một số khái niệm chính được phổ biến cho tất cả các phương pháp bố trí.

- -

Mối quan hệ với chế độ viết

- -

Sự liên kết được liên kết với các chế độ viết trong đó khi chúng ta căn chỉnh một mục, chúng ta không xem xét liệu chúng ta đang căn chỉnh nó với các kích thước vật lý của trên cùng, bên phải, phía dưới và bên trái. Thay vào đó, chúng tôi mô tả sự liên kết về mặt bắt đầu và kết thúc của thứ nguyên cụ thể mà chúng tôi đang làm việc. Điều này đảm bảo rằng liên kết hoạt động theo cùng một cách mà bất kỳ chế độ ghi nào của tài liệu.

- -

Hai kích thước căn chỉnh

- -

Khi sử dụng các thuộc tính căn chỉnh hộp, bạn sẽ căn chỉnh nội dung trên một trong hai trục - trục nội tuyến (hoặc trục chính) và trục khối (hoặc chéo). Trục nội tuyến là trục dọc theo đó các từ trong dòng câu trong chế độ viết đang được sử dụng - cho tiếng Anh, ví dụ, trục nội tuyến nằm ngang. Trục khối là trục dọc theo đó các khối, chẳng hạn như các phần tử đoạn, được đặt ra và nó chạy trên trục Inline.

- -

- -

Khi căn chỉnh các mục trên trục nội tuyến, bạn sẽ sử dụng các thuộc tính bắt đầu bằng justify-:

- - - -

Khi căn chỉnh các mục trên trục khối, bạn sẽ sử dụng các thuộc tính bắt đầu align-:

- - - -

Flexbox bổ sung thêm một biến chứng trong đó ở trên là đúng khi {{cssxref ("flex-direction")}} được đặt thành row. Các thuộc tính được hoán đổi khi flexbox được đặt thành column. Vì vậy, khi làm việc với flexbox, bạn sẽ dễ dàng nghĩ về trục chính và trục chéo hơn là nội tuyến và khối. Các justify-thuộc tính luôn được sử dụng để căn chỉnh trên trục chính, các align-thuộc tính trên trục chéo.

- -

Chủ thể căn chỉnh

- -

Các chủ đề liên kết là điều đang được liên kết. Đối với justify-selfhoặc align-self, hoặc khi thiết lập các giá trị này dưới dạng một nhóm có justify-itemshoặc align-items, đây sẽ là hộp lề của phần tử mà thuộc tính này đang được sử dụng. Các thuộc tính justify-contentalign-contentkhác nhau theo phương thức bố cục.

- -

Container liên kết

- -

Các thùng chứa liên kết là hộp đề tài này đã được liên kết bên trong. Điều này thường sẽ là khối chứa của đối tượng căn chỉnh. Vùng chứa liên kết có thể chứa một hoặc nhiều đối tượng căn chỉnh.

- -

Hình ảnh dưới đây cho thấy một container liên kết với hai đối tượng căn chỉnh bên trong.

- -

- -

Căn chỉnh dự phòng

- -

Nếu bạn đặt căn chỉnh không thể hoàn thành, thì căn chỉnh dự phòng sẽ đi vào hoạt động và đối phó với không gian có sẵn. Liên kết dự phòng này được chỉ định riêng cho từng phương thức bố cục và được trình bày chi tiết trên trang cho phương thức đó.

- -

Các loại căn chỉnh

- -

Có ba loại căn chỉnh khác nhau mà chi tiết đặc điểm kỹ thuật; các giá trị từ khóa này sử dụng.

- - - -

Giá trị từ khóa liên kết vị trí

- -

Các giá trị sau được định nghĩa cho sự liên kết vị trí, và có thể được sử dụng như giá trị cho sự liên kết nội dung với justify-contentalign-contentvà còn cho sự liên kết tự với justify-selfalign-self.

- - - -

Khác với các giá trị vật lý leftright, liên quan đến các thuộc tính vật lý của màn hình, tất cả các giá trị khác là các giá trị logic và liên quan đến chế độ viết của nội dung.

- -

Ví dụ, khi làm việc trong CSS Grid Layout, nếu bạn đang làm việc bằng tiếng Anh và thiết lập justify-contentđể startđiều này sẽ di chuyển các mục trong kích thước nội tuyến để bắt đầu, mà sẽ được trái như câu trong tiếng Anh bắt đầu ở bên trái. Nếu bạn đang sử dụng tiếng Ả Rập, ngôn ngữ từ phải sang trái, thì giá trị tương tự startsẽ dẫn đến các mục di chuyển sang phải, như các câu trong tiếng Ả Rập bắt đầu ở phía bên tay phải của trang.

- -

Cả hai ví dụ này đều có justify-content: start, tuy nhiên vị trí bắt đầu thay đổi theo chế độ viết.

- -

- -

Căn chỉnh căn bản

- -

Các từ khóa căn chỉnh đường cơ sở được sử dụng để căn chỉnh các đường cơ sở của các hộp trên một nhóm đối tượng căn chỉnh. Chúng có thể được sử dụng như giá trị cho sự liên kết nội dung với justify-contentalign-contentvà còn cho sự liên kết tự với justify-selfalign-self.

- - - -

Căn chỉnh nội dung đường cơ sở - chỉ định giá trị căn chỉnh căn bản cho justify-contenthoặc align-content- hoạt động trong các phương thức bố cục để sắp xếp các mục ra theo hàng. Các đối tượng căn chỉnh là đường cơ sở được căn chỉnh với nhau bằng cách thêm đệm vào bên trong các hộp.

- -

Căn chỉnh tự căn chỉnh thay đổi các hộp để căn chỉnh theo đường cơ sở bằng cách thêm lề ngoài các hộp. Tự căn chỉnh là khi sử dụng justify-selfhoặc align-self, hoặc khi đặt các giá trị này thành một nhóm có justify-itemsalign-items.

- -

Căn chỉnh phân phối

- -

Các từ khóa liên kết phân tán được sử dụng với các thuộc tính align-contentjustify-content. Những từ khóa này xác định những gì sẽ xảy ra với bất kỳ không gian bổ sung nào sau khi đối tượng căn chỉnh được hiển thị. Các giá trị như sau:

- - - -

Ví dụ, trong các mục Flex Layout được căn chỉnh với flex-startban đầu. Làm việc ở chế độ viết ngang từ trên xuống dưới như tiếng Anh, flex-directionkhi rowcác mục bắt đầu ở phía xa bên trái và bất kỳ khoảng trống nào sau khi hiển thị các mục được đặt sau các mục.

- -

- -

Nếu bạn đặt justify-content: space-betweentrên thùng chứa flex, không gian có sẵn hiện được chia sẻ và đặt giữa các mục.

- -

- -

Cần có khoảng trống trong thứ nguyên bạn muốn căn chỉnh các mục để các từ khóa này có hiệu lực. Không có không gian, không có gì để phân phối.

- -

Căn chỉnh tràn

- -

Các từ khóa safeunsafetừ khóa giúp xác định hành vi khi đối tượng căn chỉnh lớn hơn vùng chứa căn chỉnh. Các safetừ khóa sẽ sắp xếp để starttrong trường hợp của một liên kết cụ thể gây ra một tràn, mục đích là để tránh “mất dữ liệu”, nơi một phần của mặt hàng đó nằm ngoài ranh giới của container liên kết và không thể được cuộn để.

- -

Nếu bạn chỉ định unsafesau đó sự liên kết sẽ được tôn trọng ngay cả khi nó sẽ gây ra mất dữ liệu như vậy.

- -

Khoảng cách giữa các hộp

- -

Các đặc điểm kỹ thuật liên kết hộp cũng bao gồm gap, row-gapcolumn-gaptài sản. Các thuộc tính này cho phép thiết lập khoảng cách nhất quán giữa các mục trong một hàng hoặc cột, trong bất kỳ phương thức bố cục nào có các mục được sắp xếp theo cách này.

- -

Tài gapsản là một cách viết tắt row-gapcolumn-gapcho phép chúng tôi thiết lập các thuộc tính này cùng một lúc:

- - - -

Trong ví dụ dưới đây, bố cục lưới sử dụng gapviết tắt để đặt 10pxkhoảng cách giữa các bản nhạc hàng và 2emkhoảng cách giữa các bản nhạc cột.

- -

{{EmbedGHLiveSample ("css-example / box-alignment / overview / grid-gap.html", '100%', 500)}}

- -

Trong ví dụ này, tôi đang sử dụng thuộc tính {{cssxref ("grid-gap")}} ngoài {{cssxref ("gap")}}. Các thuộc tính khoảng trống ban đầu được bắt đầu bằng grid-đặc tả bố cục lưới và một số trình duyệt chỉ hỗ trợ các phiên bản tiền tố này.

- - - -

Các phiên bản tiền tố sẽ được duy trì như một bí danh của những cái chưa được sửa đổi, tuy nhiên bạn luôn có thể tăng gấp đôi theo cách bạn muốn với tiền tố của nhà cung cấp, thêm thuộc grid-gaptính và sau đó thuộc gaptính có cùng giá trị.

- -

Ngoài ra, hãy lưu ý rằng những thứ khác có thể làm tăng khoảng cách trực quan được hiển thị, ví dụ bằng cách sử dụng các từ khóa phân phối không gian hoặc thêm các lề vào các mục.

- -

Các trang chi tiết các thuộc tính căn chỉnh riêng lẻ

- -

Vì các thuộc tính căn chỉnh hộp CSS được thực hiện khác nhau tùy thuộc vào đặc tả mà chúng tương tác, hãy tham khảo các trang sau cho từng loại bố cục để biết chi tiết về cách sử dụng các thuộc tính căn chỉnh với nó:

- - - -

Tài liệu tham khảo

- -

Thuộc tính CSS

- -
- -
- -

Thuật ngữ

- -
- -
- -

Hướng dẫn

- - - -

Tài nguyên bên ngoài

- - diff --git a/files/vi/web/css/css_box_model/index.html b/files/vi/web/css/css_box_model/index.html deleted file mode 100644 index 08152c9c16..0000000000 --- a/files/vi/web/css/css_box_model/index.html +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: CSS Basic Box Model -slug: Web/CSS/CSS_Box_Model -tags: - - CSS - - CSS Box Model - - NeedsTranslation - - Overview - - Reference - - TopicStub -translation_of: Web/CSS/CSS_Box_Model ---- -
{{CSSRef}}
- -

CSS Basic Box Model is a module of CSS that defines the rectangular boxes—including their padding and margin—that are generated for elements and laid out according to the visual formatting model.

- -

Reference

- -

Properties

- -

Properties controlling the flow of content in a box

- -
- -
- -

Properties controlling the size of a box

- -
- -
- -

Properties controlling the margins of a box

- -
- -
- -

Properties controlling the paddings of a box

- -
- -
- -

Other properties

- -
- -
- -

Guides

- -
-
Introduction to the CSS box model
-
Explains one of the fundamental concept of CSS: the box model. This model defines how CSS lays out elements, including their content, padding, border, and margin areas.
-
Mastering margin collapsing
-
Sometimes, two adjacent margins are collapsed into one. This article describes the rules that govern when and why this happens, and how to control it.
-
Visual formatting model
-
Explains the visual formatting model.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("CSS3 Box")}}{{Spec2("CSS3 Box")}}Added margin-trim
{{SpecName("CSS2.1", "box.html")}}{{Spec2("CSS2.1")}} 
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Initial definition.
diff --git a/files/vi/web/css/css_box_model/introduction_to_the_css_box_model/index.html b/files/vi/web/css/css_box_model/introduction_to_the_css_box_model/index.html deleted file mode 100644 index 88e2103617..0000000000 --- a/files/vi/web/css/css_box_model/introduction_to_the_css_box_model/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Kiến thức cơ bản về CSS box model -slug: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model -tags: - - CSS - - CSS Box Model - - Layout -translation_of: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model -original_slug: Web/CSS/CSS_Box_Model/Kien_thuc_co_ban_ve_css_box_model ---- -
{{CSSRef}}
- -

Khi dựng giao diện của một trang web, theo lý thuyết chuẩn của CSS box model, engine của trình duyệt thể hiện các element trên trang web dưới dạng một hình chữ nhật. CSS sẽ giúp định nghĩa các thuộc tính như kích thước, vị trí và các thuộc tính khác (màu sắc, màu nền, kích thước của border...) của các element này.

- -

Mỗi element được cấu tạo bởi bốn phần (vùng), các phần này được xác định thông qua các cạnh (đường biên) tương ứng: cạnh ngoài vùng nội dung (content edge), cạnh ngoài vùng padding (padding edge), cạnh ngoài vùng border (border edge), và cạnh ngoài vùng margin (margin edge).

- -

CSS Box model

- -

Vùng nội dung, được bọc bởi các cạnh ngoài (content edge), là nơi chứa nội dung chính của element như văn bản, hình ảnh, hoặc video. Các thông số về kích thước của vùng này gồm chiều rộng (content width) và chiều cao (content height). Vùng này thường có cả màu nền hoặc ảnh nền.

- -

Nếu thuộc tính {{cssxref("box-sizing")}} được gán giá trị content-box (mặc định) và nếu element này có kiểu hiển thị block, thì kích thước của vùng nội dung có thể được định nghĩa bởi các thông số thuộc tính {{cssxref("width")}}, {{cssxref("min-width")}}, {{cssxref("max-width")}}, {{ cssxref("height") }}, {{cssxref("min-height")}}, và {{cssxref("max-height")}}.

- -

Vùng padding, được bọc bởi các cạnh ngoài (padding edge), bọc lấy bên ngoài vùng nội dung bằng padding của element. Các thông số kích thước của vùng này gồm chiều rộng (padding-box width) và chiều cao (padding-box height).

- -

Độ dày của padding được xác định dựa trên các thuộc tính {{cssxref("padding-top")}}, {{cssxref("padding-right")}}, {{cssxref("padding-bottom")}}, {{cssxref("padding-left")}}, hay viết tắt là {{cssxref("padding")}}.

- -

Vùng border, được bọc bởi các cạnh ngoài (border edge), bọc lấy bên ngoài vùng padding bằng border của element. Các thông số kích thước của vùng này gồm chiều rộng (border-box width) và chiều cao (border-box height);

- -

Độ dày của border được xác định dựa trên thuộc tính {{cssxref("border-width")}}. Nếu thuộc tính {{cssxref("box-sizing")}} được gán giá trị border-box, thì kích thước của vùng border có thể được định nghĩa bởi các thông số thuộc tính {{cssxref("width")}}, {{cssxref("min-width")}}, {{cssxref("max-width")}}, {{ cssxref("height") }}, {{cssxref("min-height")}}, và {{cssxref("max-height")}}. Nếu element có background bằng cách gán thuộc tính ({{cssxref("background-color")}} hoặc {{cssxref("background-image")}}),  thì background sẽ tràn ra cả vùng border. Bạn có thể thay đổi trạng thái mặc định này bằng cách sử dụng kèm thuộc tính {{cssxref("background-clip")}}.

- -

Vùng margin, được bọc bởi các cạnh ngoài (margn edge), bọc lấy bên ngoài vùng border và tạo ra một vùng trống để giãn cách vị trí của element này với các element khác xung quanh. Các thông số kích thước của vùng này gồm chiều rộng (margin-box width) và chiều cao (margin-box height);

- -

Kích thước của vùng margin được xác định dựa trên các thuộc tính  {{cssxref("margin-top")}}, {{cssxref("margin-right")}}, {{cssxref("margin-bottom")}}, {{cssxref("margin-left")}}, hay viết tắt là  {{cssxref("margin")}}. Khi có sự xung đột margin xảy ra (margin collapsing), sẽ khó xác định chính xác vùng margin của một element vì nó được chia sẻ cho các element với nhau.

- -

Cuối cùng, lưu ý với một elements với thuộc tính hiển thị là inline (inline element), thì khoảng không gian mà nó chiếm dụng (chiều cao) được xác định bởi thuộc tính {{cssxref('line-height')}}, dù cho nó có các thuộc tính border hay padding thêm vào.

- -

Tham khảo thêm

- - - -

Đặc tả kĩ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tả kĩ thuậtTrạng tháiGhi chú
{{SpecName('CSS3 Box', '#intro')}}{{Spec2('CSS3 Box')}}
{{ SpecName("CSS2.1","box.html#box-dimensions")}}{{ Spec2('CSS2.1') }}Chỉnh sửa từ ngữ chính xác hơn, không có thay đổi gì về quan trọng.
{{ SpecName("CSS1","#formatting-model")}}{{ Spec2('CSS1') }}Các định nghĩa ban đầu.
- -

Tham khảo thêm

- - diff --git a/files/vi/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html b/files/vi/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html deleted file mode 100644 index 07473396c2..0000000000 --- a/files/vi/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html +++ /dev/null @@ -1,764 +0,0 @@ ---- -title: Tổng quan về Bố cục Lưới -slug: Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout -tags: - - ok -translation_of: Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout -original_slug: Web/CSS/CSS_Grid_Layout/tong_quan_ve_grid_layout ---- -

Bố cục Lưới CSS đưa vào CSS một hệ thống lưới hai chiều. Các lưới có thể dùng để bố cục những vùng lớn trong trang hoặc những thành phần giao diện người dùng nhỏ. Bài viết này giới thiệu Bố cục Lưới CSS và hệ thống thuật ngữ nằm trong chi tiết kỹ thuật của Bố cục Lưới CSS Cấp 1. Những đặc trưng được thể hiện trong tổng quan này sẽ được giải thích chi tiết hơn trong phần còn lại của hướng dẫn.

- -

Lưới là gì?

- -

Một lưới là một tổ hợp của những đường ngang và dọc cắt nhau - một nhóm xác định các cột và nhóm kia xác định các hàng. Các phần tử có thể được đặt lên lưới, dựa vào các đường hàng và cột này. Lưới CSS có các đặc trưng sau:

- -

Kích thước đường ray cố định và linh hoạt

- -

Bạn có thể tạo một lưới có kích thước đường ray cố định - bằng điểm ảnh chẳng hạn. Điều này sẽ đặt lưới vào điểm ảnh xác định khớp với bố cục bạn mong muốn. Bạn cũng có thể tạo một lưới sử dụng kích thước linh hoạt bằng phần trăm hoặc dùng đơn vị mới fr được thiết kế cho mục đích này.

- -

Sắp đặt phần tử

- -

Bạn có thể đặt những phần tử vào những vị trí chính xác trên lưới bằng cách dùng số thứ tự đường, bằng tên hoặc trỏ vào một khu vực của lưới. Lưới có bao gồm một thuật toán để điều khiển việc sắp đặt các phần tử không có vị trí rõ ràng trên lưới.

- -

Creation of additional tracks to hold content

- -

You can define an explicit grid with grid layout but the specification also deals with the content added outside of a declared grid, which adds additional rows and columns when needed. Features such as adding “as many columns that will fit into a container” are included.

- -

Alignment control

- -

Grid contains alignment features so that we can control how the items align once placed into a grid area, and how the entire grid is aligned. 

- -

Control of overlapping content

- -

More than one item can be placed into a grid cell or area, they can partially overlap each other. This layering may then be controlled with {{cssxref("z-index")}} property.

- -

Grid is a powerful specification and when combined with other parts of CSS such as flexbox, can help you to create layouts that were previously impossible to build in CSS. It all starts by creating a grid in your grid container.

- -

The Grid container

- -

We create a grid container by declaring display: grid or display: inline-grid on an element. As soon as we do this all direct children of that element will become grid items.

- -

In this example, I have a containing div with a class of wrapper, inside are five child elements.

- -
<div class="wrapper">
-  <div>One</div>
-  <div>Two</div>
-  <div>Three</div>
-  <div>Four</div>
-  <div>Five</div>
-</div>
-
- -

I make the .wrapper a grid container.

- -
.wrapper {
-  display: grid;
-}
-
- - - -

{{ EmbedLiveSample('The_Grid_container', '200', '330') }}

- -

All the direct children are now grid items. In a web browser, you won’t see any difference to how these items are displayed before turning them into a grid, as grid has created a single column grid for the items. At this point, you may find it useful to work in Firefox Developer Edition, which has the Grid Inspector available as part of the Developer Tools. If you view this example in Firefox and inspect the grid, you will see a small icon next to the value grid. Click this and then the grid on this element will be overlaid in the browser window.

- -

Using the Grid Highlighter in DevTools to view a grid

- -

As you learn and then work with the CSS Grid Layout this tool will give you a better idea of what is happening with your grids visually.

- -

If we want to start making this more grid-like we need to add column tracks.

- -

Grid Tracks

- -

We define rows and columns on our grid with the {{cssxref("grid-template-columns")}} and {{cssxref("grid-template-rows")}} properties. These define grid tracks. A grid track is the space between any two lines on the grid. In the below image you can see a track highlighted – this is the first row track in our grid.

- -

- -

I can add to our earlier example by adding the grid-template-columns property, then defining the size of the column tracks.

- -

I have now created a grid with three 200-pixel-wide column tracks. The child items will be laid out on this grid one in each grid cell.

- -
-
<div class="wrapper">
-  <div>One</div>
-  <div>Two</div>
-  <div>Three</div>
-  <div>Four</div>
-  <div>Five</div>
-</div>
-
- -
.wrapper {
-  display: grid;
-  grid-template-columns: 200px 200px 200px;
-}
-
- - - -

{{ EmbedLiveSample('grid_first', '610', '140') }}

-
- -

The fr Unit

- -

Tracks can be defined using any length unit. Grid also introduces an additional length unit to help us create flexible grid tracks. The new fr unit represents a fraction of the available space in the grid container. The next grid definition would create three equal width tracks that grow and shrink according to the available space.

- -
-
<div class="wrapper">
-  <div>One</div>
-  <div>Two</div>
-  <div>Three</div>
-  <div>Four</div>
-  <div>Five</div>
-</div>
-
- -
.wrapper {
-  display: grid;
-  grid-template-columns: 1fr 1fr 1fr;
-}
-
- - - -

{{ EmbedLiveSample('fr_unit_ls', '220', '140') }}

-
- -

In this next example, we create a definition with a 2fr track then two 1fr tracks. The available space is split into four. Two parts are given to the first track and one part each to the next two tracks.

- -
.wrapper {
-  display: grid;
-  grid-template-columns: 2fr 1fr 1fr;
-}
-
- -

In this final example, we mix absolute sized tracks with fraction units. The first track is 500 pixels, so the fixed width is taken away from the available space. The remaining space is divided into three and assigned in proportion to the two flexible tracks.

- -
.wrapper {
-  display: grid;
-  grid-template-columns: 500px 1fr 2fr;
-}
-
- -

Track listings with repeat() notation

- -

Large grids with many tracks can use the repeat() notation, to repeat all or a section of the track listing. For example the grid definition:

- -
.wrapper {
-  display: grid;
-  grid-template-columns: 1fr 1fr 1fr;
-}
-
- -

Can also be written as:

- -
.wrapper {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-}
-
- -

Repeat notation can be used for a part of the track listing. In this next example I have created a grid with an initial 20-pixel track, then a repeating section of 6 1fr tracks then a final 20-pixel track.

- -
.wrapper {
-  display: grid;
-  grid-template-columns: 20px repeat(6, 1fr) 20px;
-}
-
- -

Repeat notation takes the track listing, and uses it to create a repeating pattern of tracks. In this next example, my grid will consist of 10 tracks, a 1fr track, and then followed by a 2fr track. This pattern will be repeated five times.

- -
.wrapper {
-  display: grid;
-  grid-template-columns: repeat(5, 1fr 2fr);
-}
-
- -

The implicit and explicit grid

- -

When creating our example grid we defined our column tracks with the {{cssxref("grid-template-columns")}} property, but in addition let the grid create rows it needed for any other content. These rows are created in the implicit grid. The explicit grid consists of the rows and columns you define with {{cssxref("grid-template-columns")}} and {{cssxref("grid-template-rows")}}. If you place something outside of that defined grid, or due to the amount of content more grid tracks are needed, then the grid creates rows and columns in the implicit grid. These tracks will be auto-sized by default, resulting in their size being based on the content that is inside them.

- -

You can also define a set size for tracks created in the implicit grid with the {{cssxref("grid-auto-rows")}} and {{cssxref("grid-auto-columns")}} properties.

- -

In the below example we use grid-auto-rows to ensure that tracks created in the implicit grid are 200 pixels tall.

- -
<div class="wrapper">
-  <div>One</div>
-  <div>Two</div>
-  <div>Three</div>
-  <div>Four</div>
-  <div>Five</div>
-</div>
-
- -
.wrapper {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  grid-auto-rows: 200px;
-}
-
- - - -

{{ EmbedLiveSample('The_implicit_and_explicit_grid', '230', '420') }}

- -

Track sizing and minmax()

- -

When setting up an explicit grid or defining the sizing for automatically created rows or columns we may want to give tracks a minimum size, but also ensure they expand to fit any content that is added. For example, I may want my rows to never collapse smaller than 100 pixels, but if my content stretches to 300 pixels in height, then I would like the row to stretch to that height.

- -

Grid has a solution for this with the {{cssxref("minmax", "minmax()")}} function. In this next example I am using minmax() in the value of {{cssxref("grid-auto-rows")}}. This means automatically created rows will be a minimum of 100 pixels tall, and a maximum of auto. Using auto means that the size will look at the content size and will stretch to give space for the tallest item in a cell, in this row.

- -
.wrapper {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  grid-auto-rows: minmax(100px, auto);
-}
-
- - - -
<div class="wrapper">
-  <div>One</div>
-  <div>Two
-    <p>I have some more content in.</p>
-    <p>This makes me taller than 100 pixels.</p>
-  </div>
-  <div>Three</div>
-  <div>Four</div>
-  <div>Five</div>
-</div>
-
- -

{{ EmbedLiveSample('Track_sizing_and_minmax()', '240', '470') }}

- -

Grid Lines

- -

It should be noted that when we define a grid we define the grid tracks, not the lines. Grid then gives us numbered lines to use when positioning items. In our three column, two row grid we have four column lines.

- -

Diagram showing numbered grid lines.

- -

Lines are numbered according to the writing mode of the document. In a left-to-right language, line 1 is on the left-hand side of the grid. In a right-to-left language, it is on the right-hand side of the grid. Lines can also be named, and we will look at how to do this in a later guide in this series.

- -

Positioning items against lines

- -

We will be exploring line based placement in full detail in a later article. The following example demonstrates doing this in a simple way. When placing an item, we target the line – rather than the track.

- -

In the following example I am placing the first two items on our three column track grid, using the {{cssxref("grid-column-start")}}, {{cssxref("grid-column-end")}}, {{cssxref("grid-row-start")}} and {{cssxref("grid-row-end")}} properties. Working from left to right, the first item is placed against column line 1, and spans to column line 4, which in our case is the far-right line on the grid. It begins at row line 1 and ends at row line 3, therefore spanning two row tracks.

- -

The second item starts on grid column line 1, and spans one track. This is the default so I do not need to specify the end line. It also spans two row tracks from row line 3 to row line 5. The other items will place themselves into empty spaces on the grid.

- -
<div class="wrapper">
-  <div class="box1">One</div>
-  <div class="box2">Two</div>
-  <div class="box3">Three</div>
-  <div class="box4">Four</div>
-  <div class="box5">Five</div>
-</div>
-
- -
.wrapper {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  grid-auto-rows: 100px;
-}
-
-.box1 {
-  grid-column-start: 1;
-  grid-column-end: 4;
-  grid-row-start: 1;
-  grid-row-end: 3;
-}
-
-.box2 {
-  grid-column-start: 1;
-  grid-row-start: 3;
-  grid-row-end: 5;
-}
-
- - - -

{{ EmbedLiveSample('Positioning_items_against_lines', '230', '420') }}

- -

Don't forget that you can use the Grid Inspector in Firefox Developer Tools to see how the items are positioned against the lines of the grid.

- -

Grid Cells

- -

A grid cell is the smallest unit on a grid. Conceptually it is like a table cell. As we saw in our earlier examples, once a grid is defined as a parent the child items will lay themselves out in one cell each of the defined grid. In the below image, I have highlighted the first cell of the grid.

- -

The first cell of the grid highlighted

- -

Grid Areas

- -

Items can span one or more cells both by row or by column, and this creates a grid area. Grid areas must be rectangular – it isn’t possible to create an L-shaped area for example. The highlighted grid area spans two row and two column tracks.

- -

A grid area

- -

Gutters

- -

Gutters or alleys between grid cells can be created using the {{cssxref("grid-column-gap")}} and {{cssxref("grid-row-gap")}} properties, or the shorthand {{cssxref("grid-gap")}}. In the below example, I am creating a 10-pixel gap between columns and a 1em gap between rows.

- -
.wrapper {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  grid-column-gap: 10px;
-  grid-row-gap: 1em;
-}
-
- -
<div class="wrapper">
-  <div>One</div>
-  <div>Two</div>
-  <div>Three</div>
-  <div>Four</div>
-  <div>Five</div>
-</div>
-
- - - -

{{ EmbedLiveSample('Gutters') }}

- -

Any space used by gaps will be accounted for before space is assigned to the flexible length fr tracks, and gaps act for sizing purposes like a regular grid track, however you cannot place anything into a gap. In terms of line-based positioning, the gap acts like a fat line.

- -

Nesting grids

- -

A grid item can become a grid container. In the following example, I have the three-column grid that I created earlier, with our two positioned items. In this case the first item has some sub-items. As these items are not direct children of the grid they do not participate in grid layout and so display in a normal document flow.

- -
-
<div class="wrapper">
-  <div class="box box1">
-    <div class="nested">a</div>
-    <div class="nested">b</div>
-    <div class="nested">c</div>
-  </div>
-  <div class="box box2">Two</div>
-  <div class="box box3">Three</div>
-  <div class="box box4">Four</div>
-  <div class="box box5">Five</div>
-</div>
-
- -

Nested grid in flow

- -

If I set box1 to display: grid I can give it a track definition and it too will become a grid. The items then lay out on this new grid.

- -
.box1 {
-  grid-column-start: 1;
-  grid-column-end: 4;
-  grid-row-start: 1;
-  grid-row-end: 3;
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-}
-
- - -
- -

{{ EmbedLiveSample('nesting', '600', '340') }}

- -

In this case the nested grid has no relationship to the parent. As you can see in the example it has not inherited the {{cssxref("grid-gap")}} of the parent and the lines in the nested grid do not align to the lines in the parent grid.

- -

Subgrid

- -

In the level 1 grid specification there is a feature called subgrid which would let us create nested grids that use the track definition of the parent grid.

- -
-

Subgrids are not yet implemented in any browsers, and the specification is subject to change.

-
- -

In the current specification, we would edit the above nested grid example to use display: subgrid rather than display: grid, then remove the track definition. The nested grid will use the parent grid tracks to layout items.

- -

It should be noted that the nested grid is in both dimensions—rows and columns. There is no concept of the implicit grid working with subgrids. This means you need to ensure that the parent grid has enough row and column tracks for all the subitems.

- -
.box1 {
-  grid-column-start: 1;
-  grid-column-end: 4;
-  grid-row-start: 1;
-  grid-row-end: 3;
-  display: subgrid;
-}
-
- -

Layering items with z-index

- -

Grid items can occupy the same cell. If we return to our example with items positioned by line number, we can change this to make two items overlap.

- -
-
<div class="wrapper">
-  <div class="box box1">One</div>
-  <div class="box box2">Two</div>
-  <div class="box box3">Three</div>
-  <div class="box box4">Four</div>
-  <div class="box box5">Five</div>
-</div>
-
- -
.wrapper {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  grid-auto-rows: 100px;
-}
-
-.box1 {
-  grid-column-start: 1;
-  grid-column-end: 4;
-  grid-row-start: 1;
-  grid-row-end: 3;
-}
-
-.box2 {
-  grid-column-start: 1;
-  grid-row-start: 2;
-  grid-row-end: 4;
-}
-
- - -
- -

{{ EmbedLiveSample('l_ex', '230', '420') }}

- -

The item box2 is now overlapping box1, it displays on top as it comes later in the source order.

- -

Controlling the order

- -

We can control the order in which items stack up by using the z-index property - just like positioned items. If we give box2 a lower z-index than box1 it will display below box1 in the stack.

- -
.wrapper {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  grid-auto-rows: 100px;
-}
-
-.box1 {
-  grid-column-start: 1;
-  grid-column-end: 4;
-  grid-row-start: 1;
-  grid-row-end: 3;
-  z-index: 2;
-}
-
-.box2 {
-  grid-column-start: 1;
-  grid-row-start: 2;
-  grid-row-end: 4;
-  z-index: 1;
-}
-
- - - -

{{ EmbedLiveSample('Controlling_the_order', '230', '420') }}

- -

Next Steps

- -

In this article we have had a very quick look through the Grid Layout Specification. Have a play with the code examples, and then move onto the next part of this guide where we will really start to dig into the detail of CSS Grid Layout.

- - diff --git a/files/vi/web/css/css_grid_layout/index.html b/files/vi/web/css/css_grid_layout/index.html deleted file mode 100644 index 9869d6b999..0000000000 --- a/files/vi/web/css/css_grid_layout/index.html +++ /dev/null @@ -1,243 +0,0 @@ ---- -title: CSS Grid Layout -slug: Web/CSS/CSS_Grid_Layout -translation_of: Web/CSS/CSS_Grid_Layout ---- -

CSS Grid Layout chia trang thành các nhiều phần và định hình mối quan hệ giữa các phần dựa trên kích thước, vị trí, và lớp (layer) xây dựng từ HTML nguyên thủy.

- -

Giống như tables, grid layout cho phép chúng ta sắp xếp các phần thành cột và hàng. Tuy nhiên, đối với nhiều bố cục, việc sử dụng CSS grid sẽ dễ dàng hơn là table. Ví dụ như các phần tử con trong grid có thể chồng chéo lên nhau thành các layer, giống như việc sử dụng cách định hình vị trí của CSS.

- -

Ví dụ cơ bản

- -

Ví dụ dưới đây sẽ cho bạn thấy một bố cục grid gồm 3 cột có kích thước nhỏ nhất là 100 pixels và kích thước lớn nhất được chỉnh tự động. Các phần được sắp xếp vào grid theo đường thẳng.

- -
- - -

HTML

- -
<div class="wrapper">
-  <div class="one">One</div>
-  <div class="two">Two</div>
-  <div class="three">Three</div>
-  <div class="four">Four</div>
-  <div class="five">Five</div>
-  <div class="six">Six</div>
-</div>
- -

CSS

- -
.wrapper {
-  display: grid;
-  grid-template-columns: repeat(3, 1fr);
-  grid-gap: 10px;
-  grid-auto-rows: minmax(100px, auto);
-}
-.one {
-  grid-column: 1 / 3;
-  grid-row: 1;
-}
-.two {
-  grid-column: 2 / 4;
-  grid-row: 1 / 3;
-}
-.three {
-  grid-column: 1;
-  grid-row: 2 / 5;
-}
-.four {
-  grid-column: 3;
-  grid-row: 3;
-}
-.five {
-  grid-column: 2;
-  grid-row: 4;
-}
-.six {
-  grid-column: 3;
-  grid-row: 4;
-}
-
- -

{{ EmbedLiveSample('example', '500', '440') }}

-
- -

Liên quan

- -

Thuộc tính CSS

- -
- -
- -

Chức năng CSS

- -
- -
- -

Kiểu dữ liệu CSS

- -
- -
- -

Glossary entries

- -
- -
- -

Chỉ dẫn

- -
- -
- -

Nguồn bên ngoài

- - - -

Đặc điểm

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{ SpecName('CSS3 Grid') }}{{ Spec2('CSS3 Grid') }}Initial definition.
- - diff --git a/files/vi/web/css/css_transitions/index.html b/files/vi/web/css/css_transitions/index.html deleted file mode 100644 index 23559df42c..0000000000 --- a/files/vi/web/css/css_transitions/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: CSS Transitions -slug: Web/CSS/CSS_Transitions -tags: - - CSS - - CSS Transitions - - NeedsTranslation - - Overview - - Reference - - TopicStub -translation_of: Web/CSS/CSS_Transitions ---- -
{{CSSRef}}
- -

CSS Transitions is a module of CSS that lets you create gradual transitions between the values of specific CSS properties. The behavior of these transitions can be controlled by specifying their timing function, duration, and other attributes.

- -

Reference

- -

Properties

- -
- -
- -

Guides

- -
-
Using CSS transitions
-
Step-by-step tutorial about how to create transitions using CSS. This article describes each relevant CSS property and explains how they interact with each other.
-
- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS3 Transitions')}}{{Spec2('CSS3 Transitions')}}Initial definition.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0 {{property_prefix("-webkit")}}
- 26.0
{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}} {{property_prefix("-moz")}}
- {{CompatGeckoDesktop("16.0")}}
10.011.6 {{property_prefix("-o")}}
- 12.10 #
3.0 {{property_prefix("-webkit")}}
- 6.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1 {{property_prefix("-webkit")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}} {{property_prefix("-moz")}}
- {{CompatGeckoMobile("16.0")}}
{{CompatUnknown}}10.0 {{property_prefix("-o")}}
- 12.10 #
3.2 {{property_prefix("-webkit")}}
-
- -

See also

- - diff --git a/files/vi/web/css/css_transitions/using_css_transitions/index.html b/files/vi/web/css/css_transitions/using_css_transitions/index.html deleted file mode 100644 index 3409d5313e..0000000000 --- a/files/vi/web/css/css_transitions/using_css_transitions/index.html +++ /dev/null @@ -1,1139 +0,0 @@ ---- -title: Sử dụng CSS transitions -slug: Web/CSS/CSS_Transitions/Using_CSS_transitions -translation_of: Web/CSS/CSS_Transitions/Using_CSS_transitions ---- -

{{CSSref}}

- -

CSS transitions cung cấp một cách để điều khiển tốc độ của hiệu ứng khi thay đổi các thuộc tính của CSS. Thay vì, các thay đổi thuộc tính tạo ra ảnh hưởng ngay lập tức, bạn có thể làm cho các thay đổi này diễn ra trong một khoảng thời gian. Ví dụ, nếu bạn thay đổi màu sắc của một phần tử từ trắng thành đen, thông thường sự thay đổi là tức thời. Với CSS transitions, các thay đổi xảy ra tại những khoảng thời gian, theo một đường cong tăng tốc, có thể tùy chỉnh.

- -

Các hình động liên quan đến quá trình chuyển tiếp giữa hai trạng thái thường được gọi là các chuyển tiếp tiềm ẩn (implicit transitions) vì các trạng thái ở giữa trạng thái bắt đầu và kết thúc đã được ngầm định bởi trình duyệt.

- -

A CSS transition tells the browser to draw the intermediate states between the initial and final states, showing the user a smooth transitions.

- -

CSS transitions giúp bạn quyết định những thuộc tính nào có hiệu ứng (bằng cách liệt kê chúng), khi nào thì hiệu ứng sẽ bắt đầu (bằng cách thiết lập thời gian trì hoãn - delay), bao lâu thì chuyển đổi sẽ kết thúc (bằng cách thiết lập khoảng thời gian - duration), và cách chuyển đổi diễn ra (bằng cách định nghĩa timing function, ... tuyến tính hoặc nhanh ở lúc bắt đầu, chậm ở lúc kết thúc).

- -
Chú ý: các thuộc tính CSS transition có thể được sử dụng mà không cần bất kỳ prefix provider (nhà cung cấp tiền tố nào), nhưng hiện nay, các vender prefix (tiền tố nhà cung cấp) vẫn cần thiết để tương thích với các trình duyệt cũ (ví dụ Firefox 15 và các phiên bản trước đó, Opera 12 và các phiên bản trước đó, WebKit 5.1.10 và các phiên bản trước đó, Chrome 25 và các phiên bản thấp hơn). Một bảng thống kê khả năng tương thích ở phần cuối của trang này sẽ cung cấp nhiều thông tin hơn.
- -

Những thuộc tính CSS nào có thể tạo hiệu ứng?

- -

Những lập trình viên Web có thể định nghĩa thuộc tính nào có hiệu ứng và theo cách nào. Điều này cho phép tạo ra các chuyển đổi phức tạo. Tuy nhiên, không phải tất cả các thuộc tính đều có thể tạo hiệu ứng, vì vậy bạn cần biết danh sách các thuộc tính có thể tạo hiệu ứng.

- -
Chú ý: Danh sách này có thể thay đổi. Bạn cần chú  ý tới điều này.
- -

Ngoài ra giá trị auto là một trường hợp rất phức tạp. Một vài trình duyệt, dựa trên Gecko, triển khai giá trị này khác so với những trình duyệt dựa trên WebKit, ít chặt chẽ hơn. Sử dụng các hiệu ứng với auto có thể dẫn tới những kết quả khác nhau, phụ thuộc vào trình duyệt và phiên bản của nó, vì vậy nên tránh sử dụng giá trị này.

- -

Cũng cần lưu ý khi sử dụng một transition ngay sau khi thêm phần tử tới DOM bằng cách sử dụng .appendChild() hoặc loại bỏ thuộc tính display: none của nó. Điều này xem như trạng thái ban đầu không bao giờ xảy ra và phần tử luôn luôn ở trạng thái kết thúc. Cách dễ nhất để giải quyết vấn đề này là sử dụng window.setTimeout() trước khi thay đổi thuộc tính CSS mà bạn muốn tạo hiệu ứng.

- -

Ví dụ nhiều thuộc tính với hiệu ứng

- -

Nội dung HTML

- -
<body>
-    <p>The box below combines transitions for: width, height, background-color, transform. Hover over the box to see these properties animated.</p>
-    <div class="box">Sample</div>
-</body>
- -

Nội dung CSS

- -
.box {
-    border-style: solid;
-    border-width: 1px;
-    display: block;
-    width: 100px;
-    height: 100px;
-    background-color: #0000FF;
-    -webkit-transition: width 2s, height 2s, background-color 2s, -webkit-transform 2s;
-    transition: width 2s, height 2s, background-color 2s, transform 2s;
-}
-
-.box:hover {
-    background-color: #FFCCCC;
-    width: 200px;
-    height: 200px;
-    -webkit-transform: rotate(180deg);
-    transform: rotate(180deg);
-}
-
- -

{{EmbedLiveSample('Multiple_animated_properties_example', 600, 300)}}

- -

Các thuộc tính được sử dụng để định nghĩa các transition

- -

CSS Transitions được điều khiển bằng cách viết tắt thuộc tính {{cssxref("transition")}}. Đây là cách tốt nhất để cấu hình các transition, nó tránh việc có một danh sách dài các tham số, cái có thể gây khó chịu khi phải dành nhiều thời gian để gỡ lỗi.

- -

Bạn có thể điều khiển từng thành phần của transition với các thuộc tính sau:

- -

(Chú ý các vòng lặp vô hạn chỉ dành cho mục đích mục đích minh họa; CSS transitions chỉ thay đổi một thuộc tính từ bắt đầu tới kết thúc. Nếu bạn cần các hiệu ứng như vòng lặp, hãy sử dụng CSS animation)

- -
-
{{cssxref("transition-property")}}
-
Chỉ định tên các thuộc tính CSS để áp dụng hiệu ứng. Chỉ các các thuộc tính được liệt kê ở đây có hiệu ứng trong thời gian chuyển đổi; những thay đổi của các thuộc tính khác xảy ra ngay lập tức như thường lệ.
-
{{cssxref("transition-duration")}}
-
Chỉ định khoảng thời gian các chuyển tiếp xảy ra. Bạn có thể chỉ định một khoảng thời gian duy nhất áp dụng cho tất cả các thuộc tính, hoặc nhiều giá trị cho mỗi cho phép mỗi thuộc tính chuyển đổi qua các khoảng thời gian khác nhau.
-
-
-
-

transition-duration: 0.5s

- - - -
{{EmbedLiveSample("duration_0_5s", 275, 150)}}
-
- -
-

transition-duration: 1s

- - - -
{{EmbedLiveSample("duration_1s",275,150)}}
-
- -
-

transition-duration: 2s

- - - -
{{EmbedLiveSample("duration_2s",275,150)}}
-
- -
-

transition-duration: 4s

- - - -
{{EmbedLiveSample("duration_4s",275,150)}}
-
-
-
-
{{cssxref("transition-timing-function")}}
-
Chỉ định một hàm để định nghĩa cách các giá trị trung gian cho các thuộc tính được tính toán như thế nào. Timing functions xác định cách các giá trị trung gian của chuyển đổi được tính toán. Hầu hết timing function có thể được xác định bằng cách cung cấp các đồ thị tương ứng, như định nghĩa bốn đỉnh của một khối cubic bezier. Bạn cũng có thể chọn easing từ Easing Functions Cheat Sheet.
-
-
-
-

transition-timing-function: ease

- - - -
{{EmbedLiveSample("ttf_ease",275,150)}}
-
- -
-

transition-timing-function: linear

- - - -
{{EmbedLiveSample("ttf_linear",275,150)}}
-
- -
-

transition-timing-function: step-end

- - - -
{{EmbedLiveSample("ttf_stepend",275,150)}}
-
- -
-

transition-timing-function: steps(4, end)

- - - -
{{EmbedLiveSample("ttf_step4end",275,150)}}
-
-
-
-
{{cssxref("transition-delay")}}
-
Xác định khoảng thời gian trì hoãn giữa thời gian một thuộc tính thay đổi và lúc chuyển tiếp thực sự bắt đầu.
-
-
-
-

transition-delay: 0.5s

- - - -
{{EmbedLiveSample("delay_0_5s",275,150)}}
-
- -
-

transition-delay: 1s

- - - -
{{EmbedLiveSample("delay_1s",275,150)}}
-
- -
-

transition-delay: 2s

- - - -
{{EmbedLiveSample("delay_2s",275,150)}}
-
- -
-

transition-delay: 4s

- - - -
{{EmbedLiveSample("delay_4s",275,150)}}
-
-
-
-
- -

Cú pháp CSS được viết tắt như sau:

- -
div {
-    transition: <property> <duration> <timing-function> <delay>;
-}
- -

Phát hiện sự bắt đầu và hoàn thành của quá trình chuyển tiếp

- -

Bạn có thể sử dụng sự kiện {{event("transitionend")}} để phát hiện một hiệu ứng đã kết thúc. Đây là một đối tượng {{domxref("TransitionEvent")}}, trong đó có 2 thuộc tính được thêm vào một đối tượng {{domxref("Event")}} thông thường là:

- -
-
propertyName
-
Một chuỗi báo hiệu tên thuộc tính CSS đã hoàn thành quá trình chuyển tiếp.
-
elapsedTime
-
Một số thực báo hiệu số giây quá trình chuyển tiếp đã diễn ra tại thời điểm sự kiện xảy ra. Giá trị này không ảnh hưởng tới giá trị của {{cssxref("transition-delay")}}.
-
- -

Thông thường, bạn có thể sử dụng phương thức {{domxref("EventTarget.addEventListener", "addEventListener()")}} để theo dõi sự kiện này:

- -
el.addEventListener("transitionend", updateTransition, true);
-
- -

Để phát hiện quá trình chuyển tiếp bắt đầu sử dụng {{event("transitionrun")}} (xảy ra trước thời gian chờ) và {{event("transitionstart")}} (xảy ra sau thời gian chờ), theo cùng một mẫu:

- -
el.addEventListener("transitionrun", signalStart, true);
-el.addEventListener("transitionstart", signalStart, true);
- -
Chú ý: Sự kiện transitioned không xảy ra nếu quá trình chuyển tiếp bị hủy bỏ trước khi nó hoàn thành vì phần tử {{cssxref("display")}}: none hoặc giá trị của thuộc tính đã thay đổi.
- -

Khi danh sách thuộc tính và giá trị có độ dài khác nhau

- -

Nếu danh sách giá trị ngắn hơn danh sách thuộc tính, giá trị của nó sẽ được lặp lại để phù hợp. Ví dụ:

- -
div {
-  transition-property: opacity, left, top, height;
-  transition-duration: 3s, 5s;
-}
-
- -

Điều này sẽ tương ứng với:

- -
div {
-  transition-property: opacity, left, top, height;
-  transition-duration: 3s, 5s, 3s, 5s;
-}
- -

Tương tự, nếu danh sách giá trị dài hơn danh sách thuộc tính, nó sẽ bị cắt bớt, như ví dụ dưới đây:

- -
div {
-  transition-property: opacity, left;
-  transition-duration: 3s, 5s, 2s, 1s;
-}
- -

Sẽ được biên dịch thành:

- -
div {
-  transition-property: opacity, left;
-  transition-duration: 3s, 5s;
-}
- -

Một ví dụ đơn giản

- -

Đây là ví dụ thực hiện quá trình chuyển tiếp font size trong bốn giây với 2 giây trì hoãn giữa thời điểm người dùng di chuyển chuột lên phần tử và khi hiệu ứng bắt đầu:

- -
#delay {
-  font-size: 14px;
-  transition-property: font-size;
-  transition-duration: 4s;
-  transition-delay: 2s;
-}
-
-#delay:hover {
-  font-size: 36px;
-}
-
- -

Sử dụng transitions khi highlighting menus

- -

Một trường hợp phổ biến là sử dụng CSS làm nổi bật các item trong một menu khi người dùng di chuột lên chúng. Việc sử dụng transition giúp hiệu ứng hấp dẫn hơn.

- -

Trước khi xem code, bạn có thể muốn xem live demo (giả sử trình duyệt của bạn hỗ trợ transitions).

- -

Đầu tiên chúng ta thiết lập menu sử dụng HTML:

- -
<nav>
-  <a href="#">Home</a>
-  <a href="#">About</a>
-  <a href="#">Contact Us</a>
-  <a href="#">Links</a>
-</nav>
- -

Sau đó chúng ta sử dụng CSS để style và tạo hiệu ứng cho menu:

- -
a {
-  color: #fff;
-  background-color: #333;
-  transition: all 1s ease-out;
-}
-
-a:hover,
-a:focus {
-  color: #333;
-  background-color: #fff;
-}
-
- -

Đoạn CSS quyết định menu trông như thế nào, với cả màu background và text thay đổi khi phần tử có trạng thái là {{cssxref(":hover")}} và {{cssxref(":focus")}}.

- -

Sử dụng transitions để làm cho tính năng JavaScript mượt mà

- -

Transitions là một công cụ tuyệt vời để làm mọi thứ trong mượt mà hơn mà không cần phải làm mọi thứ với JavaScript. Hãy xem ví dụ.

- -
<p>Click anywhere to move the ball</p>
-<div id="foo"></div>
-
- -

Sử dụng JavaScript bạn có thể làm hiệu ứng quả bóng di chuyển tới một vị trí nhất định xảy ra:

- -
var f = document.getElementById('foo');
-document.addEventListener('click', function(ev){
-    f.style.transform = 'translateY('+(ev.clientY-25)+'px)';
-    f.style.transform += 'translateX('+(ev.clientX-25)+'px)';
-},false);
-
- -

Với CSS bạn có thể làm cho nó diễn ra mượt mà, mà không cần nhiều nỗ lực. Đơn giản thêm một transition tới phần tử và mọi thay đổi sẽ diễn ra mượt mà:

- -
p {
-  padding-left: 60px;
-}
-
-#foo {
-  border-radius: 50px;
-  width: 50px;
-  height: 50px;
-  background: #c00;
-  position: absolute;
-  top: 0;
-  left: 0;
-  transition: transform 1s;
-}
-
- -

Bạn có thể thử ở đây: http://jsfiddle.net/9h261pzo/291/

- -

Các thông số kỹ thuật

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS3 Transitions', '', '')}}{{Spec2('CSS3 Transitions')}}Initial definition
- -

Khả năng tương thích với trình duyệt

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0 {{property_prefix("-webkit")}}
- 26.0
{{CompatGeckoDesktop("2.0")}} {{property_prefix("-moz")}}
- {{CompatGeckoDesktop("16.0")}}
1010.5 {{property_prefix("-o")}}
- 12.10
3.2 {{property_prefix("-webkit")}}
transitionend event1.0[1]
- 26.0
{{CompatGeckoDesktop("2.0")}}1010.5[2]
- 12
- 12.10
3.2[1]
- 6.0
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{CompatGeckoMobile("2.0")}} {{property_prefix("-moz")}}
- {{CompatGeckoMobile("16.0")}}
1010 {{property_prefix("-o")}}
- 12.10
3.2
transitionend event2.1[1]{{CompatGeckoMobile("2.0")}}1010[2]
- 12
- 12.10
3.2[1]
-
- -

[1] Chrome 1.0, WebKit 3.2 and Android 2.1 implemented this as the non-standard webkitTransitionEnd. Chrome 26.0 and WebKit 6.0 implement the standard transitionend.

- -

[2] Opera 10.5 and Opera Mobile 10 implemented this as oTransitionEnd, version 12 as otransitionend and version 12.10 as the standard transitionend.

- -

Các bài liên quan

- - diff --git a/files/vi/web/css/filter-function/index.html b/files/vi/web/css/filter-function/index.html deleted file mode 100644 index d991ffe975..0000000000 --- a/files/vi/web/css/filter-function/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: -slug: Web/CSS/filter-function -tags: - - CSS - - CSS Data Type - - Filter Effects - - NeedsCompatTable - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/CSS/filter-function ---- -
{{cssref}}
- -

The <filter-function> CSS data type represents a graphical effect that can change the appearance of an input image. It is used in the {{cssxref("filter")}} and {{cssxref("backdrop-filter")}} properties.

- -

Syntax

- -

The <filter-function> data type is specified using one of the filter functions listed below. Each function requires an argument which, if invalid, results in no filter being applied.

- -
-
{{cssxref("filter-function/blur", "blur()")}}
-
Blurs the image.
-
{{cssxref("filter-function/brightness", "brightness()")}}
-
Makes the image brighter or darker.
-
{{cssxref("filter-function/contrast", "contrast()")}}
-
Increases or decreases the image's contrast.
-
{{cssxref("filter-function/drop-shadow", "drop-shadow()")}}
-
Applies a drop shadow behind the image.
-
{{cssxref("filter-function/grayscale", "grayscale()")}}
-
Converts the image to grayscale.
-
{{cssxref("filter-function/hue-rotate", "hue-rotate()")}}​​​​​​​​​​​​​​
-
Changes the overall hue of the image.
-
{{cssxref("filter-function/invert", "invert()")}}
-
Inverts the colors of the image.
-
{{cssxref("filter-function/opacity", "opacity()")}}
-
Makes the image transparent.
-
{{cssxref("filter-function/saturate", "saturate()")}}
-
Super-saturates or desaturates the input image.
-
{{cssxref("filter-function/sepia", "sepia()")}}
-
Converts the image to sepia.
-
- -

Specification

- - - - - - - - - - - - - - - - -
SpecificationStatusComments
{{ SpecName('Filters 1.0', '#typedef-filter-function', '<filter-function>') }}{{ Spec2('Filters 1.0') }}Initial definition.
- -

See also

- - diff --git a/files/vi/web/css/flex-basis/index.html b/files/vi/web/css/flex-basis/index.html deleted file mode 100644 index 7163463f37..0000000000 --- a/files/vi/web/css/flex-basis/index.html +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: flex-basis -slug: Web/CSS/flex-basis -translation_of: Web/CSS/flex-basis ---- -
{{CSSRef}}
- -

The flex-basis CSS property sets the initial main size of a flex item. It sets the size of the content box unless otherwise set with {{Cssxref("box-sizing")}}.

- -
{{EmbedInteractiveExample("pages/css/flex-basis.html")}}
- - - -
-

Note: in case both flex-basis (other than auto) and width (or height in case of flex-direction: column) are set for an element, flex-basis has priority.

-
- -

Syntax

- -
/* Specify <'width'> */
-flex-basis: 10em;
-flex-basis: 3px;
-flex-basis: auto;
-
-/* Intrinsic sizing keywords */
-flex-basis: fill;
-flex-basis: max-content;
-flex-basis: min-content;
-flex-basis: fit-content;
-
-/* Automatically size based on the flex item’s content */
-flex-basis: content;
-
-/* Global values */
-flex-basis: inherit;
-flex-basis: initial;
-flex-basis: unset;
-
- -

The flex-basis property is specified as either the keyword content or a <'width'>.

- -

Values

- -
-
<'width'>
-
An absolute {{cssxref("<length>")}}, a {{cssxref("<percentage>")}} of the parent flex container's main size property, or the keyword auto. Negative values are invalid. Defaults to auto.
-
content
-
Indicates automatic sizing, based on the flex item’s content.
-
-
Note: This value was not present in the initial release of Flexible Box Layout, and thus some older implementations will not support it. The equivalent effect can be had by using auto together with a main size (width or height) of auto.
- -
-

History:

- -
    -
  • Originally, flex-basis:auto meant "look at my width or height property".
  • -
  • Then, flex-basis:auto was changed to mean automatic sizing, and "main-size" was introduced as the "look at my width or height property" keyword. It was implemented in bug 1032922.
  • -
  • Then, that change was reverted in bug 1093316, so auto once again means "look at my width or height property"; and a new content keyword is being introduced to trigger automatic sizing. ({{bug("1105111")}} covers adding that keyword).
  • -
-
-
-
- -

Formal syntax

- -{{csssyntax}} - -

Example

- -

HTML

- -
<ul class="container">
-  <li class="flex flex1">1: flex-basis test</li>
-  <li class="flex flex2">2: flex-basis test</li>
-  <li class="flex flex3">3: flex-basis test</li>
-  <li class="flex flex4">4: flex-basis test</li>
-  <li class="flex flex5">5: flex-basis test</li>
-</ul>
-
-<ul class="container">
-  <li class="flex flex6">6: flex-basis test</li>
-</ul>
-
- -

CSS

- -
.container {
-  font-family: arial, sans-serif;
-  margin: 0;
-  padding: 0;
-  list-style-type: none;
-  display: flex;
-  flex-wrap: wrap;
-}
-
-.flex {
-  background: #6AB6D8;
-  padding: 10px;
-  margin-bottom: 50px;
-  border: 3px solid #2E86BB;
-  color: white;
-  font-size: 20px;
-  text-align: center;
-  position: relative;
-}
-
-.flex:after {
-  position: absolute;
-  z-index: 1;
-  left: 0;
-  top: 100%;
-  margin-top: 10px;
-  width: 100%;
-  color: #333;
-  font-size: 18px;
-}
-
-.flex1 {
-  flex-basis: auto;
-}
-
-.flex1:after {
-  content: 'auto';
-}
-
-.flex2 {
-  flex-basis: max-content;
-}
-
-.flex2:after {
-  content: 'max-content';
-}
-
-.flex3 {
-  flex-basis: min-content;
-}
-
-.flex3:after {
-  content: 'min-content';
-}
-
-.flex4 {
-  flex-basis: fit-content;
-}
-
-.flex4:after {
-  content: 'fit-content';
-}
-
-.flex5 {
-   flex-basis: content;
-}
-
-.flex5:after {
-  content: 'content';
-}
-
-.flex6 {
-  flex-basis: fill;
-}
-
-.flex6:after {
-  content: 'fill';
-}
-
- -

Results

- -

{{EmbedLiveSample('Example', '860', '360', '', 'Web/CSS/flex-basis')}}

- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS3 Flexbox', '#propdef-flex-basis', 'flex-basis')}}{{Spec2('CSS3 Flexbox')}}Initial definition
- -

{{cssinfo}}

- -

Browser compatibility

- - - -

{{Compat("css.properties.flex-basis")}}

- -

See also

- - - -
diff --git a/files/vi/web/css/flex-wrap/index.html b/files/vi/web/css/flex-wrap/index.html deleted file mode 100644 index d96d7f17f5..0000000000 --- a/files/vi/web/css/flex-wrap/index.html +++ /dev/null @@ -1,173 +0,0 @@ ---- -title: flex-wrap -slug: Web/CSS/flex-wrap -tags: - - CSS - - CSS Flexible Boxes - - CSS Property -translation_of: Web/CSS/flex-wrap ---- -

{{ CSSRef}}

- -

Tóm tắt

- -

Thuộc tính flex-wrap xác định xem flex item có bị ép vào một dòng đơn hay có thể được rớt dòng thành nhiều dòng. Nếu việc rớt dòng được chấp nhận, thuộc tính này còn cho phép bạn xác định hướng để rớt dùng.

- -

{{cssinfo}}

- -

Xem bài sử dụng flexible box để biết thêm thông tin cũng như đọc thêm về các thuộc tính khác.

- -

Cú pháp

- -
flex-wrap: nowrap;
-flex-wrap: wrap;
-flex-wrap: wrap-reverse;
-
-/* Global values */
-flex-wrap: inherit;
-flex-wrap: initial;
-flex-wrap: unset;
-
- -

Các giá trị

- -

Thuộc tính flex-wrap chấp nhận những giá trị sau đây.:

- -
-
nowrap
-
Các flex item phải nằm trên một dòng đơn, việc này có thể khiến cho các item này tràn ra ngoài container.
-
Cross-start sẽ tương đương với start hoặc before tùy thuộc vào giá trị của {{cssxref("flex-direction")}}.
-
wrap
-
Những flex item sẽ có thể bị tách thành hai dòng nếu như tổng chiều rộng của các item lớn hơn chiều rộng của container. Cross-start sẽ tương đương với start hoặc before tùy thuộc vào giá trị của flex-direction và cross-end sẽ có giá trị ngược lại với cross-start.
-
wrap-reverse
-
Nó giống như wrap nhưng cross-start và cross-end thì có giá trị ngược lại.
-
-

Cú pháp chính quy

-
-
- -{{csssyntax}} - -

Ví dụ

- -

HTML

- -
-
<h4>This is an example for flex-wrap:wrap </h4>
-<div class="content">
-  <div class="red">1</div>
-  <div class="green">2</div>
-  <div class="blue">3</div>
-</div>
-<h4>This is an example for flex-wrap:nowrap </h4>
-<div class="content1">
-  <div class="red">1</div>
-  <div class="green">2</div>
-  <div class="blue">3</div>
-</div>
-<h4>This is an example for flex-wrap:wrap-reverse </h4>
-<div class="content2">
-  <div class="red">1</div>
-  <div class="green">2</div>
-  <div class="blue">3</div>
-</div>
-
- -

CSS

- -
/* Common Styles */
-.content,
-.content1,
-.content2 {
-    color: #fff;
-    font: 100 24px/100px sans-serif;
-    height: 150px;
-    text-align: center;
-}
-
-.content div,
-.content1 div,
-.content2 div {
-    height: 50%;
-    width: 50%;
-}
-.red {
-    background: orangered;
-}
-.green {
-    background: yellowgreen;
-}
-.blue {
-    background: steelblue;
-}
-
-/* Flexbox Styles */
-.content {
-    display: -webkit-box;
-    display: -moz-box;
-    display: -ms-flexbox;
-    display: -moz-flex;
-    display: -webkit-flex;
-    display: flex;
-    flex-wrap: wrap;
-}
-.content1 {
-    display: -webkit-box;
-    display: -moz-box;
-    display: -ms-flexbox;
-    display: -moz-flex;
-    display: -webkit-flex;
-    display: flex;
-    flex-wrap: nowrap;
-}
-.content2 {
-    display: -webkit-box;
-    display: -moz-box;
-    display: -ms-flexbox;
-    display: -moz-flex;
-    display: -webkit-flex;
-    display: flex;
-    flex-wrap: wrap-reverse;
-}
-
-
-
- -

Kết quả

- -

{{ EmbedLiveSample('Examples', '700px', '700px', '', 'Web/CSS/flex-wrap') }}

- -

Các thông số kỹ thuật

- - - - - - - - - - - - - - - - -
Thông sốTrang tháiComment
{{ SpecName('CSS3 Flexbox', '#flex-wrap-property', 'flex-wrap') }}{{ Spec2('CSS3 Flexbox') }} 
- -

Tương thích

- -

 

- - - -

{{Compat("css.properties.flex-wrap")}}

- -

 

- -

Xem thêm

- - diff --git a/files/vi/web/css/flex/index.html b/files/vi/web/css/flex/index.html deleted file mode 100644 index 2d626dc4cd..0000000000 --- a/files/vi/web/css/flex/index.html +++ /dev/null @@ -1,347 +0,0 @@ ---- -title: flex -slug: Web/CSS/flex -tags: - - CSS - - CSS Flexible Boxes - - Tham khảo - - Tham số CSS -translation_of: Web/CSS/flex ---- -
{{CSSRef}}
- -
Tham số CSS flex qui định những thành phần con bên trong thành phần cha sẽ co lại hoặc giản ra như thế nào.
- -
Dưới đây là các giá trị có thể:
- -
{{cssxref("flex-grow")}}, {{cssxref("flex-shrink")}}, và {{cssxref("flex-basis")}}
- -
 
- -
/* Giá trị cơ bản */
-flex: auto;
-flex: initial;
-flex: none;
-flex: 2;
-
-/* Một giá trị thể hiện cho flex-grow */
-flex: 2;
-
-/* Một giá trị (độ rộng hoặc chiều cao) thể hiện cho flex-basis */
-flex: 10em;
-flex: 30px;
-
-/* Hai giá trị thể hiện cho  flex-grow (1) và flex-basis (30px) */
-/* Bởi vì 30px nên thể hiện cho flex-basis */
-flex: 1 30px;
-
-/* Hai giá trị thể  hiện cho flex-grow và flex-shrink */
-flex: 2 2;
-
-/* Ba giá trị thể hiện cho  flex-grow và flex-shrink và flex-basis */
-flex: 2 2 10%;
-
-/* Nhữg giá trị khái quát */
-flex: inherit;
-flex: initial;
-flex: unset;
-
- -

Trong hầu hết các trường hợp, Bạn nên sử dụng những giá trị sau: auto, initial, none, hoặc những số dương duy nhất. Để nhìn thấy hiệu quả của những giá trị này thử thay đổi kích thước của những "thành phần cha" sau đây:

- -
- - - - -

{{EmbedLiveSample("flex", 1200, 370, "", "", "example-outcome-frame")}}

- -
-
auto
-
 
-
Những "thành phần con" được quy định kích thước bởi những tham số width và height, nhưng "thành phần con" này sẽ cố gắng lấp đầy hoặc là thu nhỏ lại để phù hợp với "thành phần cha". Cú pháp này tương ứng với: "flex: 1 1 auto".
-
initial
-
Đây là giá trị mặc định ( giá trị khi bạn không khai báo cho "thành phần con"). "Thành phần con" có kích thước tùy theo tham số width và height. "Thành phần con" sẽ co lại để phù hợp với "thành phần cha", nhưng nó sẽ không phình to ra để lấp đầy khoảng trống trong thành phần cha. Cú pháp này tương ứng với: "flex: 0 1 auto."
-
none
-
"Thành phần con" có kích thước tùy theo tham số width và height. Nó sẽ không co lại hay phình to trong "thành phần cha". Cú pháp  này tương ứng với: "flex: 0 0 auto"
-
<số dương>
-
"Thành phần con" được cho một tỉ lệ cụ thể trong khoảng trống của thành phần cha. Cú pháp này tương ứng với: "flex: <số dương> 1 0"
-
- -

Theo quy định, thì "thành phần con" không thu nhỏ lại quá kích thước  nhỏ nhất mà nó cho phép. Để thay đổi kích thước nhỏ nhất bạn có thể dùng: {{cssxref("min-width")}} hoặc {{cssxref("min-height")}}.

-
- -

{{cssinfo}}

- -

Cú pháp

- -

Tham số flex có thể sử dụng với một, hai hoặc 3 giá trị.

- -

Cú pháp với 1 giá trị: Giá trị đó có thể là:

- - - -

Cú pháp với 2 giá trị: giá trị đầu phải là giá trị đơn lẻ {{cssxref("<number>")}} được xem là <flex-grow>. Giá trị thứ 2 phải thuộc 1 trong 2 giá trị sau:

- - - -

Cú pháp với 3 giá trị:

- - - -

Values

- -
-
<'flex-grow'>
-
Định nghĩa {{cssxref("flex-grow")}} cho "thành phần con". Tìm hiểu {{cssxref("<number>")}} để biết thêm thông tin chi tiết Giá trị âm là không hợp lệ. Giá trị mặc định là 0 nếu không cung cấp.
-
<'flex-shrink'>
-
Định nghĩa {{cssxref("flex-shrink")}} cho "thành phần con". Tìm hiểu {{cssxref("<number>")}} để biết thêm thông tin chi tiết. Giá trị âm là không hợp lệ. Giá trị mặc định là 1 nếu không cung cấp.
-
<'flex-basis'>
-
Định nghĩa {{cssxref("flex-basis")}} cho "thành phần con". Bất cứ giá trị hợp lệ nào cho độ rộng hoặc chiều cao điều sử dụng được. Tốt nhất là phải cung cấp đơn vị. Giá trị mặc định là auto nếu không cung cấp.
-
none
-
Định nghĩa này tương đương với 0 0 auto.
-
- -
-

Khi sử dụng một hoặc nhiều giá trị đơn lẻ, flex-basis sẽ đổi từ auto tới 0. Để biết thêm chi tiết có thể xem bản draft Flexible Box Layout Module.

-
- -
-
-

Formal syntax

-
-
- -{{csssyntax}} - -

Ví dụ

- -
#flex-container {
-  display: flex;
-  flex-direction: row;
-}
-
-#flex-container > .flex-item {
-  flex: auto;
-}
-
-#flex-container > .raw-item {
-  width: 5rem;
-}
-
- -
<div id="flex-container">
-  <div class="flex-item" id="flex">Flex box (click to toggle raw box)</div>
-  <div class="raw-item" id="raw">Raw box</div>
-</div>
-
- - - -

Kết quả

- -

{{EmbedLiveSample('Example','100%','60')}}

- -

Thông số kỷ thuật

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS3 Flexbox', '#flex-property', 'flex')}}{{Spec2('CSS3 Flexbox')}}Initial definition
- -

Độ tương thích với các trình duyệt hiện tại

- -

{{CompatibilityTable()}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("18.0")}}[1]
- {{CompatGeckoDesktop("20.0")}}
- {{CompatGeckoDesktop("28.0")}}[2]
21.0{{property_prefix("-webkit")}}
- 29.0
{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
- {{CompatVersionUnknown}}
10.0{{property_prefix("-ms")}}[3]
- 11.0[3]
12.10 -

6.1{{property_prefix("-webkit")}}
- 9.0

-
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidEdgeIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}4.4{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
- {{CompatVersionUnknown}}
1112.107.1{{property_prefix("-webkit")}}
-
- -

[1] In Gecko 18.0 {{geckoRelease("18.0")}} và 19.0 {{geckoRelease("19.0")}} tính năng flexbox hổ trợ ẩn trong  about:config với cấu hình layout.css.flexbox.enabled, giá trị mặc định là false.

- -

[2] Multi-line flexbox được hỗ trợ  từ Gecko 28.0 {{geckoRelease("28.0")}}.

- -

Thêm nửa về hỗ trợ unprefixed, Gecko 48.0 {{geckoRelease("48.0")}} được hỗ trợ với tiền tố  -webkit vì lý do tương thích xem layout.css.prefixes.webkit, giá trị mặc định to false. Từ Gecko 49.0 {{geckoRelease("49.0")}} giá trị mặc định là true.

- -

[3] Internet Explorer 10-11 (but not 12+) bỏ qua việc sử dụng calc() trong phần flex-basis part của cú pháp flex . Có thể dùng longhand thay thế cho shorthand như một sự thay thế. Nhìn Flexbug #8 để tìm hiểu thêm. Thêm nửa cú pháp flex với một giá trị đơn lẻ trong flex-basis được xem như không hợp lệ trong những version trên và vì vậy sẽ bị phớt lờ . Một cách để giải quyết vấn đề này là luôn luôn thêm một đơn vị cho phần flex-basis trong cú pháp đơn giản. Nhìn Flexbug #4 để  tìm hiểu thêm.

- -

Nên xem thêm

- - diff --git a/files/vi/web/css/index.html b/files/vi/web/css/index.html deleted file mode 100644 index 25d2c39f23..0000000000 --- a/files/vi/web/css/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: CSS -slug: Web/CSS -tags: - - CSS - - Design - - Layout - - NeedsTranslation - - References - - TopicStub -translation_of: Web/CSS ---- -

Cascading Style Sheets, viết tắt là CSS, là một ngôn ngữ định kiểu được sử dụng để mô tả việc trình bày một tài liệu được viết bằng HTML or XML (bao gồm các ngôn ngữ khác nhau như XML, SVG or XHTML). CSS mô tả cách các phần tử được hiển thị trên màn hình, trên giấy, trong lời nói, hoặc trên các phương tiện khác.

- -

CSS là một trong những ngôn ngữ cốt lõi của web mở và có đặt tả W3C specification. Được phát triển theo cấp độ, CSS1 hiện tại đã lỗi thời, CSS2.1 là một đề xuất và CSS3, hiên được chia thành các mô-đun nhỏ hơn, đang tiến triển trên bản theo dõi chuẩn. Bản thảo đầu tiên của các mô-đun CSS4 đang được viết.

- -
-
-
Tài liệu tham khảo CSS
- -

Tài liệu tham khảo đầy đủ của chúng tôi dành cho các nhà phát triển web dày dặn kinh nghiệm mô tả mọi thuộc tính và khái niệm về CSS.

-
- -
-
Hướng dẫn CSS
- -

Giới thiệu từng bước hỗ trợ đầy đủ cho người mới bắt đầu. Nó trình bày tất cả các nguyên tắc cơ bản cần thiết.

-
- -
-
CSS3 Demos
- -

Một bộ sưa tập các bản trình diễn hiển thị các công nghệ CSS mới nhất đang hoạt động: một sự thúc đẩy cho sự sáng tạo.

-
-
- -
-
-

Tài liệu và hướng dẫn về CSS

- -
-
Các khái niệm chính về CSS
-
Mô tả cú pháp của ngôn ngữ và giới thiệu các nguyên tắc cơ bản như đặc tính và sự kế thừamô hình hộp và biên độ thu hẹp, xếp chồng và các định dạng khối, hoặc các giá trị ban đầu, được tính toán, được sử dụng và thực tế. Các thực thể như các thuộc tính CSS viết tắt cũng được xác định.
-
Viết CSS hiệu quả
-
Giải thích cách các công cụ định kiểu thực hiện việc so khớp bộ chọn và mô tả các quy tắc để viết CSS hiệu quả hơn.
-
Chuyển đổi CSS
-
Trình bày các hoạt động 2D có thể được áp dụng cho từng phần tử để xoay, nghiêng, dịch chuyển nó.
-
Chuyển tiếp CSS
-
Giải thích cách thay của một phần tử bằng cách sử dụng một động mượt giữa trạng thái ban đầu và trạng thái cuối cùng.
-
Hoạt ảnh trong CSS
-
Mô tả cách xác định hoạt ảnh của một phần tử mà còn cách phát hiện trong Javascript nếu trình duyệt hỗ trợ nó.
-
Sử dụng Gradient trong CSS
-
Giải thích cách xác định gradient, hình ảnh bao gồm các biến thể mượt mà của màu sắc.
-
Bố cục nhiều cột trong CSS
-
Trình bày cách tạo trang nhiều cột bằng cách sử dụng bố cục nhiều cột CSS3.
-
Sử dụng nhiều nền trong CSS
-
Mô tả cách xác định một số hình nền trên cùng một thành phần.
-
Chia tỷ lệ hình ảnh nền
-
Hiển thị cách kiểm soát hình nền khi hình ảnh và vùng chứa không cùng kích thước.
-
CSS media queries
-
Trình bày cách chọn các định kiểu dựa trên những chi tiết của thiết bị được hiển thị, như kích thước màn hình, độ phân giải hoặc nếu nó có màn hình cảm ứng.
-
Bộ đếm trong CSS
-
Giải thích cách sử dụng bộ đếm tự động và đánh số, về cơ bản được sử dụng làm bộ đếm cho danh sách.
-
Fonts và Typography
-
Thông báo về quản lý phông chữ bằng cách sử dụng {{ cssxref("@font-face") }} và định dạng phông chữ WOFF.
-
Sử dụng các hộp linh hoạt CSS
-
Mô tả cách sử dụng các hộp linh hoạt để thiết kế bố cục.
-
Consistent List Indentation
-
Việc cố gắng thay đổi thụt đầu dòng của các danh sách bằng CSS thì phức tạp hơn, nhưng vì các trình duyệt tuân thủ CSS có các đường dẫn khác nhau để thụt lề mặc định. Tìm hiểu làm thế nào để có được tất cả trong dòng.
-
Using dynamic styling information
-
Cách lấy thông tin và thao tác kiểu dáng thông qua DOM..
-
- -

Xem tất cả ...

-
- -
-

Hỗ trợ từ cộng đồng

- -

Bạn cần trợ giúp về vấn đề liên quan đến CSS và không thể tìm thấy giải pháp trong tài liệu?

- -
    -
  • Kiểm tra các câu hỏi CSS phổ biến để có gợi ý giải quyết vấn đề CSS.
  • -
  • Stack Overflow, một trang web hỏi - đáp được xây dựng và duy trì, tại đây bạn có thể tìm thấy đáp án cho câu hỏi của mình hay không. Nếu không bạn sẽ có thể đặt câu hỏi của mình ở đó.
  • -
  • Tham khảo diễn đàn về bố cục, bao gồm CSS và HTML - -
  • -
- -

Don't forget about the netiquette...

- -

Công cụ dễ dàng phát triển CSS

- -
    -
  • Dịch vụ Xác thực CSS W3C kiểm tra CSS có hợp lệ. Nó là một công cụ gỡ lỗi vô cùng hữu ích.
  • -
  • Firebug tiện ích mở rộng của Firefox, một phần mở rộng phổ biến đó cho phép chỉnh sửa CSS trực tiếp trên các trang web mà bạn muốn xem. Rất thực tế để kiểm tra một số thay đổi, mặc dù tiện ích mở rộng này làm được nhiều hơn nữa.
  • -
  • Tiện ích mở rộng Web Developer của Firefox cũng cho phép xem và chỉnh sửa trực tuyến trên trang web bạn đang xem. Đơn giản hơn Firebug, mặc dù ít mạnh mẽ hơn.
  • -
  • Tiện ích EditCSS của Firefox' cho phép sửa CSS trên Sidebar.
  • -
- -

Xem tất cả...

- - - - -
-
diff --git a/files/vi/web/css/length/index.html b/files/vi/web/css/length/index.html deleted file mode 100644 index a73aeee55f..0000000000 --- a/files/vi/web/css/length/index.html +++ /dev/null @@ -1,324 +0,0 @@ ---- -title: -slug: Web/CSS/length -translation_of: Web/CSS/length ---- -
{{CSSRef}}
- -

The <length> CSS data type denotes distance measurements. It is a {{cssxref("<number>")}} immediately followed by a length unit (px, em, pc, in, mm, …). Like for any CSS dimension, there is no space between the unit literal and the number. The length unit is optional after the {{cssxref("<number>")}} 0.

- -

Many CSS properties take <length> values, such as {{Cssxref("width")}}, {{Cssxref("margin")}},  {{Cssxref("padding")}}, {{Cssxref("font-size")}}, {{Cssxref("border-width")}}, {{Cssxref("text-shadow")}}, …

- -

For some properties, using negative lengths is a syntax error, but for some properties, negative lengths are allowed. Please note that although {{cssxref("<percentage>")}} values are also CSS dimensions and are accepted by some CSS properties that accept <length> values, they are not themselves, <length> values.

- -

Interpolation

- -

Values of the <length> CSS data type can be interpolated in order to allow animations. In that case they are interpolated as real, floating-point, numbers. The interpolation happens on the calculated value. The speed of the interpolation is determined by the timing function associated with the animation.

- -

Units

- -

Relative length units

- -

Font-relative lengths

- -
-
em
-
This unit represents the calculated {{Cssxref("font-size")}} of the element. If used on the {{Cssxref("font-size")}} property itself, it represents the inherited font-size of the element. -
This unit is often used to create scalable layouts, which keep the vertical rhythm of the page, even when the user changes the size of the fonts. The CSS properties {{cssxref("line-height")}}, {{cssxref("font-size")}}, {{cssxref("margin-bottom")}} and {{cssxref("margin-top")}} often have values expressed in em.
-
-
ex
-
This unit represents the x-height of the element's {{Cssxref("font")}}. On fonts with the 'x' letter, this is generally the height of lowercase letters in the font; 1ex ≈ 0.5em in many fonts.
-
ch
-
This unit represents the width, or more precisely the advance measure, of the glyph '0' (zero, the Unicode character U+0030) in the element's {{Cssxref("font")}}.
-
rem
-
This unit represents the {{Cssxref("font-size")}} of the root element (e.g. the font-size of the {{HTMLElement("html")}} element). When used on the {{Cssxref("font-size")}} on this root element, it represents its initial value. -
This unit is practical in creating perfectly scalable layout. If not supported by the targeted browsers, such layout can be achieved using the em unit, though this is slightly more complex.
-
-
- -

Viewport-percentage lengths

- -

Viewport-percentage lengths defined a length relatively to the size of viewport, that is the visible portion of the document. Only Gecko-based browsers are updating the viewport values dynamically, when the size of the viewport is modified (by modifying the size of the window on a desktop computer or by turning the device on a phone or a tablet).

- -

In conjunction with overflow:auto, space taken by eventual scrollbars is not subtracted from the viewport, whereas in the case of overflow:scroll, it is.

- -

In a {{cssxref("@page")}} at-rule declaration block, the use of the viewport lengths are invalid and the declaration will be dropped.

- -
-
vh
-
1/100th of the height of the viewport.
-
vw
-
1/100th of the width of the viewport.
-
vmin
-
1/100th of the minimum value between the height and the width of the viewport.
-
vmax
-
1/100th of the maximum value between the height and the width of the viewport.
-
- -

Absolute length units

- -

Absolute length units represents a physical measurement and when the physical properties of the output medium are known, such as for print layout. This is done by anchored one of the unit to a physical unit and to defined the other relatively to it. The anchor is done differently for low-resolution devices, like screens, and high-resolution devices, like printers.

- -

For low-dpi devices, the unit px represents the physical reference pixel and the others are defined relative to it. Thus, 1in is defined as 96px which equals 72pt. The consequence of this definition is that on such devices, length described in inches (in), centimeters (cm), millimeters (mm) doesn't necessary match the length of the physical unit with the same name.

- -

For high-dpi devices, inches (in), centimeters (cm), millimeters (mm) are defined as their physical counterparts. Therefore the px unit is defined relative to them (1/96 of 1 inch).

- -
-

Users may increase font size for accessibility purpose. To allow for usable layouts whatever is the used font size, use only absolute length units when the physical characteristics of the output medium are known, such as bitmap images. When setting length related to font-size, prefer relative units like em or rem.

-
- -
-
px
-
Relative to the viewing device.
- For screen display, typically one device pixel (dot) of the display.
- For printers and very high resolution screens one CSS pixel implies multiple device pixels, so that the number of pixel per inch stays around 96.
-
mm
-
One millimeter.
-
q
-
A quarter of a millimeter (1/40th of a centimeter).
-
cm
-
One centimeter (10 millimeters).
-
in
-
One inch (2.54 centimeters).
-
pt
-
One point (1/72th of an inch).
-
pc
-
One pica (12 points).
-
mozmm {{non-standard_inline}}
-
An experimental unit which attempts to render at exactly one millimeter regardless of the size or resolution of the display. This is rarely actually what you want, but may be useful in particular for mobile devices.
-
- -

CSS units and dots-per-inch

- -

The unit in doesn't represent a physical inch on screen, but represents 96px. That means that whatever is the real screen pixel density, it is assumed to be 96dpi. On devices with a greater pixel density, 1in will be smaller than 1 physical inch. Similarly mm, cm, and pt are not absolute length.

- -

Some specific examples:

- -
    -
  • 1in is always 96px,
  • -
  • 3pt is always 4px,
  • -
  • 25.4mm is always 96px.
  • -
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS3 Values', '#lengths', '<length>')}}{{Spec2('CSS3 Values')}}Added ch, rem, vw, vh, vmin, vmax and q
{{SpecName('CSS2.1', 'syndata.html#length-units', '<length>')}}{{Spec2('CSS2.1')}}pt, pc, px are explicitly defined (were implicitly defined in CSS1)
{{SpecName('CSS1', '#length-units', '<length>')}}{{Spec2('CSS1')}}Initial definition
- -

Browser compatibility

- -

{{CompatibilityTable}} 

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{ CompatGeckoDesktop("1.0")}}3.03.51.0
ch -

27

-
{{ CompatGeckoDesktop("1.0")}}[1]9.020.07.0
ex{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
rem4 (532.3){{ CompatGeckoDesktop("1.9.2")}}9.011.64.1
vh, vw20{{CompatGeckoDesktop("19")}}9.020.06.0
vmin -

20

-
{{CompatGeckoDesktop("19")}}9.0[2]20.06.0
vmax26{{CompatGeckoDesktop("19")}}{{CompatNo}}20.0{{CompatVersionUnknown}}
Viewport-percentage lengths invalid in {{cssxref("@page")}}{{CompatUnknown}}{{CompatGeckoDesktop("21")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
mozmm {{non-standard_inline}}{{CompatNo}}{{ CompatGeckoDesktop("2.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
1in always is 96dpi{{CompatVersionUnknown}}{{ CompatGeckoDesktop("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
q{{CompatNo}}{{CompatGeckoDesktop("49.0")}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ch{{CompatNo}}{{CompatVersionUnknown}}7.8{{CompatUnknown}}7.1.1
ex{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
rem2.1{{CompatVersionUnknown}}{{CompatUnknown}}12.04.0
vh, vw, vmin{{CompatVersionUnknown}}{{CompatGeckoMobile("19")}}{{CompatUnknown}}{{CompatNo}}6.0
vmax1.5{{CompatGeckoMobile("19")}}{{CompatUnknown}}{{CompatNo}}4.0
Viewport-percentage lengths invalid in {{cssxref("@page")}}{{CompatUnknown}}{{CompatGeckoMobile("21.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
q{{CompatUnknown}}{{CompatGeckoMobile("49.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] In Gecko 1.0-1.9.0 (Firefox 1.0-3.0) ch was the width of 'M' and it didn't work for {{CSSxref("border-width")}} and {{CSSxref("outline-width")}} CSS properties.

- -

[2] Internet Explorer implements this with the non-standard name vm.

diff --git a/files/vi/web/css/perspective/index.html b/files/vi/web/css/perspective/index.html deleted file mode 100644 index 05ba95250d..0000000000 --- a/files/vi/web/css/perspective/index.html +++ /dev/null @@ -1,289 +0,0 @@ ---- -title: perspective -slug: Web/CSS/perspective -translation_of: Web/CSS/perspective ---- -
{{CSSRef}}
- -

Thuộc tính perspective của CSS xác định khoảng cách từ mặt phẳng z=0 cho đến người dùng, việc này nhằm tạo ra một phối cảnh xa-gần cho những phần tử muốn hiển thị dưới dạng 3D. Mỗi phần tử hiển thị dạng 3D với z > 0 sẽ trở nên to ra (vì "gần" với người xem hơn); ngược lại phần tử dạng 3D có z < 0 sẽ trở nên bé lại (vì "xa" người xem hơn). Giá trị của thuộc tính này sẽ quyết định cường độ của hiệu ứng.

- -
/* Keyword value */
-perspective: none;
-
-/* <length> values */
-perspective: 20px;
-perspective: 3.5em;
-
-/* Global values */
-perspective: inherit;
-perspective: initial;
-perspective: unset;
-
- -

Những phần của phần tử 3D có toạ độ trục z lớn hơn giá trị của thuộc tính perspective sẽ không được vẽ (nó xuất hiện ở "phía sau" người xem). 

- -

Mặc định thì điểm "biến mất" (vanishing point) được đặt tại chính giữa của phẩn tử, nhưng lập trình viên có thể thay điểm vị trí của điểm này thông qua thuộc tính {{cssxref("perspective-origin")}}.

- -

Đặt giá trị của thuộc tính perspective-origin bằng 0 hoặc none sẽ tạo một cụm môi trường mới (stacking context).

- -

{{cssinfo}}

- -

Syntax

- -

Giá trị

- -
-
none
-
là từ khoá chỉ thị việc không áp dụng phối cảnh xa gần.
-
<length>
-
{{cssxref("<length>")}} giá trị này là khoảng cáh từ người xem đến mặt phẳng z = 0.  Khi giá trị này lớn hơn 0, phối cảnh xa gần sẽ được thiết lập cho phần tử. Khi nó bằng 0 hoặc nhỏ hơn 0,  thì bỏ đi phối cảnh xa-gần. 
-
- -

Cú pháp

- -{{csssyntax}} - -

Ví dụ

- -

Nội dung file HTML 

- -
<table>
-  <tbody>
-    <tr>
-      <th><code>perspective: 250px;</code>
-      </th>
-      <th><code>perspective: 350px;</code>
-      </th>
-      <th><code>perspective: 500px;</code>
-      </th>
-    </tr>
-    <tr>
-      <td>
-        <div class="container">
-          <div class="cube pers250">
-            <div class="face front">1</div>
-            <div class="face back">2</div>
-            <div class="face right">3</div>
-            <div class="face left">4</div>
-            <div class="face top">5</div>
-            <div class="face bottom">6</div>
-          </div>
-        </div>
-      </td>
-      <td>
-        <div class="container">
-          <div class="cube pers350">
-            <div class="face front">1</div>
-            <div class="face back">2</div>
-            <div class="face right">3</div>
-            <div class="face left">4</div>
-            <div class="face top">5</div>
-            <div class="face bottom">6</div>
-          </div>
-        </div>
-      </td>
-      <td>
-        <div class="container">
-          <div class="cube pers500">
-            <div class="face front">1</div>
-            <div class="face back">2</div>
-            <div class="face right">3</div>
-            <div class="face left">4</div>
-            <div class="face top">5</div>
-            <div class="face bottom">6</div>
-          </div>
-        </div>
-      </td>
-    </tr>
-  </tbody>
-</table>
- -

Nội dung file CSS

- -
/* Shorthand classes for different perspective values */
-.pers250 {
-  perspective: 250px;
-  -webkit-perspective: 250px;
-}
-
-.pers350 {
-  perspective: 350px;
-  -webkit-perspective: 350px;
-}
-
-.pers500 {
-  perspective: 500px;
-  -webkit-perspective: 500px;
-}
-
-/* Define the container div, the cube div, and a generic face */
- .container {
-  width: 200px;
-  height: 200px;
-  margin: 75px 0 0 75px;
-  border: none;
-}
-
-.cube {
-  width: 100%;
-  height: 100%;
-  backface-visibility: visible;
-  perspective-origin: 150% 150%;
-  transform-style: preserve-3d;
-  -webkit-backface-visibility: visible;
-  -webkit-perspective-origin: 150% 150%;
-  -webkit-transform-style: preserve-3d;
-}
-
-.face {
-  display: block;
-  position: absolute;
-  width: 100px;
-  height: 100px;
-   border: none;
-  line-height: 100px;
-  font-family: sans-serif;
-  font-size: 60px;
-  color: white;
-  text-align: center;
-}
-
-/* Define each face based on direction */
-.front {
-  background: rgba(0, 0, 0, 0.3);
-  transform: translateZ(50px);
-  -webkit-transform: translateZ(50px);
-}
-
-.back {
-  background: rgba(0, 255, 0, 1);
-  color: black;
-  transform: rotateY(180deg) translateZ(50px);
-  -webkit-transform: rotateY(180deg) translateZ(50px);
-}
-
-.right {
-  background: rgba(196, 0, 0, 0.7);
-  transform: rotateY(90deg) translateZ(50px);
-  -webkit-transform: rotateY(90deg) translateZ(50px);
-}
-
-.left {
-  background: rgba(0, 0, 196, 0.7);
-  transform: rotateY(-90deg) translateZ(50px);
-  -webkit-transform: rotateY(-90deg) translateZ(50px);
-}
-
-.top {
-  background: rgba(196, 196, 0, 0.7);
-  transform: rotateX(90deg) translateZ(50px);
-  -webkit-transform: rotateX(90deg) translateZ(50px)
-}
-
-.bottom {
-  background: rgba(196, 0, 196, 0.7);
-  transform: rotateX(-90deg) translateZ(50px);
-  -webkit-transform: rotateX(-90deg) translateZ(50px);
-}
-
-/* Make the table a little nicer */
-th, p, td {
-  background-color: #EEEEEE;
-  padding: 10px;
-  font-family: sans-serif;
-  text-align: left;
-}
- -

Kết quả

- -

{{EmbedLiveSample('Example', 940, 460)}}

- -

Chi tiết kỹ thuật

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{Specname('CSS Transforms 2', '#propdef-perspective', 'perspective')}}{{Spec2('CSS Transforms 2')}}Initial definition
- -

Danh sách trình duyệt tương thích

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support -

12{{property_prefix('-webkit')}}{{CompatGeckoDesktop("10")}}
- 45

-
{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
- {{CompatVersionUnknown}}
-

{{CompatGeckoDesktop("10")}}{{property_prefix('-moz')}}
- {{CompatGeckoDesktop("16")}}[1]

-
1015{{property_prefix('-webkit')}}{{CompatVersionUnknown}}{{property_prefix('-webkit')}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support3.0{{property_prefix('-webkit')}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
- {{CompatVersionUnknown}}
{{CompatGeckoMobile("10")}}{{property_prefix('-moz')}}
- {{CompatGeckoMobile("16")}}[1]
8.1{{CompatVersionUnknown}}{{property_prefix('-webkit')}}{{CompatVersionUnknown}}{{property_prefix('-webkit')}}
-
- -

[1] In addition to the unprefixed support, Gecko 45.0 {{geckoRelease("45.0")}} added support for a -webkit prefixed version of the property for web compatibility reasons behind the preference layout.css.prefixes.webkit, defaulting to false. Since Gecko 49.0 {{geckoRelease("49.0")}} the preference defaults to true.

- -

See also

- - diff --git a/files/vi/web/css/transform-function/index.html b/files/vi/web/css/transform-function/index.html deleted file mode 100644 index 2237c7c1fb..0000000000 --- a/files/vi/web/css/transform-function/index.html +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: -slug: Web/CSS/transform-function -tags: - - CSS - - CSS Data Type - - CSS Transforms - - Layout - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/CSS/transform-function ---- -
{{CSSRef}}
- -

The <transform-function> CSS data type represents a transformation that affects an element's appearance. Transformation functions can rotate, resize, distort, or move an element in 2D or 3D space. It is used in the {{cssxref("transform")}} property.

- -

Describing transformations mathematically

- -

Various coordinate models can be used to describe an HTML element's size and shape, as well as any transformations applied to it. The most common is the Cartesian coordinate system, although homogeneous coordinates are also sometimes used.

- -

Cartesian coordinates

- -

In the Cartesian coordinate system, a two-dimensional point is described using two values: an x coordinate (abscissa) and a y coordinate (ordinate). This is represented by the vector notation (x, y).

- -

In CSS (and most computer graphics), the origin (0, 0) represents the top-left corner of any element. Positive coordinates are down and to the right of the origin, while negative ones are up and to the left. Thus, a point that's 2 units to the right and 5 units down would be (2, 5), while a point 3 units to the left and 12 units up would be (-3, -12).

- -

Transformation functions

- -

Transformation functions alter the appearance of an element by manipulating the values of its coordinates. A linear transformation function is described using a 2×2 matrix, like this:

- -

ac bd

- -

The function is applied to an element by using matrix multiplication. Thus, each coordinate changes based on the values in the matrix:

- -

ac bd xy = ax+cy bx+dy

- -

It is even possible to apply several transformations in a row:

- -

a1 c1 b1 d1 a2 c2 b2 d2 = a1 a2 + c1 b2 a1 c2 + c1 d2 b1 a2 + d1 b2 b1 c2 + d1 d2

- -

With this notation, it is possible to describe, and therefore compose, most common transformations: rotations, scaling, or skewing. (In fact, all transformations that are linear functions can be described.) Composite transformations are effectively applied in order from right to left.

- -

However, one major transformation is not linear, and therefore must be special-cased when using this notation: translation. The translation vector (tx, ty) must be expressed separately, as two additional parameters.

- -
-

Note: Though trickier than Cartesian coordinates, homogeneous coordinates in projective geometry lead to 3×3 transformation matrices, and can simply express translations as linear functions.

-
- -

Syntax

- -

The <transform-function> data type is specified using one of the transformation functions listed below. Each function applies a geometric operation in either 2D or 3D.

- -

Matrix transformation

- -
-
matrix()
-
Describes a homogeneous 2D transformation matrix.
-
matrix3d()
-
Describes a 3D transformation as a 4×4 homogeneous matrix.
-
- -

Perspective

- -
-
perspective()
-
Sets the distance between the user and the z=0 plane.
-
- -

Rotation

- -
-
rotate()
-
Rotates an element around a fixed point on the 2D plane.
-
rotate3d()
-
Rotates an element around a fixed axis in 3D space.
-
rotateX()
-
Rotates an element around the horizontal axis.
-
rotateY()
-
Rotates an element around the vertical axis.
-
rotateZ()
-
Rotates an element around the z-axis.
-
- -

Scaling (resizing)

- -
-
scale()
-
Scales an element up or down on the 2D plane.
-
scale3d()
-
Scales an element up or down in 3D space.
-
scaleX()
-
Scales an element up or down horizontally.
-
scaleY()
-
Scales an element up or down vertically.
-
scaleZ()
-
Scales an element up or down along the z-axis.
-
- -

Skewing (distortion)

- -
-
skew()
-
Skews an element on the 2D plane.
-
skewX()
-
Skews an element in the horizontal direction.
-
skewY()
-
Skews an element in the vertical direction.
-
- -

Translation (moving)

- -
-
translate()
-
Translates an element on the 2D plane.
-
translate3d()
-
Translates an element in 3D space.
-
translateX()
-
Translates an element horizontally.
-
translateY()
-
Translates an element vertically.
-
translateZ()
-
Translates an element along the z-axis.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS Transforms 2', '#transform-functions', '<transform-function>')}}{{Spec2('CSS Transforms 2')}}Added 3D transform functions.
{{SpecName('CSS3 Transforms', '#transform-functions', '<transform-function>')}}{{Spec2('CSS3 Transforms')}}Initial definition
- -

Browser compatibility

- - - -

{{Compat("css.types.transform-function")}}

- -

See also

- -
    -
  • CSS {{cssxref("transform")}} property
  • -
diff --git a/files/vi/web/css/transform-function/perspective()/index.html b/files/vi/web/css/transform-function/perspective()/index.html deleted file mode 100644 index a69e46e094..0000000000 --- a/files/vi/web/css/transform-function/perspective()/index.html +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: perspective() -slug: Web/CSS/transform-function/perspective() -translation_of: Web/CSS/transform-function/perspective() ---- -
{{CSSRef}}
- -

The perspective() CSS function defines a transformation that sets the distance between the user and the z=0 plane, the perspective from which the viewer would be if the 2-dimensional interface were 3-dimensional. Its result is a {{cssxref("<transform-function>")}} data type.

- -
{{EmbedInteractiveExample("pages/css/function-perspective.html")}}
- - - -

The perspective() transform function is part of the {{cssxref('transform')}} value applied on the element being transformed. This differs from the {{cssxref('perspective')}} and {{cssxref('perspective-origin')}} properties which are attached to the parent of a child transformed in 3-dimensional space.

- -

Syntax

- -

The perspective distance used by perspective() is specified by a {{cssxref("<length>")}} value, which represents the distance between the user and the z=0 plane. The z=0 plane is the plane where everything appears in a 2-dimensional view, or the screen. A positive value makes the element appear closer to the user than the rest of the interface, a negative value farther. The greater the value, the further away the perspective of the user is.

- -
perspective(d)
-
- -

Values

- -
-
d
-
Is a {{cssxref("<length>")}} representing the distance from the user to the z=0 plane. If it is 0 or a negative value, no perspective transform is applied.
-
- - - - - - - - - - - - - - - - - -
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
-

This transformation applies to the 3D space and can't be represented on the plane.

-
This transformation is not a linear transformation in ℝ3, and can't be represented using a Cartesian-coordinate matrix. 100001000010001/d1
- -

Examples

- -

HTML

- -
<p>Without perspective:</p>
-<div class="no-perspective-box">
-  <div class="face front">A</div>
-  <div class="face top">B</div>
-  <div class="face left">C</div>
-</div>
-
-<p>With perspective (9cm):</p>
-<div class="perspective-box-far">
-  <div class="face front">A</div>
-  <div class="face top">B</div>
-  <div class="face left">C</div>
-</div>
-
-<p>With perspective (4cm):</p>
-<div class="perspective-box-closer">
-  <div class="face front">A</div>
-  <div class="face top">B</div>
-  <div class="face left">C</div>
-</div>
-
- -

CSS

- -
.face {
-  position: absolute;
-  width: 100px;
-  height: 100px;
-  line-height: 100px;
-  font-size: 100px;
-  text-align: center;
-}
-
-p + div {
-  width: 100px;
-  height: 100px;
-  transform-style: preserve-3d;
-  margin-left: 100px;
-}
-.no-perspective-box {
-  transform: rotateX(-15deg) rotateY(30deg);
-}
-
-.perspective-box-far {
-  transform: perspective(9cm) rotateX(-15deg) rotateY(30deg);
-}
-
-.perspective-box-closer {
-  transform: perspective(4cm) rotateX(-15deg) rotateY(30deg);
-}
-
-.top {
-  background-color: skyblue;
-  transform: rotateX(90deg) translate3d(0, 0, 50px);
-}
-
-.left {
-  background-color: pink;
-  transform: rotateY(-90deg) translate3d(0, 0, 50px);
-}
-
-.front {
-  background-color: limegreen;
-  transform: translate3d(0, 0, 50px);
-}
-
- -

Result

- -

{{ EmbedLiveSample('Examples', '250', '350') }}

- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("CSS Transforms 2", "#funcdef-perspective", "perspective()")}}{{Spec2("CSS Transforms 2")}}Initial definition
- -

Browser compatibility

- -

Please see the <transform-function> data type for compatibility info.

- -

See also

- -
    -
  • {{cssxref("transform")}}
  • -
  • {{cssxref("<transform-function>")}}
  • -
diff --git a/files/vi/web/css/universal_selectors/index.html b/files/vi/web/css/universal_selectors/index.html deleted file mode 100644 index da87129972..0000000000 --- a/files/vi/web/css/universal_selectors/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Universal selectors -slug: Web/CSS/Universal_selectors -translation_of: Web/CSS/Universal_selectors ---- -
{{CSSRef}}
- -

Ký hiệu chọn toàn bộ của CSS (*) sẽ chọn mọi đối tượng thuộc bất kỳ loại nào.

- -
/* Chọn tất cả đối tượng */
-* {
-  color: green;
-}
- -

Bắt đầu từ CSS3, dấu sao * có thể được dùng kết hợp cùng với {{cssxref("CSS_Namespaces", "namespaces")}}:

- -
    -
  • ns|* - khớp với mọi đối tượng trong namespace ns
  • -
  • *|* - khớp với mọi đối tượng
  • -
  • |* - khớp với mọi đối tượng không được khai báo namespace
  • -
- -

Cú pháp

- -
* { các thuộc tính }
- -

Dấu * không bắt buộc đối với những bộ chọn đơn giản. Ví dụ, *.warning và .warning tương đương nhau.

- -

Ví dụ

- -

CSS

- -
* [lang^=en] {
-  color: green;
-}
-
-*.warning {
-  color: red;
-}
-
-*#maincontent {
-  border: 1px solid blue;
-}
-
-.floating {
-  float: left
-}
-
-/* tự động giãn cách đối tượng liền kề sau một đối tượng float */
-.floating + * {
-  clear: left;
-}
-
- -

HTML

- -
<p class="warning">
-  <span lang="en-us">A green span</span> in a red paragraph.</span>
-</p>
-<p id="maincontent" lang="en-gb">
-  <span class="warning">A red span</span> in a green paragraph.</span>
-</p>
- -

Kết quả

- -

{{EmbedLiveSample('Examples')}}

- -

Quy cách

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Quy cáchTrạng tháiGhi chú
{{SpecName('CSS4 Selectors', '#the-universal-selector', 'universal selector')}}{{Spec2('CSS4 Selectors')}}Không đổi
{{SpecName('CSS3 Selectors', '#universal-selector', 'universal selector')}}{{Spec2('CSS3 Selectors')}}Defines behavior regarding namespaces and adds hint that omitting the selector is allowed within pseudo-elements
{{SpecName('CSS2.1', 'selector.html#universal-selector', 'universal selector')}}{{Spec2('CSS2.1')}}Định nghĩa ban đầu
- -

Tương thích trình duyệt

- - - -

{{Compat("css.selectors.universal")}}

diff --git a/files/vi/web/css/url()/index.html b/files/vi/web/css/url()/index.html deleted file mode 100644 index cf6c32736c..0000000000 --- a/files/vi/web/css/url()/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: url() -slug: Web/CSS/url() -translation_of: Web/CSS/url() -translation_of_original: Web/CSS/filter-function/url -original_slug: Web/CSS/filter-function/url ---- -
{{cssref}}
- -

Hàm url() CSS dùng SVG filter để thay đổi bề ngoài của ảnh.

- -

Cú pháp

- -
url(location)
- -

Thông số

- -
-
location
-
 {{cssxref("<url>")}} của tệp {{glossary("XML")}} chỉ định bộ lọc SVG, và có thể bao gồm một neo cho một phần tử bộ lọc cụ thể.
-
- -

Ví dụ

- -
url(resources.svg#c1)
- -

Liên quan

- -
    -
  • {{cssxref("<filter-function>")}}
  • -
diff --git a/files/vi/web/events/index.html b/files/vi/web/events/index.html deleted file mode 100644 index 9fffbd92ed..0000000000 --- a/files/vi/web/events/index.html +++ /dev/null @@ -1,3078 +0,0 @@ ---- -title: Event reference -slug: Web/Events -tags: - - Event - - NeedsTranslation - - Overview - - Reference - - TopicStub -translation_of: Web/Events ---- -

Sự kiện DOM được gửi để thông báo những điều thú vị đã diễn ra trong code. Mỗi sự kiện được đại diện bởi một đối tượng dựa trên interface {{DOMxRef("Event")}}, và có thể có các trường và / hoặc chức năng tùy chỉnh bổ sung được sử dụng để có thêm thông tin về những gì đã xảy ra. Sự kiện có thể đại diện cho mọi thứ, từ tương tác người dùng cơ bản đến thông báo tự động về những điều xảy ra trong mô hình kết xuất.

- -

Bài viết này cung cấp một danh sách các sự kiện có thể được gửi; một số là sự kiện tiêu chuẩn được định nghĩa trong những đặc điểm chính thức, trong khi những sự kiện khác được sử dụng dành riêng cho một số trình duyệt ; ví dụ, Các sự kiện dành riêng cho Mozilla được liệt kê để các tiện ích bổ sung (add-on) có thể sử dụng chúng để tương tác với trình duyệt.

- -

Danh mục phổ biến nhất

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Sự kiện tài nguyên

-
Tên sự kiệnBắt đầu khi
{{Event("cached")}}Các tài nguyên được liệt kê trong tệp kê khai đã được tải xuống và ứng dụng hiện được lưu trữ.
{{Event("error")}}Một tài nguyên không thể tải được.
{{Event("abort")}} -

Việc tải tài nguyên đã bị hủy bỏ

-
{{Event("load")}}Một tài nguyên và tài nguyên phụ thuộc của nó đã được tải xong..
{{Event("beforeunload")}}Cửa sổ, tài liệu và tài nguyên của nó sắp được dỡ bỏ.
{{Event("unload")}}Tài liệu hoặc tài nguyên phụ thuộc đang được dỡ bỏ.
- - - - - - - - - - - - - - - - - - - -
-

Sự kiện mạng

-
Tên sự kiệnBắt đầu khi
{{Event("online")}}Trình duyệt đã giành được quyền truy cập vào mạng
{{Event("offline")}}Trình duyệt đã mất quyền truy cập vào mạng
- - - - - - - - - - - - - - - - - - - -
-

Focus events

-
Event NameFired When
{{Event("focus")}}An element has received focus (does not bubble).
{{Event("blur")}}An element has lost focus (does not bubble).
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

WebSocket events

-
Event NameFired When
openA WebSocket connection has been established.
messageA message is received through a WebSocket.
{{Event("error")}}A WebSocket connection has been closed with prejudice (some data couldn't be sent for example).
closeA WebSocket connection has been closed.
- - - - - - - - - - - - - - - - - - - - - - - -
-

Session History events

-
Event NameFired When
{{Event("pagehide")}}A session history entry is being traversed from.
{{Event("pageshow")}}A session history entry is being traversed to.
{{Event("popstate")}}A session history entry is being navigated to (in certain cases).
- - - - - - - - - - - - - - - - - - - - - - - -
-

CSS Animation events

-
Event NameFired When
{{Event("animationstart")}}A CSS animation has started.
{{Event("animationend")}}A CSS animation has completed.
{{Event("animationiteration")}}A CSS animation is repeated.
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

CSS Transition events

-
Event NameFired When
{{Event("transitionstart")}}A CSS transition has actually started (fired after any delay).
{{Event("transitioncancel")}}A CSS transition has been cancelled.
{{Event("transitionend")}}A CSS transition has completed.
{{Event("transitionrun")}}A CSS transition has begun running (fired before any delay starts).
- - - - - - - - - - - - - - - - - - - -
-

Form events

-
Event NameFired When
{{Event("reset")}}The reset button is pressed
{{Event("submit")}}The submit button is pressed
- - - - - - - - - - - - - - - - - - - -
-

Printing events

-
Event NameFired When
{{Event("beforeprint")}}The print dialog is opened
{{Event("afterprint")}}The print dialog is closed
- - - - - - - - - - - - - - - - - - - - - - - -
-

Text Composition events

-
Event NameFired When
{{Event("compositionstart")}}The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).
{{Event("compositionupdate")}}A character is added to a passage of text being composed.
{{Event("compositionend")}}The composition of a passage of text has been completed or canceled.
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

View events

-
Event NameFired When
{{Event("fullscreenchange")}}An element was turned to fullscreen mode or back to normal mode.
{{Event("fullscreenerror")}}It was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
{{Event("resize")}}The document view has been resized.
{{Event("scroll")}}The document view or an element has been scrolled.
- - - - - - - - - - - - - - - - - - - - - - - -
-

Clipboard events

-
Event NameFired When
{{Event("cut")}}The selection has been cut and copied to the clipboard
{{Event("copy")}}The selection has been copied to the clipboard
{{Event("paste")}}The item from the clipboard has been pasted
- - - - - - - - - - - - - - - - - - - - - -
-

Keyboard events

-
Event NameFired When
{{Event("keydown")}}ANY key is pressed
{{Event("keypress")}}ANY key except Shift, Fn, CapsLock is in pressed position. (Fired continously.)
{{Event("keyup")}}ANY key is released
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Mouse events

-
Event NameFired When
{{Event("auxclick")}}A pointing device button (ANY non-primary button) has been pressed and released on an element.
{{Event("click")}}A pointing device button (ANY button; soon to be primary button only) has been pressed and released on an element.
{{Event("contextmenu")}}The right button of the mouse is clicked (before the context menu is displayed).
{{Event("dblclick")}}A pointing device button is clicked twice on an element.
{{Event("mousedown")}}A pointing device button is pressed on an element.
{{Event("mouseenter")}}A pointing device is moved onto the element that has the listener attached.
{{Event("mouseleave")}}A pointing device is moved off the element that has the listener attached.
{{Event("mousemove")}}A pointing device is moved over an element. (Fired continously as the mouse moves.)
{{Event("mouseover")}}A pointing device is moved onto the element that has the listener attached or onto one of its children.
{{Event("mouseout")}}A pointing device is moved off the element that has the listener attached or off one of its children.
{{Event("mouseup")}}A pointing device button is released over an element.
{{Event("pointerlockchange")}}The pointer was locked or released.
{{Event("pointerlockerror")}}It was impossible to lock the pointer for technical reasons or because the permission was denied.
{{Event("select")}}Some text is being selected.
{{Event("wheel")}}A wheel button of a pointing device is rotated in any direction.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Drag & Drop events

-
Event NameFired When
{{Event("drag")}}An element or text selection is being dragged (Fired continuously every 350ms).
{{Event("dragend")}}A drag operation is being ended (by releasing a mouse button or hitting the escape key).
{{Event("dragenter")}}A dragged element or text selection enters a valid drop target.
{{Event("dragstart")}}The user starts dragging an element or text selection.
{{Event("dragleave")}}A dragged element or text selection leaves a valid drop target.
{{Event("dragover")}}An element or text selection is being dragged over a valid drop target. (Fired continuously every 350ms.)
{{Event("drop")}}An element is dropped on a valid drop target.
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Media events

-
Event NameFired When
{{Event("audioprocess")}}The input buffer of a {{DOMxRef("ScriptProcessorNode")}} is ready to be processed.
{{Event("canplay")}}The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
{{Event("canplaythrough")}}The browser estimates it can play the media up to its end without stopping for content buffering.
{{Event("complete")}}The rendering of an {{DOMxRef("OfflineAudioContext")}} is terminated.
{{Event("durationchange")}}The duration attribute has been updated.
{{Event("emptied")}}The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
{{Event("ended")}}Playback has stopped because the end of the media was reached.
{{Event("loadeddata")}}The first frame of the media has finished loading.
{{Event("loadedmetadata")}}The metadata has been loaded.
{{Event("pause")}}Playback has been paused.
{{Event("play")}}Playback has begun.
{{Event("playing")}}Playback is ready to start after having been paused or delayed due to lack of data.
{{Event("ratechange")}}The playback rate has changed.
{{Event("seeked")}}A seek operation completed.
{{Event("seeking")}}A seek operation began.
{{Event("stalled")}}The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
{{Event("suspend")}}Media data loading has been suspended.
{{Event("timeupdate")}}The time indicated by the currentTime attribute has been updated.
{{Event("volumechange")}}The volume has changed.
{{Event("waiting")}}Playback has stopped because of a temporary lack of data.
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Progress events

-
Event NameFired When
abortProgression has been terminated (not due to an error).
{{Event("error")}}Progression has failed.
loadProgression has been successful.
{{Event("loadend")}}Progress has stopped (after "error", "abort" or "load" have been dispatched).
{{Event("loadstart")}}Progress has begun.
{{Event("progress")}}In progress.
{{Event("timeout")}}Progression is terminated due to preset time expiring.
- -

Storage events

- -

{{Event("change")}} (see {{anch("Non-standard events")}})
- {{Event("storage")}}

- -

Update events

- -

{{Event("checking")}}
- {{Event("downloading")}}
- {{Event("error")}}
- {{Event("noupdate")}}
- {{Event("obsolete")}}
- {{Event("updateready")}}

- -

Value change events

- -

{{Event("broadcast")}}
- {{Event("CheckboxStateChange")}}
- {{Event("hashchange")}}
- {{Event("input")}}
- {{Event("RadioStateChange")}}
- {{Event("readystatechange")}}
- {{Event("ValueChange")}}

- -

Uncategorized events

- -

{{Event("invalid")}}
- {{Event("localized")}}
- message
- message
- message
- open
- {{Event("show")}}

- -

Less common and non-standard events

- -

Abortable Fetch events

- - - - - - - - - - - - - - -
Event nameFired when
{{Event("abort_(dom_abort_api)", "abort")}}A DOM request is aborted, i.e. using {{DOMxRef("AbortController.abort()")}}.
- -

WebVR events

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event nameFired when
{{Event("vrdisplayactivate")}}When a VR display is able to be presented to, for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
{{Event("vrdisplayblur")}}when presentation to a {{DOMxRef("VRDisplay")}} has been paused for some reason by the browser, OS, or VR hardware — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
{{Event("vrdisplayconnect")}}when a compatible {{DOMxRef("VRDisplay")}} is connected to the computer.
{{Event("vrdisplaydeactivate")}}When a {{DOMxRef("VRDisplay")}} can no longer be presented to, for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
{{Event("vrdisplaydisconnect")}}When a compatible {{DOMxRef("VRDisplay")}} is disconnected from the computer.
{{Event("vrdisplayfocus")}}When presentation to a {{DOMxRef("VRDisplay")}} has resumed after being blurred.
{{Event("vrdisplaypresentchange")}}The presenting state of a {{DOMxRef("VRDisplay")}} changes — i.e. goes from presenting to not presenting, or vice versa.
- -

SVG events

- -

{{Event("SVGAbort")}}
- {{Event("SVGError")}}
- {{Event("SVGLoad")}}
- {{Event("SVGResize")}}
- {{Event("SVGScroll")}}
- {{Event("SVGUnload")}}
- {{Event("SVGZoom")}}

- -

Database events

- -

abort
- blocked
- complete
- {{Event("error")}} (link)
- success
- upgradeneeded
- versionchange

- -

Notification events

- -

AlertActive
- AlertClose

- -

CSS events

- - - -

Script events

- -

{{Event("afterscriptexecute")}}
- {{Event("beforescriptexecute")}}

- - - -

{{Event("DOMMenuItemActive")}}
- {{Event("DOMMenuItemInactive")}}

- -

Window events

- - - -

Document events

- -

DOMLinkAdded
- DOMLinkRemoved
- DOMMetaAdded
- DOMMetaRemoved
- DOMModalDialogClosed
- DOMWillOpenModalDialog

- - - -

{{Event("popuphidden")}}
- {{Event("popuphiding")}}
- {{Event("popupshowing")}}
- {{Event("popupshown")}}
- DOMPopupBlocked

- -

Tab events

- - - -

Battery events

- -

{{Event("chargingchange")}}
- {{Event("chargingtimechange")}}
- {{Event("dischargingtimechange")}}
- {{Event("levelchange")}}

- -

Call events

- -

{{Event("alerting")}}
- {{Event("busy")}}
- {{Event("callschanged")}}
- {{Event("cfstatechange")}}
- {{Event("connected")}}
- {{Event("connecting")}}
- {{Event("dialing")}}
- {{Event("disconnected")}}
- {{Event("disconnecting")}}
- {{Event("error_(Telephony)","error")}}
- {{Event("held")}}, {{Event("holding")}}
- {{Event("incoming")}}
- {{Event("resuming")}}
- {{Event("statechange")}}
- {{Event("voicechange")}}

- -

Sensor events

- -

{{Event("compassneedscalibration")}}
- {{Event("devicelight")}}
- {{Event("devicemotion")}}
- {{Event("deviceorientation")}}
- {{Event("deviceproximity")}}
- {{Event("MozOrientation")}}
- {{Event("orientationchange")}}
- {{Event("userproximity")}}

- -

Smartcard events

- -

{{Event("icccardlockerror")}}
- {{Event("iccinfochange")}}
- {{Event("smartcard-insert")}}
- {{Event("smartcard-remove")}}
- {{Event("stkcommand")}}
- {{Event("stksessionend")}}
- {{Event("cardstatechange")}}

- -

SMS and USSD events

- -

{{Event("delivered")}}
- {{Event("received")}}
- {{Event("sent")}}
- {{Event("ussdreceived")}}

- -

Frame events

- -

{{Event("mozbrowserclose")}}
- {{Event("mozbrowsercontextmenu")}}
- {{Event("mozbrowsererror")}}
- {{Event("mozbrowsericonchange")}}
- {{Event("mozbrowserlocationchange")}}
- {{Event("mozbrowserloadend")}}
- {{Event("mozbrowserloadstart")}}
- {{Event("mozbrowseropenwindow")}}
- {{Event("mozbrowsersecuritychange")}}
- {{Event("mozbrowsershowmodalprompt")}} (link)
- {{Event("mozbrowsertitlechange")}}
- DOMFrameContentLoaded

- -

DOM mutation events

- -

DOMAttributeNameChanged
- DOMAttrModified
- DOMCharacterDataModified
- {{Event("DOMContentLoaded")}}
- DOMElementNameChanged
- DOMNodeInserted
- DOMNodeInsertedIntoDocument
- DOMNodeRemoved
- DOMNodeRemovedFromDocument
- DOMSubtreeModified

- -

Touch events

- -

MozEdgeUIGesture
- MozMagnifyGesture
- MozMagnifyGestureStart
- MozMagnifyGestureUpdate
- MozPressTapGesture
- MozRotateGesture
- MozRotateGestureStart
- MozRotateGestureUpdate
- MozSwipeGesture
- MozTapGesture
- MozTouchDown
- MozTouchMove
- MozTouchUp
- {{Event("touchcancel")}}
- {{Event("touchend")}}
- {{Event("touchenter")}}
- {{Event("touchleave")}}
- {{Event("touchmove")}}
- {{Event("touchstart")}}

- -

Pointer events

- -

{{Event("pointerover")}}
- {{Event("pointerenter")}}
- {{Event("pointerdown")}}
- {{Event("pointermove")}}
- {{Event("pointerup")}}
- {{Event("pointercancel")}}
- {{Event("pointerout")}}
- {{Event("pointerleave")}}
- {{Event("gotpointercapture")}}
- {{Event("lostpointercapture")}}

- -

Standard events

- -

These events are defined in official Web specifications, and should be common across browsers. Each event is listed along with the interface representing the object sent to recipients of the event (so you can find information about what data is provided with each event) as well as a link to the specification or specifications that define the event.

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event NameEvent TypeSpecificationFired when...
{{Event("abort")}}{{DOMxRef("UIEvent")}}DOM L3The loading of a resource has been aborted.
abort{{DOMxRef("ProgressEvent")}}Progress and XMLHttpRequestProgression has been terminated (not due to an error).
abort{{DOMxRef("Event")}}IndexedDBA transaction has been aborted.
{{Event("afterprint")}}{{gecko_minversion_inline("6")}}{{DOMxRef("Event")}}HTML5The associated document has started printing or the print preview has been closed.
{{Event("animationend")}}{{DOMxRef("AnimationEvent")}} {{Experimental_Inline}}CSS AnimationsA CSS animation has completed.
{{Event("animationiteration")}}{{DOMxRef("AnimationEvent")}} {{Experimental_Inline}}CSS AnimationsA CSS animation is repeated.
{{Event("animationstart")}}{{DOMxRef("AnimationEvent")}} {{Experimental_Inline}}CSS AnimationsA CSS animation has started.
{{Event("appinstalled")}}{{DOMxRef("Event")}}Web App ManifestA web application is successfully installed as a progressive web app.
{{Event("audioprocess")}}{{DOMxRef("AudioProcessingEvent")}} {{Deprecated_Inline}}{{SpecName('Web Audio API', '#AudioProcessingEvent', 'audioprocess')}}The input buffer of a {{DOMxRef("ScriptProcessorNode")}} is ready to be processed.
{{Event("audioend")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{SpecName('Web Speech API')}}The user agent has finished capturing audio for speech recognition.
{{Event("audiostart")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{SpecName('Web Speech API')}}The user agent has started to capture audio for speech recognition.
{{Event("beforeprint")}} {{gecko_minversion_inline("6")}}{{DOMxRef("Event")}}HTML5The associated document is about to be printed or previewed for printing.
{{Event("beforeunload")}}{{DOMxRef("BeforeUnloadEvent")}}HTML5The window, the document and its resources are about to be unloaded.
{{Event("beginEvent")}}{{DOMxRef("TimeEvent")}}SVGA SMIL animation element begins.
blockedIndexedDBAn open connection to a database is blocking a versionchange transaction on the same database.
{{Event("blur")}}{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}DOM L3An element has lost focus (does not bubble).
{{Event("boundary")}} {{Experimental_Inline}}{{DOMxRef("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a word or sentence boundary
{{Event("cached")}}{{DOMxRef("Event")}}OfflineThe resources listed in the manifest have been downloaded, and the application is now cached.
{{Event("canplay")}}{{DOMxRef("Event")}}HTML5 mediaThe user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
{{Event("canplaythrough")}}{{DOMxRef("Event")}}HTML5 mediaThe user agent can play the media up to its end without having to stop for further buffering of content.
{{Event("change")}}{{DOMxRef("Event")}}DOM L2, HTML5The change event is fired for {{HTMLElement("input")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}} elements when a change to the element's value is committed by the user.
{{Event("chargingchange")}}{{DOMxRef("Event")}}Battery statusThe battery begins or stops charging.
{{Event("chargingtimechange")}}{{DOMxRef("Event")}}Battery statusThe chargingTime attribute has been updated.
{{Event("checking")}}{{DOMxRef("Event")}}OfflineThe user agent is checking for an update, or attempting to download the cache manifest for the first time.
{{Event("click")}}{{DOMxRef("MouseEvent")}}DOM L3A pointing device button has been pressed and released on an element.
close{{DOMxRef("Event")}}WebSocketA WebSocket connection has been closed.
completeIndexedDBA transaction successfully completed.
{{Event("complete")}}{{DOMxRef("OfflineAudioCompletionEvent")}} {{Deprecated_Inline}}{{SpecName('Web Audio API', '#OfflineAudioCompletionEvent-section', 'OfflineAudioCompletionEvent')}}The rendering of an {{DOMxRef("OfflineAudioContext")}} is terminated.
{{Event("compositionend")}}{{gecko_minversion_inline("9")}}{{DOMxRef("CompositionEvent")}}DOM L3The composition of a passage of text has been completed or canceled.
{{Event("compositionstart")}}{{gecko_minversion_inline("9")}}{{DOMxRef("CompositionEvent")}}DOM L3The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).
{{Event("compositionupdate")}}{{gecko_minversion_inline("9")}}{{DOMxRef("CompositionEvent")}}DOM L3A character is added to a passage of text being composed.
{{Event("contextmenu")}}{{DOMxRef("MouseEvent")}}HTML5The right button of the mouse is clicked (before the context menu is displayed).
{{Event("copy")}}{{DOMxRef("ClipboardEvent")}} {{Experimental_Inline}}ClipboardThe text selection has been added to the clipboard.
{{Event("cut")}}{{DOMxRef("ClipboardEvent")}} {{Experimental_Inline}}ClipboardThe text selection has been removed from the document and added to the clipboard.
{{Event("dblclick")}}{{DOMxRef("MouseEvent")}}DOM L3A pointing device button is clicked twice on an element.
{{Event("devicechange")}}{{DOMxRef("Event")}}{{SpecName("Media Capture")}}A media device such as a camera, microphone, or speaker is connected or removed from the system.
{{Event("devicelight")}}{{DOMxRef("DeviceLightEvent")}} {{Experimental_Inline}}Ambient Light EventsFresh data is available from a light sensor.
{{Event("devicemotion")}}{{DOMxRef("DeviceMotionEvent")}} {{Experimental_Inline}}Device Orientation EventsFresh data is available from a motion sensor.
{{Event("deviceorientation")}}{{DOMxRef("DeviceOrientationEvent")}} {{Experimental_Inline}}Device Orientation EventsFresh data is available from an orientation sensor.
{{Event("deviceproximity")}}{{DOMxRef("DeviceProximityEvent")}} {{Experimental_Inline}}Proximity EventsFresh data is available from a proximity sensor (indicates an approximated distance between the device and a nearby object).
{{Event("dischargingtimechange")}}{{DOMxRef("Event")}}Battery statusThe dischargingTime attribute has been updated.
DOMActivate {{Deprecated_Inline}}{{DOMxRef("UIEvent")}}DOM L3A button, link or state changing element is activated (use {{Event("click")}} instead).
DOMAttributeNameChanged {{Deprecated_Inline}}{{DOMxRef("MutationNameEvent")}}DOM L3 RemovedThe name of an attribute changed (use mutation observers instead).
DOMAttrModified {{Deprecated_Inline}}{{DOMxRef("MutationEvent")}}DOM L3The value of an attribute has been modified (use mutation observers instead).
DOMCharacterDataModified {{Deprecated_Inline}}{{DOMxRef("MutationEvent")}}DOM L3A text or another CharacterData has changed (use mutation observers instead).
{{Event("DOMContentLoaded")}}{{DOMxRef("Event")}}HTML5The document has finished loading (but not its dependent resources).
DOMElementNameChanged {{Deprecated_Inline}}{{DOMxRef("MutationNameEvent")}}DOM L3 RemovedThe name of an element changed (use mutation observers instead).
DOMFocusIn {{Deprecated_Inline}}{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}DOM L3An element has received focus (use {{Event("focus")}} or {{Event("focusin")}} instead).
DOMFocusOut {{Deprecated_Inline}}{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}DOM L3An element has lost focus (use {{Event("blur")}} or {{Event("focusout")}} instead).
DOMNodeInserted {{Deprecated_Inline}}{{DOMxRef("MutationEvent")}}DOM L3A node has been added as a child of another node (use mutation observers instead).
DOMNodeInsertedIntoDocument {{Deprecated_Inline}}{{DOMxRef("MutationEvent")}}DOM L3A node has been inserted into the document (use mutation observers instead).
DOMNodeRemoved {{Deprecated_Inline}}{{DOMxRef("MutationEvent")}}DOM L3A node has been removed from its parent node (use mutation observers instead).
DOMNodeRemovedFromDocument {{Deprecated_Inline}}{{DOMxRef("MutationEvent")}}DOM L3A node has been removed from the document (use mutation observers instead).
DOMSubtreeModified {{Deprecated_Inline}}{{DOMxRef("MutationEvent")}}DOM L3A change happened in the document (use mutation observers instead).
{{Event("downloading")}}{{DOMxRef("Event")}}OfflineThe user agent has found an update and is fetching it, or is downloading the resources listed by the cache manifest for the first time.
{{Event("drag")}}{{DOMxRef("DragEvent")}}HTML5An element or text selection is being dragged (every 350ms).
{{Event("dragend")}}{{DOMxRef("DragEvent")}}HTML5A drag operation is being ended (by releasing a mouse button or hitting the escape key).
{{Event("dragenter")}}{{DOMxRef("DragEvent")}}HTML5A dragged element or text selection enters a valid drop target.
{{Event("dragleave")}}{{DOMxRef("DragEvent")}}HTML5A dragged element or text selection leaves a valid drop target.
{{Event("dragover")}}{{DOMxRef("DragEvent")}}HTML5An element or text selection is being dragged over a valid drop target (every 350ms).
{{Event("dragstart")}}{{DOMxRef("DragEvent")}}HTML5The user starts dragging an element or text selection.
{{Event("drop")}}{{DOMxRef("DragEvent")}}HTML5An element is dropped on a valid drop target.
{{Event("durationchange")}}{{DOMxRef("Event")}}HTML5 mediaThe duration attribute has been updated.
{{Event("emptied")}}{{DOMxRef("Event")}}HTML5 mediaThe media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
{{Event("end_(SpeechRecognition)","end")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has disconnected.
{{Event("end_(SpeechSynthesis)","end")}} {{Experimental_Inline}}{{DOMxRef("SpeechSynthesisEvent")}}{{SpecName("Web Speech API")}}The utterance has finished being spoken.
{{Event("ended")}}{{DOMxRef("Event")}}HTML5 mediaPlayback has stopped because the end of the media was reached.
{{Event("ended_(Web_Audio)", "ended")}}{{DOMxRef("Event")}}{{SpecName("Web Audio API")}}Playback has stopped because the end of the media was reached.
{{Event("endEvent")}}{{DOMxRef("TimeEvent")}}SVGA SMIL animation element ends.
{{Event("error")}}{{DOMxRef("UIEvent")}}DOM L3A resource failed to load.
{{Event("error")}}{{DOMxRef("ProgressEvent")}}Progress and XMLHttpRequestProgression has failed.
{{Event("error")}}{{DOMxRef("Event")}}OfflineAn error occurred while downloading the cache manifest or updating the content of the application.
{{Event("error")}}{{DOMxRef("Event")}}WebSocketA WebSocket connection has been closed with prejudice (some data couldn't be sent for example).
{{Event("error")}}{{DOMxRef("Event")}}Server Sent EventsAn event source connection has been failed.
{{Event("error")}}{{DOMxRef("Event")}}IndexedDBA request caused an error and failed.
{{Event("error_(SpeechRecognitionError)","error")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{SpecName('Web Speech API')}}A speech recognition error occurs.
{{Event("error_(SpeechSynthesisError)","error")}}{{DOMxRef("SpeechSynthesisErrorEvent")}}{{SpecName('Web Speech API')}}An error occurs that prevents the utterance from being successfully spoken.
{{Event("focus")}}{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}DOM L3An element has received focus (does not bubble).
{{Event("focusin")}}{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}DOM L3An element is about to receive focus (bubbles).
{{Event("focusout")}}{{DOMxRef("FocusEvent")}} {{Experimental_Inline}}DOM L3An element is about to lose focus (bubbles).
{{Event("fullscreenchange")}}{{gecko_minversion_inline("9")}}{{DOMxRef("Event")}}Full ScreenAn element was turned to fullscreen mode or back to normal mode.
{{Event("fullscreenerror")}}{{gecko_minversion_inline("9")}}{{DOMxRef("Event")}}Full ScreenIt was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
{{Event("gamepadconnected")}}{{DOMxRef("GamepadEvent")}} {{Experimental_Inline}}GamepadA gamepad has been connected.
{{Event("gamepaddisconnected")}}{{DOMxRef("GamepadEvent")}} {{Experimental_Inline}}GamepadA gamepad has been disconnected.
{{Event("gotpointercapture")}}{{DOMxRef("PointerEvent")}}Pointer EventsElement receives pointer capture.
{{Event("hashchange")}}{{DOMxRef("HashChangeEvent")}}HTML5The fragment identifier of the URL has changed (the part of the URL after the #).
{{Event("lostpointercapture")}}{{DOMxRef("PointerEvent")}}Pointer EventsElement lost pointer capture.
{{Event("input")}}{{DOMxRef("Event")}}HTML5The value of an element changes or the content of an element with the attribute contenteditable is modified.
{{Event("invalid")}}{{DOMxRef("Event")}}HTML5A submittable element has been checked and doesn't satisfy its constraints.
{{Event("keydown")}}{{DOMxRef("KeyboardEvent")}}DOM L3A key is pressed down.
{{Event("keypress")}}{{DOMxRef("KeyboardEvent")}}DOM L3A key is pressed down and that key normally produces a character value (use input instead).
{{Event("keyup")}}{{DOMxRef("KeyboardEvent")}}DOM L3A key is released.
{{Event("languagechange")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{ SpecName('HTML5.1', '#dom-navigator-languages', 'NavigatorLanguage.languages') }}The user's preferred languages have changed.
{{Event("levelchange")}}{{DOMxRef("Event")}}Battery statusThe level attribute has been updated.
{{Event("load")}}{{DOMxRef("UIEvent")}}DOM L3A resource and its dependent resources have finished loading.
load{{DOMxRef("ProgressEvent")}}Progress and XMLHttpRequestProgression has been successful.
{{Event("loadeddata")}}{{DOMxRef("Event")}}HTML5 mediaThe first frame of the media has finished loading.
{{Event("loadedmetadata")}}{{DOMxRef("Event")}}HTML5 mediaThe metadata has been loaded.
{{Event("loadend")}}{{DOMxRef("ProgressEvent")}}Progress and XMLHttpRequestProgress has stopped (after "error", "abort" or "load" have been dispatched).
{{Event("loadstart")}}{{DOMxRef("ProgressEvent")}}Progress and XMLHttpRequestProgress has begun.
{{Event("mark")}} {{Experimental_Inline}}{{DOMxRef("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a named SSML "mark" tag.
message{{DOMxRef("MessageEvent")}}WebSocketA message is received through a WebSocket.
message{{DOMxRef("MessageEvent")}}Web WorkersA message is received from a Web Worker.
message{{DOMxRef("MessageEvent")}}Web MessagingA message is received from a child (i)frame or a parent window.
message{{DOMxRef("MessageEvent")}}Server Sent EventsA message is received through an event source.
{{Event("messageerror")}}{{DOMxRef("MessageEvent")}}{{DOMxRef("MessagePort")}}, Web Workers, Broadcast Channel, {{DOMxRef("Window")}}A message error is raised when a message is received by an object.
{{Event("message_(ServiceWorker)","message")}} {{Experimental_Inline}}{{DOMxRef("ServiceWorkerMessageEvent")}} or {{DOMxRef("ExtendableMessageEvent")}}, depending on context.Service WorkersA message is received from a service worker, or a message is received in a service worker from another context.
{{Event("mousedown")}}{{DOMxRef("MouseEvent")}}DOM L3A pointing device button (usually a mouse) is pressed on an element.
{{Event("mouseenter")}}{{DOMxRef("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached.
{{Event("mouseleave")}}{{DOMxRef("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached.
{{Event("mousemove")}}{{DOMxRef("MouseEvent")}}DOM L3A pointing device is moved over an element.
{{Event("mouseout")}}{{DOMxRef("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached or off one of its children.
{{Event("mouseover")}}{{DOMxRef("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached or onto one of its children.
{{Event("mouseup")}}{{DOMxRef("MouseEvent")}}DOM L3A pointing device button is released over an element.
{{Event("nomatch")}} {{Experimental_Inline}}{{DOMxRef("SpeechRecognitionEvent")}}{{SpecName('Web Speech API')}}The speech recognition service returns a final result with no significant recognition.
{{Event("notificationclick")}}{{DOMxRef("NotificationEvent")}} {{Experimental_Inline}}{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}A system notification spawned by {{DOMxRef("ServiceWorkerRegistration.showNotification()")}} has been clicked.
{{Event("noupdate")}}{{DOMxRef("Event")}}OfflineThe manifest hadn't changed.
{{Event("obsolete")}}{{DOMxRef("Event")}}OfflineThe manifest was found to have become a 404 or 410 page, so the application cache is being deleted.
{{Event("offline")}}{{DOMxRef("Event")}}HTML5 offlineThe browser has lost access to the network.
{{Event("online")}}{{DOMxRef("Event")}}HTML5 offlineThe browser has gained access to the network (but particular websites might be unreachable).
open{{DOMxRef("Event")}}WebSocketA WebSocket connection has been established.
open{{DOMxRef("Event")}}Server Sent EventsAn event source connection has been established.
{{Event("orientationchange")}}{{DOMxRef("Event")}}Screen OrientationThe orientation of the device (portrait/landscape) has changed
{{Event("pagehide")}}{{DOMxRef("PageTransitionEvent")}}HTML5A session history entry is being traversed from.
{{Event("pageshow")}}{{DOMxRef("PageTransitionEvent")}}HTML5A session history entry is being traversed to.
{{Event("paste")}}{{DOMxRef("ClipboardEvent")}} {{Experimental_Inline}}ClipboardData has been transferred from the system clipboard to the document.
{{Event("pause")}}{{DOMxRef("Event")}}HTML5 mediaPlayback has been paused.
{{Event("pause_(SpeechSynthesis)", "pause")}} {{Experimental_Inline}}{{DOMxRef("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance is paused part way through.
{{Event("pointercancel")}}{{DOMxRef("PointerEvent")}}Pointer EventsThe pointer is unlikely to produce any more events.
{{Event("pointerdown")}}{{DOMxRef("PointerEvent")}}Pointer EventsThe pointer enters the active buttons state.
{{Event("pointerenter")}}{{DOMxRef("PointerEvent")}}Pointer EventsPointing device is moved inside the hit-testing boundary.
{{Event("pointerleave")}}{{DOMxRef("PointerEvent")}}Pointer EventsPointing device is moved out of the hit-testing boundary.
{{Event("pointerlockchange")}}{{DOMxRef("Event")}}Pointer LockThe pointer was locked or released.
{{Event("pointerlockerror")}}{{DOMxRef("Event")}}Pointer LockIt was impossible to lock the pointer for technical reasons or because the permission was denied.
{{Event("pointermove")}}{{DOMxRef("PointerEvent")}}Pointer EventsThe pointer changed coordinates.
{{Event("pointerout")}}{{DOMxRef("PointerEvent")}}Pointer EventsThe pointing device moved out of hit-testing boundary or leaves detectable hover range.
{{Event("pointerover")}}{{DOMxRef("PointerEvent")}}Pointer EventsThe pointing device is moved into the hit-testing boundary.
{{Event("pointerup")}}{{DOMxRef("PointerEvent")}}Pointer EventsThe pointer leaves the active buttons state.
{{Event("play")}}{{DOMxRef("Event")}}HTML5 mediaPlayback has begun.
{{Event("playing")}}{{DOMxRef("Event")}}HTML5 mediaPlayback is ready to start after having been paused or delayed due to lack of data.
{{Event("popstate")}}{{DOMxRef("PopStateEvent")}}HTML5A session history entry is being navigated to (in certain cases).
{{Event("progress")}}{{DOMxRef("ProgressEvent")}}Progress and XMLHttpRequestIn progress.
progress{{DOMxRef("ProgressEvent")}}OfflineThe user agent is downloading resources listed by the manifest.
{{Event("push")}}{{DOMxRef("PushEvent")}} {{Experimental_Inline}}{{SpecName("Push API")}}A Service Worker has received a push message.
{{Event("pushsubscriptionchange")}}{{DOMxRef("PushEvent")}} {{Experimental_Inline}}{{SpecName("Push API")}}A PushSubscription has expired.
{{Event("ratechange")}}{{DOMxRef("Event")}}HTML5 mediaThe playback rate has changed.
{{Event("readystatechange")}}{{DOMxRef("Event")}}HTML5 and XMLHttpRequestThe readyState attribute of a document has changed.
{{Event("repeatEvent")}}{{DOMxRef("TimeEvent")}}SVGA SMIL animation element is repeated.
{{Event("reset")}}{{DOMxRef("Event")}}DOM L2, HTML5A form is reset.
{{Event("resize")}}{{DOMxRef("UIEvent")}}DOM L3The document view has been resized.
{{Event("resourcetimingbufferfull")}}{{DOMxRef("Performance")}}Resource TimingThe browser's resource timing buffer is full.
{{Event("result")}} {{Experimental_Inline}}{{DOMxRef("SpeechRecognitionEvent")}} {{Experimental_Inline}}{{SpecName('Web Speech API')}}The speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app.
{{Event("resume")}} {{Experimental_Inline}}{{DOMxRef("SpeechSynthesisEvent")}} {{Experimental_Inline}}{{SpecName('Web Speech API')}}A paused utterance is resumed.
{{Event("scroll")}}{{DOMxRef("UIEvent")}}DOM L3The document view or an element has been scrolled.
{{Event("seeked")}}{{DOMxRef("Event")}}HTML5 mediaA seek operation completed.
{{Event("seeking")}}{{DOMxRef("Event")}}HTML5 mediaA seek operation began.
{{Event("select")}}{{DOMxRef("UIEvent")}}DOM L3Some text is being selected.
{{Event("selectstart")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{ SpecName('Selection API')}}A selection just started.
{{Event("selectionchange")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{ SpecName('Selection API')}}The selection in the document has been changed.
{{Event("show")}}{{DOMxRef("MouseEvent")}}HTML5A contextmenu event was fired on/bubbled to an element that has a contextmenu attribute
{{Event("slotchange")}}{{DOMxRef("Event")}}{{ SpecName('DOM WHATWG')}}The node contents of a {{DOMxRef("HTMLSlotElement")}} ({{htmlelement("slot")}}) have changed.
{{Event("soundend")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has stopped being detected.
{{Event("soundstart")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has been detected.
{{Event("speechend")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{SpecName('Web Speech API')}}Speech recognised by the speech recognition service has stopped being detected.
{{Event("speechstart")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{SpecName('Web Speech API')}}Sound that is recognised by the speech recognition service as speech has been detected.
{{Event("stalled")}}{{DOMxRef("Event")}}HTML5 mediaThe user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
{{Event("start_(SpeechRecognition)","start")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition.
{{Event("start_(SpeechSynthesis)","start")}}{{DOMxRef("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance has begun to be spoken.
{{Event("storage")}}{{DOMxRef("StorageEvent")}}Web StorageA storage area (localStorage or sessionStorage) has changed.
{{Event("submit")}}{{DOMxRef("Event")}}DOM L2, HTML5A form is submitted.
success{{DOMxRef("Event")}}IndexedDBA request successfully completed.
{{Event("suspend")}}{{DOMxRef("Event")}}HTML5 mediaMedia data loading has been suspended.
{{Event("SVGAbort")}}{{DOMxRef("SVGEvent")}}SVGPage loading has been stopped before the SVG was loaded.
{{Event("SVGError")}}{{DOMxRef("SVGEvent")}}SVGAn error has occurred before the SVG was loaded.
{{Event("SVGLoad")}}{{DOMxRef("SVGEvent")}}SVGAn SVG document has been loaded and parsed.
{{Event("SVGResize")}}{{DOMxRef("SVGEvent")}}SVGAn SVG document is being resized.
{{Event("SVGScroll")}}{{DOMxRef("SVGEvent")}}SVGAn SVG document is being scrolled.
{{Event("SVGUnload")}}{{DOMxRef("SVGEvent")}}SVGAn SVG document has been removed from a window or frame.
{{Event("SVGZoom")}}{{DOMxRef("SVGZoomEvent")}}SVGAn SVG document is being zoomed.
{{Event("timeout")}}{{DOMxRef("ProgressEvent")}}XMLHttpRequest
{{Event("timeupdate")}}{{DOMxRef("Event")}}HTML5 mediaThe time indicated by the currentTime attribute has been updated.
{{Event("touchcancel")}}{{DOMxRef("TouchEvent")}}Touch EventsA touch point has been disrupted in an implementation-specific manners (too many touch points for example).
{{Event("touchend")}}{{DOMxRef("TouchEvent")}}Touch EventsA touch point is removed from the touch surface.
{{Event("touchmove")}}{{DOMxRef("TouchEvent")}}Touch EventsA touch point is moved along the touch surface.
{{Event("touchstart")}}{{DOMxRef("TouchEvent")}}Touch EventsA touch point is placed on the touch surface.
{{Event("transitionend")}}{{DOMxRef("TransitionEvent")}} {{Experimental_Inline}}CSS TransitionsA CSS transition has completed.
{{Event("unload")}}{{DOMxRef("UIEvent")}}DOM L3The document or a dependent resource is being unloaded.
{{Event("updateready")}}{{DOMxRef("Event")}}OfflineThe resources listed in the manifest have been newly redownloaded, and the script can use swapCache() to switch to the new cache.
upgradeneededIndexedDBAn attempt was made to open a database with a version number higher than its current version. A versionchange transaction has been created.
{{Event("userproximity")}}{{DOMxRef("UserProximityEvent")}} {{Experimental_Inline}}{{SpecName("Proximity Events")}}Fresh data is available from a proximity sensor (indicates whether the nearby object is near the device or not).
{{Event("voiceschanged")}} {{Experimental_Inline}}{{DOMxRef("Event")}}{{SpecName('Web Speech API')}}The list of {{DOMxRef("SpeechSynthesisVoice")}} objects that would be returned by the {{DOMxRef("SpeechSynthesis.getVoices()")}} method has changed (when the {{Event("voiceschanged")}} event fires.)
versionchangeIndexedDBA versionchange transaction completed.
{{Event("visibilitychange")}}{{DOMxRef("Event")}}Page visibilityThe content of a tab has become visible or has been hidden.
{{Event("volumechange")}}{{DOMxRef("Event")}}HTML5 mediaThe volume has changed.
{{Event("waiting")}}{{DOMxRef("Event")}}HTML5 mediaPlayback has stopped because of a temporary lack of data.
{{Event("wheel")}}{{gecko_minversion_inline("17")}}{{DOMxRef("WheelEvent")}}DOM L3A wheel button of a pointing device is rotated in any direction.
-
- -

Non-standard events

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event NameEvent TypeSpecificationFired when...
{{Event("afterscriptexecute")}}{{DOMxRef("Event")}}Mozilla SpecificA script has been executed.
{{Event("beforescriptexecute")}}{{DOMxRef("Event")}}Mozilla SpecificA script is about to be executed.
{{Event("beforeinstallprompt")}}{{DOMxRef("Event")}}Chrome specificA user is prompted to save a web site to a home screen on mobile.
{{Event("cardstatechange")}}Firefox OS specificThe {{DOMxRef("MozMobileConnection.cardState")}} property changes value.
{{Event("change")}}{{DOMxRef("DeviceStorageChangeEvent")}}Firefox OS specificThis event is triggered each time a file is created, modified or deleted on a given storage area.
{{Event("connectionInfoUpdate")}}Firefox OS specificThe informations about the signal strength and the link speed have been updated.
{{Event("cfstatechange")}}Firefox OS specificThe call forwarding state changes.
{{Event("datachange")}}Firefox OS specificThe {{DOMxRef("MozMobileConnection.data")}} object changes values.
{{Event("dataerror")}}Firefox OS specificThe {{DOMxRef("MozMobileConnection.data")}} object receive an error from the RIL.
{{Event("DOMMouseScroll")}}{{Deprecated_Inline}}Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of lines). (use {{Event("wheel")}} instead)
dragdrop {{Deprecated_Inline}}DragEventMozilla specificAn element is dropped (use {{Event("drop")}} instead).
dragexit {{Deprecated_Inline}}DragEventMozilla specificA drag operation is being ended(use {{Event("dragend")}} instead).
draggesture {{Deprecated_Inline}}DragEventMozilla specificThe user starts dragging an element or text selection (use {{Event("dragstart")}} instead).
{{Event("icccardlockerror")}}Firefox OS specificthe {{DOMxRef("MozMobileConnection.unlockCardLock()")}} or {{DOMxRef("MozMobileConnection.setCardLock()")}} methods fails.
{{Event("iccinfochange")}}Firefox OS specificThe {{DOMxRef("MozMobileConnection.iccInfo")}} object changes.
{{Event("localized")}}Mozilla SpecificThe page has been localized using data-l10n-* attributes.
{{Event("mousewheel")}}{{Deprecated_Inline}}IE inventedThe wheel button of a pointing device is rotated.
{{Event("MozAudioAvailable")}}{{DOMxRef("Event")}}Mozilla specificThe audio buffer is full and the corresponding raw samples are available.
MozBeforeResize {{Obsolete_Inline}}Mozilla specificA window is about to be resized.
{{Event("mozbrowseractivitydone")}}Firefox OS Browser API-specificSent when some activity has been completed (complete description TBD.)
{{Event("mozbrowserasyncscroll")}}Firefox OS Browser API-specificSent when the scroll position within a browser {{HTMLElement("iframe")}} changes.
{{Event("mozbrowseraudioplaybackchange")}}Firefox OS Browser API-specificSent when audio starts or stops playing within the browser {{HTMLElement("iframe")}} content.
{{Event("mozbrowsercaretstatechanged")}}Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes.
{{Event("mozbrowserclose")}}Firefox OS Browser API-specificSent when window.close() is called within a browser {{HTMLElement("iframe")}}.
{{Event("mozbrowsercontextmenu")}}Firefox OS Browser API-specificSent when a browser {{HTMLElement("iframe")}} try to open a context menu.
{{Event("mozbrowserdocumentfirstpaint")}}Firefox OS Browser API-specificSent when a new paint occurs on any document in the browser {{HTMLElement("iframe")}}.
{{Event("mozbrowsererror")}}Firefox OS Browser API-specificSent when an error occured while trying to load a content within a browser iframe
{{Event("mozbrowserfindchange")}}Firefox OS Browser API-specificSent when a search operation is performed on the browser {{HTMLElement("iframe")}} content (see HTMLIFrameElement search methods.)
{{Event("mozbrowserfirstpaint")}}Firefox OS Browser API-specificSent when the {{HTMLElement("iframe")}} paints content for the first time (this doesn't include the initial paint from about:blank.)
{{Event("mozbrowsericonchange")}}Firefox OS Browser API-specificSent when the favicon of a browser iframe changes.
{{Event("mozbrowserlocationchange")}}Firefox OS Browser API-specificSent when an browser iframe's location changes.
{{Event("mozbrowserloadend")}}Firefox OS Browser API-specificSent when the browser iframe has finished loading all its assets.
{{Event("mozbrowserloadstart")}}Firefox OS Browser API-specificSent when the browser iframe starts to load a new page.
{{Event("mozbrowsermanifestchange")}}Firefox OS Browser API-specificSent when a the path to the app manifest changes, in the case of a browser {{HTMLElement("iframe")}} with an open web app embedded in it.
{{Event("mozbrowsermetachange")}}Firefox OS Browser API-specificSent when a {{htmlelement("meta")}} elelment is added to, removed from or changed in the browser {{HTMLElement("iframe")}}'s content.
{{Event("mozbrowseropensearch")}}Firefox OS Browser API-specificSent when a link to a search engine is found.
{{Event("mozbrowseropentab")}}Firefox OS Browser API-specificSent when a new tab is opened within a browser {{HTMLElement("iframe")}} as a result of the user issuing a command to open a link target in a new tab (for example ctrl/cmd + click.)
{{Event("mozbrowseropenwindow")}}Firefox OS Browser API-specificSent when {{DOMxRef("window.open()")}} is called within a browser iframe.
{{Event("mozbrowserresize")}}Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}}'s window size has changed.
{{Event("mozbrowserscroll")}}Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}} content scrolls.
{{Event("mozbrowserscrollareachanged")}}Firefox OS Browser API-specificSent when the available scrolling area in the browser {{HTMLElement("iframe")}} changes. This can occur on resize and when the page size changes (while loading for example.)
{{Event("mozbrowserscrollviewchange")}}Firefox OS Browser API-specificSent when asynchronous scrolling (i.e. APCZ) starts or stops.
{{Event("mozbrowsersecuritychange")}}Firefox OS Browser API-specificSent when the SSL state changes within a browser iframe.
{{Event("mozbrowserselectionstatechanged")}}Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes. Note that this is deprecated, and newer implementations use {{Event("mozbrowsercaretstatechanged")}} instead.
{{Event("mozbrowsershowmodalprompt")}}Firefox OS Browser API-specificSent when {{DOMxRef("window.alert","alert()")}}, {{DOMxRef("window.confirm","confirm()")}} or {{DOMxRef("window.prompt","prompt()")}} are called within a browser iframe
{{Event("mozbrowsertitlechange")}}Firefox OS Browser API-specificSent when the document.title changes within a browser iframe.
{{Event("mozbrowserusernameandpasswordrequired")}}Firefox OS Browser API-specificSent when an HTTP authentification is requested.
{{Event("mozbrowservisibilitychange")}}Firefox OS Browser API-specificSent when the visibility state of the current browser iframe {{HTMLElement("iframe")}} changes, for example due to a call to {{DOMxRef("HTMLIFrameElement.setVisible","setVisible()")}}.
{{Event("MozGamepadButtonDown")}}To be specifiedA gamepad button is pressed down.
{{Event("MozGamepadButtonUp")}}To be specifiedA gamepad button is released.
{{Event("MozMousePixelScroll")}} {{Deprecated_Inline}}Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of pixels). (use wheel instead)
{{Event("MozOrientation")}} {{Deprecated_Inline}}Mozilla specificFresh data is available from an orientation sensor (see deviceorientation).
{{Event("MozScrolledAreaChanged")}}{{DOMxRef("UIEvent")}}Mozilla specificThe document view has been scrolled or resized.
{{Event("moztimechange")}}Mozilla specificThe time of the device has been changed.
MozTouchDown {{Deprecated_Inline}}Mozilla specificA touch point is placed on the touch surface (use touchstart instead).
MozTouchMove {{Deprecated_Inline}}Mozilla specificA touch point is moved along the touch surface (use touchmove instead).
MozTouchUp {{Deprecated_Inline}}Mozilla specificA touch point is removed from the touch surface (use touchend instead).
{{Event("alerting")}}{{DOMxRef("CallEvent")}}To be specifiedThe correspondent is being alerted (his/her phone is ringing).
{{Event("busy")}}{{DOMxRef("CallEvent")}}To be specifiedThe line of the correspondent is busy.
{{Event("callschanged")}}{{DOMxRef("CallEvent")}}To be specifiedA call has been added or removed from the list of current calls.
onconnected {{Event("connected")}}{{DOMxRef("CallEvent")}}To be specifiedA call has been connected.
{{Event("connecting")}}{{DOMxRef("CallEvent")}}To be specifiedA call is about to connect.
{{Event("delivered")}}{{DOMxRef("SMSEvent")}}To be specifiedAn SMS has been successfully delivered.
{{Event("dialing")}}{{DOMxRef("CallEvent")}}To be specifiedThe number of a correspondent has been dialed.
{{Event("disabled")}}Firefox OS specificWifi has been disabled on the device.
{{Event("disconnected")}}{{DOMxRef("CallEvent")}}To be specifiedA call has been disconnected.
{{Event("disconnecting")}}{{DOMxRef("CallEvent")}}To be specifiedA call is about to disconnect.
{{Event("enabled")}}Firefox OS specificWifi has been enabled on the device.
{{Event("error_(Telephony)","error")}}{{DOMxRef("CallEvent")}}To be specifiedAn error occurred.
{{Event("held")}}{{DOMxRef("CallEvent")}}To be specifiedA call has been held.
{{Event("holding")}}{{DOMxRef("CallEvent")}}To be specifiedA call is about to be held.
{{Event("incoming")}}{{DOMxRef("CallEvent")}}To be specifiedA call is being received.
{{Event("received")}}{{DOMxRef("SMSEvent")}}To be specifiedAn SMS has been received.
{{Event("resuming")}}{{DOMxRef("CallEvent")}}To be specifiedA call is about to resume.
{{Event("sent")}}{{DOMxRef("SMSEvent")}}To be specifiedAn SMS has been sent.
{{Event("statechange")}}{{DOMxRef("CallEvent")}}To be specifiedThe state of a call has changed.
{{Event("statuschange")}}Firefox OS specificThe status of the Wifi connection changed.
{{Event("overflow")}}{{DOMxRef("UIEvent")}}Mozilla specificAn element has been overflowed by its content or has been rendered for the first time in this state (only works for elements styled with overflow != visible).
{{Event("smartcard-insert")}}Mozilla specificA smartcard has been inserted.
{{Event("smartcard-remove")}}Mozilla specificA smartcard has been removed.
{{Event("stkcommand")}}Firefox OS specificThe STK Proactive Command is issued from ICC.
{{Event("stksessionend")}}Firefox OS specificThe STK Session is terminated by ICC.
{{Event("touchenter")}}{{DOMxRef("TouchEvent")}}Touch Events Removed
{{Event("touchleave")}}{{DOMxRef("TouchEvent")}}Touch Events Removed
{{Event("underflow")}}{{DOMxRef("UIEvent")}}Mozilla specificAn element is no longer overflowed by its content (only works for elements styled with overflow != visible).
uploadprogress {{Deprecated_Inline}}{{DOMxRef("ProgressEvent")}}Mozilla SpecificUpload is in progress (see {{Event("progress")}}).
-

{{Event("ussdreceived")}}

-
Firefox OS specificA new USSD message is received
{{Event("voicechange")}}Firefox OS specificThe {{DOMxRef("MozMobileConnection.voice")}} object changes values.
{{Event("msContentZoom")}}Microsoft specific
{{Event("MSManipulationStateChanged")}}Microsoft specific
{{Event("MSPointerHover")}} {{Deprecated_Inline}}Microsoft specific
-
- -

Mozilla-specific events

- -
-

Note: those events are never exposed to web content and can only be used in chrome content context.

-
- -

XUL events

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event NameEvent TypeSpecificationFired when...
{{Event("broadcast")}}XULAn observer noticed a change to the attributes of a watched broadcaster.
{{Event("CheckboxStateChange")}}XULThe state of a checkbox has been changed either by a user action or by a script (useful for accessibility).
closeXULThe close button of the window has been clicked.
{{Event("command")}}XULAn element has been activated.
{{Event("commandupdate")}}XULA command update occurred on a commandset element.
{{Event("DOMMenuItemActive")}}XULA menu or menuitem has been hovered or highlighted.
{{Event("DOMMenuItemInactive")}}XULA menu or menuitem is no longer hovered or highlighted.
{{Event("popuphidden")}}PopupEventXULA menupopup, panel or tooltip has been hidden.
{{Event("popuphiding")}}PopupEventXULA menupopup, panel or tooltip is about to be hidden.
{{Event("popupshowing")}}PopupEventXULA menupopup, panel or tooltip is about to become visible.
{{Event("popupshown")}}PopupEventXULA menupopup, panel or tooltip has become visible.
{{Event("RadioStateChange")}}XULThe state of a radio has been changed either by a user action or by a script (useful for accessibility).
{{Event("ValueChange")}}XULThe value of an element has changed (a progress bar for example, useful for accessibility).
-
- -

Add-on-specific events

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event NameEvent TypeSpecificationFired when...
MozSwipeGestureAddons specificA touch point is swiped across the touch surface
MozMagnifyGestureStartAddons specificTwo touch points start to move away from each other.
MozMagnifyGestureUpdateAddons specificTwo touch points move away from each other (after a MozMagnifyGestureStart).
MozMagnifyGestureAddons specificTwo touch points moved away from each other (after a sequence of MozMagnifyGestureUpdate).
MozRotateGestureStartAddons specificTwo touch points start to rotate around a point.
MozRotateGestureUpdateAddons specificTwo touch points rotate around a point (after a MozRotateGestureStart).
MozRotateGestureAddons specificTwo touch points rotate around a point (after a sequence of MozRotateGestureUpdate).
MozTapGestureAddons specificTwo touch points are tapped on the touch surface.
MozPressTapGestureAddons specificA "press-tap" gesture happened on the touch surface (first finger down, second finger down, second finger up, first finger up).
MozEdgeUIGestureAddons specificA touch point is swiped across the touch surface to invoke the edge UI (Win8 only).
MozAfterPaintAddons specificContent has been repainted.
DOMPopupBlockedAddons specificA popup has been blocked
DOMWindowCreatedAddons specificA window has been created.
DOMWindowCloseAddons specificA window is about to be closed.
DOMTitleChangedAddons specifcThe title of a window has changed.
DOMLinkAddedAddons specifcA link has been added a document.
DOMLinkRemovedAddons specifcA link has been removed inside from a document.
DOMMetaAddedAddons specificA meta element has been added to a document.
DOMMetaRemovedAddons specificA meta element has been removed from a document.
DOMWillOpenModalDialogAddons specificA modal dialog is about to open.
DOMModalDialogClosedAddons specificA modal dialog has been closed.
DOMAutoCompleteAddons specificThe content of an element has been auto-completed.
DOMFrameContentLoadedAddons specificThe frame has finished loading (but not its dependent resources).
AlertActiveAddons specificA notification element is shown.
AlertCloseAddons specificA notification element is closed.
fullscreenAddons specificBrowser fullscreen mode has been entered or left.
sizemodechangeAddons specificWindow has entered/left fullscreen mode, or has been minimized/unminimized.
MozEnteredDomFullscreenAddons specificDOM fullscreen mode has been entered.
SSWindowClosingAddons specificThe session store will stop tracking this window.
SSTabClosingAddons specificThe session store will stop tracking this tab.
SSTabRestoringAddons specificA tab is about to be restored.
SSTabRestoredAddons specificA tab has been restored.
SSWindowStateReadyAddons specificA window state has switched to "ready".
SSWindowStateBusyAddons specificA window state has switched to "busy".
TabOpenAddons specificA tab has been opened.
TabCloseAddons specificA tab has been closed.
TabSelectAddons specificA tab has been selected.
TabShowAddons specificA tab has been shown.
TabHideAddons specificA tab has been hidden.
TabPinnedAddons specificA tab has been pinned.
TabUnpinnedAddons specificA tab has been unpinned.
-
- -

Developer tool-specific events

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Event NameEvent TypeSpecificationFired when...
CssRuleViewRefresheddevtools specificThe "Rules" view of the style inspector has been updated.
CssRuleViewChangeddevtools specificThe "Rules" view of the style inspector has been changed.
CssRuleViewCSSLinkClickeddevtools specificA link to a CSS file has been clicked in the "Rules" view of the style inspector.
-
- -

See also

- - diff --git a/files/vi/web/guide/api/index.html b/files/vi/web/guide/api/index.html deleted file mode 100644 index b27f6a95d9..0000000000 --- a/files/vi/web/guide/api/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Hướng dẫn Web APIs -slug: Web/Guide/API -tags: - - API - - Hướng dẫn - - Landing -translation_of: Web/Guide/API ---- -

Web bao gồm một loạt các API có thể được sử dụng từ JavaScript để xây dựng các ứng dụng ngày càng mạnh hơn và có khả năng hơn, chạy trên web, cục bộ hoặc thông qua công nghệ như Node.js, trên máy chủ. Trên trang này, bạn sẽ tìm thấy một danh sách đầy đủ tất cả các API được cung cấp bởi công nghệ web đầy đủ.

- -

Web APIs từ A tới Z

- -

{{ListGroups}}

- -

Xem thêm

- - diff --git a/files/vi/web/guide/html/html5/index.html b/files/vi/web/guide/html/html5/index.html deleted file mode 100644 index 0900e23811..0000000000 --- a/files/vi/web/guide/html/html5/index.html +++ /dev/null @@ -1,173 +0,0 @@ ---- -title: HTML5 -slug: Web/Guide/HTML/HTML5 -translation_of: Web/Guide/HTML/HTML5 ---- -

HTML5 là phiên bản mới nhất của HTML. Hai phiên bản này khá khác nhau. HTML5 là phiên bản mới về ngôn ngữ, thuộc tính và công nghệ mới cho phép xây dựng các trang web, ứng dụng đa dạng và mạnh mẽ hơn. Hai bản này thường được gọi là HTML5.

- -

HTML5 được thiết kế để có thể sử dụng trên tất cả cá nhà phát triển web mở, trang này liên kết với nhiều tài nguyeenn công nghệ HTML5, phân thành nhiều nhóm dựa vào từng chức năng.

- -

- -

- -
    -
- -
-
-
    -
  • Ngữ nghĩa: cho phép mô tả chính xác nội dung.
  • -
  • Kết nối: cho phép giao tiếp với máy chủ theo nhiều cách.
  • -
  • Ngoại tuyến và lưu trữ: cho phép các trang web lưu trữ dữ liệu ở máy khách hàng và hoạt động ngoại tuyến hiệu quả hơn.
  • -
  • Đa phương tiện: tạo video và âm thanh trong web mở.
  • -
  • Hiệu ứng và đồ họa 2D/3D: cho phép phạm vi trình bày đa dạng hơn.
  • -
  • Hiệu suất và tích hợp: tối ưu hóa tốc độ và phần cứng.
  • -
  • Truy cập thiết bị: cho phép sử dụng các thiết bị đầu vào và ra khác nhau.
  • -
  • Chủ đề: cho phép viết các chủ đề phức tạp.
  • -
- -

Ý nghĩa

- -

Sections and outlines in HTML5

- -

A look at the new outlining and sectioning elements in HTML5: {{HTMLElement("section")}}, {{HTMLElement("article")}}, {{HTMLElement("nav")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}} and {{HTMLElement("aside")}}.

- -
-
Using HTML5 audio and video
-
The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.
-
Forms improvements
-
A look at the constraint validation API, several new attributes, new values for the {{HTMLElement("input")}} attribute {{htmlattrxref("type", "input")}} and the new {{HTMLElement("output")}} element.
-
New semantic elements
-
Beside sections, media and forms elements, there are numerous new elements, like {{HTMLElement("mark")}}, {{HTMLElement("figure")}}, {{HTMLElement("figcaption")}}, {{HTMLElement("data")}}, {{HTMLElement("time")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, or {{HTMLElement("meter")}} and {{HTMLElement("main")}}, increasing the number of valid HTML5 elements.
-
Improvement in {{HTMLElement("iframe")}}
-
Using the {{htmlattrxref("sandbox", "iframe")}} and {{htmlattrxref("srcdoc", "iframe")}} attributes, authors can now be precise about the level of security and the wished rendering of an {{HTMLElement("iframe")}} element.
-
MathML
-
Allows directly embedding mathematical formulas.
-
Introduction to HTML5
-
This article introduces how to indicate to the browser that you are using HTML5 in your web design or web application.
-
Downloadable HTML5 Guide
-
A quick guide to HTML5, including the common HTML tags as well as the new HTML5 tags. Downloadable in PDF and PNG formats.
-
HTML5 Cheat Sheet 
-
A handy HTML 5 cheat sheet for beginners who want to master HTML 5, its elements, event attributes and compatibility.
-
HTML5-compliant parser
-
The parser, which turns the bytes of an HTML document into a DOM, has been extended and now precisely defines the behavior to use in all cases, even when faced with invalid HTML. This leads to far greater predictability and interoperability between HTML5-compliant browsers.
-
- -

Connectivity

- -
-
Web Sockets
-
Allows creating a permanent connection between the page and the server and to exchange non-HTML data through that means.
-
Server-sent events
-
Allows a server to push events to a client, rather than the classical paradigm where the server could send data only in response to a client's request.
-
WebRTC
-
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
-
- -

Offline & storage

- -

Offline resources: The application cache

- -
-
Firefox fully supports the HTML5 offline resource specification. Most others have offline resource support at some level.
-
Online and offline events
-
Firefox 3 supports WHATWG online and offline events, which let applications and extensions detect whether or not there's an active Internet connection, as well as to detect when the connection goes up and down.
-
WHATWG client-side session and persistent storage (aka DOM storage)
-
Client-side session and persistent storage allows web applications to store structured data on the client side.
-
IndexedDB
-
IndexedDB is a web standard for the storage of significant amounts of structured data in the browser and for high performance searches on this data using indexes.
-
Using files from web applications
-
Support for the new HTML5 File API has been added to Gecko, making it possible for web applications to access local files selected by the user. This includes support for selecting multiple files using the {{HTMLElement("input")}} of type file HTML element's new multiple attribute. There also is FileReader.
-
- -

Multimedia

- -
-
Using HTML5 audio and video
-
The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.
-
WebRTC
-
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
-
Using the Camera API
-
Allows using, manipulating, and storing an image from the computer's camera.
-
Track and WebVTT
-
The {{HTMLElement("track")}} element allows subtitles and chapters. WebVTT is a text track format.
-
- -

2D/3D graphics AND effects

- -
-
Canvas tutorial
-
Learn about the new {{HTMLElement("canvas")}} element and how to draw graphs and other objects in Firefox.
-
HTML5 Text API for <canvas> elements
-
The HTML5 text API is now supported by {{HTMLElement("canvas")}} elements.
-
WebGL
-
WebGL brings 3D graphics to the Web by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 {{HTMLElement("canvas")}} elements.
-
SVG
-
An XML-based format of vectorial images that can directly be embedded in the HTML.
-
-
- -
-

Performance and Integration

- -
-
Web Workers
-
Allows delegation of JavaScript evaluation to background threads, allowing these activities to prevent slowing down interactive events.
-
XMLHttpRequest level 2
-
Allows fetching asynchronously some parts of the page, allowing it to display dynamic content, varying according to the time and user actions. This is the technology behind Ajax.
-
JIT-compiling JavaScript engines
-
The new generation of JavaScript engines is much more powerful, leading to greater performance.
-
History API
-
Allows the manipulation of the browser history. This is especially useful for pages loading interactively new information.
-
The contentEditable Attribute: Transform your website to a wiki!
-
HTML5 has standardized the contentEditable attribute. Learn more about this feature.
-
Drag and drop
-
The HTML5 drag and drop API allows support for dragging and dropping items within and between web sites. This also provides a simpler API for use by extensions and Mozilla-based applications.
-
Focus management in HTML
-
The new HTML5 activeElement and hasFocus attributes are supported.
-
Web-based protocol handlers
-
You can now register web applications as protocol handlers using the navigator.registerProtocolHandler() method.
-
requestAnimationFrame
-
Allows control of animations rendering to obtain optimal performance.
-
Fullscreen API
-
Controls the usage of the whole screen for a Web page or application, without the browser UI displayed.
-
Pointer Lock API
-
Allows locking the pointer to the content, so games and similar applications don't lose focus when the pointer reaches the window limit.
-
Online and offline events
-
In order to build a good offline-capable web application, you need to know when your application is actually offline. Incidentally, you also need to know when your application has returned to an online status again.
-
- -

Device access

- -
-
Using the Camera API
-
Allows using, manipulating, and storing an image from the computer's camera.
-
Touch events
-
Handlers to react to events created by a user pressing touch screens.
-
Using geolocation
-
Let browsers locate the position of the user using geolocation.
-
Detecting device orientation
-
Get the information when the device on which the browser runs changes orientation. This can be used as an input device (e.g., to make games that react to the position of the device) or to adapt the layout of a page to the orientation of the screen (portrait or landscape).
-
Pointer Lock API
-
Allows locking the pointer to the content, so games and similar application don't lose focus when the pointer reaches the window limit.
-
- -

StylIng

- -

CSS has been extended to be able to style elements in a much more complex way. This is often referred as CSS3, though CSS is not a monolithic specification any more and the different modules are not all at level 3: some are at level 1 and others at level 4, with all the intermediate levels covered.

- -
-
New background styling features
-
It is now possible to put shadows on elements using {{cssxref("box-shadow")}}, multiple backgrounds, and CSS {{cssxref("filter")}}s. You can learn more about these by reading Advanced box effects.
-
More fancy borders
-
Not only it is now possible to use images to style borders, using {{cssxref("border-image")}} and its associated longhand properties, but rounded borders are supported via the {{cssxref("border-radius")}} property.
-
Animating your style
-
Using CSS Transitions to animate between different states or using CSS Animations to animate parts of the page without a triggering event, you can now control mobile elements on your page.
-
Typography improvement
-
Authors have better control to reach better typography. They can control {{cssxref("text-overflow")}} and hyphenation, but also can add a shadow to it or control more precisely its decorations. Custom typefaces can be downloaded and applied thanks to the new {{cssxref("@font-face")}} at-rule.
-
New presentational layouts
-
In order to improve the flexibility of designs, two new layouts have been added: the CSS multi-column layouts and CSS flexible box layout.
-
-
-
diff --git a/files/vi/web/guide/index.html b/files/vi/web/guide/index.html deleted file mode 100644 index 00f533cf85..0000000000 --- a/files/vi/web/guide/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Web developer guide -slug: Web/Guide -tags: - - Guide - - Landing - - NeedsTranslation - - TopicStub - - Web -translation_of: Web/Guide ---- -

Các bài dưới đây cung cấp những thông tin cần thiết nhằm giúp bạn tận dụng các công nghệ và API cụ thể.

- -
-
-
-
-
HTML Learning Area
-
HyperText Markup Language (HTML) là ngôn ngữ nền tảng của gần như toàn bộ các thành phần trong một trang Web. Hầu hết mọi thứ hiển thị trên màn hình của bạn đều được định dạng bởi HTML.
-
CSS Learning Area
-
Cascading Style Sheets (CSS) là một ngôn ngữ quy định cách trình bày, được dùng để định ra các quy tắc thể hiện một tài liệu HTML.
-
Audio and video delivery
-
Video và audio có thể được cung cấp trên môi trường web thông qua một số cách, từ các file media tĩnh đến adaptive live streams. Bài này là một khởi điểm cho việc tìm hiểu về các phương thức cung cấp khác nhau cho web based media và sự tương thích với các trình duyệt thông dụng.
-
Audio and video manipulation
-
Sự tuyệt vời của web đó là chúng ta có thể tổ hợp các công nghệ khác nhau để tạo nên một dạng mới. Chẳng hạn như kết hợp các công nghệ Canvas,  WebGL or Web Audio API để thay đổi audio và video. Bài này cung cấp các tham khảo để giải thích những gì mà bạn cần để làm điều đó.
-
Event developer guide
-
Events liên hệ đến 2 vấn đề: nó là một design pattern sử dụng cho việc handling các sự kiện bất đồng bộ xảy ra đối với 1 web page; và nó là tên gọi chung, đặc tính của các sự kiện bất ngờ khác nhau xảy ra.
-
AJAX
-
AJAX là một khái niệm xác định một nhóm các công nghệ cho phép tạo ra các ứng dụng web động nhanh nhạy cho giao diện người dùng mà không phải tải lại nguyên trang. Nó hỗ trợ các ứng dụng xử lý nhanh và hiệu quả hơn khi thực hiện tác vụ. 
-
Graphics on the Web
-
Các trang Web và ứng dụng hiện đại thường cần hiển thị đồ hoạ với sự tinh tế riêng biệt.
-
Guide to Web APIs
-
Danh sách những Web API và phương thức hoạt động của chúng.
-
JavaScript
-
JavaScript là ngôn ngữ lập trình thông dịch cực kỳ mạnh mẽ, được dùng để khởi tạo các ứng dụng cho trang Web.
-
Localizations a character encodings
-
Trình duyệt xử lý văn bản dưới dạng Unicode. Tuy nhiên, trong quá trình truyền dữ liệu đến trình duyệt, các ký tự được biểu diễn dưới dạng bytes (mã hóa ký tự).  Đặc tả HTML khuyến nghị việc sử dụng phương thức mã hóa UTF-8 (có thể biểu diễn được tất cả ký tự Unicode), bất kể hình thức khai báo mã hóa nào được yêu cầu.
-
Mobile Web Development
-
Bài này cung cấp một cái nhìn tổng quát về một vài công nghệ chính được sử dụng để thiết kế web sites có thể hoạt động tốt trên các thiết bị di động. Xem thêm tại Firefox for Android.
-
- -
-
-
- -
-
-
 
-
Progressive web apps
-
Progressive web apps (PWAs) sử dụng các web APIs tiên tiến cùng với chiến lược phát triển lũy tiến để tạo nên một web application đa nền tảng. Các apps này hoạt động được trên mọi thiết bị và cung cấp các tính năng đem lại trải nghiệm của một native app. Các bài hướng dẫn này sẽ cung cấp cho bạn các kiến thức cần thiết về PWAs.
-
Optimization and performance
-
Khi xây dựng web apps và site hiện nay, điều quan trọng đó là làm sao để chúng hoạt động một cách nhanh nhất và hiệu quả nhất. Chính điều này đem lại cho chúng khả năng hoạt động hiệu quả trên cả các thiết bị desktop với cấu hình mạnh mẽ và các thiết bị handheld với cấu hình yếu.
-
Parsing and serializing XML
-
Nền tảng web cung cấp các phương thức cho việc parsing và serializing XML, mỗi phương thức với các điểm mạnh và yếu khác nhau.
-
The Web Open Font Format (WOFF)
-
WOFF là một kiểu file cho font chữ được cung cấp miễn phí cho bất kỳ ai có nhu cầu sử dụng cho web.
-
Using FormData objects
-
FormData giúp cho việc tạo nên tổ hợp các key/value để gửi thông qua XMLHttpRequest. Mục đích ban đầu của nó là gửi dữ liệu form, nhưng nó cũng có thể hoạt động 1 cách độc lập với form để gửi các dữ liệu khác nhau. Cách thức truyền nhận tương tự như khi một form với type "multipart/form-data" thực thi method submit() .
-
User input and controls
-
Input người dùng web hiện nay không chỉ đơn giản là chuột và bàn phím mà còn có các phương thức khác, chẳng hạn touchscreen. Bài này cung cấp các recommendations cho việc quản lý input người dùng và hiện thực việc điều khiển đối với web apps, cùng với các FAQs, ví dụ thực tế và đường dẫn đến các thông tin khác nếu bạn cần tìm hiểu chi tiết thêm về các công nghệ bên dưới.
-
Glossary
-
Định nghĩa các khái niệm kỹ thuật liên quan đến Web và Internet.
-
-
-
-
- -

Xem thêm

- - diff --git a/files/vi/web/html/element/center/index.html b/files/vi/web/html/element/center/index.html deleted file mode 100644 index 8303b88549..0000000000 --- a/files/vi/web/html/element/center/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: '
: The Centered Text element (obsolete)' -slug: Web/HTML/Element/center -translation_of: Web/HTML/Element/center ---- -
{{obsolete_header}}
- -

Phần tử trung tâm HTML lỗi thời ( <center>) là phần tử cấp khối hiển thị nội dung cấp khối hoặc nội dòng được căn giữa theo chiều ngang bên trong phần tử chứa nó. Vùng chứa thường là, nhưng không bắt buộc, {{HTMLElement ("body")}}.

- -

Thẻ này đã không được chấp nhận trong HTML 4 (và XHTML 1) vì thuộc tính CSS {{Cssxref("text-align")}}, có thể được áp dụng cho phần tử {{HTMLElement ("div")}} hoặc cho một cá nhân {{HTMLElement("p")}}. Đối với các khối căn giữa, hãy sử dụng các thuộc tính CSS khác như {{Cssxref ("margin-left")}} và {{Cssxref ("margin-right")}} và đặt chúng thành auto(hoặc đặt {{Cssxref ("margin")}} đến 0 auto).

- -

Giao diện DOM

- -

Phần tử này thực hiện giao diện {{domxref ("HTMLElement")}}.

- -
-

Lưu ý triển khai: bao gồm cả Gecko 1.9.2, Firefox triển khai giao diện {{domxref("HTMLSpanElement")}} cho phần tử này.

-
- -

ví dụ 1

- -
<center> Văn bản này sẽ được căn giữa.
-<p> Đoạn này cũng vậy. </p> </center>
-
- -

Ví dụ 2 (CSS thay thế)

- -
<div style = "text-align: center"> Văn bản này sẽ được căn giữa.
-<p> Đoạn này cũng vậy. </p> </div>
-
- -

Ví dụ 3 (CSS thay thế)

- -
<p style = "text-align: center"> Dòng này sẽ được căn giữa. <br>
-Và dòng này cũng vậy. </p>
-
- -

Ghi chú

- -

Việc áp dụng {{Cssxref ("text-align")}} :centercho phần tử {{HTMLElement("div")}} hoặc {{HTMLElement("p")}} sẽ căn giữa nội dung của các phần tử đó trong khi giữ nguyên kích thước tổng thể của chúng.

- -

Tính tương thích của trình duyệt web

- - - -

{{Compat("html.elements.center")}}

- -

Xem thêm

- -
    -
  • {{Cssxref("text-align")}}
  • -
  • {{Cssxref("hiển thị")}}
  • -
- -
{{HTMLRef}}
diff --git a/files/vi/web/html/element/dialog/index.html b/files/vi/web/html/element/dialog/index.html deleted file mode 100644 index d6d63404b4..0000000000 --- a/files/vi/web/html/element/dialog/index.html +++ /dev/null @@ -1,163 +0,0 @@ ---- -title: ': Phần tử Hộp thoại' -slug: Web/HTML/Element/dialog -tags: - - Dialog - - HTML - - Hộp thoại - - Phần tử - - Phần tử HTML tương tác được - - Tham khảo - - Thử nghiệm - - Web -translation_of: Web/HTML/Element/dialog ---- -

Phần tử HTML <dialog> đại diện cho một hộp thoại hoặc một component tương tác được, chẳng hạn như giao diện cửa sổ hoặc khảo sát.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Loại nội dungFlow content, sectioning root
Nội dung cho phépFlow content
Thẻ được phép bỏ{{no_tag_omission}}
Thẻ cha cho phépAny element that accepts flow content
ARIA role cho phép{{ARIARole("alertdialog")}}
Giao diện lập trình DOM{{domxref("HTMLDialogElement")}}
- -

Thuộc tính

- -

Phần tử này có các thuộc tính chung. Thuộc tính tabindex không được phép sử dụng với phần tử <dialog>.

- -
-
{{htmlattrdef("open")}}
-
Cho biết hộp thoại có được kích hoạt và sẵn sàng tương tác hay không. Khi thuộc tính open này không được bật (không có trong thẻ), hộp thoại sẽ không hiện ra cho người dùng.
-
- -

Lưu ý khi sử dụng

- -
    -
  • Phần tử <form> có thể được tính hợp với dialog bằng cách thêm thuộc tính method="dialog" tại <form> bên trong. Khi form được gửi đi, hộp thoại sẽ đóng lại với returnValue là giá trị value của nút submit được bấm.
  • -
  • CSS pseudo-element {{cssxref('::backdrop')}} là một phần tử giả phía sau hộp thoại dùng để che đi hoặc làm mờ nội dung bên dưới khi mà hộp thoại đang hiện ra. Backdrop chỉ được hiển thị khi phần tử dialog được hiện với dialog.showModal().
  • -
- -

Ví dụ

- -

Ví dụ đơn giản

- -
<dialog open>
-  <p>Greetings, one and all!</p>
-</dialog>
-
- -

Ví dụ nâng cao

- -

Trong ví dụ này, một hộp thoại sẽ hiện ra với một form bên trong khi mà nút "Update details" được bấm.

- -

HTML

- -
<!-- Simple pop-up dialog box containing a form -->
-<dialog id="favDialog">
-  <form method="dialog">
-    <p><label>Favorite animal:
-      <select>
-        <option></option>
-        <option>Brine shrimp</option>
-        <option>Red panda</option>
-        <option>Spider monkey</option>
-      </select>
-    </label></p>
-    <menu>
-      <button>Cancel</button>
-      <button>Confirm</button>
-    </menu>
-  </form>
-</dialog>
-
-<menu>
-  <button id="updateDetails">Update details</button>
-</menu>
-
- -

JavaScript

- -
(function() {
-  var updateButton = document.getElementById('updateDetails');
-  var favDialog = document.getElementById('favDialog');
-
-  // “Update details” button opens the <dialog> modally
-  updateButton.addEventListener('click', function() {
-    favDialog.showModal();
-  });
-})();
-
- -

Kết quả nhận được

- -

{{EmbedLiveSample("Ví_dụ_nâng_cao", "100%", 300)}}

- -

Nút submit nào được bấm có thể được xác định với returnValue của favDialog.

- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('HTML WHATWG', 'forms.html#the-dialog-element', '<dialog>')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.2', 'interactive-elements.html#the-dialog-element', '<dialog>')}}{{Spec2('HTML5.2')}}Định nghĩa ban đầu.
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("html.elements.dialog")}}

- -

Polyfill

- -

Dùng polyfill sau để hỗ trợ <dialog> cho các trình duyệt cũ:

- -

dialog-polyfill

- -

Xem thêm

- - - -
{{HTMLRef}}
diff --git a/files/vi/web/html/element/em/index.html b/files/vi/web/html/element/em/index.html deleted file mode 100644 index 3f52dea31a..0000000000 --- a/files/vi/web/html/element/em/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: ': The Emphasis element' -slug: Web/HTML/Element/em -translation_of: Web/HTML/Element/em ---- -
{{HTMLRef}}
- -

The HTML <em> element marks text that has stress emphasis. The <em> element can be nested, with each level of nesting indicating a greater degree of emphasis.

- -
{{EmbedInteractiveExample("pages/tabbed/em.html", "tabbed-shorter")}}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Content categoriesFlow content, phrasing content, palpable content.
Permitted contentPhrasing content.
Tag omission{{no_tag_omission}}
Permitted parentsAny element that accepts phrasing content.
Implicit ARIA roleNo corresponding role
Permitted ARIA rolesAny
DOM interface{{domxref("HTMLElement")}} Up to Gecko 1.9.2 (Firefox 4) inclusive, Firefox implements the {{domxref("HTMLSpanElement")}} interface for this element.
- -

Attributes

- -

This element only includes the global attributes.

- -

Usage notes

- -

The <em> element is for words that have a stressed emphasis compared to surrounding text, which is often limited to a word or words of a sentence and affects the meaning of the sentence itself.

- -

Typically this element is displayed in italic type. However, it should not be used simply to apply italic styling; use the CSS {{cssxref("font-style")}} property for that purpose. Use the {{HTMLElement("cite")}} element to mark the title of a work (book, play, song, etc.). Use the {{HTMLElement("i")}} element to mark text that is in an alternate tone or mood, which covers many common situations for italics such as scientific names or words in other languages. Use the {{HTMLElement("strong")}} element to mark text that has greater importance than surrounding text.

- -

<i> vs. <em>

- -

New developers are often confused at seeing multiple elements that produce similar results. <em> and <i> are a common example, since they both italicize text. What's the difference? Which should you use?

- -

By default, the visual result is the same. However, the semantic meaning is different. The <em> element represents stress emphasis of its contents, while the <i> element represents text that is set off from the normal prose, such a foreign word, fictional character thoughts, or when the text refers to the definition of a word instead of representing its semantic meaning. (The title of a work, such as the name of a book or movie, should use <cite>.)

- -

This means the right one to use depends on the situation. Neither is for purely decorational purposes, that's what CSS styling is for.

- -

An example for <em> could be: "Just do it already!", or: "We had to do something about it". A person or software reading the text would pronounce the words in italics with an emphasis, using verbal stress.

- -

An example for <i> could be: "The Queen Mary sailed last night". Here, there is no added emphasis or importance on the word "Queen Mary". It is merely indicated that the object in question is not a queen named Mary, but a ship named Queen Mary. Another example for <i> could be: "The word the is an article".

- -

Example

- -

The <em> element is often used to indicate an implicit or explicit contrast.

- -
<p>
-  In HTML 5, what was previously called
-  <em>block-level</em> content is now called
-  <em>flow</em> content.
-</p>
- -

Result

- -

{{EmbedLiveSample("Example")}}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'text-level-semantics.html#the-em-element', '<em>')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'textlevel-semantics.html#the-em-element', '<em>')}}{{Spec2('HTML5 W3C')}}
{{SpecName('HTML4.01', 'struct/text.html#h-9.2.1', '<em>')}}{{Spec2('HTML4.01')}}
- -

Trình duyệt tương thích

- - - -

{{Compat("html.elements.em")}}

- -

Xem thêm

- -
    -
  • {{HTMLElement("i")}}
  • -
diff --git a/files/vi/web/html/element/header/index.html b/files/vi/web/html/element/header/index.html deleted file mode 100644 index 3f7c96c7a5..0000000000 --- a/files/vi/web/html/element/header/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title:
-slug: Web/HTML/Element/header -translation_of: Web/HTML/Element/header ---- -
{{HTMLRef}}
- -

The HTML <header> element represents a group of introductory or navigational aids. It may contain some heading elements but also other elements like a logo, a search form, and so on.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Content categoriesFlow content, palpable content.
Permitted contentFlow content, but with no <header> or {{HTMLElement("footer")}} descendant.
Tag omission{{no_tag_omission}}
Permitted parentsAny element that accepts flow content. Note that a <header> element must not be a descendant of an {{HTMLElement("address")}}, {{HTMLElement("footer")}} or another {{HTMLElement("header")}} element.
Permitted ARIA roles{{ARIARole("group")}}, {{ARIARole("presentation")}}
DOM interface{{domxref("HTMLElement")}}
- -

Usage notes

- -

The <header> element is not sectioning content and therefore does not introduce a new section in the outline. That said, a header element is intended to usually contain the surrounding section's heading (an h1h6 element), but this is not required.

- -

Attributes

- -

This element only includes the global attributes.

- -

Example

- -
<header>
-  <h1>Main Page Title</h1>
-  <img src="mdn-logo-sm.png" alt="MDN logo">
-</header>
-
- -

Main Page Title

- -

MDN

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'semantics.html#the-header-element', '<header>')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'sections.html#the-header-element', '<header>')}}{{Spec2('HTML5 W3C')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}9.011.104.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.2{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}9.011.05.0
-
- -

See also

- -
    -
  • Others section-related elements: {{HTMLElement("body")}}, {{HTMLElement("nav")}}, {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}, {{HTMLElement("hgroup")}}, {{HTMLElement("footer")}}, {{HTMLElement("section")}}, {{HTMLElement("address")}}.
  • -
  • Sections and outlines of a HTML5 document.
  • -
diff --git a/files/vi/web/html/element/html/index.html b/files/vi/web/html/element/html/index.html deleted file mode 100644 index 8609afe4a2..0000000000 --- a/files/vi/web/html/element/html/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: -slug: Web/HTML/Element/html -tags: - - HTML - - Phần tử - - Phần tử gốc HTML - - Tài liệu tham khảo - - Web -translation_of: Web/HTML/Element/html ---- -

{{HTMLRef}}

- -

The HTML <html> element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Content categoriesNone.
Permitted contentOne {{HTMLElement("head")}} element, followed by one {{HTMLElement("body")}} element.
Tag omissionThe start tag may be omitted if the first thing inside the <html> element is not a comment.
- The end tag may be omitted if the <html> element is not immediately followed by a comment, and it contains a {{HTMLElement("body")}} element either that is not empty or whose start tag is present.
Perimitted parentsAs the root element of a document, or wherever a subdocument fragment is allowed in a compound document.
Permitted ARIA rolesNone
DOM interface{{domxref("HTMLHtmlElement")}}
- -

Attributes

- -

This element includes the global attributes.

- -
-
{{htmlattrdef("manifest")}} {{obsolete_inline}}
-
Specifies the URI of a resource manifest indicating resources that should be cached locally. See Using the application cache for details.
-
{{htmlattrdef("version")}} {{obsolete_inline}}
-
Specifies the version of the HTML {{glossary("DTD", "Document Type Definition")}} that governs the current document. This attribute is not needed, because it is redundant with the version information in the document type declaration.
-
{{htmlattrdef("xmlns")}} 
-
Specifies the XML Namespace of the document. Default value is "http://www.w3.org/1999/xhtml". This is required in documents parsed with XML parsers, and optional in text/html documents.
-
- -

Example

- -
<!DOCTYPE html>
-<html>
-  <head>...</head>
-  <body>...</body>
-</html>
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'semantics.html#the-html-element', '<html>')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'semantics.html#the-html-element', '<html>')}}{{Spec2('HTML5 W3C')}}Added support for the manifest attribute (deprecated later).
- Obsoleted the version attribute
{{SpecName('HTML4.01', 'struct/global.html#h-7.3', '<html>')}}{{Spec2('HTML4.01')}}Deprecated the version attribute
- -

Browser compatibility

- - - -

{{Compat("html.elements.html")}}

- -

See also

- -
    -
  • MathML top-level element: {{MathMLElement("math")}}
  • -
  • SVG top-level element: {{SVGElement("svg")}}
  • -
diff --git a/files/vi/web/html/element/index.html b/files/vi/web/html/element/index.html deleted file mode 100644 index 8c380bf350..0000000000 --- a/files/vi/web/html/element/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Phần tử HTML -slug: Web/HTML/Element -translation_of: Web/HTML/Element ---- -

{{HTMLSidebar("Elements")}}

- -

Trang này bao gồm {{Glossary("HTML")}} {{Glossary("Element","elements")}}. Chúng được chia thành các nhóm bởi chức năng với mong muốn giúp bạn dễ dàng tìm kiếm để có thể đạt được điều mà bạn có trong tâm trí một cách dễ dàng . Dù cho bản hướng dẫn này được viết ra để dành cho những người mới hoặc những người mới bắt đầu trong việc mã hóa, chúng tôi mong rằng đây có thể là tài liệu tham khảo hữu ích cho tất cả mọi người. 

- -

Các phần tử căn bản

- -

Các phần tử căn bản là cột sống cho tất cả các văn bản HTML nào. bạn sẽ thấy rằng những nguyên tố này nằm trong mã nguồn của bất cứ trang web nào đằng sau dòng trên cùng khai báo hiệu trang đó. Dòng khai báo xác định loại phiên bản (X)HTML mà trang đó sử dụng. Các phần tử được đặt giữa thẻ <html> mở và thẻ </html> đóng, đồng thời cũng được gọi là phần tử gốc.

- -

{{HTMLRefTable("HTML Root Element")}}

- -

Document metadata

- -

Metadata contains information about the page. This includes information about styles, scripts and data to help software (Search engines, {{Glossary("Browser","browsers")}}, etc.) use and render the page. Metadata for styles and scripts may be defined in the page or link to another file that has the information. 

- -

{{HTMLRefTable("HTML document metadata")}}

- -

Phân chia nội dung

- -

Các phần tử chia thành các mục giúp bạn trình bày nội dung tài liệu một cách loogic. Sử dụng các phần tử phân chia nội dung để tạo ra hình thể rộng cho nội dung trang, bao gồm tiêu đề và chân trang, và phần tử tiêu đề để đánh dấu phần nội dung.

- -

{{HTMLRefTable("HTML sections")}}

- -

Text content

- -

Use HTML text content elements to organize blocks or sections of content placed between the opening <body> and closing </body> tags. Important for {{Glossary("accessibility")}} and {{Glossary("SEO")}}, these elements identify the purpose or structure of that content.     

- -

{{HTMLRefTable("HTML grouping content")}}

- -

Inline text semantics

- -

Sử dụng ngữ nghĩa văn bản bên trong HTML để xác định ý nghĩa, cấu trúc hoặc kiểu của từ, dòng hoặc bất kỳ phần văn bản tùy ý nào

- -

{{HTMLRefTable("HTML text-level semantics")}}

- -

Image & multimedia

- -

HTML allows to use various multimedia ressources such as images, audio and video.

- -

{{HTMLRefTable("multimedia")}}

- -

embedded content

- -

Beyond multimedia contents HTML can include many other stuff, even if it's not always easy to interact with.

- -

{{HTMLRefTable({"include":["HTML embedded content"], "exclude":["multimedia"]})}}

- -

Scripting

- -

{{HTMLRefTable("HTML scripting")}}

- -

Edits

- -

{{HTMLRefTable("HTML edits")}}

- -

Table content

- -

Those set of elements is specificaly made to handle tabular data

- -

{{HTMLRefTable("HTML tabular data")}}

- -

Forms

- -

{{HTMLRefTable("HTML forms")}}

- -

Interactive elements

- -

{{HTMLRefTable("HTML interactive elements")}}

- -

Web Components

- -
Those elements are defined in the {{Glossary("W3C","World Wide Web Consortium")}} (W3C) Web Components collection of specifications rather than the HTML specification.
- -

{{HTMLRefTable({"include":["Web Components"],"elements":["decorator","shadow"]})}}

- -

Obsolete and deprecated elements

- -
-

Some old HTML elements were deprecated and their usage is strongly discouraged. You should never use them for new project, and replace them in old projects. There are listed here for information only.

-
- -

{{HTMLRefTable({"include":["Deprecated","Obsolete"]})}}

diff --git a/files/vi/web/html/element/meta/index.html b/files/vi/web/html/element/meta/index.html deleted file mode 100644 index 861a343c66..0000000000 --- a/files/vi/web/html/element/meta/index.html +++ /dev/null @@ -1,441 +0,0 @@ ---- -title: ': The Document-level Metadata element' -slug: Web/HTML/Element/meta -translation_of: Web/HTML/Element/meta ---- -
{{HTMLRef}}
- -

The HTML <meta> element represents {{Glossary("Metadata","metadata")}} that cannot be represented by other HTML meta-related elements, like {{HTMLElement("base")}}, {{HTMLElement("link")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}} or {{HTMLElement("title")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Content categoriesMetadata content. If the {{htmlattrxref("itemprop", "meta")}} attribute is present: flow content, phrasing content.
Permitted contentNone, it is an {{Glossary("empty element")}}.
Tag omissionAs it is a void element, the start tag must be present and the end tag must not be present.
Permitted parents<meta charset>, <meta http-equiv>: a {{HTMLElement("head")}} element. If the {{htmlattrxref("http-equiv", "meta")}} is not an encoding declaration, it can also be inside a {{HTMLElement("noscript")}} element, itself inside a {{HTMLElement("head")}} element.
Permitted ARIA rolesNone
DOM interface{{domxref("HTMLMetaElement")}}
- -

Attributes

- -

This element includes the global attributes.

- -
-

Note: the global attribute {{htmlattrxref("name", "meta")}} has a specific meaning for the {{HTMLElement("meta")}} element, and the {{htmlattrxref("itemprop", "meta")}} attribute must not be set on the same <meta> element that has any existing {{htmlattrxref("name", "meta")}}, {{htmlattrxref("http-equiv", "meta")}} or {{htmlattrxref("charset", "meta")}} attributes.

-
- -
-
{{htmlattrdef("charset")}}
-
This attribute declares the page's character encoding. It must contain a standard IANA MIME name for character encodings. Although the standard doesn't request a specific encoding, it suggests: -
    -
  • Authors are encouraged to use UTF-8.
  • -
  • Authors should not use ASCII-incompatible encodings to avoid security risk: browsers not supporting them may interpret harmful content as HTML. This happens with the JIS_C6226-1983, JIS_X0212-1990, HZ-GB-2312, JOHAB, the ISO-2022 family and the EBCDIC family.
  • -
- -
-

Note: ASCII-incompatible encodings are those that don't map the 8-bit code points 0x20 to 0x7E to the 0x0020 to 0x007E Unicode code points)

-
- -
-
    -
  • Authors must not use CESU-8, UTF-7, BOCU-1 and/or SCSU as cross-site scripting attacks with these encodings have been demonstrated.
  • -
  • Authors should not use UTF-32 because not all HTML5 encoding algorithms can distinguish it from UTF-16.
  • -
-
- -
Notes: - -
    -
  • The declared character encoding must match the one the page was saved with to avoid garbled characters and security holes.
  • -
  • The {{HTMLElement("meta")}} element declaring the encoding must be inside the {{HTMLElement("head")}} element and within the first 1024 bytes of the HTML as some browsers only look at those bytes before choosing an encoding.
  • -
  • This {{HTMLElement("meta")}} element is only one part of the algorithm to determine a page's character set. The Content-Type header and any {{Glossary("Byte-Order Mark","Byte-Order Marks")}} override this element.
  • -
  • It is strongly recommended to define the character encoding. If a page's encoding is undefined, cross-scripting techniques are possible, such as the UTF-7 fallback cross-scripting technique.
  • -
  • The {{HTMLElement("meta")}} element with a charset attribute is a synonym for the pre-HTML5 <meta http-equiv="Content-Type" content="text/html; charset=IANAcharset">, where IANAcharset contains the value of the equivalent {{htmlattrxref("charset", "meta")}} attribute. This syntax is still allowed, although no longer recommended.
  • -
-
-
-
{{htmlattrdef("content")}}
-
This attribute contains the value for the {{htmlattrxref("http-equiv", "meta")}} or {{htmlattrxref("name", "meta")}} attribute, depending on which is used.
-
{{htmlattrdef("http-equiv")}}
-
Defines a pragma directive. The attribute is named http-equiv(alent) because all the allowed values are names of particular HTTP headers: -
    -
  • "content-language" {{obsolete_inline}}
    - Defines the default language of the page. It can be overridden by the lang attribute on any element. -
    -

    Warning: Do not use this value, as it is obsolete. Prefer the lang attribute on the {{HTMLElement("html")}} element.

    -
    -
  • -
  • "content-security-policy"
    - Allows page authors to define a content policy for the current page. Content policies mostly specify allowed server origins and script endpoints which help guard against cross-site scripting attacks.
  • -
  • "content-type" {{obsolete_inline}}
    - Defines the MIME type of the document, followed by its character encoding. It follows the same syntax as the HTTP content-type entity-header field, but as it is inside a HTML page, most values other than text/html are impossible. Therefore the valid syntax for its content is the string 'text/html' followed by a character set with the following syntax: '; charset=IANAcharset', where IANAcharset is the preferred MIME name for a character set as defined by the IANA. -
    -

    Warning: Do not use this value, as it is obsolete. Use the {{htmlattrxref("charset", "meta")}} attribute on the {{HTMLElement("meta")}} element.

    -
    - -
    -

    Note: As {{HTMLElement("meta")}} can't change documents' types in XHTML or HTML5's XHTML serialization, never set the MIME type to an XHTML MIME type with <meta>.

    -
    -
  • -
  • "refresh"
    - This instruction specifies: -
      -
    • The number of seconds until the page should be reloaded - only if the {{htmlattrxref("content", "meta")}} attribute contains a positive integer.
    • -
    • The number of seconds until the page should redirect to another - only if the {{htmlattrxref("content", "meta")}} attribute contains a positive integer followed by the string ';url=', and a valid URL.
    • -
    -
  • -
  • "set-cookie" {{obsolete_inline}}
    - Defines a cookie for the page. Its content must follow the syntax defined in the IETF HTTP Cookie Specification. -
    -

    Warning: Do not use this instruction, as it is obsolete. Use the HTTP header Set-Cookie instead.

    -
    -
  • -
-
-
{{htmlattrdef("name")}}
-
-

This attribute defines the name of a piece of document-level metadata. It should not be set if one of the attributes {{htmlattrxref("itemprop", "meta")}}, {{htmlattrxref("http-equiv", "meta")}} or {{htmlattrxref("charset", "meta")}} is also set.

- -

This metadata name is associated with the value contained by the {{htmlattrxref("content", "meta")}} attribute. The possible values for the name attribute are:

- -
    -
  • application-name which defines the name of the application running in the web page. - -
    Note: - -
      -
    • Browsers may use this to identify the application. It is different from the {{HTMLElement("title")}} element, which usually contain the application name, but may also contain information like the document name or a status.
    • -
    • Simple web pages shouldn't define an application-name.
    • -
    -
    -
  • -
  • author which defines the name of the document's author.
  • -
  • description which contains a short and accurate summary of the content of the page. Several browsers, like Firefox and Opera, use this as the default description of bookmarked pages.
  • -
  • generator which contains the identifier of the software that generated the page.
  • -
  • keywords which contains words relevant to the page's content separated by commas.
  • -
  • referrer which controls the Referer HTTP header attached to requests sent from the document: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Values for the content attribute of <meta name="referrer">
    no-referrerDo not send a HTTP Referrer header.
    originSend the origin of the document.
    no-referrer-when-downgradeSend the origin as a referrer to URLs as secure as the current page, (https→https), but does not send a referrer to less secure URLs (https→http). This is the default behaviour.
    origin-when-cross-originSend the full URL (stripped of parameters) for same-origin requests, but only send the origin for other cases.
    same-originA referrer will be sent for same-site origins, but cross-origin requests will contain no referrer information.
    strict-originOnly send the origin of the document as the referrer to a-priori as-much-secure destination (HTTPS->HTTPS), but don't send it to a less secure destination (HTTPS->HTTP).
    strict-origin-when-cross-originSend a full URL when performing a same-origin request, only send the origin of the document to a-priori as-much-secure destination (HTTPS->HTTPS), and send no header to a less secure destination (HTTPS->HTTP).
    unsafe-URLSend the full URL (stripped of parameters) for same-origin or cross-origin requests.
    - -
    -

    Notes:

    - -
      -
    • Some browsers support the deprecated values of always, default, and never for referrer.
    • -
    • Dynamically inserting <meta name="referrer"> (with document.write or appendChild) makes the referrer behaviour unpredictable.
    • -
    • When several conflicting policies are defined, the no-referrer policy is applied.
    • -
    -
    -
  • -
- -

This attribute may also have a value taken from the extended list defined on WHATWG Wiki MetaExtensions page. Although none have been formally accepted yet, a few commonly used names are:

- -
    -
  • creator which defines the name of the creator of the document, such as an organization or institution. If there are more than one, several {{HTMLElement("meta")}} elements should be used.
  • -
  • googlebot, a synonym of robots, is only followed by Googlebot (the indexing crawler for Google).
  • -
  • publisher which defines the name of the document's publisher.
  • -
  • robots which defines the behaviour that cooperative crawlers, or "robots", should use with the page. It is a comma-separated list of the values below: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Values for the content of <meta name="robots">
    ValueDescriptionUsed by
    indexAllows the robot to index the page (default).All
    noindexRequests the robot to not index the page.All
    followAllows the robot to follow the links on the page (default).All
    nofollowRequests the robot to not follow the links on the page.All
    noneEquivalent to noindex, nofollowGoogle
    noodpPrevents using the Open Directory Project description, if any, as the page description in search engine results. -

    Google, Yahoo, Bing

    -
    noarchiveRequests the search engine not to cache the page content.Google, Yahoo, Bing
    nosnippetPrevents displaying any description of the page in search engine results.Google, Bing
    noimageindexRequests this page not to appear as the referring page of an indexed image.Google
    nocacheSynonym of noarchive.Bing
    - -
    Notes: - -
      -
    • Only cooperative robots follow these rules. Do not expect to prevent e-mail harvesters with them.
    • -
    • The robot still needs to access the page in order to read these rules. To prevent bandwidth consumption, use a robots.txt file.
    • -
    • If you want to remove a page, noindex will work, but only after the robot visits the page again. Ensure that the robots.txt file is not preventing revisits.
    • -
    • Some values are mutually exclusive, like index and noindex, or follow and nofollow. In these cases the robot's behaviour is undefined and may vary between them.
    • -
    • Some crawler robots, like Google, Yahoo and Bing, support the same values for the HTTP header X-Robots-Tag; this allows non-HTML documents like images to use these rules.
    • -
    -
    -
  • -
  • slurp, is a synonym of robots, but only for Slurp - the crawler for Yahoo Search.
  • -
  • viewport, which gives hints about the size of the initial size of the {{glossary("viewport")}}. Used by mobile devices only. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Values for the content of <meta name="viewport">
    ValuePossible subvaluesDescription
    widthA positive integer number, or the text device-widthDefines the pixel width of the viewport that you want the web site to be rendered at.
    heightA positive integer, or the text device-heightDefines the height of the viewport. Not used by any browser.
    initial-scaleA positive number between 0.0 and 10.0Defines the ratio between the device width (device-width in portrait mode or device-height in landscape mode) and the viewport size.
    maximum-scaleA positive number between 0.0 and 10.0Defines the maximum amount to zoom in. It must be greater or equal to the minimum-scale or the behaviour is undefined. Browser settings can ignore this rule and iOS10+ ignores it by default.
    minimum-scaleA positive number between 0.0 and 10.0Defines the minimum zoom level. It must be smaller or equal to the maximum-scale or the behaviour is undefined. Browser settings can ignore this rule and iOS10+ ignores it by default.
    user-scalableyes or noIf set to no, the user is not able to zoom in the webpage. The default is yes. Browser settings can ignore this rule, and iOS10+ ignores it by default.
    - - - - - - - - - - - - - - - - -
    SpecificationStatusComment
    {{SpecName('CSS3 Device', '#viewport-meta', '<meta name="viewport">')}}{{Spec2('CSS3 Device')}}Non-normatively describes the Viewport META element
    - -
    See also: {{cssxref("@viewport")}}
    - -
    Notes: - -
      -
    • Though unstandardized, this declaration is respected by most mobile browsers due to de-facto dominance.
    • -
    • The default values may vary between devices and browsers.
    • -
    • To learn about this declaration in Firefox for Mobile, see this article.
    • -
    -
    -
  • -
-
-
{{htmlattrdef("scheme")}} {{obsolete_inline}}
-
This attribute defines the scheme in which metadata is described. A scheme is a context leading to the correct interpretations of the {{htmlattrxref("content", "meta")}} value, like a format. -
-

Warning: Do not use this value, as it is obsolete. There is no replacement as there was no real usage for it.

-
-
-
- -

Notes

- -

Depending on the attributes set, the kind of metadata can be one of the following:

- -
    -
  • If {{htmlattrxref("name", "meta")}} is set, it is document-level metadata, applying to the whole page.
  • -
  • If {{htmlattrxref("http-equiv", "meta")}} is set, it is a pragma directive — information normally given by the web server about how the web page is served.
  • -
  • If {{htmlattrxref("charset", "meta")}} is set, it is a charset declaration — the character encoding used by the webpage.
  • -
  • If {{htmlattrxref("itemprop", "meta")}} is set, it is user-defined metadata — transparent for the user-agent as the semantics of the metadata is user-specific. {{experimental_inline}}
  • -
- -

Examples

- -
<meta charset="utf-8">
-
-<!-- Redirect page after 3 seconds -->
-<meta http-equiv="refresh" content="3;url=https://www.mozilla.org">
-
- -

Accessibility concerns

- -

Refreshing content

- -

Pages set with a refresh value run the risk of having the time interval being too short. People navigating with the aid of assistive technology such as a screen reader may be unable to read through and understand the page's content before being automatically redirected. The abrupt, unannounced updating of the page content may also be disorienting for people experiencing low vision conditions. 

- - - -

Viewport scaling

- -

Disabling zooming capabilities by setting user-scalable to a value of no prevents people experiencing low vision conditions from being able to read and understand page content.

- - - -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Referrer Policy', '#referrer-policy-delivery-meta', '<meta name="referrer">')}}{{Spec2('Referrer Policy')}}Defines values and semantics of <meta name="referrer">.
{{SpecName('HTML WHATWG', 'semantics.html#the-meta-element', '<meta>')}}{{Spec2('HTML WHATWG')}}Added itemprop attribute
{{SpecName('HTML5 W3C', 'document-metadata.html#the-meta-element', '<meta>')}}{{Spec2('HTML5 W3C')}}Added charset attribute
{{SpecName('HTML4.01', 'struct/global.html#h-7.4.4.2', '<meta>')}}{{Spec2('HTML4.01')}} 
- -

Browser compatibility

- -

The information shown below has been pulled from MDN's Github (https://github.com/mdn/browser-compat-data).

- - - -

{{Compat("html.elements.meta")}}

- -

See also

- -
    -
  • The other elements containing metadata: {{HTMLElement("base")}}, {{HTMLElement("head")}}, {{HTMLElement("link")}}, {{HTMLElement("style")}},{{HTMLElement("title")}}.
  • -
diff --git a/files/vi/web/html/element/span/index.html b/files/vi/web/html/element/span/index.html deleted file mode 100644 index b97e83587f..0000000000 --- a/files/vi/web/html/element/span/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: -slug: Web/HTML/Element/span -translation_of: Web/HTML/Element/span ---- -
{{HTMLRef}}
- -

Phần tử <span> HTML là một bộ chứa nội tuyến chung cho nội dung cụm từ, vốn không đại diện cho bất cứ điều gì. Nó có thể được sử dụng để nhóm các thành phần cho mục đích tạo kiểu (sử dụng các thuộc tính {{htmlattrxref ("class")}} hoặc {{htmlattrxref ("id")}}) hoặc vì chúng chia sẻ các giá trị thuộc tính, như {{htmlattrxref ( "lang")}}. Nó chỉ được sử dụng khi không có yếu tố ngữ nghĩa nào khác phù hợp. <span> rất giống với phần tử {{HTMLElement("div")}}, nhưng {{HTMLElement("div")}} là phần tử cấp khối trong khi <span> là phần tử nội tuyến.

- -
{{EmbedInteractiveExample("pages/tabbed/span.html", "tabbed-shorter")}}
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Content categoriesFlow content, phrasing content.
Permitted contentPhrasing content.
Tag omission{{no_tag_omission}}
Permitted parentsAny element that accepts phrasing content, or any element that accepts flow content.
Implicit ARIA roleNo corresponding role
Permitted ARIA rolesAny
DOM interface{{domxref("HTMLSpanElement")}} (before {{glossary("HTML5")}}, the interface was {{domxref("HTMLElement")}})
- -

Attributes

- -

This element only includes the global attributes.

- -

Example

- -

Example 1

- -

HTML

- -
<p><span>Some text</span></p>
- -

Result

- -

{{EmbedLiveSample('Example_1')}}

- -

Example 2

- -

HTML

- -
<li><span>
-    <a href="portfolio.html" target="_blank">See my portfolio</a>
-</span></li>
-
- -

CSS

- -
li span {
-  background: gold;
- }
-
- -

Result

- -

{{EmbedLiveSample('Example_2')}}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'text-level-semantics.html#the-span-element', '<span>')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'textlevel-semantics.html#the-span-element', '<span>')}}{{Spec2('HTML5 W3C')}}The {{glossary("DOM")}} interface is now {{domxref("HTMLSpanElement")}}.
{{SpecName('HTML4.01', 'struct/global.html#edef-SPAN', '<span>')}}{{Spec2('HTML4.01')}}
- -

Browser compatibility

- - - -

{{Compat("html.elements.span")}}

- -

See also

- -
    -
  • HTML {{HTMLElement("div")}} element
  • -
diff --git a/files/vi/web/html/index.html b/files/vi/web/html/index.html deleted file mode 100644 index 11e9223087..0000000000 --- a/files/vi/web/html/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: HTML -slug: Web/HTML -tags: - - HTML -translation_of: Web/HTML -translation_of_original: HTML ---- -
-
HTML5 Demos
- -

Bộ sưu tập demo  cho thấy những công nghệ HTML mới nhất trong thực tiễn.

- -

HTML5_Logo

-
- -

Ngôn ngữ đánh dấu siêu văn bản (HyperText Markup Language - HTML) được sử dụng trong việc tạo trang web và các loại tài liệu khác có thể xem được bằng trình duyệt. HTML là một tiêu chuẩn quốc tế, được duy trì bởi  World Wide Web Consortium - Liên hợp Web toàn cầu. Trên phương diện kỹ thuật, HTML5 vẫn đang trong quá trình phát triển. Tuy nhiên nó được xem là  "tiêu chuẩn sống" và là phiên bản nâng cấp được cập nhật của HTML.

- - - - - - - - -
-

 Tài liệu HTML

- -
-
Giới thiệu về HTML
-
Phần này đề cập đến các thông tin cơ bản về cú pháp và ngữ nghĩa của một trang (tài liệu) HTML. Đây là những thông tin cơ bản và cần thiết trong việc phát triển những tài liệu HTML
-
Tham khảo về yếu tố của HTML
-
Đi vào chi tiết về từng phần tử được hỗ trợ bởi các trình duyệt khác nhau.
-
Danh sách thuộc tính HTML
-
Tìm hiểu tất cả các thuộc tính và những phần tử liên quan.
-
HTML5
-
Khám phá về API mới trong HTML5 và các  phần tử được hỗ trợ.
-
Thói quen xấu: copy-paste
-
Công nghệ web thường được học bằng cách xem nguồn từ những trang khác rồi copy-paste. Thói quen xấu này vẫn đang tiếp tục tồn tại.
-
  Vẽ đồ hoạ với Canvas
-
Một phần tử HTML mới : <canvas> có thể được dùng để tạo ra biểu đồ, các phần tử UI, và những yếu tố đồ hoạ tuỳ chỉnh khác từ phía máy khách - client.
-
Các mẹo tạo trang HTML với tốc độ tải nhanh
-
Web được tối ưu không đơn thuần chỉ là trang web có tương tác cao với khách truy cập, mà còn được kỳ vọng là có khả năng giảm tải lên máy chủ và kết nối internet.
-
- -

Xem tất cả...

-
-

Nhận trợ giúp từ cộng đồng

- -

Bạn cần trợ giúp về một vấn đề liên quan đến HTML mà không thể tìm thấy giải pháp trong phần tài liệu?

- - - -

Đừng quên giao tiếp một cách netiquette...

- -

Công cụ hỗ trợ phát triển HTML

- - - -

Xem tất cả...

- - - - -
diff --git a/files/vi/web/http/headers/content-security-policy/index.html b/files/vi/web/http/headers/content-security-policy/index.html deleted file mode 100644 index 94ee94b509..0000000000 --- a/files/vi/web/http/headers/content-security-policy/index.html +++ /dev/null @@ -1,258 +0,0 @@ ---- -title: Content-Security-Policy -slug: Web/HTTP/Headers/Content-Security-Policy -tags: - - CSP - - Content Security Policy - - HTTP - - NeedsTranslation - - Reference - - Security - - TopicStub - - header -translation_of: Web/HTTP/Headers/Content-Security-Policy ---- -
{{HTTPSidebar}}
- -

The HTTP Content-Security-Policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks ({{Glossary("XSS")}}).

- -

For more information, see the introductory article on Content Security Policy (CSP).

- - - - - - - - - - - - -
Header type{{Glossary("Response header")}}
{{Glossary("Forbidden header name")}}no
- -

Syntax

- -
Content-Security-Policy: <policy-directive>; <policy-directive>
-
- -

where <policy-directive> consists of: <directive> <value> with no internal punctuation.

- -

Directives

- -

Fetch directives

- -

Fetch directives control the locations from which certain resource types may be loaded.

- -
-
{{CSP("child-src")}}
-
-

Defines the valid sources for web workers and nested browsing contexts loaded using elements such as {{HTMLElement("frame")}} and {{HTMLElement("iframe")}}.

- -
-

Instead of child-src, if you want to regulate nested browsing contexts and workers, you should use the {{CSP("frame-src")}} and {{CSP("worker-src")}} directives, respectively.

-
-
-
{{CSP("connect-src")}}
-
Restricts the URLs which can be loaded using script interfaces
-
{{CSP("default-src")}}
-
Serves as a fallback for the other {{Glossary("Fetch directive", "fetch directives")}}.
-
{{CSP("font-src")}}
-
Specifies valid sources for fonts loaded using {{cssxref("@font-face")}}.
-
{{CSP("frame-src")}}
-
Specifies valid sources for nested browsing contexts loading using elements such as {{HTMLElement("frame")}} and {{HTMLElement("iframe")}}.
-
{{CSP("img-src")}}
-
Specifies valid sources of images and favicons.
-
{{CSP("manifest-src")}}
-
Specifies valid sources of application manifest files.
-
{{CSP("media-src")}}
-
Specifies valid sources for loading media using the {{HTMLElement("audio")}} , {{HTMLElement("video")}} and {{HTMLElement("track")}} elements.
-
{{CSP("object-src")}}
-
Specifies valid sources for the {{HTMLElement("object")}}, {{HTMLElement("embed")}}, and {{HTMLElement("applet")}} elements.
-
Elements controlled by object-src are perhaps coincidentally considered legacy HTML elements and are not receiving new standardized features (such as the security attributes sandbox or allow for <iframe>). Therefore it is recommended to restrict this fetch-directive (e.g., explicitly set object-src 'none' if possible).
-
{{CSP("prefetch-src")}}{{experimental_inline}}
-
Specifies valid sources to be prefetched or prerendered.
-
{{CSP("script-src")}}
-
Specifies valid sources for JavaScript.
-
{{CSP("script-src-elem")}}{{experimental_inline}}
-
Specifies valid sources for JavaScript {{HTMLElement("script")}} elements.
-
{{CSP("script-src-attr")}}{{experimental_inline}}
-
Specifies valid sources for JavaScript inline event handlers.
-
- -
-
{{CSP("style-src")}}
-
Specifies valid sources for stylesheets.
-
{{CSP("style-src-elem")}}{{experimental_inline}}
-
Specifies valid sources for stylesheets {{HTMLElement("style")}} elements and {{HTMLElement("link")}} elements with rel="stylesheet".
-
{{CSP("style-src-attr")}}{{experimental_inline}}
-
Specifies valid sources for inline styles applied to individual DOM elements.
-
{{CSP("worker-src")}}{{experimental_inline}}
-
Specifies valid sources for {{domxref("Worker")}}, {{domxref("SharedWorker")}}, or {{domxref("ServiceWorker")}} scripts.
-
- -

Document directives

- -

Document directives govern the properties of a document or worker environment to which a policy applies.

- -
-
{{CSP("base-uri")}}
-
Restricts the URLs which can be used in a document's {{HTMLElement("base")}} element.
-
{{CSP("plugin-types")}}
-
Restricts the set of plugins that can be embedded into a document by limiting the types of resources which can be loaded.
-
{{CSP("sandbox")}}
-
Enables a sandbox for the requested resource similar to the {{HTMLElement("iframe")}} {{htmlattrxref("sandbox", "iframe")}} attribute.
-
- - - -

Navigation directives govern to which locations a user can navigate or submit a form, for example.

- -
-
{{CSP("form-action")}}
-
Restricts the URLs which can be used as the target of a form submissions from a given context.
-
{{CSP("frame-ancestors")}}
-
Specifies valid parents that may embed a page using {{HTMLElement("frame")}}, {{HTMLElement("iframe")}}, {{HTMLElement("object")}}, {{HTMLElement("embed")}}, or {{HTMLElement("applet")}}.
-
{{CSP("navigate-to")}}{{experimental_inline}}
-
Restricts the URLs to which a document can initiate navigation by any means, including {{HTMLElement("form")}} (if {{CSP("form-action")}} is not specified), {{HTMLElement("a")}}, {{DOMxRef("window.location")}}, {{DOMxRef("window.open")}}, etc.
-
- -

Reporting directives

- -

Reporting directives control the reporting process of CSP violations. See also the {{HTTPHeader("Content-Security-Policy-Report-Only")}} header.

- -
-
{{CSP("report-uri")}}{{deprecated_inline}}
-
Instructs the user agent to report attempts to violate the Content Security Policy. These violation reports consist of {{Glossary("JSON")}} documents sent via an HTTP POST request to the specified URI. -
-

Though the {{CSP("report-to")}} directive is intended to replace the deprecated report-uri directive, {{CSP("report-to")}} is not supported in most browsers yet. So for compatibility with current browsers while also adding forward compatibility when browsers get {{CSP("report-to")}} support, you can specify both report-uri and {{CSP("report-to")}}:

- -
Content-Security-Policy: ...; report-uri https://endpoint.example.com; report-to groupname
- -

In browsers that support {{CSP("report-to")}}, the report-uri directive will be ignored.

-
-
-
{{CSP("report-to")}}{{experimental_inline}}
-
Fires a SecurityPolicyViolationEvent.
-
- -

Other directives

- -
-
{{CSP("block-all-mixed-content")}}
-
Prevents loading any assets using HTTP when the page is loaded using HTTPS.
-
{{CSP("referrer")}}{{deprecated_inline}}{{non-standard_inline}}
-
Used to specify information in the Referer (sic) header for links away from a page. Use the {{HTTPHeader("Referrer-Policy")}} header instead.
-
{{CSP("require-sri-for")}}{{experimental_inline}}
-
Requires the use of {{Glossary("SRI")}} for scripts or styles on the page.
-
{{CSP("require-trusted-types-for")}}{{experimental_inline}}
-
Enforces Trusted Types at the DOM XSS injection sinks.
-
- -
-
{{CSP("trusted-types")}}{{experimental_inline}}
-
Used to specify an allow-list of Trusted Types policies. Trusted Types allows applications to lock down DOM XSS injection sinks to only accept non-spoofable, typed values in place of strings.
-
- -
-
{{CSP("upgrade-insecure-requests")}}
-
Instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.
-
- -

CSP in workers

- -

Workers are in general not governed by the content security policy of the document (or parent worker) that created them. To specify a content security policy for the worker, set a Content-Security-Policy response header for the request which requested the worker script itself.

- -

The exception to this is if the worker script's origin is a globally unique identifier (for example, if its URL has a scheme of data or blob). In this case, the worker does inherit the content security policy of the document or worker that created it.

- -

Multiple content security policies

- -

The CSP mechanism allows multiple policies being specified for a resource, including via the Content-Security-Policy header, the {{HTTPHeader("Content-Security-Policy-Report-Only")}} header and a {{HTMLElement("meta")}} element.

- -

You can use the Content-Security-Policy header more than once, as in the example below. Pay special attention to the {{CSP("connect-src")}} directive here. Even though the second policy would allow the connection, the first policy contains connect-src 'none'. Adding additional policies can only further restrict the capabilities of the protected resource, which means that there will be no connection allowed and, as the strictest policy, connect-src 'none' is enforced.

- -
Content-Security-Policy: default-src 'self' http://example.com;
-                         connect-src 'none';
-Content-Security-Policy: connect-src http://example.com/;
-                         script-src http://example.com/
- -

Examples

- -

Example: Disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) over https:

- -
// header
-Content-Security-Policy: default-src https:
-
-// meta tag
-<meta http-equiv="Content-Security-Policy" content="default-src https:">
-
- -

Example: Pre-existing site that uses too much inline code to fix but wants to ensure resources are loaded only over HTTPS and to disable plugins:

- -
Content-Security-Policy: default-src https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'
- -

Example: Do not implement the above policy yet; instead just report violations that would have occurred:

- -
Content-Security-Policy-Report-Only: default-src https:; report-uri /csp-violation-report-endpoint/
- -

See Mozilla Web Security Guidelines for more examples.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{specName("CSP 3.0")}}{{Spec2("CSP 3.0")}}Adds manifest-src, navigate-to, report-to, strict-dynamic, worker-src. Undeprecates frame-src. Deprecates report-uri in favor if report-to.
{{specName("Mixed Content")}}{{Spec2("Mixed Content")}}Adds block-all-mixed-content.
{{specName("Subresource Integrity")}}{{Spec2("Subresource Integrity")}}Adds require-sri-for.
{{specName("Upgrade Insecure Requests")}}{{Spec2("Upgrade Insecure Requests")}}Adds upgrade-insecure-requests.
{{specName("CSP 1.1")}}{{Spec2("CSP 1.1")}}Adds base-uri, child-src, form-action, frame-ancestors, plugin-types, referrer, and report-uri. Deprecates frame-src.
{{specName("CSP 1.0")}}{{Spec2("CSP 1.0")}}Defines connect-src, default-src, font-src, frame-src, img-src, media-src, object-src, report-uri, sandbox, script-src, and style-src.
- -

Browser compatibility

- - - -

{{Compat("http.headers.csp.Content-Security-Policy")}}

- -

See also

- - diff --git a/files/vi/web/http/headers/content-security-policy/style-src/index.html b/files/vi/web/http/headers/content-security-policy/style-src/index.html deleted file mode 100644 index d4d81d3cce..0000000000 --- a/files/vi/web/http/headers/content-security-policy/style-src/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: 'CSP: style-src' -slug: Web/HTTP/Headers/Content-Security-Policy/style-src -translation_of: Web/HTTP/Headers/Content-Security-Policy/style-src ---- -
{{HTTPSidebar}}
- -

The HTTP {{HTTPHeader("Content-Security-Policy")}} (CSP) style-src directive specifies valid sources for stylesheets.

- - - - - - - - - - - - - - - - -
CSP version1
Directive type{{Glossary("Fetch directive")}}
{{CSP("default-src")}} fallbackYes. If this directive is absent, the user agent will look for the default-src directive.
- -

Syntax

- -

One or more sources can be allowed for the style-src policy:

- -
Content-Security-Policy: style-src <source>;
-Content-Security-Policy: style-src <source> <source>;
-
- -

Sources

- -

{{page("Web/HTTP/Headers/Content-Security-Policy/connect-src", "Sources")}}

- -

Examples

- -

Violation cases

- -

Với tiêu đề CSP này:

- -
Content-Security-Policy: style-src https://example.com/
- -

các bảng định kiểu sau bị chặn và không tải:

- -
<link href="https://not-example.com/styles/main.css" rel="stylesheet" type="text/css" />
-
-<style>
-#inline-style { background: red; }
-</style>
-
-<style>
-  @import url("https://not-example.com/styles/print.css") print;
-</style>
- -

as well as styles loaded using the {{HTTPHeader("Link")}} header:

- -
Link: <https://not-example.com/styles/stylesheet.css>;rel=stylesheet
-
- -

Inline style attributes are also blocked:

- -
<div style="display:none">Foo</div>
- -

As well as styles that are applied in Javascript by setting the style attribute directly, or by setting {{domxref("CSSStyleDeclaration.cssText", "cssText")}}:

- -
document.querySelector('div').setAttribute('style', 'display:none;');
-document.querySelector('div').style.cssText = 'display:none;';
- -

However, styles properties that are set directly on the element's {{domxref("HTMLElement.style", "style")}} property will not be blocked, allowing users to safely manipulate styles via Javascript:

- -
document.querySelector('div').style.display = 'none';
- -

These types of manipulations can be prevented by disallowing Javascript via the {{CSP("script-src")}} CSP directive.

- -

Unsafe inline styles

- -
-

Note: Disallowing inline styles and inline scripts is one of the biggest security wins CSP provides. However, if you absolutely have to use it, there are a few mechanisms that will allow them.

-
- -

To allow inline styles, 'unsafe-inline', a nonce-source or a hash-source that matches the inline block can be specified.

- -
Content-Security-Policy: style-src 'unsafe-inline';
-
- -

The above Content Security Policy will allow inline styles like the {{HTMLElement("style")}} element, and the style attribute on any element:

- -
<style>
-#inline-style { background: red; }
-</style>
-
-<div style="display:none">Foo</div>
-
- -

You can use a nonce-source to only allow specific inline style blocks:

- -
Content-Security-Policy: style-src 'nonce-2726c7f26c'
- -

You will have to set the same nonce on the {{HTMLElement("style")}} element:

- -
<style nonce="2726c7f26c">
-#inline-style { background: red; }
-</style>
- -

Alternatively, you can create hashes from your inline styles. CSP supports sha256, sha384 and sha512.

- -
Content-Security-Policy: style-src 'sha256-a330698cbe9dc4ef1fb12e2ee9fc06d5d14300262fa4dc5878103ab7347e158f'
- -

When generating the hash, don't include the {{HTMLElement("style")}} tags and note that capitalization and whitespace matter, including leading or trailing whitespace.

- -
<style>#inline-style { background: red; }</style>
- -

Unsafe style expressions

- -

The 'unsafe-eval' source expression controls several style methods that create style declarations from strings. If 'unsafe-eval' isn't specified with the style-src directive, the following methods are blocked and won't have any effect:

- -
    -
  • {{domxref("CSSStyleSheet.insertRule()")}}
  • -
  • {{domxref("CSSGroupingRule.insertRule()")}}
  • -
  • {{domxref("CSSStyleDeclaration.cssText")}}
  • -
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{specName("CSP 3.0", "#directive-style-src", "style-src")}}{{Spec2('CSP 3.0')}}No changes.
{{specName("CSP 1.1", "#directive-style-src", "style-src")}}{{Spec2('CSP 1.1')}}Initial definition.
- -

Browser compatibility

- - - -

{{Compat("http.headers.csp.Content-Security-Policy.style-src")}}

- -

See also

- -
    -
  • {{HTTPHeader("Content-Security-Policy")}}
  • -
  • {{CSP("style-src-elem")}}
  • -
  • {{CSP("style-src-attr")}}
  • -
  • {{HTTPHeader("Link")}} header
  • -
  • {{HTMLElement("style")}}, {{HTMLElement("link")}}
  • -
  • {{cssxref("@import")}}
  • -
  • {{domxref("CSSStyleSheet.insertRule()")}}
  • -
  • {{domxref("CSSGroupingRule.insertRule()")}}
  • -
  • {{domxref("CSSStyleDeclaration.cssText")}}
  • -
diff --git a/files/vi/web/http/headers/index.html b/files/vi/web/http/headers/index.html deleted file mode 100644 index 23d020b770..0000000000 --- a/files/vi/web/http/headers/index.html +++ /dev/null @@ -1,362 +0,0 @@ ---- -title: HTTP headers -slug: Web/HTTP/Headers -tags: - - HTTP - - Headers - - NeedsTranslation - - Networking - - Reference - - TopicStub -translation_of: Web/HTTP/Headers ---- -
{{HTTPSidebar}}
- -

HTTP headers allow the client and the server to pass additional information with the request or the response. A request header consists of its case-insensitive name followed by a colon ':', then by its value (without line breaks). Leading white space before the value is ignored.

- -

Custom proprietary headers can be added using the 'X-' prefix, but this convention was deprecated in June 2012, because of the inconveniences it caused when non-standard fields became standard in RFC 6648; others are listed in an IANA registry, whose original content was defined in RFC 4229. IANA also maintains a registry of proposed new HTTP message headers.

- -

Headers can be grouped according to their contexts:

- -
    -
  • {{Glossary("General header")}}: Headers applying to both requests and responses but with no relation to the data eventually transmitted in the body.
  • -
  • {{Glossary("Request header")}}: Headers containing more information about the resource to be fetched or about the client itself.
  • -
  • {{Glossary("Response header")}}: Headers with additional information about the response, like its location or about the server itself (name and version etc.).
  • -
  • {{Glossary("Entity header")}}: Headers containing more information about the body of the entity, like its content length or its MIME-type.
  • -
- -

Headers can also be grouped according to how proxies handle them:

- -
-
End-to-end headers
-
These headers must be transmitted to the final recipient of the message; that is, the server for a request or the client for a response. Intermediate proxies must retransmit end-to-end headers unmodified and caches must store them.
-
Hop-by-hop headers
-
These headers are meaningful only for a single transport-level connection and must not be retransmitted by proxies or cached. Such headers are: {{ httpheader("Connection") }}, {{ httpheader("Keep-Alive") }}, {{ httpheader("Proxy-Authenticate") }}, {{ httpheader("Proxy-Authorization") }}, {{ httpheader("TE") }}, {{ httpheader("Trailer") }}, {{ httpheader("Transfer-Encoding") }} and {{ httpheader("Upgrade") }}. Note that only hop-by-hop headers may be set using the {{ httpheader("Connection") }} general header.
-
- -

The following list summaries HTTP headers by their usage category. For an alphabetical list, see the navigation on the left side.

- -

Authentication

- -
-
{{HTTPHeader("WWW-Authenticate")}}
-
Defines the authentication method that should be used to gain access to a resource.
-
{{HTTPHeader("Authorization")}}
-
Contains the credentials to authenticate a user agent with a server.
-
{{HTTPHeader("Proxy-Authenticate")}}
-
Defines the authentication method that should be used to gain access to a resource behind a Proxy server.
-
{{HTTPHeader("Proxy-Authorization")}}
-
Contains the credentials to authenticate a user agent with a proxy server.
-
- -

Caching

- -
-
{{HTTPHeader("Age")}}
-
The time in seconds the object has been in a proxy cache.
-
{{HTTPHeader("Cache-Control")}}
-
Specifies directives for caching mechanisms in both, requests and responses.
-
{{HTTPHeader("Expires")}}
-
The date/time after which the response is considered stale.
-
{{HTTPHeader("Pragma")}}
-
Implementation-specific header that may have various effects anywhere along the request-response chain. Used for backwards compatibility with HTTP/1.0 caches where the Cache-Control header is not yet present.
-
{{HTTPHeader("Warning")}}
-
A general warning field containing information about possible problems.
-
- -

Client hints

- -
-
{{HTTPHeader("Accept-CH")}}
-
...
-
{{HTTPHeader("Content-DPR")}}
-
...
-
{{HTTPHeader("DPR")}}
-
...
-
{{HTTPHeader("Downlink")}}
-
...
-
{{HTTPHeader("Save-Data")}}
-
...
-
{{HTTPHeader("Viewport-Width")}}
-
...
-
{{HTTPHeader("Width")}}
-
...
-
- -
-
-

Conditionals

-
-
{{HTTPHeader("Last-Modified")}}
-
It is a validator, the last modification date of the resource, used to compare several versions of the same resource. It is less accurate than {{HTTPHeader("ETag")}}, but easier to calculate in some environments. Conditional requests using {{HTTPHeader("If-Modified-Since")}} and {{HTTPHeader("If-Unmodified-Since")}} use this value to change the behavior of the request.
-
{{HTTPHeader("ETag")}}
-
It is a validator, a unique string identifying the version of the resource. Conditional requests using {{HTTPHeader("If-Match")}} and {{HTTPHeader("If-None-Match")}} use this value to change the behavior of the request.
-
{{HTTPHeader("If-Match")}}
-
Makes the request conditional and applies the method only if the stored resource matches one of the given ETags.
-
{{HTTPHeader("If-None-Match")}}
-
Makes the request conditional and applies the method only if the stored resource doesn't match any of the given ETags. This is used to update caches (for safe requests), or to prevent to upload a new resource when one is already existing.
-
{{HTTPHeader("If-Modified-Since")}}
-
Makes the request conditional and expects the entity to be transmitted only if it has been modified after the given date. This is used to transmit data only when the cache is out of date.
-
{{HTTPHeader("If-Unmodified-Since")}}
-
Makes the request conditional and expects the entity to be transmitted only if it has not been modified after the given date. This is used to ensure the coherence of a new fragment of a specific range with previous ones, or to implement an optimistic concurrency control system when modifying existing documents.
-
- -

Connection management

- -
-
{{HTTPHeader("Connection")}}
-
Controls whether the network connection stays open after the current transaction finishes.
-
{{HTTPHeader("Keep-Alive")}}
-
Controls how long a persistent connection should stay open.
-
- -

Content negotiation

- -
-
{{HTTPHeader("Accept")}}
-
Informs the server about the types of data that can be sent back. It is MIME-type.
-
{{HTTPHeader("Accept-Charset")}}
-
Informs the server about which character set the client is able to understand.
-
{{HTTPHeader("Accept-Encoding")}}
-
Informs the server about the encoding algorithm, usually a compression algorithm, that can be used on the resource sent back.
-
{{HTTPHeader("Accept-Language")}}
-
Informs the server about the language the server is expected to send back. This is a hint and is not necessarily under the full control of the user: the server should always pay attention not to override an explicit user choice (like selecting a language in a drop down list).
-
- -
-
- -

Controls

- -
-
{{HTTPHeader("Expect")}}
-
Indicates expectations that need to be fulfilled by the server in order to properly handle the request.
-
{{HTTPHeader("Max-Forwards")}}
-
...
-
- -

Cookies

- -
-
{{HTTPHeader("Cookie")}}
-
Contains stored HTTP cookies previously sent by the server with the {{HTTPHeader("Set-Cookie")}} header.
-
{{HTTPHeader("Set-Cookie")}}
-
Send cookies from the server to the user agent.
-
{{HTTPHeader("Cookie2")}} {{obsolete_inline}}
-
Used to contain an HTTP cookie, previously sent by the server with the {{HTTPHeader("Set-Cookie2")}} header, but has been obsoleted by the specification. Use {{HTTPHeader("Cookie")}} instead.
-
{{HTTPHeader("Set-Cookie2")}} {{obsolete_inline}}
-
Used to send cookies from the server to the user agent, but has been obsoleted by the specification. Use {{HTTPHeader("Set-Cookie")}} instead.
-
-

CORS

-
-
{{HTTPHeader("Access-Control-Allow-Origin")}}
-
Indicates whether the response can be shared.
-
{{HTTPHeader("Access-Control-Allow-Credentials")}}
-
Indicates whether the response to the request can be exposed when the credentials flag is true.
-
{{HTTPHeader("Access-Control-Allow-Headers")}}
-
Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.
-
{{HTTPHeader("Access-Control-Allow-Methods")}}
-
Specifies the method or methods allowed when accessing the resource in response to a preflight request.
-
{{HTTPHeader("Access-Control-Expose-Headers")}}
-
Indicates which headers can be exposed as part of the response by listing their names.
-
{{HTTPHeader("Access-Control-Max-Age")}}
-
Indicates how long the results of a preflight request can be cached.
-
{{HTTPHeader("Access-Control-Request-Headers")}}
-
Used when issuing a preflight request to let the server know which HTTP headers will be used when the actual request is made.
-
{{HTTPHeader("Access-Control-Request-Method")}}
-
Used when issuing a preflight request to let the server know which HTTP method will be used when the actual request is made.
-
{{HTTPHeader("Origin")}}
-
Indicates where a fetch originates from.
-
- -

Do Not Track

- -
-
{{HTTPHeader("DNT")}}
-
Used for expressing the user's tracking preference.
-
{{HTTPHeader("Tk")}}
-
Indicates the tracking status that applied to the corresponding request.
-
- -

Downloads

- -
-
{{HTTPHeader("Content-Disposition")}}
-
Is a response header if the resource transmitted should be displayed inline (default behavior when the header is not present), or it should be handled like a download and the browser should present a 'Save As' window.
-
- -

Message body information

- -
-
{{HTTPHeader("Content-Length")}}
-
indicates the size of the entity-body, in decimal number of octets, sent to the recipient.
-
{{HTTPHeader("Content-Type")}}
-
Indicates the media type of the resource.
-
{{HTTPHeader("Content-Encoding")}}
-
Used to specify the compression algorithm.
-
{{HTTPHeader("Content-Language")}}
-
Describes the language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language.
-
{{HTTPHeader("Content-Location")}}
-
Indicates an alternate location for the returned data.
-
-

Proxies

-
-
- -
-
{{HTTPHeader("Forwarded")}}
-
Contains information from the client-facing side of proxy servers that is altered or lost when a proxy is involved in the path of the request.
-
{{HTTPHeader("X-Forwarded-For")}} {{non-standard_inline}}
-
Identifies the originating IP addresses of a client connecting to a web server through an HTTP proxy or a load balancer.
-
{{HTTPHeader("X-Forwarded-Host")}} {{non-standard_inline}}
-
Identifies the original host requested that a client used to connect to your proxy or load balancer.
-
{{HTTPHeader("X-Forwarded-Proto")}} {{non-standard_inline}}
-
identifies the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer.
-
{{HTTPHeader("Via")}}
-
Added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers.
-
- -

Redirects

- -
-
{{HTTPHeader("Location")}}
-
Indicates the URL to redirect a page to.
-
- -

Request context

- -
-
{{HTTPHeader("From")}}
-
Contains an Internet email address for a human user who controls the requesting user agent.
-
{{HTTPHeader("Host")}}
-
Specifies the domain name of the server (for virtual hosting), and (optionally) the TCP port number on which the server is listening.
-
{{HTTPHeader("Referer")}}
-
The address of the previous web page from which a link to the currently requested page was followed.
-
{{HTTPHeader("Referrer-Policy")}}
-
Governs which referrer information sent in the {{HTTPHeader("Referer")}} header should be included with requests made.
-
{{HTTPHeader("User-Agent")}}
-
Contains a characteristic string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. See also the Firefox user agent string reference.
-
- -

Response context

- -
-
{{HTTPHeader("Allow")}}
-
Lists the set of HTTP request methods support by a resource.
-
{{HTTPHeader("Server")}}
-
Contains information about the software used by the origin server to handle the request.
-
- -

Range requests

- -
-
{{HTTPHeader("Accept-Ranges")}}
-
Indicates if the server supports range requests and if so, in which unit the range can be expressed.
-
{{HTTPHeader("Range")}}
-
Indicates the part of a document that the server should return.
-
{{HTTPHeader("If-Range")}}
-
Creates a conditional range request that is only fulfilled if the given etag or date matches the remote resource. Used to prevent downloading two ranges from incompatible version of the resource.
-
{{HTTPHeader("Content-Range")}}
-
Indicates where in a full body message a partial message belongs.
-
- -

Security

- -
-
{{HTTPHeader("Content-Security-Policy")}} ({{Glossary("CSP")}})
-
Controls resources the user agent is allowed to load for a given page.
-
{{HTTPHeader("Content-Security-Policy-Report-Only")}}
-
Allows web developers to experiment with policies by monitoring (but not enforcing) their effects. These violation reports consist of {{Glossary("JSON")}} documents sent via an HTTP POST request to the specified URI.
-
{{HTTPHeader("Public-Key-Pins")}} ({{Glossary("HPKP")}})
-
Associates a specific cryptographic public key with a certain web server to decrease the risk of {{Glossary("MITM")}} attacks with forged certificates.
-
{{HTTPHeader("Public-Key-Pins-Report-Only")}}
-
Sends reports to the report-uri specified in the header and does still allow clients to connect to the server even if the pinning is violated.
-
- -
-
{{HTTPHeader("Strict-Transport-Security")}} ({{Glossary("HSTS")}})
-
Force communication using HTTPS instead of HTTP.
-
{{HTTPHeader("Upgrade-Insecure-Requests")}}
-
Sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the {{CSP("upgrade-insecure-requests")}} directive.
-
- -
-
{{HTTPHeader("X-Content-Type-Options")}}
-
Disables MIME sniffing and forces browser to use the type given in {{HTTPHeader("Content-Type")}}.
-
- -
-
{{HTTPHeader("X-Frame-Options")}} (XFO)
-
Indicates whether a browser should be allowed to render a page in a {{HTMLElement("frame")}}, {{HTMLElement("iframe")}} or {{HTMLElement("object")}}
-
{{HTTPHeader("X-XSS-Protection")}}
-
Enables cross-site scripting filtering.
-
- -

Server-sent events

- -
-
{{HTTPHeader("Ping-From")}}
-
...
-
{{HTTPHeader("Ping-To")}}
-
...
-
{{HTTPHeader("Last-Event-ID")}}
-
...
-
- -

Transfer coding

- -
-
{{HTTPHeader("Transfer-Encoding")}}
-
Specifies the the form of encoding used to safely transfer the entity to the user.
-
{{HTTPHeader("TE")}}
-
Specifies the transfer encodings the user agent is willing to accept.
-
{{HTTPHeader("Trailer")}}
-
Allows the sender to include additional fields at the end of chunked message.
-
- -

WebSockets

- -
-
{{HTTPHeader("Sec-WebSocket-Key")}}
-
...
-
{{HTTPHeader("Sec-WebSocket-Extensions")}}
-
...
-
{{HTTPHeader("Sec-WebSocket-Accept")}}
-
...
-
{{HTTPHeader("Sec-WebSocket-Protocol")}}
-
...
-
{{HTTPHeader("Sec-WebSocket-Version")}}
-
...
-
- -

Other

- -
-
{{HTTPHeader("Date")}}
-
Contains the date and time at which the message was originated.
-
{{HTTPHeader("Large-Allocation")}}
-
Tells the browser that the page being loaded is going to want to perform a large allocation.
-
{{HTTPHeader("Link")}}
-
...
-
{{HTTPHeader("Retry-After")}}
-
Indicates how long the user agent should wait before making a follow-up request.
-
{{HTTPHeader("SourceMap")}}
-
Links generated code to a source map.
-
{{HTTPHeader("Upgrade")}}
-
This is a Proposed Internet Standard. To view a comprehensive list of all Official and Proposed Internet Standards with detailed information about each, visit this Internet Standards reference, which is updated daily.  The relevant RFC document for the Upgrade header field standard is RFC 7230, section 6.7.  The standard establishes rules for upgrading or changing to a different protocol on the current client, server, transport protocol connection.  For example, this header standard allows a client to change from HTTP 1.1 to HTTP 2.0, assuming the server decides to acknowledge and implement the Upgrade header field.  Niether party is required to accept the terms specified in the Upgrade header field.  It can be used in both client and server headers.  If the Upgrade header field is specified, then the sender MUST also send the Connection header field with the upgrade option specified.  For details on the Connection header field please see section 6.1 of the aforementioned RFC.
-
{{HTTPHeader("Vary")}}
-
Determines how to match future request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server.
-
{{HTTPHeader("X-DNS-Prefetch-Control")}}
-
Controls DNS prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as URLs for items referenced by the document, including images, CSS, JavaScript, and so forth.
-
{{HTTPHeader("X-Requested-With")}}
-
...
-
{{HTTPHeader("X-UA-Compatible")}}
-
...
-
- -

See also

- - diff --git a/files/vi/web/http/index.html b/files/vi/web/http/index.html deleted file mode 100644 index 8e05d11ec0..0000000000 --- a/files/vi/web/http/index.html +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: HTTP -slug: Web/HTTP -tags: - - HTTP - - NeedsTranslation - - Reference - - TopicStub - - Web - - 'l10n:priority' -translation_of: Web/HTTP ---- -
{{HTTPSidebar}}
- -

Hypertext Transfer Protocol (HTTP) là một giao thức thuộc tầng ứng dụng được dùng để truyền tải các tài liệu đa phương tiện, ví dụ như HTML. Giao thức này được thiết kế để truyền thông giữa các trình duyệt web và máy chủ web, tuy nhiên nó cũng được dùng cho nhiều mục đích khác. HTTP tuân theo một mô hình client-server truyền thống, với một client mở một kết nối (connection) để tạo ra một yêu cầu (request), sau đó chờ đợi cho đến khi nó nhận được phản một phản hồi (response). HTTP là một giao thức không lưu lại trạng thái (stateless protocol), có nghĩa là máy chủ không lưu giữ bất cữ dữ liệu (state) gì giữa các yêu cầu. Bởi thường được dựa trên một lớp TCP/IP, nó có thể được sử dụng trên bất cứ tầng giao vận đáng tin cậy nào (reliable transport layer) - những giao thức không bị mất dữ liệu, như là UDP.

- -
-
-

Hướng dẫn

- -

Learn how to use HTTP with guides and tutorials.

- -
-
Tổng quan về HTTP
-
Các chức năng cơ bản của giao thức client-server: nó có thể làm gì và mục đích sử dụng của nó.
-
HTTP Cache
-
Caching rất quan trọng với tốc độ của các trang web. Bài viết này mô tả các cách thức cache khác nhau cũng như cách sử dụng HTTP Headers để điều khiển chúng.
-
HTTP Cookies
-
Cookies hoạt động như thế nào được định nghĩa trong RFC 6265. Khi phục vụ một yêu cầu HTTP (HTTP request), một máy chủ (server) có thể gửi một Set-Cookie HTTP header đính kèm trong phản hồi (response). Máy khách (client) sau đó sẽ gửi trả giá trị của cookie trong mỗi yêu cầu đến máy chủ (server) đó trong Cookie header của yêu cầu (request). Cookie cũng có thể được quy định ngày hết hạn hoặc hạn chế với một tên miền và đường dẫn.
-
HTTP Access Control (CORS)
-
Cross-site HTTP requests are HTTP requests for resources from a different domain than the domain of the resource making the request. For instance, an HTML page from Domain A (http://domaina.example/) makes a request for an image on Domain B (http://domainb.foo/image.jpg) via the img element. Web pages today very commonly load cross-site resources, including CSS stylesheets, images, scripts, and other resources. CORS allows web developers to control how their site reacts to cross-site requests.
-
- -
-
Evolution of HTTP
-
A brief description of the changes between the early versions of HTTP, to the modern HTTP/2 and beyond.
-
Mozilla web security guidelines
-
A collection of tips to help operational teams with creating secure web applications.
-
- -
-
HTTP Messages
-
Describes the type and structure of the different kind of messages of HTTP/1.x and HTTP/2.
-
A typical HTTP session
-
Shows and explains the flow of a usual HTTP session.
-
Connection management in HTTP/1.x
-
Describes the three connection management models available in HTTP/1.x, their strengths, and their weaknesses.
-
-
- -
-

Reference

- -

Browse through detailed HTTP reference documentation.

- -
-
HTTP Headers
-
HTTP message headers are used to describe a resource, or the behavior of the server or the client. Custom proprietary headers can be added using the X- prefix; others in an IANA registry, whose original content was defined in RFC 4229. IANA also maintains a registry of proposed new HTTP message headers.
-
HTTP Request Methods
-
The different operations that can be done with HTTP: {{HTTPMethod("GET")}}, {{HTTPMethod("POST")}}, and also less common requests like {{HTTPMethod("OPTIONS")}}, {{HTTPMethod("DELETE")}}, or {{HTTPMethod("TRACE")}}.
-
HTTP Status Response Codes
-
HTTP response codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: informational responses, successful responses, redirections, client errors, and servers errors.
-
CSP directives
-
The {{HTTPHeader("Content-Security-Policy")}} response header fields allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints.
-
- -

Tools & resources

- -

Helpful tools and resources for understanding and debugging HTTP.

- -
-
Firefox Developer Tools
-
Network monitor
-
Mozilla Observatory
-
-

A project designed to help developers, system administrators, and security professionals configure their sites safely and securely.

-
-
RedBot
-
Tools to check your cache-related headers
-
How Browsers Work
-
A very comprehensive article on browser internals and request flow through HTTP protocol. A MUST-READ for any web developer.
-
-
-
diff --git a/files/vi/web/index.html b/files/vi/web/index.html deleted file mode 100644 index 8f6b0ea4ab..0000000000 --- a/files/vi/web/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Công nghệ lập trình Web -slug: Web -tags: - - Landing - - Web -translation_of: Web ---- -

Sự phát triển rộng rãi của World Wide Web đã tạo ra cơ hội cho các lập trình viên sáng tạo các trang web cũng như ứng dụng online bổ ích. Để tận dụng đầy đủ các công nghệ này, bạn cần phải biết làm thế nào để sử dụng chúng. Dưới đây bạn sẽ tìm thấy các liên kết đến các tài liệu MDN của các công nghệ lập trình Web.

- -
-
-

Các công nghệ lập trình Web

- -

Cơ bản

- -
-
HTML
-
HyperText Markup Language (HTML) là ngôn ngữ được sử dụng để định hình cấu trúc và nội dung của trang Web.
-
CSS
-
Cascading Style Sheets (CSS) được sử dụng để biểu thị cách mà một nội dung được hiển thị như thế nào trên Web.
-
HTTP
-
Hypertext Transfer Protocol (HTTP) là giao thức truyền tải siêu văn bản, được sử dụng để truyền tải các nội dung HTML cũng như các nội dung media trên mạng.
-
- -

Scripting

- -
-
JavaScript
-
-

JavaScipt là mội ngôn ngữ lập trình chạy trên các trình duyệt, được sử dụng để xây dựng các trang Web có tính tương tác cao với người sử dụng hoặc tạo ra các ứng dụng Web.

-
-
Web APIs
-
Web Application Programming Interfaces (Web APIs) là giao diện lập trình ứng dụng Web được dùng để vận hành các tính năng đa dạng như điều khiển DOM, phát nhạc và video, hoặc tạo ra đồ họa 3D. -
    -
  • Web API interface reference - danh sách các objects bạn có thể dùng khi phát triển web.
  • -
  • WebAPI page - danh sách các thiết bị kết nối, phần cứng và các API hữu ích khác cho một ứng dụng.
  • -
  • Event reference - danh sách các sự kiện có thể giúp bạn kiểm soát và phản ứng kịp thời với những gì xảy ra trên trang web của bạn.
  • -
-
-
- -

Đồ họa

- -
-
Canvas
-
The {{HTMLElement("canvas")}} cung cấp API hỗ trợ vẽ 2D bằng Javascript.
-
- -
-
SVG
-
Scalable Vector Graphics cho phép bạn biểu thị một hình ảnh bằng cách vẽ ra các vector với các hình dạng khác nhau để cho phép hình ảnh đó có thể phóng to thu nhỏ một cách trơn tru với bất kì một kích thước nào.
-
WebGL
-
WebGL là một API cho Javascript mang lại đồ họa 3D cho Web bằng cách sử dụng HTML5: {{HTMLElement("canvas")}}.
-
-

Âm Thanh, Video, và Truyền Thông Đa Phương Tiện

-
-
Công Nghệ Truyền Thông Web
-
Danh sách các API có liên quan tới truyền thông và những tài liệu cần thiết.
-
Tổng Quan Công Nghệ Truyền Thông trên Web
-
Tổng quan về công nghệ web mở và các giao diện lập trình ứng dụng (APIs) hỗ trợ phát sóng âm thành, hình ảnh cũng như điều khiển và ghi hình. Nếu bạn muốn biết bạn nên sử dụng API nào, bạn nên tham khảo tại đây.
-
API hỗ trợ ghi hình và phát sóng truyền thông
-
Tài liệu tham khảo các API dùng để ghi hình và phát sóng trong mạng nội bộ cũng như mạng kết nối, bao gồm nhiều phương thức như sử dụng máy ghi hình cũng như máy thu âm để quay video, thu âm, và chụp ảnh tĩnh.
-
Ứng Dụng Âm Thanh và Video trong HTML5
-
Nhúng âm thanh hoặc video vào trang web và tích hợp trình điều chỉnh
-
WebRTC
-
RTC trong WebRTC là viết tắt của Real-Time Communications, công nghệ cho phép phát sóng trực tiếp âm thanh hình ảnh và truyền dữ liệu giữa các trình duyệt của những người dùng.
-
- -

Công nghệ khác

- -
-
MathML
-
Mathematical Markup Language (MathML) giúp trang web có thể hiển thị các phương trình toán học phức tạp cũng như các cú pháp toán học liên quan.
-
-
- -
-

Góc Hướng Dẫn

- -
-
 
-
Hướng Dẫn Lập Trình Web
-
Tập hợp các bài viết cho người mới bắt đầu lập trình trang web đơn giản.
-
- -

Các chủ đề khác

- -
-
Developing Web applications - Phát triển ứng dụng Web
-
Tài liệu cho các lập trình viên ứng dụng Web cho di động (mobile), máy tính bàn / laptop (desktop), và Firefox.
-
Accessibility - khả năng tiếp cận
-
Khả năng tiếp cập trong lập trình Web nghĩa là cho cho càng nhiều người sử dụng trang Web của bạn càng tốt, ngay cả khi khả năng của người đó có khiếm khuyết về thị lực hoặc thính giác. Trong phần này chúng tôi cung cấp thông tin về cách phát triển trang Web có tính tiếp cận cao.
-
Security - bảo mật 
-
Chắc chắn rằng việc bảo mật trang Web hoặc ứng dụng Web của bạn là một điều thật sự đáng quan tâm. Tập hợp bài viết ở mục này sẽ giúp cho web của bạn an toàn và bảo mât.
-
-
-
- -

Xem thêm ...

diff --git a/files/vi/web/javascript/a_re-introduction_to_javascript/index.html b/files/vi/web/javascript/a_re-introduction_to_javascript/index.html deleted file mode 100644 index 531fb96fc0..0000000000 --- a/files/vi/web/javascript/a_re-introduction_to_javascript/index.html +++ /dev/null @@ -1,950 +0,0 @@ ---- -title: A re-introduction to JavaScript (JS tutorial) -slug: Web/JavaScript/A_re-introduction_to_JavaScript -translation_of: Web/JavaScript/A_re-introduction_to_JavaScript ---- -
{{jsSidebar}}
- -

Tại sao lại là giới thiệu lại? Đó là vì JavaScript được coi là một trong những ngôn ngữ hay bị hiểu lầm nhất thế giới. Nó thường chỉ được coi như một món đồ chơi, nhưng bên dưới sự đơn giản đó lại ẩn chứa rất nhiều sức mạnh. JavaScript hiện được dùng bởi rất rất nhiều ứng dụng mạnh mẽ, và một sự hiểu biết sâu sắc về công nghệ này giờ là một trong những kỹ năng quan trọng của bất kỳ lập trình viên web hay ứng dụng di động nào.

- -

Biết một chút về lịch sử của ngôn ngữ này là rất hữu dụng. JavaScript được tạo ra năm 1995 bởi Brendan Eich khi ông đang là một kỹ sư tại Netscape. JavaScript lần đầu được phát hàng cùng với Netscape 2 đầu năm 1996. Ban đầu nó dự định được gọi là LiveScript, nhưng sau đó đổi lại trong một quyết định marketing sai lầm khi cố gắng nhấn mạnh sự phổ biến của Java, ngôn ngữ lập trình được phát triển bởi Sun Microsystems - dù rằng chúng có rất ít điểm chung. Đây chính là cội rễ của mọi sự hiểu lầm kể từ đó.

- -

Vài tháng sau đó, Microsoft đã phát hành JScript cùng với Internet Explorer 3. Đó cũng là một trong những bản tương thích JavaScript nhiều nhất. Vài tháng sau đó, Netscape gửi JavaScript lên cho Ecma International, một tổ chức tiêu chuẩn của châu Âu, và kết quả là năm đó phiên bản đầu tiên của chuẩn ECMAScript được đưa ra. Chuẩn này sau đó tiếp tục được cập nhật đáng kể với phiên bản ECMAScript edition 3 vào năm 1999, và giữ ổn định kể từ đó. Phiên bản thứ 4 bị hủy bỏ do một số khác biệt về chính sách liên quan đến sự phức tạp của ngôn ngữ. Nhiều phần của phiên bản 4 sau đó trở thành nền tảng cho ECMAScript edition 5, được phát hành vào tháng 12 năm 2009, và cho phiên bản 6 của chuẩn này, phát hành năm 2015.

- -
-

Trong tài liệu này chúng ta sẽ nói về ECMAScript với tên "JavaScript".

-
- -

Không như hầu hết các ngôn ngữ lập trình, JavaScript không có khái niệm đầu vào hay đầu ra (input/output). Nó được thiết kế để chạy như một ngôn ngữ kịch bản và thực thi trong một môi trường được quản lý (host environment), JavaScript phụ thuộc vào môi trường đang chạy để cung cấp các kỹ thuật khác nhau cho việc giao tiếp với thế giới bên ngoài. Môi trường thực thi phổ biến nhất là trình duyệt, nhưng trình thông dịch JavaScript còn có thể được tìm thấy từ một danh sách khổng lồ khác: Adobe Acrobat, Adobe Photoshop, SVG images, Yahoo's Widget engine, các môi trường thực thi phía server như Node.js, các cơ sở dữ liệu NoSQL như phần mềm mã nguồn mở Apache CouchDB, các máy tính nhúng, các môi trường desktop như GNOME (một trong những giao diện phổ biến nhất cho GNU/Linux operating systems), và nhiều nơi khác.

- -

Overview

- -

JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and methods. Its syntax is based on the Java and C languages — many structures from those languages apply to JavaScript as well. JavaScript supports object-oriented programming with object prototypes, instead of classes (see more about prototypical inheritance and ES2015 classes). JavaScript also supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object.

- -

Let's start off by looking at the building blocks of any language: the types. JavaScript programs manipulate values, and those values all belong to a type. JavaScript's types are:

- -
    -
  • {{jsxref("Number")}}
  • -
  • {{jsxref("String")}}
  • -
  • {{jsxref("Boolean")}}
  • -
  • {{jsxref("Function")}}
  • -
  • {{jsxref("Object")}}
  • -
  • {{jsxref("Symbol")}} (new in ES2015)
  • -
- -

... oh, and {{jsxref("undefined")}} and {{jsxref("null")}}, which are ... slightly odd. And {{jsxref("Array")}}, which is a special kind of object. And {{jsxref("Date")}} and {{jsxref("RegExp")}}, which are objects that you get for free. And to be technically accurate, functions are just a special type of object. So the type diagram looks more like this:

- -
    -
  • {{jsxref("Number")}}
  • -
  • {{jsxref("String")}}
  • -
  • {{jsxref("Boolean")}}
  • -
  • {{jsxref("Symbol")}} (new in ES2015)
  • -
  • {{jsxref("Object")}} -
      -
    • {{jsxref("Function")}}
    • -
    • {{jsxref("Array")}}
    • -
    • {{jsxref("Date")}}
    • -
    • {{jsxref("RegExp")}}
    • -
    -
  • -
  • {{jsxref("null")}}
  • -
  • {{jsxref("undefined")}}
  • -
- -

And there are some built-in {{jsxref("Error")}} types as well. Things are a lot easier if we stick with the first diagram, however, so we'll discuss the types listed there for now.

- -

Numbers

- -

Numbers in JavaScript are "double-precision 64-bit format IEEE 754 values", according to the spec. This has some interesting consequences. There's no such thing as an integer in JavaScript, so you have to be a little careful with your arithmetic if you're used to math in C or Java.

- -

Also, watch out for stuff like:

- -
0.1 + 0.2 == 0.30000000000000004;
-
- -

In practice, integer values are treated as 32-bit ints, and some implementations even store it that way until they are asked to perform an instruction that's valid on a Number but not on a 32-bit integer. This can be important for bit-wise operations.

- -

The standard arithmetic operators are supported, including addition, subtraction, modulus (or remainder) arithmetic, and so forth. There's also a built-in object that we did not mention earlier called {{jsxref("Math")}} that provides advanced mathematical functions and constants:

- -
Math.sin(3.5);
-var circumference = 2 * Math.PI * r;
-
- -

You can convert a string to an integer using the built-in {{jsxref("Global_Objects/parseInt", "parseInt()")}} function. This takes the base for the conversion as an optional second argument, which you should always provide:

- -
parseInt('123', 10); // 123
-parseInt('010', 10); // 10
-
- -

In older browsers, strings beginning with a "0" are assumed to be in octal (radix 8), but this hasn't been the case since 2013 or so. Unless you're certain of your string format, you can get surprising results on those older browsers:

- -
parseInt('010');  //  8
-parseInt('0x10'); // 16
-
- -

Here, we see the {{jsxref("Global_Objects/parseInt", "parseInt()")}} function treat the first string as octal due to the leading 0, and the second string as hexadecimal due to the leading "0x". The hexadecimal notation is still in place; only octal has been removed.

- -

If you want to convert a binary number to an integer, just change the base:

- -
parseInt('11', 2); // 3
-
- -

Similarly, you can parse floating point numbers using the built-in {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} function. Unlike its {{jsxref("Global_Objects/parseInt", "parseInt()")}} cousin, parseFloat() always uses base 10.

- -

You can also use the unary + operator to convert values to numbers:

- -
+ '42';   // 42
-+ '010';  // 10
-+ '0x10'; // 16
-
- -

A special value called {{jsxref("NaN")}} (short for "Not a Number") is returned if the string is non-numeric:

- -
parseInt('hello', 10); // NaN
-
- -

NaN is toxic: if you provide it as an operand to any mathematical operation, the result will also be NaN:

- -
NaN + 5; // NaN
-
- -

You can test for NaN using the built-in {{jsxref("Global_Objects/isNaN", "isNaN()")}} function:

- -
isNaN(NaN); // true
-
- -

JavaScript also has the special values {{jsxref("Infinity")}} and -Infinity:

- -
 1 / 0; //  Infinity
--1 / 0; // -Infinity
-
- -

You can test for Infinity, -Infinity and NaN values using the built-in {{jsxref("Global_Objects/isFinite", "isFinite()")}} function:

- -
isFinite(1 / 0); // false
-isFinite(-Infinity); // false
-isFinite(NaN); // false
-
- -
The {{jsxref("Global_Objects/parseInt", "parseInt()")}} and {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. However the "+" operator simply converts the string to NaN if there is an invalid character contained within it. Just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better.
- -

Strings

- -

Strings in JavaScript are sequences of Unicode characters. This should be welcome news to anyone who has had to deal with internationalization. More accurately, they are sequences of UTF-16 code units; each code unit is represented by a 16-bit number. Each Unicode character is represented by either 1 or 2 code units.

- -

If you want to represent a single character, you just use a string consisting of that single character.

- -

To find the length of a string (in code units), access its length property:

- -
'hello'.length; // 5
-
- -

There's our first brush with JavaScript objects! Did we mention that you can use strings like {{jsxref("Object", "objects", "", 1)}} too? They have {{jsxref("String", "methods", "#Methods", 1)}} as well that allow you to manipulate the string and access information about the string:

- -
'hello'.charAt(0); // "h"
-'hello, world'.replace('world', 'mars'); // "hello, mars"
-'hello'.toUpperCase(); // "HELLO"
-
- -

Other types

- -

JavaScript distinguishes between {{jsxref("null")}}, which is a value that indicates a deliberate non-value (and is only accessible through the null keyword), and {{jsxref("undefined")}}, which is a value of type undefined that indicates an uninitialized variable — that is, a value hasn't even been assigned yet. We'll talk about variables later, but in JavaScript it is possible to declare a variable without assigning a value to it. If you do this, the variable's type is undefined. undefined is actually a constant.

- -

JavaScript has a boolean type, with possible values true and false (both of which are keywords.) Any value can be converted to a boolean according to the following rules:

- -
    -
  1. false, 0, empty strings (""), NaN, null, and undefined all become false.
  2. -
  3. All other values become true.
  4. -
- -

You can perform this conversion explicitly using the Boolean() function:

- -
Boolean('');  // false
-Boolean(234); // true
-
- -

However, this is rarely necessary, as JavaScript will silently perform this conversion when it expects a boolean, such as in an if statement (see below). For this reason, we sometimes speak simply of "true values" and "false values," meaning values that become true and false, respectively, when converted to booleans. Alternatively, such values can be called "truthy" and "falsy", respectively.

- -

Boolean operations such as && (logical and), || (logical or), and ! (logical not) are supported; see below.

- -

Variables

- -

New variables in JavaScript are declared using one of three keywords: let, const, or var.
-
- let allows you to declare block-level variables. The declared variable is available from the block it is enclosed in.

- -
let a;
-let name = 'Simon';
-
- -

The following is an example of scope with a variable declared with let:

- -
// myLetVariable is *not* visible out here
-
-for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) {
-  // myLetVariable is only visible in here
-}
-
-// myLetVariable is *not* visible out here
-
-
- -

const allows you to declare variables whose values are never intended to change. The variable is available from the block it is declared in.

- -
const Pi = 3.14; // variable Pi is set
-Pi = 1; // will throw an error because you cannot change a constant variable.
- -


- var is the most common declarative keyword. It does not have the restrictions that the other two keywords have. This is because it was traditionally the only way to declare a variable in JavaScript. A variable declared with the var keyword is available from the function it is declared in.

- -
var a;
-var name = 'Simon';
- -

An example of scope with a variable declared with var:

- -
// myVarVariable *is* visible out here
-
-for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) {
-  // myVarVariable is visible to the whole function
-}
-
-// myVarVariable *is* visible out here
-
- -

If you declare a variable without assigning any value to it, its type is undefined.

- -

An important difference between JavaScript and other languages like Java is that in JavaScript, blocks do not have scope; only functions have a scope. So if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function. However, starting with ECMAScript 2015, let and const declarations allow you to create block-scoped variables.

- -

Operators

- -

JavaScript's numeric operators are +, -, *, / and % which is the remainder operator (which is the same as modulo.) Values are assigned using =, and there are also compound assignment statements such as += and -=. These extend out to x = x operator y.

- -
x += 5;
-x = x + 5;
-
- -

You can use ++ and -- to increment and decrement respectively. These can be used as a prefix or postfix operators.

- -

The + operator also does string concatenation:

- -
'hello' + ' world'; // "hello world"
-
- -

If you add a string to a number (or other value) everything is converted into a string first. This might trip you up:

- -
'3' + 4 + 5;  // "345"
- 3 + 4 + '5'; // "75"
-
- -

Adding an empty string to something is a useful way of converting it to a string itself.

- -

Comparisons in JavaScript can be made using <, >, <= and >=. These work for both strings and numbers. Equality is a little less straightforward. The double-equals operator performs type coercion if you give it different types, with sometimes interesting results:

- -
123 == '123'; // true
-1 == true; // true
-
- -

To avoid type coercion, use the triple-equals operator:

- -
123 === '123'; // false
-1 === true;    // false
-
- -

There are also != and !== operators.

- -

JavaScript also has bitwise operations. If you want to use them, they're there.

- -

Control structures

- -

JavaScript has a similar set of control structures to other languages in the C family. Conditional statements are supported by if and else; you can chain them together if you like:

- -
var name = 'kittens';
-if (name == 'puppies') {
-  name += ' woof';
-} else if (name == 'kittens') {
-  name += ' meow';
-} else {
-  name += '!';
-}
-name == 'kittens meow';
-
- -

JavaScript has while loops and do-while loops. The first is good for basic looping; the second for loops where you wish to ensure that the body of the loop is executed at least once:

- -
while (true) {
-  // an infinite loop!
-}
-
-var input;
-do {
-  input = get_input();
-} while (inputIsNotValid(input));
-
- -

JavaScript's for loop is the same as that in C and Java: it lets you provide the control information for your loop on a single line.

- -
for (var i = 0; i < 5; i++) {
-  // Will execute 5 times
-}
-
- -

JavaScript also contains two other prominent for loops: for...of

- -
for (let value of array) {
-  // do something with value
-}
-
- -

and for...in:

- -
for (let property in object) {
-  // do something with object property
-}
-
- -

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:

- -
var name = o && o.getName();
-
- -

Or for caching values (when falsy values are invalid):

- -
var name = cachedName || (cachedName = getName());
-
- -

JavaScript has a ternary operator for conditional expressions:

- -
var allowed = (age > 18) ? 'yes' : 'no';
-
- -

The switch statement can be used for multiple branches based on a number or string:

- -
switch (action) {
-  case 'draw':
-    drawIt();
-    break;
-  case 'eat':
-    eatIt();
-    break;
-  default:
-    doNothing();
-}
-
- -

If you don't add a break statement, execution will "fall through" to the next level. This is very rarely what you want — in fact it's worth specifically labeling deliberate fallthrough with a comment if you really meant it to aid debugging:

- -
switch (a) {
-  case 1: // fallthrough
-  case 2:
-    eatIt();
-    break;
-  default:
-    doNothing();
-}
-
- -

The default clause is optional. You can have expressions in both the switch part and the cases if you like; comparisons take place between the two using the === operator:

- -
switch (1 + 3) {
-  case 2 + 2:
-    yay();
-    break;
-  default:
-    neverhappens();
-}
-
- -

Objects

- -

JavaScript objects can be thought of as simple collections of name-value pairs. As such, they are similar to:

- -
    -
  • Dictionaries in Python.
  • -
  • Hashes in Perl and Ruby.
  • -
  • Hash tables in C and C++.
  • -
  • HashMaps in Java.
  • -
  • Associative arrays in PHP.
  • -
- -

The fact that this data structure is so widely used is a testament to its versatility. Since everything (bare core types) in JavaScript is an object, any JavaScript program naturally involves a great deal of hash table lookups. It's a good thing they're so fast!

- -

The "name" part is a JavaScript string, while the value can be any JavaScript value — including more objects. This allows you to build data structures of arbitrary complexity.

- -

There are two basic ways to create an empty object:

- -
var obj = new Object();
-
- -

And:

- -
var obj = {};
-
- -

These are semantically equivalent; the second is called object literal syntax and is more convenient. This syntax is also the core of JSON format and should be preferred at all times.

- -

Object literal syntax can be used to initialize an object in its entirety:

- -
var obj = {
-  name: 'Carrot',
-  for: 'Max', // 'for' is a reserved word, use '_for' instead.
-  details: {
-    color: 'orange',
-    size: 12
-  }
-};
-
- -

Attribute access can be chained together:

- -
obj.details.color; // orange
-obj['details']['size']; // 12
-
- -

The following example creates an object prototype(Person) and an instance of that prototype(you).

- -
function Person(name, age) {
-  this.name = name;
-  this.age = age;
-}
-
-// Define an object
-var you = new Person('You', 24);
-// We are creating a new person named "You" aged 24.
-
-
- -

Once created, an object's properties can again be accessed in one of two ways:

- -
// dot notation
-obj.name = 'Simon';
-var name = obj.name;
-
- -

And...

- -
// bracket notation
-obj['name'] = 'Simon';
-var name = obj['name'];
-// can use a variable to define a key
-var user = prompt('what is your key?')
-obj[user] = prompt('what is its value?')
-
- -

These are also semantically equivalent. The second method has the advantage that the name of the property is provided as a string, which means it can be calculated at run-time. However, using this method prevents some JavaScript engine and minifier optimizations being applied. It can also be used to set and get properties with names that are reserved words:

- -
obj.for = 'Simon'; // Syntax error, because 'for' is a reserved word
-obj['for'] = 'Simon'; // works fine
-
- -
-

Starting in ECMAScript 5, reserved words may be used as object property names "in the buff". This means that they don't need to be "clothed" in quotes when defining object literals. See the ES5 Spec.

-
- -

For more on objects and prototypes see Object.prototype. For an explanation of object prototypes and the object prototype chains see Inheritance and the prototype chain.

- -
-

Starting in ECMAScript 2015, object keys can be defined by the variable using bracket notation upon being created. {[phoneType]: 12345} is possible instead of just var userPhone = {}; userPhone[phoneType] = 12345.

-
- -

Arrays

- -

Arrays in JavaScript are actually a special type of object. They work very much like regular objects (numerical properties can naturally be accessed only using [] syntax) but they have one magic property called 'length'. This is always one more than the highest index in the array.

- -

One way of creating arrays is as follows:

- -
var a = new Array();
-a[0] = 'dog';
-a[1] = 'cat';
-a[2] = 'hen';
-a.length; // 3
-
- -

A more convenient notation is to use an array literal:

- -
var a = ['dog', 'cat', 'hen'];
-a.length; // 3
-
- -

Note that array.length isn't necessarily the number of items in the array. Consider the following:

- -
var a = ['dog', 'cat', 'hen'];
-a[100] = 'fox';
-a.length; // 101
-
- -

Remember — the length of the array is one more than the highest index.

- -

If you query a non-existent array index, you'll get a value of undefined in return:

- -
typeof a[90]; // undefined
-
- -

If you take the above about [] and length into account, you can iterate over an array using the following for loop:

- -
for (var i = 0; i < a.length; i++) {
-  // Do something with a[i]
-}
-
- -

ES2015 introduced the more concise for...of loop for iterable objects such as arrays:

- -
for (const currentValue of a) {
-  // Do something with currentValue
-}
- -

You could also iterate over an array using a for...in loop, however this does not iterate over the array elements, but the array indices. Furthermore, if someone added new properties to Array.prototype, they would also be iterated over by such a loop. Therefore this loop type is not recommended for arrays.

- -

Another way of iterating over an array that was added with ECMAScript 5 is forEach():

- -
['dog', 'cat', 'hen'].forEach(function(currentValue, index, array) {
-  // Do something with currentValue or array[index]
-});
-
- -

If you want to append an item to an array simply do it like this:

- -
a.push(item);
- -

Arrays come with a number of methods. See also the full documentation for array methods.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Method nameDescription
a.toString()Returns a string with the toString() of each element separated by commas.
a.toLocaleString()Returns a string with the toLocaleString() of each element separated by commas.
a.concat(item1[, item2[, ...[, itemN]]])Returns a new array with the items added on to it.
a.join(sep)Converts the array to a string — with values delimited by the sep param
a.pop()Removes and returns the last item.
a.push(item1, ..., itemN)Appends items to the end of the array.
a.reverse()Reverses the array.
a.shift()Removes and returns the first item.
a.slice(start[, end])Returns a sub-array.
a.sort([cmpfn])Takes an optional comparison function.
a.splice(start, delcount[, item1[, ...[, itemN]]])Lets you modify an array by deleting a section and replacing it with more items.
a.unshift(item1[, item2[, ...[, itemN]]])Prepends items to the start of the array.
- -

Functions

- -

Along with objects, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler:

- -
function add(x, y) {
-  var total = x + y;
-  return total;
-}
-
- -

This demonstrates a basic function. A JavaScript function can take 0 or more named parameters. The function body can contain as many statements as you like and can declare its own variables which are local to that function. The return statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns undefined.

- -

The named parameters turn out to be more like guidelines than anything else. You can call a function without passing the parameters it expects, in which case they will be set to undefined.

- -
add(); // NaN
-// You can't perform addition on undefined
-
- -

You can also pass in more arguments than the function is expecting:

- -
add(2, 3, 4); // 5
-// added the first two; 4 was ignored
-
- -

That may seem a little silly, but functions have access to an additional variable inside their body called arguments, which is an array-like object holding all of the values passed to the function. Let's re-write the add function to take as many values as we want:

- -
function add() {
-  var sum = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    sum += arguments[i];
-  }
-  return sum;
-}
-
-add(2, 3, 4, 5); // 14
-
- -

That's really not any more useful than writing 2 + 3 + 4 + 5 though. Let's create an averaging function:

- -
function avg() {
-  var sum = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    sum += arguments[i];
-  }
-  return sum / arguments.length;
-}
-
-avg(2, 3, 4, 5); // 3.5
-
- -

This is pretty useful, but it does seem a little verbose. To reduce this code a bit more we can look at substituting the use of the arguments array through Rest parameter syntax. In this way, we can pass in any number of arguments into the function while keeping our code minimal. The rest parameter operator is used in function parameter lists with the format: ...variable and it will include within that variable the entire list of uncaptured arguments that the function was called with. We will also replace the for loop with a for...of loop to return the values within our variable.

- -
function avg(...args) {
-  var sum = 0;
-  for (let value of args) {
-    sum += value;
-  }
-  return sum / args.length;
-}
-
-avg(2, 3, 4, 5); // 3.5
-
- -
In the above code, the variable args holds all the values that were passed into the function.
-
-It is important to note that wherever the rest parameter operator is placed in a function declaration it will store all arguments after its declaration, but not before. i.e. function avg(firstValue, ...args) will store the first value passed into the function in the firstValue variable and the remaining arguments in args. That's another useful language feature but it does lead us to a new problem. The avg() function takes a comma-separated list of arguments — but what if you want to find the average of an array? You could just rewrite the function as follows:
- -
function avgArray(arr) {
-  var sum = 0;
-  for (var i = 0, j = arr.length; i < j; i++) {
-    sum += arr[i];
-  }
-  return sum / arr.length;
-}
-
-avgArray([2, 3, 4, 5]); // 3.5
-
- -

But it would be nice to be able to reuse the function that we've already created. Luckily, JavaScript lets you call a function with an arbitrary array of arguments, using the {{jsxref("Function.apply", "apply()")}} method of any function object.

- -
avg.apply(null, [2, 3, 4, 5]); // 3.5
-
- -

The second argument to apply() is the array to use as arguments; the first will be discussed later on. This emphasizes the fact that functions are objects too.

- -
-

You can achieve the same result using the spread operator in the function call.

- -

For instance: avg(...numbers)

-
- -

JavaScript lets you create anonymous functions.

- -
var avg = function() {
-  var sum = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    sum += arguments[i];
-  }
-  return sum / arguments.length;
-};
-
- -

This is semantically equivalent to the function avg() form. It's extremely powerful, as it lets you put a full function definition anywhere that you would normally put an expression. This enables all sorts of clever tricks. Here's a way of "hiding" some local variables — like block scope in C:

- -
var a = 1;
-var b = 2;
-
-(function() {
-  var b = 3;
-  a += b;
-})();
-
-a; // 4
-b; // 2
-
- -

JavaScript allows you to call functions recursively. This is particularly useful for dealing with tree structures, such as those found in the browser DOM.

- -
function countChars(elm) {
-  if (elm.nodeType == 3) { // TEXT_NODE
-    return elm.nodeValue.length;
-  }
-  var count = 0;
-  for (var i = 0, child; child = elm.childNodes[i]; i++) {
-    count += countChars(child);
-  }
-  return count;
-}
-
- -

This highlights a potential problem with anonymous functions: how do you call them recursively if they don't have a name? JavaScript lets you name function expressions for this. You can use named IIFEs (Immediately Invoked Function Expressions) as shown below:

- -
var charsInBody = (function counter(elm) {
-  if (elm.nodeType == 3) { // TEXT_NODE
-    return elm.nodeValue.length;
-  }
-  var count = 0;
-  for (var i = 0, child; child = elm.childNodes[i]; i++) {
-    count += counter(child);
-  }
-  return count;
-})(document.body);
-
- -

The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the engine and results in more readable code. The name also shows up in the debugger and some stack traces, which can save you time when debugging.

- -

Note that JavaScript functions are themselves objects — like everything else in JavaScript — and you can add or change properties on them just like we've seen earlier in the Objects section.

- -

Custom objects

- -
For a more detailed discussion of object-oriented programming in JavaScript, see Introduction to Object-Oriented JavaScript.
- -

In classic Object Oriented Programming, objects are collections of data and methods that operate on that data. JavaScript is a prototype-based language that contains no class statement, as you'd find in C++ or Java (this is sometimes confusing for programmers accustomed to languages with a class statement). Instead, JavaScript uses functions as classes. Let's consider a person object with first and last name fields. There are two ways in which the name might be displayed: as "first last" or as "last, first". Using the functions and objects that we've discussed previously, we could display the data like this:

- -
function makePerson(first, last) {
-  return {
-    first: first,
-    last: last
-  };
-}
-function personFullName(person) {
-  return person.first + ' ' + person.last;
-}
-function personFullNameReversed(person) {
-  return person.last + ', ' + person.first;
-}
-
-var s = makePerson('Simon', 'Willison');
-personFullName(s); // "Simon Willison"
-personFullNameReversed(s); // "Willison, Simon"
-
- -

This works, but it's pretty ugly. You end up with dozens of functions in your global namespace. What we really need is a way to attach a function to an object. Since functions are objects, this is easy:

- -
function makePerson(first, last) {
-  return {
-    first: first,
-    last: last,
-    fullName: function() {
-      return this.first + ' ' + this.last;
-    },
-    fullNameReversed: function() {
-      return this.last + ', ' + this.first;
-    }
-  };
-}
-
-var s = makePerson('Simon', 'Willison');
-s.fullName(); // "Simon Willison"
-s.fullNameReversed(); // "Willison, Simon"
-
- -

Note on the this keyword. Used inside a function, this refers to the current object. What that actually means is specified by the way in which you called that function. If you called it using dot notation or bracket notation on an object, that object becomes this. If dot notation wasn't used for the call, this refers to the global object.

- -

Note that this is a frequent cause of mistakes. For example:

- -
var s = makePerson('Simon', 'Willison');
-var fullName = s.fullName;
-fullName(); // undefined undefined
-
- -

When we call fullName() alone, without using s.fullName(), this is bound to the global object. Since there are no global variables called first or last we get undefined for each one.

- -

We can take advantage of the this keyword to improve our makePerson function:

- -
function Person(first, last) {
-  this.first = first;
-  this.last = last;
-  this.fullName = function() {
-    return this.first + ' ' + this.last;
-  };
-  this.fullNameReversed = function() {
-    return this.last + ', ' + this.first;
-  };
-}
-var s = new Person('Simon', 'Willison');
-
- -

We have introduced another keyword: new. new is strongly related to this. It creates a brand new empty object, and then calls the function specified, with this set to that new object. Notice though that the function specified with this does not return a value but merely modifies the this object. It's new that returns the this object to the calling site. Functions that are designed to be called by new are called constructor functions. Common practice is to capitalize these functions as a reminder to call them with new.

- -

The improved function still has the same pitfall with calling fullName() alone.

- -

Our person objects are getting better, but there are still some ugly edges to them. Every time we create a person object we are creating two brand new function objects within it — wouldn't it be better if this code was shared?

- -
function personFullName() {
-  return this.first + ' ' + this.last;
-}
-function personFullNameReversed() {
-  return this.last + ', ' + this.first;
-}
-function Person(first, last) {
-  this.first = first;
-  this.last = last;
-  this.fullName = personFullName;
-  this.fullNameReversed = personFullNameReversed;
-}
-
- -

That's better: we are creating the method functions only once, and assigning references to them inside the constructor. Can we do any better than that? The answer is yes:

- -
function Person(first, last) {
-  this.first = first;
-  this.last = last;
-}
-Person.prototype.fullName = function() {
-  return this.first + ' ' + this.last;
-};
-Person.prototype.fullNameReversed = function() {
-  return this.last + ', ' + this.first;
-};
-
- -

Person.prototype is an object shared by all instances of Person. It forms part of a lookup chain (that has a special name, "prototype chain"): any time you attempt to access a property of Person that isn't set, JavaScript will check Person.prototype to see if that property exists there instead. As a result, anything assigned to Person.prototype becomes available to all instances of that constructor via the this object.

- -

This is an incredibly powerful tool. JavaScript lets you modify something's prototype at any time in your program, which means you can add extra methods to existing objects at runtime:

- -
var s = new Person('Simon', 'Willison');
-s.firstNameCaps(); // TypeError on line 1: s.firstNameCaps is not a function
-
-Person.prototype.firstNameCaps = function() {
-  return this.first.toUpperCase();
-};
-s.firstNameCaps(); // "SIMON"
-
- -

Interestingly, you can also add things to the prototype of built-in JavaScript objects. Let's add a method to String that returns that string in reverse:

- -
var s = 'Simon';
-s.reversed(); // TypeError on line 1: s.reversed is not a function
-
-String.prototype.reversed = function() {
-  var r = '';
-  for (var i = this.length - 1; i >= 0; i--) {
-    r += this[i];
-  }
-  return r;
-};
-
-s.reversed(); // nomiS
-
- -

Our new method even works on string literals!

- -
'This can now be reversed'.reversed(); // desrever eb won nac sihT
-
- -

As mentioned before, the prototype forms part of a chain. The root of that chain is Object.prototype, whose methods include toString() — it is this method that is called when you try to represent an object as a string. This is useful for debugging our Person objects:

- -
var s = new Person('Simon', 'Willison');
-s.toString(); // [object Object]
-
-Person.prototype.toString = function() {
-  return '<Person: ' + this.fullName() + '>';
-}
-
-s.toString(); // "<Person: Simon Willison>"
-
- -

Remember how avg.apply() had a null first argument? We can revisit that now. The first argument to apply() is the object that should be treated as 'this'. For example, here's a trivial implementation of new:

- -
function trivialNew(constructor, ...args) {
-  var o = {}; // Create an object
-  constructor.apply(o, args);
-  return o;
-}
-
- -

This isn't an exact replica of new as it doesn't set up the prototype chain (it would be difficult to illustrate). This is not something you use very often, but it's useful to know about. In this snippet, ...args (including the ellipsis) is called the "rest arguments" — as the name implies, this contains the rest of the arguments.

- -

Calling

- -
var bill = trivialNew(Person, 'William', 'Orange');
- -

is therefore almost equivalent to

- -
var bill = new Person('William', 'Orange');
- -

apply() has a sister function named call, which again lets you set this but takes an expanded argument list as opposed to an array.

- -
function lastNameCaps() {
-  return this.last.toUpperCase();
-}
-var s = new Person('Simon', 'Willison');
-lastNameCaps.call(s);
-// Is the same as:
-s.lastNameCaps = lastNameCaps;
-s.lastNameCaps(); // WILLISON
-
- -

Inner functions

- -

JavaScript function declarations are allowed inside other functions. We've seen this once before, with an earlier makePerson() function. An important detail of nested functions in JavaScript is that they can access variables in their parent function's scope:

- -
function parentFunc() {
-  var a = 1;
-
-  function nestedFunc() {
-    var b = 4; // parentFunc can't use this
-    return a + b;
-  }
-  return nestedFunc(); // 5
-}
-
- -

This provides a great deal of utility in writing more maintainable code. If a called function relies on one or two other functions that are not useful to any other part of your code, you can nest those utility functions inside it. This keeps the number of functions that are in the global scope down, which is always a good thing.

- -

This is also a great counter to the lure of global variables. When writing complex code it is often tempting to use global variables to share values between multiple functions — which leads to code that is hard to maintain. Nested functions can share variables in their parent, so you can use that mechanism to couple functions together when it makes sense without polluting your global namespace — "local globals" if you like. This technique should be used with caution, but it's a useful ability to have.

- -

Closures

- -

This leads us to one of the most powerful abstractions that JavaScript has to offer — but also the most potentially confusing. What does this do?

- -
function makeAdder(a) {
-  return function(b) {
-    return a + b;
-  };
-}
-var add5 = makeAdder(5);
-var add20 = makeAdder(20);
-add5(6); // ?
-add20(7); // ?
-
- -

The name of the makeAdder() function should give it away: it creates new 'adder' functions, each of which, when called with one argument, adds it to the argument that it was created with.

- -

What's happening here is pretty much the same as was happening with the inner functions earlier on: a function defined inside another function has access to the outer function's variables. The only difference here is that the outer function has returned, and hence common sense would seem to dictate that its local variables no longer exist. But they do still exist — otherwise, the adder functions would be unable to work. What's more, there are two different "copies" of makeAdder()'s local variables — one in which a is 5 and the other one where a is 20. So the result of that function calls is as follows:

- -
add5(6); // returns 11
-add20(7); // returns 27
-
- -

Here's what's actually happening. Whenever JavaScript executes a function, a 'scope' object is created to hold the local variables created within that function. It is initialized with any variables passed in as function parameters. This is similar to the global object that all global variables and functions live in, but with a couple of important differences: firstly, a brand new scope object is created every time a function starts executing, and secondly, unlike the global object (which is accessible as this and in browsers as window) these scope objects cannot be directly accessed from your JavaScript code. There is no mechanism for iterating over the properties of the current scope object, for example.

- -

So when makeAdder() is called, a scope object is created with one property: a, which is the argument passed to the makeAdder() function. makeAdder() then returns a newly created function. Normally JavaScript's garbage collector would clean up the scope object created for makeAdder() at this point, but the returned function maintains a reference back to that scope object. As a result, the scope object will not be garbage-collected until there are no more references to the function object that makeAdder() returned.

- -

Scope objects form a chain called the scope chain, similar to the prototype chain used by JavaScript's object system.

- -

A closure is the combination of a function and the scope object in which it was created. Closures let you save state — as such, they can often be used in place of objects. You can find several excellent introductions to closures.

- -
-
-
diff --git a/files/vi/web/javascript/closures/index.html b/files/vi/web/javascript/closures/index.html deleted file mode 100644 index c2168a9593..0000000000 --- a/files/vi/web/javascript/closures/index.html +++ /dev/null @@ -1,452 +0,0 @@ ---- -title: Closures -slug: Web/JavaScript/Closures -translation_of: Web/JavaScript/Closures ---- -
{{jsSidebar("Intermediate")}}
- -

Closure là một hàm được viết lồng vào bên trong một hàm khác (hàm cha) nó có thể sử dụng biến toàn cục, biến cục bộ của hàm cha và biến cục bộ của chính nó (lexical scoping)

- -

Lexical scoping

- -

Xem xét ví dụ sau

- -
-
function init() {
-  var name = 'Mozilla'; // name là biến cục bộ của hàm init
-  function displayName() { // displayName() là hàm closure
-    alert(name); // sử dụng biến của hàm cha
-  }
-  displayName();
-}
-init();
-
- -

init() tạo một biến cục bộ name và một hàm displayName(). Hàm displayName() được khai báo bên trong hàm init() và chỉ tồn tại bên trong hàm  init() . Hàm displayName() không có biến cục bộ nào của chính nó. Tuy nhiên, hàm displayName() truy cập đến biến name vốn được định nghĩa ở hàm cha, init(). Nếu bên trong hàm displayName() có khai báo biến cục bộ của chính nó, biến đó sẽ được sử dụng.

- -

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

- -

Thực thi đoạn code trên sẽ nhận được kết quả từ alert() bên trong hàm displayName() , giá trị biến name . Đây là một ví dụ của lexical scoping,  cách các biến được truy cập như thế nào khi hàm được lồng nhau. Hàm lồng bên trong có thể truy suất đến biến được khai bào từ hàm bên ngoài.

- -

Closure

- -

Giờ xem xét đến ví dụ sau:

- -
function makeFunc() {
-  var name = 'Mozilla';
-  function displayName() {
-    alert(name);
-  }
-  return displayName;
-}
-
-var myFunc = makeFunc();
-myFunc();
-
- -

Chạy đoạn code trên sẽ nhận kết quả tương tự như ví dụ hàm init() ở trên; sự khác nhau ở đây là gì? khi gọi hàm makeFunc() sẽ return về hàm displayName() ,  và chưa hề chạy qua đoạn code trong hàm displayName().

- -

Thoạt nhìn, đoạn code này sẽ không dễ nhận ra đoạn code này vẫn chạy bình thường. Trong một số ngôn ngữ lập trình khác, biến cục bộ bên trong một hàm chỉ tồn tại trong quá trình hàm thực thi. Một khi makeFunc() chạy xong, chúng ta sẽ nghĩ rằng biến name sẽ không còn thể truy cập được. Tuy nhiên, đoạn code trên sẽ vẫn cho ra kết quả không khác gì ví dụ ở trên cùng, rõ ràng đây là một tính chất đặc biệt của Javascript.

- -

Trong trường hợp này, myFunc đang tham chiếu đến một instance displayName được tạo ra khi chạy makeFunc. Instance của displayName sẽ duy trì lexical environment, biến name sẽ vẫn tồn tại. Với lý do này, khi gọi hàm myFunc , giá trị biến name vẫn có và chuỗi "Mozilla" sẽ được đưa vào hàm alert.

- -

Một ví dụ thú vị khác — hàm makeAdder:

- -
function makeAdder(x) {
-  return function(y) {
-    return x + y;
-  };
-}
-
-var add5 = makeAdder(5);
-var add10 = makeAdder(10);
-
-console.log(add5(2));  // 7
-console.log(add10(2)); // 12
-
- -

Trong ví dụ này, chúng ta định nghĩa hàm makeAdder(x), nhận vào 1 argument, x, và trả về một hàm khác. Hàm trả về nhận vào 1 argument, y, và trả về kết của của x + y.

- -

Bản chất, makeAdder là một hàm factory — nó tạo ra một hàm khác nhận một argument. Ví dụ trên chúng ta sử dụng hàm factory để tạo ra 2 functions — cái thứ nhất thêm argument là 5, cái thứ 2 thêm 10.

- -

add5 và add10 đều  là closures. Cùng một xử lý bên trong, nhưng được lưu ở  lexical environments khác nhau. Trong lexical environment của add5 , x = 5, trong khi lexical environment của add10, x = 10.

- -

Ứng dụng closures

- -

Closures hữu dụng vì nó cho phép chúng ta gắn một vài dữ liệu (bên trong lexical environment) với một function sẽ tương tác với dữ liệu. Tương tự như trong object-oriented programming, các object cho phép chúng ta gắn một vài dữ liệu với một hoặc nhiều phương thức bên trong

- -

Trên nền web, hầu hết code được viết bằng JavaScript là event-based — chúng ta định nghĩa một xử lý, sau đó gắn nó vào event sẽ được gọi bởi user (ví dụ như click hay keypress). Đoạn code của chúng ta sẽ là callback: 1 function chạy khi có một sự kiện xảy ra.

- -

Ví dụ, giả sử chúng ta muốn thêm một cái button để thay đổi kích thước chữ. Một trong những cách làm là set font-size cho thẻ body bằng giá trị pixels, sau đó set kích thước của những phần từ khác (như header) sử dụng đơn vị em :

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

Khi thay đổi font-size của thẻ body , kích thước font của h1, h2 sẽ tự động được điều chỉnh.

- -

Trong JavaScript:

- -
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, và size16 là những hàm sẽ thay đổi kích thước font chữ của body qua 12, 14, và 16 pixels. Gắn cho các button tương ứng:

- -
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/7726/","","200")}}

- -

Giả lập phương thức private với closures

- -

Những ngôn ngữ như Java chúng ta có cách để khai báo các phương thức private, nghĩa là phương thức chỉ được gọi bởi các phương thức khác nằm cùng class.

- -

JavaScript không hỗ trợ cách làm chính quy cho việc này, tuy nhiên có thể giả lập việc này bằng closures. Phương thức Private không chỉ hữu dụng trong việc giới hạn việc truy cập: nó còn là một cách rất tốt để quản lý global namespace, giữ các phương thức không cần thiết có thể làm xáo trộn những phương thức public.

- -

Đoạn code bên dưới diễn giải cách sử dụng closures để khai báo một phương thức public có thể truy cập phương thức private và biến. Sử dụng closures như thế này gọi là module pattern:

- -
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
-
- -

Mỗi closure có một lexical environment. Ở đây, chúng ta tạo 1 lexical environment cho cả 3 function: counter.increment, counter.decrement, and counter.value.

- -

Lexical environment được tạo bên trong một hàm không tên function, sẽ được tạo ra ngay khi được gán cho một khai báo. Lexical environment chứa 2 private: biến  privateCounter và hàm changeBy. Cả 2 đối tượng private đều không thể được truy cập trực tiếp từ bên ngoài. Thay vào đó, nó chỉ có thể tương tác thông qua 3 phương thức public.

- -

Cả 3 phương thức public đều là closures chia sẽ cùng 1 Lexical environment. Cả 3 đều có thể truy cập đến privateCounter và changeBy

- -
-

Chúng ta khai báo một  hàm không tên tạo counter, và gọi nó ngay lập tức rồi gắn vào biến counter . Chúng ta lưu hàm này vào một biến khác makeCounter và sử dụng nó để tạo ra nhiều counter khác

-
- -
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()); /* Alerts 0 */
-counter1.increment();
-counter1.increment();
-alert(counter1.value()); /* Alerts 2 */
-counter1.decrement();
-alert(counter1.value()); /* Alerts 1 */
-alert(counter2.value()); /* Alerts 0 */
-
- -

Để ý cách 2 counters, counter1 và counter2, hoàn toàn độc lập với nhau. Mỗi closure tham chiếu đến các instance khác nhau của privateCounter .

- -
-

Sử dụng closures bằng cách này cho ta rất nhiều ưu điểm như trong object-oriented programming -- cụ thể, dữ liệu được ẩn đi và đóng gói.

-
- -

Closure Scope Chain

- -

Mỗi closure chúng ta có 3 scopes:-

- -
    -
  • Scope cục bộ
  • -
  • Scope của function chứa closure
  • -
  • Scope global
  • -
- -

Chúng ta có thể truy cập đến cả 3 scope này trong closure tuy nhiên sẽ ra sau nếu chúng lồng nhiều closure với nhau. Như ví dụ sau:

- -
// 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
-
-// chúng ta có thể không dùng hàm không tên:
-
-// 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
-
- -

Với ví dụ trên, chúng ta có thể nói toàn bộ closure sẽ có cùng scope với function cha.

- -

Tạo closures trong vòng lặp: lỗi thường thấy

- -

Trước khi có từ khóa let keyword được giới thiệu trong ECMAScript 2015, một lỗi thường gặp trong closure khi nó được tạo bên trong vòng lặp. Xem ví dụ sau:

- -
<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/8164/", "", 200)}}

- -

Mảng helpText khai báo 3 string help, tương ứng cho mỗi ID của input. Vòng lặp chạy qua cả 3 khai báo này, chèn vào sự kiện onfocus để hiển thị đoạn string phù hợp với từng input.

- -

Nếu thử chạy đoạn code này, bạn sẽ thấy kết quả không giống như chúng ta nghĩ. Mặc cho chúng ta đang focus vào input nào, dòng message hiển thị sẽ luôn là "Your age (you must be over 16)".

- -

Lý do là hàm gắn cho sự kiện onfocus là closures; nó sẽ thống nhất các khai báo trong và đưa vào chung scope của hàm setupHelp. Cả 3 closures được tạo trong vòng lặp, nhưng cùng chung lexical environment, tức là dùng chung biến item.help. Giá trị item.help được xác định khi onfocus được gọi. Vì ở đây vòng lặp đã chạy đến giá trị cuối cùng của mảng, biến item sẽ trỏ đến giá trị cuối cùng trong mảng.

- -

Giải pháp trong tình huống này là dùng thêm một closures: như cách chúng ta viết function factory trước đó:

- -
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/9573/", "", 300)}}

- -

Hàm makeHelpCallback đã tạo ra một lexical environment riêng cho mỗi callback.

- -

Một cách khác là sử dụng closure không tên

- -
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();
- -

Nếu không muốn sử dụng nhiều closure, có thể dùng từ khóa let được giới thiệu trong ES2015 :

- -
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();
- -

Ví dụ này ta sử dụng let thay cho var, như thế mỗi closure được gán cho 1 biến block-scoped.

- -

Một cách khác nữa là dùng forEach() để lặp qua mảng helpText và gắn hàm xử lý {{htmlelement("div")}}, như bên dưới:

- -
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)'}
-    ];
-
-  helpText.forEach(function(text) {
-    document.getElementById(text.id).onfocus = function() {
-      showHelp(text.help);
-    }
-  });
-}
-
-setupHelp();
- -

Cân nhắc về hiệu năng

- -

Dùng closure trong những trường hợp thực sự không cần thiết thì không khôn ngoan vì nó có thể ảnh hưởng hiệu năng lúc chạy.

- -

Một ví dụ, khi tạo mới một object/class, phương thức thường nên gán vào object mà không nên khai báo bên trong hàm khởi tạo của object. Lý do là mỗi khi hàm constructor được gọi, phương thức sẽ được gán lại một lần nữa trên mỗi một object được tạo ra

- -

Ví dụ cho trường hợp sau:

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

Bởi vì đoạn code trên không thực sự cần những lợi ích có được từ closure trên mỗi instance, chúng ta có thể viết lại mà không sử dụng closure:

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

Tuy nhiên, khai báo lại prototype không được khuyến khích. Chúng ta mở rộng prototype bằng cách sau:

- -
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;
-};
-
- -

Trong 2 ví dụ trên, tất cả object sẽ kế thừa cùng những prototype và khai báo phương thức trên mỗi object không bắt buộc. Xem Details of the Object Model để tìm hiểu thêm

diff --git a/files/vi/web/javascript/data_structures/index.html b/files/vi/web/javascript/data_structures/index.html deleted file mode 100644 index cbf63cdadf..0000000000 --- a/files/vi/web/javascript/data_structures/index.html +++ /dev/null @@ -1,285 +0,0 @@ ---- -title: Kiểu dữ liệu và cấu trúc dữ liệu trong Javascript -slug: Web/JavaScript/Data_structures -translation_of: Web/JavaScript/Data_structures ---- -
{{jsSidebar("More")}}
- -

Tất cả các ngôn ngữ lập trình đều có cấu trúc dữ liệu dựng sẵn, nhưng mỗi ngôn ngữ thường có những kiểu cấu trúc dữ liệu khác nhau. Bài viết này sẽ cố gắng liệt kê những kiểu dữ liệu dựng sẵn trong Javascript và những thuộc tính của chúng. Chúng có thể được dùng để xây dựng những kiểu cấu trúc dữ liệu khác. Khi có thể, rút ra so sánh với những ngôn ngữ khác.

- -

Kiểu động

- -

JavaScript là một ngôn ngữ định kiểu yếu hay động. Điều đó nghĩa là không cần phải khai báo kiểu của các biến trước khi dùng. Kiểu sẽ được xác định tự động trong khi chương trình được thực thi. Điều đó cũng có nghĩa là một biến có thể chứa giá trị của các kiểu dữ liệu khác nhau:

- -
let foo = 42;    // foo là một số
-foo     = 'bar'; // foo bây giờ là một chuỗi
-foo     = true;  // foo bây giờ là một boolean
-
- -

Các kiểu Dữ liệu và kiểu Cấu trúc

- -

Tiêu chuẩn ECMAScript mới nhất xác định chín kiểu:

- -
    -
  • Sáu kiểu Dữ liệu {{Glossary("Primitive", "sơ khai")}} (primitive), có thể kiểm tra với toán tử typeof: - -
      -
    • {{Glossary("Undefined", "Kiểu undefined")}}: typeof instance === "undefined"
    • -
    • {{Glossary("Boolean", "Kiểu Boolean")}}: typeof instance === "boolean"
    • -
    • {{Glossary("Number", "Kiểu số")}}: typeof instance === "number"
    • -
    • {{Glossary("String", "Kiểu chuỗi")}}: typeof instance === "string"
    • -
    • {{Glossary("BigInt", "Kiểu số BigInt")}}: typeof instance === "bigint"
    • -
    • {{Glossary("Symbol", "Kiểu Symbol")}}: typeof instance === "symbol"
    • -
    -
  • -
  • {{Glossary("null", "Kiểu null")}}: typeof instance === "object". Một kiểu {{Glossary("Primitive", "sơ khai")}} mà giá trị của nó có thêm một vai trò đặc biệt: nếu object không kế thừa từ đối tượng nào khác, null sẽ được hiển thị ở cuối chuỗi Prototype
  • -
  • {{Glossary("Object", "Object")}}: typeof instance === "object". Kiểu phi dữ liệu nhưng có cấu trúc cho các đối tượng được khởi tạo và được dùng như cấu trúc dữ liệu: new Object, new Array, new Map, new Set, new WeakMap, new WeakSet, new Date hay bất kỳ đối tượng nào được tạo ra với từ khóa new.
  • -
  • Kiểu phi dữ liệu {{Glossary("Function", "Function")}}, mặc dù khi gọi với typeof nó có nhãn riêng: typeof instance === "function". Giá trị trả về từ typeof này là một nhãn đặc biệt cho các function, cho dù constructor của Function phát sinh từ Object constructor.
  • -
- -

Lưu ý: vai trò có giá trị duy nhất của toán tử typeof là dùng để kiểm tra các kiểu Dữ liệu (sơ khai). Nếu bạn muốn kiểm tra các kiểu Cấu trúc phát sinh từ Object, typeof sẽ chẳng có ích gì vì nó sẽ luôn trả về "object". Cách đúng đắn để kiểm tra một Object thuộc loại nào là dùng từ khóa instanceof. Tuy nhiên, ngay cả với cách này cũng có một vài ngoại lệ.

- -

Giá trị sơ khai

- -

Tất cả các kiểu trừ đối tượng đều được xác định giá trị bất biến (giá trị không có khả năng thay đổi). Ví dụ (và không như ngôn ngữ C), các chuỗi là bất biến. Ta gọi chúng là "giá trị sơ khai" ("primitive").

- -

Kiểu boolean

- -

Kiểu boolean mang hai giá trị logic là: true, và false. Xem thêm {{Glossary("Boolean")}} và {{jsxref("Boolean")}}.

- -

Kiểu null

- -

Có duy nhất một giá trị: null. Xem {{jsxref("null")}} và {{Glossary("Null")}} để biết thêm chi tiết.

- -

Kiểu undefined

- -

Một biến chưa được gán giá trị có giá trị undefined. Xem {{jsxref("undefined")}} và {{Glossary("Undefined")}} để biết thêm chi tiết.

- -

Kiểu số Number

- -

Theo tiêu chuẩn ECMAScript, chỉ có duy nhất một kiểu số: the double-precision 64-bit binary format IEEE 754 value (có giá trị từ -(253 -1) đến 253 -1). Không có kiểu số nguyên. Ngoài việc có thể chứa giá trị dấu phẩy động, kiểu số có ba giá trị biểu tượng: +Infinity, -Infinity, and NaN (not-a-number).

- -

Để kiểm tra lớn hơn hay nhỏ hơn +/-Infinity, bạn có thể xem {{jsxref("Number.MAX_VALUE")}} hoặc {{jsxref("Number.MIN_VALUE")}} và bất đầu từ ECMAScript 6, bạn cũng có thể kiểm tra một số có nằm trong khoảng double-precision floating-point bằng cách dùng {{jsxref("Number.isSafeInteger()")}} cũng như {{jsxref("Number.MAX_SAFE_INTEGER")}} và {{jsxref("Number.MIN_SAFE_INTEGER")}}. Ngoài phạm vi này, một số trong Javascript không còn an toàn nữa.

- -

Có một số nguyên duy nhất có hai đại diện: 0 được đại diện bởi -0 và +0. ("0" là một bí danh của +0). Trong thực tế, điều này hầu như không có tác động. Ví dụ +0 === -0 là true. Tuy nhiên, có thể nhân thấy điều này khi chia một số cho không:

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

Mặc dù một số thường chỉ đại diện cho giá trị của nó, JavaScript cung cấp một vài toán tử nhị phân. Chúng có thể được sử dụng như một chuỗi boolean bằng cách dùng bit masking. Điều này thường được xem như là một cách tệ, tuy nhiên, JavaScript không cung cấp bất kỳ phương tiện nào khác để trình bày một tập hợp các boolean (như một mảng các boolean hay một đối tượng với các thuộc tính boolean). Bit masking cũng có xu hướng làm mã khó đọc, hiểu, và duy trì hơn. Nó có thể cấn thiết trong một môi trường rất hạn chế, giống như khi cố gắng để đối phó với hạn chế lưu trữ lưu trữ cục bộ hoặc trong trường hợp nặng khi mỗi chút so với đếm mạng. Kỹ thuật này chỉ nên được xem xét khi nó là biện pháp cuối cùng có thể được thực hiện để tối ưu hóa kích thước.

- -

Kiểu số BigInt

- -

Kiểu {{jsxref("BigInt")}} là một kiểu giá trị số sơ khai trong JavaScript, đại diện cho các giá trị số nguyên với độ chính xác (precision) bất kỳ. Với BigInt, bạn có thể lưu và tính toán trên các số nguyên lớn mà nó có thể lớn hơn cả giới hạn an toàn của kiểu Number.

- -

Một số BigInt được tạo ra bằng cách thêm n vào cuối giá trị literal số nguyên hoặc bằng cách sử dụng constructor.

- -

Bạn có thể lấy giá trị nguyên an toàn lớn nhất của kiểu Number bằng cách sử dụng constant {{jsxref("Number.MAX_SAFE_INTEGER")}}. Với sự ra đời của kiểu BigInt, giờ đây bạn có thể tính toán với những con số còn lớn hơn {{jsxref("Number.MAX_SAFE_INTEGER")}}.

- -

Trong ví dụ sau, khi tăng dần giá trị {{jsxref("Number.MAX_SAFE_INTEGER")}}, bạn vẫn nhận được kết qua như mong muốn với BigInt:

- -
> const x = 2n ** 53n;
-9007199254740992n
-> const y = x + 1n;
-9007199254740993n
- -

Bạn có thể sử dụng các toán tử +, *, -, **, và % với BigInt như với Number. Một số BigInt không hoàn toàn bằng (===) một số Number, nhưng có thể bằng khi ép kiểu (==).

- -

Số BigInt hành xử giống với Number khi được chuyển đổi kiểu về Boolean: if, ||, &&, Boolean, !.

- -

Số BigInt không thể dùng chung với số Number để tính toán. Khi đó, lỗi {{jsxref("TypeError")}} sẽ xảy ra.

- -

Kiểu chuỗi

- -

Kiểu {{jsxref("Global_Objects/String", "chuỗi")}} được dùng để biểu diễn dữ liệu dạng văn bản. Nó là một dãy "các phần tử" số nguyên 16-bit. Mỗi phần tử có một vị trí trong chuỗi. Phần tử đầu tiên có chỉ số 0, tiếp theo là 1, ... . Độ dài của chuỗi là số phần tử của nó.

- -

Không giống với những ngôn ngữ như C, Chuỗi trong Javascript là bất biến. Nghĩa là một khi chuỗi được tạo thì không thể chỉnh sửa. Tuy nhiên, vẫn có thể tạo một chuỗi mới dựa vào các thao tác trên chuỗi cũ. Ví dụ:

- -
    -
  • Tạo một chuỗi con của chuỗi ban đầu bằng cách ghép từng ký tự hoặc dùng {{jsxref("String.substr()")}}.
  • -
  • Nối hai chuỗi bằng toán tử (+) hoặc hàm {{jsxref("String.concat()")}}.
  • -
- -

Cẩn thận với việc "lưu mọi thứ bằng chuỗi" trong code của bạn!

- -

Chuỗi có thể được dùng để biểu diễn dữ liệu với cấu trúc phức tạp. Điều này mang tới một vài lợi ích ngắn hạn:

- -
    -
  • Rất dễ để xây dựng một chuỗi bằng phép nối.
  • -
  • Dễ debug (những gì bạn thấy khi in luôn là tất cả những thứ có trong chuỗi).
  • -
  • Chuỗi là mẫu số chung của rất nhiều API (nhập, local storage values, {{ domxref("XMLHttpRequest") }} phản hồi khi dùng responseText, ...) và điều này có thể khiến việc chỉ làm việc với chuỗi được yêu thích.
  • -
- -

Chuỗi có thể biểu diễn bất kì kiểu dữ liệu nào. Những đây không được xem là một ý hay. Ví dụ, đối với một separator, có thể bắt trước một chuỗi (trong khi một mảng sẽ thích hợp hơn). Thật không may, khi separator được dùng trong một "danh sách" các phần tử, danh sách bị hỏng. Một escape character có thể được chọn, ..... Tất cả những điều này yêu cầu một quy ước và tạo ra gánh nặng bảo trì không cần thiết.

- -

Chỉ nên dùng chuỗi để lưu trữ dữ liệu văn bản. Khi biểu diễn một cấu trúc phức tạp, phân tích chuỗi thành các cấu trúc dữ liệu với mức trừu tưỡng cao hơn.

- -

Kiểu Symbol

- -

Kiểu Symbol là một kiểu mới trong Javascript tiêu chuẩn ECMAScript 6. Mỗi Symbol là một giá trị sơ khai đơn nhất và bất biến và có thể được dùng như một khóa của một Object (xem bên dưới). Trên một số ngôn ngữ lập trình, Symbol còn được gọi là "atom" (nguyên tử). Ta cũng có thể so sánh với các enumeration (enum) trong C. Xem {{Glossary("Symbol")}} và {{jsxref("Symbol")}} để biết thêm chi tiết.

- -

Đối tượng

- -

Trong khoa học máy tính, một đối tượng là một giá trị trong bộ nhớ được tham chiếu bởi một {{Glossary("Identifier", "định danh")}}.

- -

Thuộc tính

- -

Trong Javascript, đối tượng có thể được xem là tập hợp các thuộc tính. Với object literal syntax, một tập hợp hữu hạn các thuộc tính được khởi tạo; sau đó thuộc tính có thể được thêm hoặc loại bỏ. Giá trị thuộc tính thuộc bất kỳ kiểu dữ liệu, bao gồm những đối tượng khác (kể cả chính đối tượng đó), điều này cho phép xây những những cấu trúc dữ liệu phức tạp. Thuộc định được định danh bằng khóa. Một khóa phải là một chuỗi hoặc một Symbol.

- -

Có hai loại thuộc tính với các đặc điểm nhất định: Chứa dữ liệu và accessor.

- -

Thuộc tính chứa dữ liệu

- -

Liên kết một khóa với một giá trị có các đặc điểm sau:

- -

Các đặc điểm của thuộc tính chứa dữ liệu

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc điểmKiểuMô tảGiá trị mặc định
[[Value]]Bất kỳGiá trị của thuộc tính.undefined
[[Writable]]BooleanNếu là false, thuộc tính [[Value]] không thể thay đổi.false
[[Enumerable]]BooleanNếu là true, khóa của giá trị có thể được liệt kê bằng vòng lặp for...in.false
[[Configurable]]BooleanNếu là false, thuộc tính không thể bị xóa cũng như không thể thay đổi các đặc điểm của nó.false
- -

Accessor

- -

Liên kết một khóa với một hoặc hai hàm accessor (get và/hoặc set):

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Attributes of an accessor property
Đặc điểmLoạiMô tảGiá trị mặc định
[[Get]]Hàm hoặc undefinedHàm được gọi không đối số và trả về giá trị mỗi khi có truy cập tới thuộc tính. Xem get.undefined
[[Set]]Hàm hoặc undefinedHàm được gọi với một đối số mỗi khi thuộc tính được gán một giá trị. Xem set.undefined
[[Enumerable]]BooleanNếu là true, khóa của giá trị có thể được liệt kê bằng vòng lặp for...in.false
[[Configurable]]BooleanNếu là false, thuộc tính không thể bị xóa cũng như không thể thay đổi các đặc điểm của nó.false
- -

Đối tượng "thông thường" và hàm

- -

Mội đối tượng là một bảng các khóa và giá trị. Khóa là một chuỗi và giá trị có thể là bất kỳ thứ gì. Điều này khiến đối tượng phù hợp với hashmaps.

- -

Hàm là một đối tượng với khả năng có thể gọi.

- -

Đối tượng Date

- -

Để biểu diễn một thời điểm hay ngày tháng, Lựa chọn tốt nhất là sử dụng Date.

- -

Tập hợp có thứ tự: Mảng và mảng đã định kiểu

- -

Mảng là một đối tượng có một quan hệ đặc biệt giữa các thuộc tính có khóa nguyên và thuộc tính 'length'. Thêm vào đó, mảng thừa kế các thuộc tính của Array.prototype cung cấp một số ít các hàm xeur lý danh sách. Ví dụ, indexOf (tìm giá trị trên một mảng) hay push (thêm một phần tử vào cuối danh sach), .... Điều này biến mảng trở thành ứng cử viên hoàn hào cho danh sách hoặc tập hợp.

- -

Mảng đã định kiểu là loại mới trong ECMAScript 6 và biểu diễn dữ liệu nhị phân như một mảng. Bảng sau đây giúp bạn so sánh với kiểu dữ liệu trong C:

- -

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

- -

Keyed collections: Maps, Sets, WeakMaps, WeakSets

- -

These data structures take object references as keys and are introduced in ECMAScript Edition 6. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

- -

One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of "less than" for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.

- -

Usually, to bind data to a DOM node, one could set properties directly on the object or use data-* attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.

- -

Structured data: JSON

- -

JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See {{Glossary("JSON")}} and {{jsxref("JSON")}} for more details.

- -

More objects in the standard library

- -

JavaScript has a standard library of built-in objects. Please have a look at the reference to find out about more objects.

- -

Determining types using the typeof operator

- -

The typeof operator can help you to find the type of your variable. Please read the reference page for more details and edge cases.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-8', 'Types')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ES6')}}
- -

See also

- - diff --git a/files/vi/web/javascript/guide/control_flow_and_error_handling/index.html b/files/vi/web/javascript/guide/control_flow_and_error_handling/index.html deleted file mode 100644 index 55931e4a1f..0000000000 --- a/files/vi/web/javascript/guide/control_flow_and_error_handling/index.html +++ /dev/null @@ -1,405 +0,0 @@ ---- -title: Control flow and error handling -slug: Web/JavaScript/Guide/Control_flow_and_error_handling -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 hỗ trợ một tập hợp lệnh gọn nhẹ, các lệnh điều khiển luồng chuyên biệt, mà khi kết hợp lại có thể tăng tính tương tác cho ứng dụng của bạn lên đáng kể. Chương này giới thiệu sơ qua về các lệnh này.

- -

Mục JavaScript reference chứa các chi tiết đầy đủ về các câu lệnh trong chương này. Dấu chấm phẩy (;) được dùng để ngăn cách giữa các lệnh trong code JavaScript.

- -

Bât cứ một biểu thức JavaScript nào cũng đều là một câu lệnh. Xem Expressions and operators để biết thông tin đầy đủ về các biểu thức.

- -

Block statement

- -

Một trong những lệnh căn bản nhất là khối lệnh (block statement), được dùng để nhóm lại các câu lệnh. Khối lệnh được phân định bởi cặp dấu ngoặc nhọn:

- -
{
-  lệnh_1;
-  lệnh_2;
-  .
-  .
-  .
-  lệnh_n;
-}
-
- -

Ví dụ

- -

Khối lệnh thường được dùng với lệnh điều khiển luồng (như là if, for, while).

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

Ở đây, { x++; } là một khối lệnh.

- -

Quan trọng: Trước ECMAScript2015 (phiên bản thứ 6), JavaScript chưa có phạm vi khối (block-scope). Trong phiên bản JavaScript cũ hơn, biến được khai báo trong khối được đặt phạm vi theo hàm hoặc đoạn mã bao bọc khối đó, và ảnh hưởng của việc thiết lập chúng sẽ vượt ra khỏi phạm vi của khối. Nói cách khác, khối lệnh không định nghĩa phạm vi. Các khối độc lập ("standalone" - tức là đi kèm với lệnh điều khiển nào) trong JavaScript có thể sản sinh kết quả khác so với khối lệnh tương tự trong Java hay C. Chẳng hạn:

- -
var x = 1;
-{
-  var x = 2;
-}
-console.log(x); // trả về 2
-
- -

Đoạn mã này trả về 2 bởi vì câu lệnh var x bên trong khối có cùng phạm vi với câu lệnh var x trước khối. Trong C hoặc Java, đoạn mã này sẽ trả về 1.

- -

Kể từ ECMAScript2015, hai kiểu khai báo biến mới là letconst đều được đặt trong phạm vi khối lệnh. Tham khảo {{jsxref("Statements/let", "let")}} và {{jsxref("Statements/const", "const")}} để biết thêm chi tiết.

- -

Lệnh điều kiện

- -

Lệnh điều kiện là tập hợp các dòng lệnh sẽ thực thi nếu một điều kiện nhất định trả về true. JavaScript hỗ trợ hai lệnh điều kiện: if...elseswitch.

- -

Lệnh if...else

- -

Dùng mệnh đề if để thực thi lệnh nếu điều kiện trả về true. Có thể dùng thêm mệnh đề else để thực thi lệnh nếu điều kiện trả về false. Lệnh if trông như sau:

- -
if (điều_kiện) {
-  lệnh_1;
-} else {
-  lệnh_2;
-}
- -

Ở đây, điều_kiện có thể là bất cứ biểu thức nào để đánh giá true hoặc false. Xem Boolean để hiểu cách thức trả về truefalse. Nếu điều_kiện trả về true, lệnh_1 sẽ được thực thi; trái lại, lệnh_2 sẽ được thực thi. lệnh_1lệnh_2 có thể là bất cứ câu lệnh nào, bao gồm các câu lệnh if lồng nhau.

- -

Bạn cũng có thể dùng lệnh else if để có một dãy điều kiện liên tiếp nhau, chẳng hạn như sau:

- -
if (điều_kiện_1) {
-  lệnh_1;
-} else if (điều_kiện_2) {
-  lệnh_2;
-} else if (điều_kiện_n) {
-  lệnh_n;
-} else {
-  lệnh_cuối;
-}
-
- -

Trong trường hợp có nhiều điều kiện, chỉ thực thi các lệnh trong điều kiện đầu tiên trả về true. Để thực thi nhiều lệnh cùng lúc, hãy nhóm chúng lại trong một khối lệnh ({ ... }) . Nói tóm lại, ta luôn nên dùng khối lệnh, nhất là khi lồng trong câu lệnh if:

- -
if (điều_kiện) {
-  lệnh_1_nếu_điều_kiện_là_true;
-  lệnh_2_nếu_điều_kiện_là_true;
-} else {
-  lệnh_3_nếu_điều_kiện_là_false;
-  lệnh_4_nếu_điều_kiện_là_false;
-}
-
- -
Đừng dùng lệnh gán trong biểu thức điều kiện, bởi vì lệnh gán có thể bị hiểu lầm với so sánh ngang bằng nếu xem sơ qua đoạn code. Chẳng hạn, đừng viết như sau:
- -
// Dễ bị hiểu lầm là "x == y" trong khi ở bên dưới là gán giá trị y cho x
-if (x = y) {
-  /* tập hợp các câu lệnh */
-}
-
- -

Nếu cần phải gán trong biểu thức điều kiện, hãy bọc chúng lại trong cặp dấu ngoặc tròn, chẳng hạn:

- -
if ((x = y)) {
-  /* tập hợp các câu lệnh */
-}
-
- -

Giá trị Falsy

- -

Các giá trị sau sẽ trả về false (còn được gọi là giá trị {{Glossary("Falsy")}}):

- -
    -
  • false
  • -
  • undefined
  • -
  • null
  • -
  • 0
  • -
  • NaN
  • -
  • Chuỗi rỗng ("")
  • -
- -

Mọi giá trị khác, bao gồm tất cả object, trả về true khi được truyền vào câu lệnh điều kiện.

- -

Chú ý: Đừng nhầm lẫn giữa giá trị Boolean sơ khai truefalse với giá trị true và false của object {{jsxref("Boolean")}}. Chẳng hạn:

- -
var b = new Boolean(false);
-if (b) // điều kiện này trả về true
-if (b == true) // điều kiện này trả về false
-
- -

Ví dụ

- -

Trong ví dụ sau, hàm checkData trả về true nếu số lượng ký tự của object Text là 3; trái lại, một thông báo sẽ hiện ra và hàm sẽ trả về 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;
-  }
-}
-
- -

Lệnh switch

- -

Lệnh switch cho phép một chương trình đánh giá một biểu thức và nổ lực thử nghiệm dần để tìm ra trường hợp giống nhau giữa giá trị của biểu thức đó với case label. Nếu một sự kết hợp được tìm thấy, chương trình sẽ chạy câu lệnh liên quan. Câu lệnh switch như sau:

- -
switch (expression) {
-  case label_1:
-    statements_1
-    [break;]
-  case label_2:
-    statements_2
-    [break;]
-    ...
-  default:
-    statements_def
-    [break;]
-}
-
- -
    -
  • Trước hết, chương trình sẽ tìm mệnh đề case có nhãn giống với giá trị của biểu thức và truyền dẫn việc điểu khiển tới mệnh đề đó, thực thi các lệnh liên quan.
  • -
  • Nếu không có nhãn nào khớp, chương trình sẽ tìm mệnh đề mặc định default, -
      -
    • Nếu tìm thấy mệnh đề mặc định default, chương trình sẽ truyền luồng điểu khiển tới mệnh đề đó, thực thi các lệnh liên quan.
    • -
    • Nếu không tìm thấy mệnh đề mặc định default, chương trình tiếp tục thực thi cho tới cuối lệnh switch. (Theo quy ước, mệnh đề default được viết cuối cùng, nhưng không bắt buộc).
    • -
    -
  • -
- -

Lệnh break

- -

Lệnh tuỳ chọn break liên kết với từng mệnh đề case nhằm đảm bảo chương trình nhảy ra khỏi switch một khi câu lệnh liên quan tại vị trí mệnh đề phù hợp đã thực hiện xong, và sau đó tiếp tục thực hiện câu lệnh phía sau lệnh switch. Nếu không có break, chương trình sẽ thực thi toàn bộ câu lệnh tiếp theo còn lại trong switch mà không cần đánh giá xem giá trị của biểu thức và case label có khớp nhau không.

- -

Ví dụ

- -

Trong ví dụ sau, nếu fruittype được gán giá trị "Bananas", chương trình sẽ khớp với nhãn "Bananas" và thực thi các lệnh đi kèm. Khi chương trình chạy tới break, chương trình ngừng và thực thi các lệnh sau khối lệnh switch. Nếu không có break, lệnh ứng với nhãn "Cherries" cũng sẽ được thực thi.

- -
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?");
- -

Lệnh xử lý ngoại lệ

- -

Bạn có thể quăng ngoại lệ (exeption) bằng lệnh throw và xử lý chúng bằng lệnh try...catch.

- - - -

Kiểu ngoại lệ

- -

Gần như mọi object đều có thể bị quăng ra trong JavaScript. Tuy vậy, không phải object nào khi quăng ra cũng được tạo ra tương tự nhau. Trong khi thông thường các số và chuỗi được quăng ra để thông báo lỗi, song sử dụng một trong số những kiểu ngoại lệ chuyên biệt cho mục đích này thường hiệu quả hơn:

- - - -

Lệnh throw

- -

Lệnh throw để quăng ra ngoại lệ. Khi muốn quăng ra ngoại lệ, bạn phải đặc tả biểu thức chứa giá trị để quăng ra:

- -
throw expression;
-
- -

Bạn có thể quăng ra biểu thức nào cũng được, không chỉ biểu thức dành riêng cho kiểu ngoại lệ. Ví dụ sau đây quăng ra vô số kiểu:

- -
throw 'Error2';   // String type
-throw 42;         // Number type
-throw true;       // Boolean type
-throw {toString: function() { return "I'm an object!"; } };
-
- -
Ghi chú: Bạn có thể đặc tả object khi quăng ngoại lệ. Rồi đặt tham chiếu tới thuộc tính của object đó trong khối catch.
- -
// Tạo object có kiểu UserException
-function UserException(message) {
-  this.message = message;
-  this.name = 'UserException';
-}
-
-// Bắt ngoại lệ in ra dòng lỗi màu mè một tí
-// (như khi in lên console chả hạn)
-UserException.prototype.toString = function() {
-  return this.name + ': "' + this.message + '"';
-}
-
-// Tạo một instance của object rồi quăng ra
-throw new UserException('Value too high');
- -

Lệnh try...catch

- -

Lệnh try...catch đánh dấu một khối để thử, và xác định khi nào sẽ quăng ra ngoại lệ. Khi ngoại lệ bị quăng ra, lệnh try...catch sẽ tóm gọn nó.

- -

Lệnh try...catch bao gồm khối try, chứa một hoặc nhiều câu lệnh, và khối catch, chứa các lệnh dành để xử lý khi có ngoại lệ bị quăng ra trong khối try.

- -

Tức là, bạn muốn lệnh trong khối try thành công, và nhỡ nó không thành công, bạn muốn truyền luồng xử lý xuống khối catch. Nếu bất cứ lệnh nào trong khối try (hoặc hàm được gọi trong khối try) quăng ra ngoại lệ, luồng điều khiển sẽ ngay lập tức chuyển xuống khối catch. Nếu không có ngoại lệ nào bị quăng ra trong khối try, khối catch sẽ bị bỏ qua. Khối finally thực thi sau khi khối trycatch thực thi xong nhưng trước các lệnh đặt ngay sau lệnh try...catch.

- -

Ví dụ sau dùng lệnh try...catch. Trong ví dụ này, ta gọi một hàm nhận vào một giá trị và trả về tên tháng tương ứng. Nếu giá trị truyền vào không tương ứng với số tháng (1-12), một ngoại lệ sẽ bị quăng ra có kiểu "InvalidMonthNo" và lệnh trong khối catch sẽ đặt lại giá trị cho biến monthName thành unknown.

- -
function getMonthName(mo) {
-  mo = mo - 1; // Chỉnh lại số tháng cho hợp với chỉ số mảng (1 = Jan, 12 = Dec)
-  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
-                'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
-  if (months[mo]) {
-    return months[mo];
-  } else {
-    throw 'InvalidMonthNo'; // dùng từ khoá throw ở đây nhé
-  }
-}
-
-try { // lệnh để thử
-  monthName = getMonthName(myMonth); // hàm để quăng ra ngoại lệ
-}
-catch (e) {
-  monthName = 'unknown';
-  logMyErrors(e); // truyền object ngoại lệ vào hàm xử lý lỗi của bạn
-}
-
- -

Khối catch

- -

Bạn có thể dùng khối catch để xử lý tất cả ngoại lệ sinh ra trong khối try.

- -
catch (catchID) {
-  statements
-}
-
- -

Khối catch nhận vào một định danh (catchID như trong cú pháp phía trên) giữ giá trị mà lệnh throw quăng ra; bạn có thể dùng định danh này để lấy thông tin về ngoại lệ bị quăng ra. JavaScript tạo ra định danh này khi chương trình chạy vào khối catch; định danh này chỉ tồn tại trong khối catch; sau khi khối catch thực thi xong, định danh đó sẽ không còn tồn tại nữa.

- -

Chẳng hạn, đoạn code sau quăng ra một ngoại lệ. Khi ngoại lệ xảy ra, điều khiển được truyền xuống khối catch.

- -
try {
-  throw 'myException'; // sinh ngoại lệ
-}
-catch (e) {
-  // lệnh xử lý ngoại lệ
-  logMyErrors(e); // truyền object ngoại lệ xuống hàm xử lý lỗi
-}
-
- -

Thực tiễn tốt nhất: Khi log error ra console bên trong một catch block, hãy sử dụng console.error() thay vì console.log(), nó sẽ định dạng dòng văn bản như là một lỗi, và thêm nó vào danh sách các dòng văn bản lỗi được tạo ra bởi trang. Điều này tốt cho việc debugging.

- -

Khối finally

- -

Khối finally chứa các lệnh thực thi ngay sau khi thực thi khối trycatch nhưng trước các lệnh liền sau lệnh try...catch. Khối finally vẫn thực thi dù có xảy ra ngoại lệ hay không. Nếu ngoại lệ bị quăng ra, các lệnh trong khối finally vẫn thực thi dù khối catch có xử lý ngoại lệ hay không.

- -

Bạn có thể dùng khối finally để khiến mã của bạn lỗi một cách yên bình nhỡ ngoại lệ xảy ra; chả hạn, bạn muốn giải phóng tài nguyên khỏi đoạn mã của mình. Ví dụ sau mở một tệp tin và thực thi lệnh dùng tài nguyên của tệp đó (JavaScript phía server cho phép bạn truy cập vào tệp tin). Nếu có ngoại lệ bị quăng ra trong lúc đang mở tệp tin, khối finally sẽ đóng đoạn tệp tin lại trước khi đoạn mã bị lỗi.

- -
openMyFile();
-try {
-  writeMyFile(theData); // Ghi vào tệp, có thể có lỗi
-} catch(e) {
-  handleError(e); // Nếu có lỗi thì dùng hàm này để xử lý
-} finally {
-  closeMyFile(); // Luôn luôn đóng tệp lại
-}
-
- -

Nếu khối finally trả về giá trị thì giá trị đó sẽ trở thành giá trị trả về của cả dãy lệnh try-catch-finally, bỏ qua mọi lệnh return trong khối trycatch:

- -
function f() {
-  try {
-    console.log(0);
-    throw 'bogus';
-  } catch(e) {
-    console.log(1);
-    return true; // lệnh return ở đây bị tạm ngưng
-                 // cho tới khi thực thi xong khối finally
-    console.log(2); // không thực thi tới
-  } finally {
-    console.log(3);
-    return false; // ghi đè lệnh "return" phía trên
-    console.log(4); // không thực thi tới
-  }
-  // "return false" sẽ thực thi ngay lúc này
-  console.log(5); // không thực thi tới
-}
-console.log(f()); // 0, 1, 3, false
-
- -

Ghi đè giá trị trả về bằng khối finally cũng áp dụng với các ngoại lệ bị quăng ra trong khối catch:

- -
function f() {
-  try {
-    throw 'bogus';
-  } catch(e) {
-    console.log('caught inner "bogus"');
-    throw e; // lệnh thow này bị tạm ngưng
-             // cho tới khi thực thi xong khối finally
-  } finally {
-    return false; // ghi đè lệnh "throw" phía trên
-  }
-  // "return false" sẽ thực thi ngay lúc này
-}
-
-try {
-  console.log(f());
-} catch(e) {
-  // khối này sẽ không bao giờ tới được
-  // bởi vì khối catch phía trên đã bị ghi đè
-  // bởi lệnh return trong finally
-  console.log('caught outer "bogus"');
-}
-
-// ĐẦU RA
-// caught inner "bogus"
-// false
- -

Lồng lệnh try...catch

- -

Bạn có thể lồng một hoặc nhiều lệnh try...catch. Nếu lệnh try...catch bên trong không có khối catch :

- -
    -
  1. Nó nên có khối finally
  2. -
  3. Lệnh try...catch bọc bên ngoài phải bắt được cái gì đấy. Để biết thêm thông tin, hãy đọc lồng khối try trên trang try...catch.
  4. -
- -

Tận dụng object Error

- -

Tuỳ theo kiểu của lỗi, bạn có thể dùng thuộc tính 'name' và 'message' để lấy ra thông điệp lỗi rõ ràng hơn. 'name' lấy ra class chung của Error (tức là 'DOMException' hoặc 'Error'), trong khi 'message' thường lấy ra thông điệp về lỗi súc tích hơn thông điệp tạo ra bởi ép object lỗi thành xâu ký tự.

- -

Nếu bạn muốn quăng ra ngoại lệ của riêng mình, để tận dụng được những thuộc tính này (ví dụ như khi khối catch không phân biệt giữa ngoại lệ của bạn và của hệ thống), bạn có thể dùng hàm khởi tạo Error. Chẳng hạn:

- -
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
-}
-
- -
{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
diff --git a/files/vi/web/javascript/guide/details_of_the_object_model/index.html b/files/vi/web/javascript/guide/details_of_the_object_model/index.html deleted file mode 100644 index 12101a6ddf..0000000000 --- a/files/vi/web/javascript/guide/details_of_the_object_model/index.html +++ /dev/null @@ -1,742 +0,0 @@ ---- -title: Details of the object model -slug: Web/JavaScript/Guide/Details_of_the_Object_Model -translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}
- -

JavaScript là một ngôn ngữ dựa trên đối tượng và nguyên mẫu, hơn là dựa trên class. Bởi vì điều này, làm nó kém rõ ràng về cách mà JavaScript cho phép chúng ta tạo cấu trúc cây của đối tượng cũng như tạo sự kế thừa cho thuộc tính và giá trị của chúng. Chương này cố gắng làm rõ đặc điểm này.

- -

Chương này giả định rằng bạn đã hiểu căn bản JavaScript và bạn đã sử dụng hàm của JavaScript để tạo đối tượng đơn giản.

- -

Ngôn ngữ Class-based vs. Ngôn ngữ prototype-based

- -

Ngôn ngữ dựa theo class, ví dụ Java và C++, tách biệt 2 thực thể chính: lớp (class) và thực thể (instance).

- -
    -
  • Một class định nghĩa tất cả các thuộc tính mà nó quy định tính chất của tập các object (xem phương thức và trường trong Java, hay thành viên trong C++, như là những thuộc tính). Một class là sự trù tượng hơn là một thành viên cụ thể của tập các object mà nó mô tả. Ví dụ, Employee class có thể biểu diễn tập hợp của tất cả employee.
  • -
  • Mặt khác một thực thể (instance) là một thực thể của một class, và là một trong những thành viên của nó. Ví dụ, Victoria có thể là một thực thể của Employee class, nó đại diện cho một cá nhân như là một employee. Một thực thể có chính xác cùng thuộc tính của class cha của nó (không hơn, không kém).
  • -
- -

Ngôn ngữ dựa trên nguyên mẫu, như JavaScript, không tách biệt điều này, nó đơn giản chỉ là những object. Một ngôn ngữ dựa trên nguyên mẫu có ký hiệu của một prototypical object, một object được dùng làm mẫu mà từ mẫu đó nó tạo ra thuộc tính cho object mới. Hơn nữa, bất kỳ object nào cũng có thể được liên kết để dùng làm nguyên mẫu của một object khác, điều này cho phép object thứ hai chia sẽ thuộc tính với object thứ nhất.

- -

Định nghĩa một class

- -

Ngôn ngữ dựa trên class, bạn định nghĩa một class bằng từ khóa định nghĩa class riêng biệt rõ ràng. Trong đó bạn có thể chỉ định phương thức đặc biệt, gọi là hàm dựng, để khởi tạo thực thể của class. Một hàm dựng có thể khởi tạo giá trị cho thuộc tính của thực thể và thực hiện những xử lý phù hợp tại thời điểm đó. Bạn có thể dùng toán tử new cùng với tên class để tạo thực thể của class.

- -

JavaScript cũng dùng mô hình tương tự, nhưng không có từ khóa riêng biệt để định nghĩa class (với phiên bản trước ES6). Thay vào đó, bạn có thể định nghĩa hàm dựng để tạo object với tập hợp các giá trị và thuộc tính ban đầu. Bất kỳ hàm JavaScript nào cũng có thể dùng như là constructor. Bạn có thể dùng từ toán tử new với hàm dựng để tạo object mới.

- -

Class con và sự kế thừa

- -

Trong ngôn ngữ dựa trên class, bạn tạo cây thứ tự của class thông qua những định nghĩa class. Khi định nghĩa một class, bạn có thể chỉ định class đang tạo là class con của một class khác đang tồn tại. Class con kế thừa tất cả các thuộc tính của class cha và có thể thêm vào những thuộc tính mới hoặc chỉnh sửa thuộc tính được kế thừa. Ví dụ, giả sử class Employee chỉ có thuộc tính namedept, và Manager là class con của Employee và định nghĩa thêm thuộc tính reports. Trong trường hợp này thực thể của class Manager sẽ có ba thuộc tính: name, dept, and reports

- -

JavaScript cài đặt tính kế thừa bằng cách cho phép bạn liên kết một object mẫu với bất kỳ hàm dựng nào. Vì vậy, bạn có thể tạo chính xác như ví dụ EmployeeManager trên, nhưng thuật cú pháp sẽ nhưng hơi khác một tí. Trước tiên bạn định nghĩa hàm dựng Employee, và trong thân hàm khởi tạo thuộc tính namedept. Tiếp theo bạn định nghĩa hàm dựng Manager, mà nó gọi hàm dựng Employee và khởi tạo thuộc tính reports. Cuối cúng bạn gán object mới kế thừa từ Employee.prototype như prototype cho hàm được dựng Manager. Sau đó, khi tạo một thực thể Manager mới, nó sẽ kế thừa thuộc tính namedept của Employee.

- -

Việc thêm và xóa những thuộc tính

- -

Trong ngôn ngữ dựa trên class, bạn thông thường tạo một class lúc biên dịch và rồi bạn khởi tạo thực thể của class tại lúc biên dịch hoặc lúc thực thi. Bạn không thể thay đổi số lượng và kiểu của thuộc tính của class sau khi bạn định nghĩa class. Trong JavaScript, bạn có thể thêm hoặc xóa thuộc tính của bất kỳ object nào. Nếu bạn thêm một thuộc tính của một object mà được sử dụng như prototype của một tập các object, những object đó cũng sẽ có những thuộc tính mới.

- -

Tóm tắt lại những khác biệt

- -

Sau đây là bản tóm tắt ngắn những khác biệt. Phần còn lại của chương mô tả chi tiết việc sử dụng hàm dựng của JavaScript và prototype để tạo cấu trúc cây đối tượng và so sánh với phương pháp tương tự trong Java.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
So sánh class-based (Java) và prototype-based (JavaScript)
Class-based (Java)Prototype-based (JavaScript)
Class và thực thể của nó là hai đối tượng riêng biệt.Tất cả đối tượng có thể kế thừa từ một đối tượng khác.
Dùng cú pháp riêng của class để định nghĩa class; khởi tạo thực thể của class dùng hàm dựng của class.Định nghĩa và tạo một tập các đối tượng chỉ với hàm dựng.
Tạo object đơn với toán tử  new.Cùng cách như class-based.
Xây dựng cấu trúc cây object bằng cách sử dụng định nghĩa class để tạo class con của class đang tồn tại.Xây dựng cấu trúc cây object bằng cách gán một object như prototype của hàm dựng.
Kế thừa thuộc tính theo cơ chế class nối tiếp.Kế thừa những thuộc tính theo cơ chế prototype nối tiếp.
Khi định nghĩa class, bạn chỉ định tất cả các thuộc tính của các thực thể của class. Và không thể thêm thuộc tính mới lúc thực thi.Hàm dựng và prototype chỉ định giá trị ban đầu của thuộc tính. Và có thể thêm hoặc xoá thuộc tính động trên từng đối tượng hoặc toàn bộ các object.
- -

Ví dụ Employee

- -

Phần còn lại của chương này sử dụng cấu trúc cây nhân viên được trình bày như hình bên dưới.

- -
-
-

Cấu trúc cây object đơn giản:

- -

-
- -
-
    -
  • Employee có những thuộc tính name (mà có giá trị mặc định là một chuỗi rỗng) và dept (mà giá trị mặc định là chuỗi "general").
  • -
  • Manager kế thừa từ Employee. Nó thêm thuộc tính reports (mà giá trị mặc định là một mảng rỗng sẽ dùng để lưu một mảng các Employee object)
  • -
  • WorkerBee cũng kế thừa từ Employee. Nó thêm thuộc tính projects (mà có giá trị mặc định là một mảng rỗng sẽ dùng để lưu trữ một mảng các giá trị kiểu chuỗi).
  • -
  • SalesPerson kế thừa từ WorkerBee. Nó thêm thuộc tính quota (mà có giá trị mặc định là 100). Nó cũng ghi đè giá trị của thuộc tính dept với giá trị "sales", để chỉ ra rằng tất cả salespersons thuộc cùng phòng ban.
  • -
  • Engineer kế thừa WorkerBee. Nó thêm vào thuộc tính machine (mà có giá trị mặc định là chuỗi rỗng) và cũng ghi đè thuộc tính dept với giá trị "engineering".
  • -
-
-
- -

Tạo hệ thống cấp bậc

- -

Có một vài cách để định nghĩa hàm dựng thích hợp để cài đặt hệ thống cấp bậc của nhân viên. Cách bạn muốn chọn để định nghĩa phụ thuộc phần lớn vào những gì bạn muốn làm trong ứng dụng của bạn.

- -

Phần này sẽ trình bày cách định nghĩa rất đơn giản để minh họa cách thực hiện sự kế thừa. Trong định nghĩa này, bạn không thể chỉ định giá trị nào cho thuộc tính khi bạn tạo một object. Một cách đơn giản một object mới được ra và nhận những thuộc tính với giá trị mặc định, sau đó bạn có thể thay đổi giá trị của những thuộc tính đó.

- -

Trong ứng dụng thực tế, bạn có thể định nghĩa hàm dựng mà cho phép bạn cung cấp những giá trị của thuộc tính tại thời điểm tạo object (xem thêm More flexible constructors). Bây giờ, ta chỉ dùng cách đơn giản để minh họa sự kế thừa.

- -

Việc định nghĩa Employee trong Java và JavaScript thì khá tương tự. Sự khác biệt chỉ là bạn cần chỉ định kiểu của mỗi thuộc tính trong Java nhưng không cần trong JavaScript (bởi vì Java là ngôn ngữ kiểu ràng buộc mạnh trong khi JavaScript là ngôn ngữ kiểu rành buộc yếu.

- -
-

JavaScript

- -
function Employee() {
-  this.name = '';
-  this.dept = 'general';
-}
-
- -


- Java

- -
public class Employee {
-   public String name = "";
-   public String dept = "general";
-}
-
-
- -

Việc định nghĩa ManagerWorkerBee chỉ ra sự khác nhau trong cách chỉ định đối tượng cấp cao hơn trong chuỗi kế thừa nối tiếp. Trong JavaScript, bạn có thể thêm nguyên mẫu (trở thành class cha) như là thuộc tính prototype của hàm dựng, rồi ghi đè prototype.constructor lên hàm dựng. Bạn có thể làm điều này bất kỳ thời điểm nào sau khi đã định nghĩa hàm dựng. Trong Java, bạn chỉ định class cha trong khi định nghĩa class. Bạn không thể thay đổi class cha sau khi định nghĩa class.

- -
-

JavaScript

- -
function Manager() {
-  Employee.call(this);
-  this.reports = [];
-}
-Manager.prototype = Object.create(Employee.prototype);
-Manager.prototype.constructor = Manager;
-
-function WorkerBee() {
-  Employee.call(this);
-  this.projects = [];
-}
-WorkerBee.prototype = Object.create(Employee.prototype);
-WorkerBee.prototype.constructor = WorkerBee;
-
- -


- Java

- -
public class Manager extends Employee {
-   public Employee[] reports =
-       new Employee[0];
-}
-
-
-
-public class WorkerBee extends Employee {
-   public String[] projects = new String[0];
-}
-
-
-
-
- -

 

- -

Việc định nghĩa EngineerSalesPerson giúp tạo objects theo thứ tự giảm dần từ Employee rồi xuống WorkerBee. Một object được tạo ra từ lớp con sẽ có tất cả thuộc tính của lớp cha ở trên trong chuỗi nối tiếp đó. Hơn nữa những định nghĩa ở lớp con có thể ghi đè những giá trị kế thừa từ lớp cha.

- -
-

JavaScript

- -
function SalesPerson() {
-   WorkerBee.call(this);
-   this.dept = 'sales';
-   this.quota = 100;
-}
-SalesPerson.prototype = Object.create(WorkerBee.prototype);
-SalesPerson.prototype.constructor = SalesPerson;
-
-function Engineer() {
-   WorkerBee.call(this);
-   this.dept = 'engineering';
-   this.machine = '';
-}
-Engineer.prototype = Object.create(WorkerBee.prototype)
-Engineer.prototype.constructor = Engineer;
-
- -


- Java

- -
public class SalesPerson extends WorkerBee {
-   public String dept = "sales";
-   public double quota = 100.0;
-}
-
-
-public class Engineer extends WorkerBee {
-   public String dept = "engineering";
-   public String machine = "";
-}
-
-
-
- -

Với việc sử dụng cách định nghĩa này, bạn có thể tạp hóa việc khởi tạo giá trị cho thuộc tính của thực thể với những giá trị mặc định cho các thuộc tính. Hình tiếp theo sẽ minh họa việc sử dụng cách định nghĩa trong JavaScript để tạo những object mới và hiển thị giá trị của thuộc tính của những object đó.

- -
-

Lưu Ý: Thuật ngữ thực thể (instance) có ý nghĩa kỹ thuật cụ thể trong ngôn ngữ class-based. Trong ngôn ngữ này, một thực thể (instance) là một thực thể riêng biệt của class và là tách biệt với class. Trong JavaScript, "thực thể" không có khái niệm kỹ thuật riêng bởi vì JavaScript không tách biệt sự khác nhau giữa class và instance. Tuy nhiên, khi nói về JavaScript, "thực thể" có thể được sử dụng để ám chỉ những object được tạo ra bằng hàm dựng. Vì vậy, trong ví dụ này, bạn có thể nói jane là một thực thể của Engineer. Tương tự, mặc dù những thuật ngữ parent, child, ancestor, và descendant không có ý nghĩa chính thống trong JavaScript, bạn có thể sử dụng chúng để ám chỉ những đối tượng cấp cao hơn hoặc thấp hơn trong cây thừa kế.

-
- -

Việc tạo những đối tượng bằng cách đơn giản

- -
-

Cây object

- -

Cây sau được tạo ra bằng những câu lệnh ở bên phải.

- -

- -

 

- -

Individual objects = Jim, Sally, Mark, Fred, Jane, etc.
- "Instances" created from constructor

- -
var jim = new Employee;
-// Parentheses can be omitted if the
-// constructor takes no arguments.
-// 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 ''
-
-
- -

Thuộc tính của Object

- -

Phần này mô tả cách mà những thuộc tính của những object có thể được kế thừa từ object khác trong chuỗi prototype và điều gì xãy ra khi bạn thêm một thuộc tính lúc thực thi.

- -

Việc kế thừa thuộc tính

- -

Giả định bạn tạo mark object như là một WorkerBee với câu lệnh sau:

- -
var mark = new WorkerBee;
-
- -

khi JavaScript thấy toán tử new, nó sẽ tạo một object mới và âm thầm đặt những giá trị của thuộc tính bên trong [[Prototype]] cho WorkerBee.prototype và truyền đối tượng mới tạo như là giá trị của từ khóa this cho hàm dựng WorkerBee. Thuộc tính [[Prototype]] xác định chuỗi prototype được dùng để trả về cho những giá trị của thuộc tính. Một khi những thuộc tính được thiết lập, JavaScript trả về đối tượng mới và những câu lệnh gán thiết lập giá trị thuộc tính của đối tượng mark.

- -

Quy trình này không đặt giá trị cho những thuộc tính kế thừa từ chuỗi prototype trực tiếp vào trong đối tượng mark. Khi bạn lấy giá trị của một thuộc tính, JavaScript đầu tiên sẽ kiểm tra xem nếu giá trị tồn tại trực tiếp trên chính đối tượng đó. Nếu có, giá trị sẽ được trả về. Nếu không tồn tại trên chính đối tượng đó, JavaScript kiểm tra chuỗi prototype (sử dụng thuộc tính [[Prototype]]). Nếu một object trong chuỗi prototype có giá trị cho thuộc tính, giá trị sẽ được trả về. Nếu không tồn tại thuộc tính, JavaScript sẽ trả lời là không có thuộc tính. Bằng cách này, đối tượng mark có những thuộc tính và những giá trị sau:

- -
mark.name = '';
-mark.dept = 'general';
-mark.projects = [];
-
- -

Đối tượng mark được gán những giá trị cục bộ cho thuộc tính name và  dept bằng hàm dựng Employee. Nó được gán giá trị cục bộ cho thuộc tính projects bằng hàm dựng WorkerBee. Điều này giúp tạo ra sự kế thừa của các thuộc tính trong JavaScript. Một vài điểm tinh tế trong qui trình này được mô tả trong Property inheritance revisited.

- -

Bởi vì hàm dựng không cho phép bạn chỉ định những giá trị riêng của thực thể, những thông tin này là chung. Những giá trị của thuộc tính là mặc định được chia sẻ cho tất cả các đối tượng được tạo ra từ WorkerBee. Tất nhiên bạn có thể thay đổi giá trị của bất kỳ thuộc tính nào. Bạn có thể làm điều đó trên mark object bằng những câu lệnh sau:

- -
mark.name = 'Doe, Mark';
-mark.dept = 'admin';
-mark.projects = ['navigator'];
- -

Thêm thuộc tính

- -

Trong JavaScript, bạn có thể thêm thuộc tính cho object lúc thực thi. Bạn không bị rành buộc phải sử dụng chỉ những thuộc tính được cung cấp bởi hàm dựng. Để thêm một thuộc tính cụ thể cho một object riêng lẻ, bạn có thể gán giá trị cho thuộc tính của object đó như sau:

- -
mark.bonus = 3000;
-
- -

Bây giờ object mark có thuộc tính bonus, những thực thể của WorkerBee không có thuộc tính này.

- -

Nếu bạn thêm thuộc tính mới vào một object mà đang được sử dụng làm prototype cho một hàm dựng, bạn đang thêm thuộc tính đó cho tất cả các object mà kế thừa từ prototype. Ví dụ, bạn có thể thêm thuộc tính specialty cho tất cả employees bằng câu lệnh sau:

- -
Employee.prototype.specialty = 'none';
-
- -

Ngay sau khi thực thi câu lệnh này, đối tượng mark cũng có thuộc tính specialty với giá trị "none". Hình sau minh họa việc thêm thuộc tính vào prototype của Employee và sau đó ghi đè nó lên prototype của Engineer.

- -


- Adding properties

- -

Những hàm dựng linh hoạt hơn

- -

Những hàm dựng đã được trình bày ở trên không cho phép chúng ta chỉ định giá trị cho thuộc tính khi chúng ta tạo thực thể. Với Java, bạn có thể cung cấp đối số cho hàm dựng để khởi tạo giá trị của thuộc tính cho những thực thể. Hình sau minh họa cách để thực hiện điều này.
-  

- -


- Việc chỉ định thuộc tính trong hàm dựng, cách 1

- -

Bảng minh họa sau trình bày cách định nghĩa những đối tượng này trong Java và JavaScript.

- -
-

JavaScript

- -

Java

-
- -
-
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;
-   }
-}
-
-
- -

Những định nghĩa này trong JavaScript sử dụng cú pháp đặc biệt để thiết lập giá trị mặc định:

- -
this.name = name || '';
-
- -

Trong JavaScript toán tử luận lý OR (||) ước lượng giá trị đầu tiên của đối số. Nếu đối số được chuyển đổi thành true, toán tử trả về giá trị của đối số đó. Ngược lại toán tử trả về đối số thứ hai. Vì vậy, đoạn mã trên kiểm tra xem nếu name có giá trị cho thuộc tính name. Nếu có, nó thiết lập giá trị đó cho this.name. Ngược lại, nó đặt giá trị chuỗi rỗng vào this.name. Chương này sử dụng cú pháp vắn tắt, tuy nhiên nó có thể làm chúng ta khó hiểu lúc ban đầu.

- -
-

Lưu Ý: Cách này có thể không hoạt động như mong đợi nếu hàm dựng được gọi với đối số mà được chuyển đổi thành false (ví dụ như 0 (zero) và chuỗi rỗng (""). trong trường hợp này giá trị mặc định sẽ được chọn)

-
- -

Với những định nghĩa này, khi bạn tạo một thực thể của một object, bạn có thể chỉ định giá trị cho những thuộc tính được định nghĩa cục bộ. Bạn có thể sử dụng những câu lệnh sau để tạo một Engineer:

- -
var jane = new Engineer('belau');
-
- -

Thuộc tính của Jane bây giờ là:

- -
jane.name == '';
-jane.dept == 'engineering';
-jane.projects == [];
-jane.machine == 'belau';
-
- -

Lưu ý là với những định nghĩa này, bạn không thể chỉ định giá trị khởi tạo cho một thuộc tính được kế thừa như thuộc tính name. Nếu bạn muốn chỉ định một giá trị khởi tạo cho thuộc tính được kế thừa trong JavaScript, bạn cần để thêm câu lệnh cho hàm khởi tạo.

- -

Hàm tạo đã tạo một đối tượng chung và rồi sau đó những giá trị được khởi tạo cho những thuộc tính cục bộ trực tiếp của đối tượng mới. Bạn có thể khởi tạo thêm những thuộc tính bằng cách trực tiếp gọi những hàm dựng khác của chuỗi prototype. Hình sau sẽ minh họa điều đó.

- -


- Những giá trị đang được chỉ định trong hàm dựng, hình 2

- -

Hãy xem xét một trong những định nghĩa một cách chi tiết. Đây là định nghĩa mới cho hàm dựng Engineer:

- -
function Engineer(name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, 'engineering', projs);
-  this.machine = mach || '';
-}
-
- -

Giả định rằng bạn tạo một đối tượng Engineer mới như sau:

- -
var jane = new Engineer('Doe, Jane', ['navigator', 'javascript'], 'belau');
-
- -

JavaScript thực thi theo những bước sau:

- -
    -
  1. Toán tử new tạo một object và thiết lập giá trị __proto__ của object mới tạo với giá trị là Engineer.prototype.
  2. -
  3. Toán tử mới sẽ truyền object mới cho hàm dựng Engineer như là giá trị của từ khóa this.
  4. -
  5. Hàm dựng tạo một thuộc tính mới được gọi là base cho đối tượng đó và gán giá trị của hàm dựng WorkerBee cho thuộc tính base. Điều này làm hàm dựng trở thành một phương thức của đối tượng Engineer. Tên của thuộc tính base thì không có gì đặc biệt. Bạn có thể dùng bất kỳ tên hợp lệ nào như là classBase, _base,... base đơn giản chỉ là một con trỏ đến hàm.
  6. -
  7. Hàm dựng gọi phương thức base, truyền vào hàm dựng như những đối số ("Doe, Jane" and ["navigator", "javascript"]"engineering"). Việc sử dụng tường minh "engineering" trong hàm dựng mà tất cả đối tượng Engineer có cùng giá trị cho thuộc tính được kế thừa dept, và giá trị ghi đè giá trị mà được kế thừa từ Employee.
  8. -
  9. Bởi vì base là phương thức của Engineer, JavaScript gắn từ khóa this với object được tạo ra ở bước 1. Vì thế hàm WorkerBee truyền các giá trị "Doe, Jane""engineering" cho hàm dựng Employee. Dựa trên giá trị trả về của hàm dựng Employee, hàm WorkerBee sử dụng những đối số còn lại để thiết lập giá trị cho thuộc tính projects.
  10. -
  11. Dựa trên giá trị trả về của phương thức base, hàm dựng Engineer khởi tạo thuộc tính machine của đối tượng với giá trị "belau".
  12. -
  13. Dựa trên giá trị trả về của hàm dựng, JavaScript gán đối tượng cho biến jane.
  14. -
- -

Bạn có thể nghĩ rằng, việc phải gọi hàm dựng WorkerBee bên trong hàm dựng Engineer, để đảm bảo việc cài đặt sự kế thừa cho tất cả đối tượng Engineer. Điều này không quá quan trọng. Việc gọi hàm dựng WorkerBee để đảm bảo tất cả đối tượng Engineer được tạo ra với các thuộc tính được chỉ định trong tất cả các hàm dựng được gọi. Tuy nhiên nếu bạn thêm thuộc tính vào prototype của Employee hoặc WorkerBee, những thuộc tính đó không được kế thừa bởi đối tượng Engineer. Ví dụ, giả sử bạn có đoạn mã sau:

- -
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';
-
- -

Đối tượng jane không kế thừa thuộc tính specialty. Bạn vẫn cần cài đặt tường minh prototype để đảm bảo sự kế thừa động. Giả sử bạn có đoạn mã sau:

- -
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';
-
- -

Bây giờ thuộc tính specialty của đối tượng jane là "none".

- -

Một cách khác để kế thừa là dùng hàm phương thức call() / apply(). Hai đoạn mã sau là tương đương:

- -
-
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 || '';
-}
-
-
- -

Việc sử dụng phương thức call() làm cho code rõ ràng hơn và base không còn cần thiết nữa.

- -

Xem lại sự kế thừa thuộc tính

- -

Đoạn trên đã mô tả cách hàm dựng và prototype trong JavaScript cung cấp cơ chế kế thừa và cây kế thừa. Trong phần này, chúng ta sẽ nói về điểm tinh tế mà thật sự chưa phù hợp để mô tả ở những phần trước.

- -

Dùng Giá Trị Cục Bộ hay là Giá Trị Được Kế  Thừa

- -

Khi bạn truy xuất thuộc tính của object, JavaScript thực hiện những bước sau:

- -
    -
  1. Kiểm tra nếu tồn tại thuộc tính trực tiếp, nó trả về giá trị của thuộc tính đó.
  2. -
  3. Nếu không có thuộc tính trực tiếp, kiểm tra trong chuỗi prototype (sử dụng thuộc tính __proto__).
  4. -
  5. Nếu một object trong chuỗi prototype chứa giá trị cho một thuộc tính đang tìm thì trả về giá trị của thuộc tính đó.
  6. -
  7. Nếu không tồn tại thuộc tính như vậy, thì object đó không có thuộc tính đang truy xuất.
  8. -
- -

Kết quả nhận được của những bước trên phụ thuộc vào cách bạn định nghĩa đối tượng. Ví dụ sau minh họa những cách định nghĩa đối tượng:

- -
function Employee() {
-  this.name = '';
-  this.dept = 'general';
-}
-
-function WorkerBee() {
-  this.projects = [];
-}
-WorkerBee.prototype = new Employee;
-
- -

Với cách định nghĩa này, giả định rằng bạn tạo đối tượng amy là thực thể của WorkerBee với đoạn lệnh sau:

- -
var amy = new WorkerBee;
-
- -

Đối tượng amy có một biến cục bộ (riêng) là projects. Các thuộc tính namedept thì không là thuộc tính riêng của amy mà được lấy ra từ thuộc tính __proto__. Vì vậy, đối tượng amy có những thuộc tính với những giá trị sau:

- -
amy.name == '';
-amy.dept == 'general';
-amy.projects == [];
-
- -

Giả định rằng bạn thay đổi giá trị của thuộc tính name trong prototype của Employee:

- -
Employee.prototype.name = 'Unknown';
-
- -

Bạn mong muốn rằng giá trị mới sẽ được thiết lập cho tất cả các thực thể của Employee. Nhưng điều nay không xãy ra.

- -

Khi bạn tạo bất kỳ thực thể nào của đối tượng từ Employee, thì thực thể đó sẽ tạo thuộc tính name riêng trực tiếp trên chính thực thể đó (cụ thể đó là giá trị rỗng). Điều này có nghĩa là khi bạn thiết lập giá trị cho prototype của  WorkerBee bằng một đối tượng kiểu Employee, thì WorkerBee.prototype có lưu giá trị riêng cho thuộc tính name. Vì vậy, khi JavaScript tìm kiếm thuộc tính name của đối tượng amy (tạo ra từ WorkerBee), JavaScript tìm kiếm giá riêng cho thuộc tính đó trong WorkerBee.prototype. Do đó nó không tìm kiếm xa hơn trong chuỗi prototype.

- -

Nếu bạn muốn thay đổi giá trị của một thuộc tính lúc thực thi và muốn giá trị mới đó áp dụng cho tất cả các thực thể được tạo ra, thì bạn không thể khởi tạo thuộc tính trong hàm dựng. Thay vào đó, ban thêm nó vào hàm vào trong thuộc tính prototype của hàm dựng. Ví dụ sau minh họa cách chúng ta đạt được mục đích này:

- -
function Employee() {
-  this.dept = 'general';    // Note that this.name (a local variable) does not appear here
-}
-Employee.prototype.name = '';    // A single copy
-
-function WorkerBee() {
-  this.projects = [];
-}
-WorkerBee.prototype = new Employee;
-
-var amy = new WorkerBee;
-
-Employee.prototype.name = 'Unknown';
-
- -

Trong trường hợp này thuộc tính name của amy nhận giá trị "Unknown".

- -

Tóm lại, nếu bạn muốn đặt giá trị mặc định cho thuộc tính và bạn muốn thay đổi giá trị mặc định lúc thực thi, bạn nên cài đặt thuộc tính trên prototype của hàm dựng, không phải tạo trực tiếp thuộc tính lúc thực thi hàm dựng.

- -

Xác định mối quan hể của thực thể

- -

Việc tìm kiếm thuộc tính trong JavaScript sẽ được thực hiện trên chính danh sách các thuộc tính riêng trực tiếp của object trước, nếu thuộc tính không được tìm thấy, nó sẽ tìm trên object đặc biệt là __proto__. Việc kiểm tra sẽ được thực thi đệ qui, qui trình này được gọi là "Tìm kiếm trong chuỗi prototype".

- -

Thuộc tính đặc biệt __proto__ được tạo ra khi một đối tượng được tạo ra. Nó chính là giá trị được gán cho thuộc tính prototype của hàm dựng. Ví vậy biểu thức new Foo() tạo ra một object với __proto__ == Foo.prototype. Tiếp theo đó, những thay đổi trên thuộc tính Foo.prototype sẽ làm thay đổi thuộc tính cho tất cả đối tượng mà được tạo ra bởi new Foo().

- -

Mỗi object đều cho thuộc tính __proto__ và mỗi hàm đều có thuộc tính prototype. Vì vậy những đối tượng có mối liên hệ thông qua cơ chế 'thừa kế prototype' với những đối tượng khác. Bạn có thể kiểm tra sự thừa kế bằng cách so sánh thuộc tính __proto__ của object với prototype của một hàm. JavaScript cung cấp một toán tử để thực hiện điều này là instanceof, Toán tử sẽ trả về kết quả true nếu đối tượng được kết thừa từ prototype của hàm. Như ví dụ sau:

- -
var f = new Foo();
-var isTrue = (f instanceof Foo);
- -

Để minh họa cụ thể hơn, chúng ta xem ví dụ sau. Giả định bạn đã có đoạn mã như định nghĩa trong Kế thừa thuộc tính. Tạo một đối tượng Engineer như sau:

- -
var chris = new Engineer('Pigman, Chris', ['jsd'], 'fiji');
-
- -

Với đối tượng nay, những câu lệnh sau tất cả đều đúng:

- -
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;
-
- -

Dựa trên những điểm trên, bạn có thể viết hàm instanceOf như sau:

- -
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;
-}
-
- -
Lưu Ý: Đoạn lệnh trên dùng toán tử typeof để kiểm tra object để kiểm tra đó là XML object, đây là cách khắc phục lỗi của JavaScript cho đối tượng XML.
- -

Dùng hàm instanceOf trên, biểu thức luôn đúng:

- -
instanceOf(chris, Engineer)
-instanceOf(chris, WorkerBee)
-instanceOf(chris, Employee)
-instanceOf(chris, Object)
-
- -

Nhưng biểu thức sau thì sai:

- -
instanceOf(chris, SalesPerson)
-
- -

Thông tin toàn cục trong hàm dựng

- -

Khi bạn định nghĩa hàm dựng, bạn cần cẩn thận nếu bạn thiết lập giá trị cho biến toàn cục. Giả sử bạn muốn giá trị ID duy nhất được tự động gán cho mỗi employee mới. Bạn có thể sử dụng cách định nghĩa sau cho Employee sau:

- -
var idCounter = 1;
-
-function Employee(name, dept) {
-   this.name = name || '';
-   this.dept = dept || 'general';
-   this.id = idCounter++;
-}
-
- -

Với định nghĩa này, khi bạn tạo một Employee mới, hàm dựng gán giá trị ID kế tiếp và rồi tăng biến đếm toàn cục ID lên một đơn vị. Vì vậy, những câu lệnh tiếp theo sau đây, victoria.id là 1 và harry.id là 2:

- -
var victoria = new Employee('Pigbert, Victoria', 'pubs');
-var harry = new Employee('Tschopik, Harry', 'sales');
-
- -

Thoạt nhìn mọi thứ có vẽ tốt. Tuy nhiên, idCounter được tăng lên mỗi lần một đối tượng Employee được tạo ra cho mọi trường hợp cả những trường hợp không mong muốn. Nếu bạn tạo toàn bộ cây cấp bậc Employee như hình trong chương này, hàm dựng Employee được gọi mỗi là bạn cài đặt một prototype. Giả sử bạn có đoạn lệnh sau:

- -
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');
-
- -

Giả sử ta không quan tâm những câu lệnh bên trong hàm dựng, thuộc tính base và gọi hàm base trong chuỗi prototype. Trong trường hợp này, ngay khi đối tượng mac được tạo, mac.id là 5.

- -

Tuy theo yêu cầu của ứng dụng, nó có thể là vấn đề quan trọng hoặc không khi biến đếm được tăng lên. Nếu bạn quan tâm tính chính xác của giá trị tăng thêm của biến đếm, Một giải pháp cho vấn đề này là:

- -
function Employee(name, dept) {
-   this.name = name || '';
-   this.dept = dept || 'general';
-   if (name)
-      this.id = idCounter++;
-}
-
- -

Khi bạn tạo một thực thể của Employee để sử dụng như prototype, bạn không cung cấp đối số cho hàm dựng. Việc sử dụng định nghĩa của hàm dựng, khi bạn không cung cấp đối số, hàm dựng không gán giá trị cho id và không cập nhật biến đếm. Vì vậy, để một đối tượng Employee được gán id, bạn phải chỉ định tên cho employee. Trong ví dụ này, mac.id sẽ là 1.

- -

Một cách khác, bạn có thể tạo một bản sao của đối tượng prototype của Employee để gán cho WorkerBee:

- -
WorkerBee.prototype = Object.create(Employee.prototype);
-// instead of WorkerBee.prototype = new Employee
-
- -

Không hỗ trợ đa kế thừa

- -

Một vài ngôn ngữ hướng đối tượng cho phép đa kế thừa. Nghĩa là một object có thể kế thừa những thuộc tính và giá rị từ những đối tượng cha không liên quan.

- -

Việc kế thừa những thuộc tính xảy ra lúc thực thi bởi JavaScript trong khi tìm kiếm chuỗi prototype của object cho một giá trị. Bởi vì một object chỉ có một prototype đơn, JavaScript không thể kế thừa động từ nhiều hơn một chuỗi prototype.

- -

Trong JavaScript, bạn có thể áp dụng nhiều hàm dựng trong hàm dựng. Điều này chứng minh tính khả thi của đa kế thừa. Xem xét ví dụ sau:

- -
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');
-
- -

Giả sử WorkerBee được định nghĩa như trên. Trong trường hợp này, đối tượng dennis có những thuộc tính sau:

- -
dennis.name == 'Doe, Dennis';
-dennis.dept == 'engineering';
-dennis.projects == ['collabra'];
-dennis.machine == 'hugo';
-dennis.hobby == 'scuba';
-
- -

Vì vậy dennis có thuộc tính từ hàm dựng Hobbyist. Tuy nhiên, giả sử sau đó bạn thêm một thuộc tính vào prototype của hàm dựng của Hobbyist:

- -
Hobbyist.prototype.equipment = ['mask', 'fins', 'regulator', 'bcd'];
-
- -

Đối tượng dennis không kế thừa thuộc tính mới này.

- -
{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}
diff --git a/files/vi/web/javascript/guide/expressions_and_operators/index.html b/files/vi/web/javascript/guide/expressions_and_operators/index.html deleted file mode 100644 index a843b8d769..0000000000 --- a/files/vi/web/javascript/guide/expressions_and_operators/index.html +++ /dev/null @@ -1,920 +0,0 @@ ---- -title: Biểu thức và toán tử -slug: Web/JavaScript/Guide/Expressions_and_Operators -translation_of: Web/JavaScript/Guide/Expressions_and_Operators ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}
- -

Chương này mô tả biểu thức và toán tử của JavaScript, bao gồm toán tử gán, toán tử so sánh, arithmetic, thao tác bit, toán tử luận lý, chuỗi, toán tử ba ngôi và nhiều hơn nữa.

- -

Để xem danh sách đầy đủ và chi tiết các toán tử và biểu thức, mời truy cập vào reference.

- -

Toán tử

- -

JavaScript có các loại toán tử như sau. Phần này mô tả về các toán tử và có bao gồm thông tin về thứ tự ưu tiên của chúng.

- - - -

JavaScript có cả toán tử hai ngôimột ngôi, và một toán tử đặc biệt ba ngôi, toán tử quan hệ. Toán tử hai ngôi yêu cầu hai toán hạng, một toán hạng ở trước và một toán hạng ở sau toán tử:

- -
toán_hạng_1 toán_tử toán_hạng_2
-
- -

Chẳng hạn, 3+4 hoặc x*y.

- -

Toán tử một ngôi yêu cầu một toán tử, ở trước hoặc ở sau toán tử:

- -
toán_tử toán_hạng
-
- -

hoặc

- -
toán_hạng toán_tử
-
- -

Chẳng hạn, x++ hoặc ++x.

- -

Toán tử gán

- -

Toán tử gán gán giá trị cho toán hạng bên trái nó dựa theo giá trị của toán hạng bên phải nó. Toná tử gán đơn giản là toán tử bằng (=), gán giá trị cho toán hạng bên trái nó bằng giá trị của toán hạng bên phải nó. Vậy, x = y tức là gán giá trị của y cho x.

- -

Ngoài ra còn có các toán tử gán kết hợp được liệt kê trong bảng dưới:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Toán tử gán kết hợp
TênViết tắtÝ nghĩa
Toán tử gánx = yx = y
Cộng xong rồi gánx += yx = x + y
Trừ xong rồi gánx -= yx = x - y
Nhân xong rồi gánx *= yx = x * y
Chia xong rồi gánx /= yx = x / y
Chia lấy dư xong rồi gánx %= yx = x % y
Luỹ thừa rồi gán{{experimental_inline}}x **= yx = x ** y
Dịch bit trái rồi gánx <<= yx = x << y
Dịch bit phải rồi gánx >>= yx = x >> y
Dịch phải kiểu unsigned rồi gánx >>>= yx = x >>> y
AND bit rồi gánx &= yx = x & y
XOR bit rồi gánx ^= yx = x ^ y
OR bit rồi gánx |= yx = x | y
- -

Phân rã

- -

Với phép gán phức tạp hơn, cú pháp phân rã rồi gán là một biểu thức JavaScript cho phép phân tách dữ liệu từ mảng hoặc object sử dụng cú pháp sao chép cấu trúc của mảng hoặc object literal.

- -
var foo = ['one', 'two', 'three'];
-
-// không dùng phân rã
-var one   = foo[0];
-var two   = foo[1];
-var three = foo[2];
-
-// dùng phân rã
-var [one, two, three] = foo;
- -

Toán tử so sánh

- -

Toán tử so sánh so sánh toán hạng của nó và trả về giá trị luận lý dựa theo tính đúng sai của phép so sánh. Toán hạng có thể thuộc là số, chuỗi, luận lý, hoặc object. Chuỗi được so sánh theo thứ tự từ điển, qua giá trị mã Unicode. Trong nhiều trường hợp, nếu hai toán hạng không cùng kiểu, JavaScript sẽ tự động ép kiểu sao cho phù hợp. Hành vi này thường xảy ra khi so sánh dữ liệu kiểu số. Duy có hai toán tử so sánh, bao gồm ===!==, không tự động ép kiểu mà sẽ so sánh bằng chính xác. Bảng sau mô tả các toán tử so sánh bao gồm cả code mẫu:

- -
var var1 = 3;
-var var2 = 4;
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Toán tử so sánh
Toán tửMô tảVí dụ trả về true/th>
Bằng (==)Trả về true nếu các toán hạng bằng nhau.3 == var1 -

"3" == var1

- 3 == '3'
Không bằng (!=)Trả về true nếu các toán hạng không bằng nhau.var1 != 4
- var2 != "3"
Bằng chính xác (===)Trả về true nếu các toán hạng bằng nhau và cùng kiểu. Xem thêm tại {{jsxref("Object.is")}} và sameness in JS.3 === var1
Không bằng chính xác (!==)Trả về true nếu các toán hạng không bằng nhau, hoặc khác kiểu.var1 !== "3"
- 3 !== '3'
Lớn hơn (>)Trả về true nếu toán hạng bên trái lớn hơn toán hạng bên phải.var2 > var1
- "12" > 2
Lớn hơn hoặc bằng (>=)Trả về true nếu toán hạng bên trái lớn hơn hoặc bằng toán hạng bên phải.var2 >= var1
- var1 >= 3
Nhỏ hơn (<)Trả về true nếu toán hạng bên trái nhỏ hơn toán hạng bên phải.var1 < var2
- "2" < 12
Nhỏ hơn hoặc bằng (<=)Trả về true nếu toán hạng bên trái ?nhỏ hơn hoặc bằng toán hạng bên phải.var1 <= var2
- var2 <= 5
- -
-

Lưu ý: (=>) không phải là toán tử, mà là cú pháp của Hàm mũi tên.

-
- -

Toán tử số học

- -

Toán tử số học nhận giá trị kiểu số (cả literal lẫn biến) là toán hạng của nó và trả về một giá trị kiểu số. Các toán tử số học thông thường là toán tử cộng (+), trừ (-), nhân (*), và chia (/). Những toán tử này hoạt động tương tự như trong các ngôn ngữ lập trình khác khi xử lý với số thực dấu phẩy động (nói chung, ?phép chia cho 0 sẽ trả về {{jsxref("Infinity")}}). Ví dụ:

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

Ngoài những toán tử số học thông thường (+, -, * /), JavaScript cung cấp thêm các toán tử số học được liệt kê trong bảng sau:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Toán tử số học
Toán tửMô tảVí dụ
Chia lấy dư (%)Toán tử hai ngôi. Trả về phần nguyên trong phép chia của hai toán hạng.12 % 5 trả về 2.
Tăng (++)Toán tử một ngôi. Cộng thêm một đơn vị cho toán hạng. Nếu dùng như tiền tố (++x), trả về giá trị sau khi cộng thêm một; nếu dùng như hậu tố (x++), trả về giá trị trước khi cộng thêm một.Nếu x bằng 3, rồi ++x sẽ thiết lập giá trị của x lên 4 và trả về 4, trong khi x++ trả về 3 và sau đó mới thiết lập giá trị của x lên 4.
Giảm (--)Toán tử một ngôi. Trừ đi một đơn vị cho toán hạng. Giá trị trả về tương tự như toán tử tăng.Nếu x bằng 3, rồi --x sẽ thiết lập giá trị của x về 2 và trả về 2, trong khi x-- trả về 3 và sau đó mới thiết lập giá trị của x về 2.
Phủ định một ngôi (-)Toán tử một ngôi. Trả về giá trị phủ định của toán hạng.Nếu x bằng 3, thì -x trả về -3.
Cộng một ngôi (+)Toán tử một ngôi. Ép kiểu toán hạng về dạng số học, nếu kiểu của toán hạng đó không phải là số.+"3" trả về 3.
- +true trả về 1.
Toán tử luỹ thừa (**) {{experimental_inline}}Tính toán giá trị cơ số theo luỹ thừa số mũ, tức là, cơ sốsố mũ2 ** 3 trả về 8.
- 10 ** -1 trả về 0.1.
- -

Toán tử thao tác bit

- -

Toán tử thao tác bit coi toán hạng của nó là một tập 32 bit (gồm 0 và 1), thay vì là kiểu thập phân, thập lục phân, hay bát phân. Chẳng hạn, số thập phân 9 được biểu diễn trong hệ nhị phân là 1001. Toán tử thao tác bit xử lý phép toán dựa theo dạng biểu diễn nhị phân ấy, nhưng trả về giá trị kiểu số thông thường trong JavaScript.

- -

Bảng tóm tắt các toán tử thao tác bit của JavaScript.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Toán tử thao tác bit
Toán tửCách dùngMô tả
Toán tử AND bita & btrả về a one in each bit position for which the corresponding bits of both operands are ones.
Toán tử OR bita | btrả về a zero in each bit position for which the corresponding bits of both operands are zeros.
Toán tử XOR bita ^ btrả về a zero in each bit position for which the corresponding bits are the same.
- [trả về a one in each bit position for which the corresponding bits are different.]
Toán tử NOT bit~ aInverts the bits of its operand.
Dịch tráia << bShifts a in binary representation b bits to the left, shifting in zeros from the right.
Dịch phải giữ nguyên dấua >> bShifts a in binary representation b bits to the right, discarding bits shifted off.
Dịch phải với 0a >>> bShifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.
- -

Toán tử luận lý bit

- -

Về lý thuyết, cơ chế hoạt động của toán tử luận lý bit được giải thích như sau:

- -
    -
  • Toán hạng được chuyển đổi về dạng số nguyên 32-bit và biểu diễn bằng một dãy bit (0 và 1). Số dài hơn 32 bit sẽ bị cắt đi một số bit. Chẳng hạn, số nguyên sau đây, dài hơn 32 bit sẽ được chuyển đổi về dạng số nguyên 32 bit: -
    Trước: 11100110111110100000000000000110000000000001
    -Sau:               10100000000000000110000000000001
    -
  • -
  • Mỗi bit của toán hạng thứ nhất sẽ dóng với bit tương ứng của toán hạng thứ hai.
  • -
  • Toán tử sẽ áp dụng với từng cặp bit và trả.
  • -
- -

Chẳng hạn, biểu diễn nhị phân của 9 là 1001, và biểu diễn nhị phân của 15 là 1111. Vậy nếu áp dụng toán tử luận lý bit vào các giá trị này, thì kết quả trả về sẽ được như trong bảng sau:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Ví dụ về toán tử thao tác bit
Biểu thứcKết quảMô tả nhị phân
15 & 991111 & 1001 = 1001
15 | 9151111 | 1001 = 1111
15 ^ 961111 ^ 1001 = 0110
~15-16~00000000...00001111 = 11111111...11110000
~9-10~00000000...00001001 = 11111111...11110110
- -

Chú ý: tất cả 32 bit được đảo ngược bởi toán tử luận lý NOT có bit trái nhất đặt thành 1 để biểu diễn số âm (biểu diễn bù hai). ~x thực thi ra cùng một kết quả như -x - 1.

- -

Toán tử dịch bit

- -

Toán tử dịch bit nhận hai toán hạng: toán hạng thứ nhất là số lượng bit được dịch, còn toán hạng thứ hai chỉ ra vị trí bit để bắt đầu dịch. Hướng dịch bit phụ thuộc vào toán tử được sử dụng.

- -

Toán tử dịch bit chuyển đổi toán hạng của nó thành dạng số nguyên 32-bit và trả về kết quả cùng kiểu với toán hạng bên trái.

- -

Toán tử dịch bit được liệt kê theo danh sách sau.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Toán tử dịch bit
Toán tửMô tảVí dụ
Dịch trái
- (<<)
Dịch toán hạng thứ nhất theo một lượng bằng toán hạng thứ hai sang trái. Các bit dịch trái bị tràn sẽ bị loại bỏ. Các bit 0 được dịch vào từ bên phải.9<<2 trả về 36, bởi vì 1001 dịch 2 bit sang trái sẽ thành 100100, tương ứng với 36.
Dịch phải bit giữ nguyên dấu (>>)Dịch toán hạng thứ nhất theo một lượng bằng toán hạng thứ hai sang phải. Các bit dịch phải bị tràn sẽ bị loại bỏ. Bản sao của bit trái nhất được dịch vào từ trái.9>>2 trả về 2, bởi vì 1001 dịch 2 bit sang phải sẽ thành 10, tương ứng với 2. Tương tự, -9>>2 trả về -3, bởi vì dấu vẫn được giữ nguyên.
Dịch phải bit với 0 (>>>)Dịch toán hạng thứ nhất theo một lượng bằng toán hạng thứ hai sang phải. Các bit dịch phải bị tràn sẽ bị loại bỏ. Bit 0 được dịch vào từ trái sang.19>>>2 trả về 4, bởi vì 10011 dịch 2 bit sang phải sẽ thành 100, tương ứng với 4. Với số không âm, toán tử này tương tự với dịch phải giữ nguyên dấu.
- -

Toán tử luận lý

- -

Toán tử logic thường được dùng với giá trị Boolean (kiểu logic); khi đó, chúng trả về giá trị Boolean. Tuy nhiên, toán tử &&|| thực tế trả về giá trị của một trong những toán hạng xác định, nên nếu hai toán tử này được dùng với giá trị không phải kiểu Boolean, chúng có thể trả về một giá trị không phải Boolean. Toán tử logic được mô tả trong bảng dưới.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Toán tử logic
Toán tửCách dùngMô tả
Logic AND (&&)expr1 && expr2Trả về expr1 nếu nó có thể biến đổi thành false; ngược lại, trả về expr2. Như vậy, khi dùng với giá trị Boolean, && trả về true nếu cả hai toán hạng đều là true; ngược lại, trả về false.
Logic OR (||)expr1 || expr2Trả về expr1 nếu nó có thể biến đổi thành true; ngược lại, trả về expr2. Vì vậy, khi dùng với giá trị Boolean, || trả về true nếu cả hai toán hạng đều là true; nếu cả hai false, trả về false.
Logic NOT (!)!exprTrả về false nếu toán hạng đứng ngay sau nó có thể biến đổi thành true; ngược lại, trả về true.
- -

Ví dụ về các biểu thức có thể biến đổi thành false là những biểu thức khi thực thi trả về null, 0, NaN, chuỗi rỗng (""), hoặc undefined.

- -

Sau đây là các ví dụ cho toán tử && (luận lý AND).

- -
var a1 =  true && true;     // t && t trả về true
-var a2 =  true && false;    // t && f trả về false
-var a3 = false && true;     // f && t trả về false
-var a4 = false && (3 == 4); // f && f trả về false
-var a5 = 'Cat' && 'Dog';    // t && t trả về Dog
-var a6 = false && 'Cat';    // f && t trả về false
-var a7 = 'Cat' && false;    // t && f trả về false
-
- -

Sau đây là các ví dụ cho toán tử || (luận lý OR).

- -
var o1 =  true || true;     // t || t trả về true
-var o2 = false || true;     // f || t trả về true
-var o3 =  true || false;    // t || f trả về true
-var o4 = false || (3 == 4); // f || f trả về false
-var o5 = 'Cat' || 'Dog';    // t || t trả về Cat
-var o6 = false || 'Cat';    // f || t trả về Cat
-var o7 = 'Cat' || false;    // t || f trả về Cat
-
- -

Sau đây là các ví dụ cho toán tử ! (luận lý NOT).

- -
var n1 = !true;  // !t trả về false
-var n2 = !false; // !f trả về true
-var n3 = !'Cat'; // !t trả về false
-
- -

Thực thi đoản-mạch

- -

Vì các biểu thức luận lý được thực thi từ trái sang phải, ta có thể dùng chúng để thử tính "đoán-mạch" qua các quy định sau:

- -
    -
  • false && bất cứ gì là thực thi đoản-mạch ra false.
  • -
  • true || bất cứ gì là thực thi đoản-mạch ra true.
  • -
- -

Quy định luận lý đảm bảo rằng các thực thi trên luôn đúng. Chú ý phần bất cứ gì trong các biểu thức trên không được thực thi, bởi vậy sẽ không xảy ra bất cứ tác dụng phụ nào.

- -

Toán tử chuỗi

- -

Ngoài toán tử so sánh, có thể dùng để so sánh chuỗi, toán tử ghép (+) ghép hai giá trị chuỗi lại với nhau, trả về một chuỗi mới là hợp của hai chuỗi cũ.

- -

Chẳng hạn,

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

Toán tử gán rút gọn += cũng có thể dùng để ghép chuỗi.

- -

Chẳng hạn,

- -
var mystring = 'alpha';
-mystring += 'bet'; // "alphabet" sẽ ghép với giá trị này trước khi gán vào mystring.
- -

Toán tử điều kiện (ba ngôi)

- -

Toán tử điều kiện là toán tử duy nhất của JavaScript cần tới ba toán hạng. Kết quả có thể là một trong hai giá trị tuỳ theo điều kiện. Cú pháp:

- -
điều_kiện ? giá_trị_1 : giá_trị_2
-
- -

Nếu điều_kiện trả về true, toán tử có giá trị giá_trị_1. Ngược lại toán tử có giá trị giá_trị_2. Bạn có thể dùng toán tử điều kiện ở bất cứ đâu như một toán tử bình thường.

- -

Chẳng hạn,

- -
var status = (age >= 18) ? 'adult' : 'minor';
-
- -

Đoạn code này gán giá trị "adult" cho biến status nếu age lớn hơn hoặc bằng 18. Ngược lại, nó gán giá trị "minor" cho status.

- -

Toán tử dấu phẩy

- -

Toán tử dấu phẩy (,) đơn thuần tính toán cả hai giá trị toán hạng của nó và trả về giá trị của toán hạng cuối. Toán tử này được dùng chủ yếu trong vòng lặp for, để cho phép cập nhật nhiều biến cùng lúc sau mỗi lần thực hiện vòng lặp.

- -

Chẳng hạn, nếu a là một mảng 2-chiều với 10 phần tử mỗi chiều, đoạn code sau dùng toán tử dấu phẩy để cập nhật hai biến cùng một lúc. Console in ra giá trị của các phần tử nằm trong đường chéo:

- -
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]);
-
- -

Toán tử một ngôi

- -

Toán tử một ngôi là phép toán chỉ có duy nhất một toán hạng.

- -

delete

- -

Toán tử delete xoá một object, một thuộc tính của object, hoặc một phần tử ở chỉ mục xác định trong mảng. Cú pháp là:

- -
delete objectName;
-delete objectName.property;
-delete objectName[index];
-delete property; // chỉ được khi cài trong lệnh with
-
- -

Với objectName là tên của object, property là thuộc tính đang tồn tại, và index là giá trị nguyên của chỉ mục tương ứng với vị trí của thuộc tính trong mảng.

- -

Dạng thứ tư chỉ hoạt động khi được cài trong lệnh with, để xoá một thuộc tính khỏi object.

- -

Bạn có thể dùng toán tử delete để xoá biến được khởi tạo ngầm nhưng không thể xoá được các biến được khởi tạo bằng lệnh var.

- -

Nếu toán tử delete thành công, nó đặt thuộc tính hoặc phần tử đó thành undefined. Toán tử delete trả về true nếu phép toán khả thi; nó trả về false nếu phép toán bất khả thi.

- -
x = 42;
-var y = 43;
-myobj = new Number();
-myobj.h = 4;    // tạo thuộc tính h
-delete x;       // trả về true (có thể xoá nếu khởi tạo ngầm)
-delete y;       // trả về false (không thể xoá nếu khởi tạo bằng var)
-delete Math.PI; // trả về false (không thể xoá thuộc tính tiền định nghĩa)
-delete myobj.h; // trả về true (có thể xoá thuộc tính người dùng định nghĩa)
-delete myobj;   // trả về true (có thể xoá nếu khợi tạo ngầm)
-
- -
Xoá phần tử mảng
- -

Khi bạn xoá một phần tử của mảng, chiều dài mảng không bị ảnh hưởng. Chẳng hạn, nếu bạn xoá a[3], a[4] vẫn là a[4]a[3] là undefined.

- -

Khi toán tử delete loại bỏ một phần tử khỏi mảng, phần tử đó không còn tồn tại trong mảng. Trong ví dụ sau, trees[3] đã được loại bỏ bởi delete. Tuy nhiên, trees[3] vẫn có thể được trỏ tới và trả về undefined.

- -
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
-delete trees[3];
-if (3 in trees) {
-  // sẽ không chạy vào đây
-}
-
- -

Nếu bạn muốn kiểm tra sự tồn tại của một phần tử trong mảng nhưng có giá trị là undefined, hãy dùng từ khoá undefined thay cho toán tử delete. Trong ví dụ tiếp sau đây, trees[3] được gán giá trị undefined, nhưng phần tử của mảng vẫn tồn tại:

- -
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
-trees[3] = undefined;
-if (3 in trees) {
-  // sẽ chạy vào đây
-}
-
- -

typeof

- -

Toán tử typeof có thể dùng theo cả hai cách dưới đây:

- -
typeof operand
-typeof (operand)
-
- -

Toán tử typeof trả về một chuỗi ký tự thể hiện kiểu của toán hạng. operand có thể là chuỗi ký tự, biến, từ khoá, hoặc object cần xác định kiểu. Không bắt buộc phải thêm dấu ngoặc tròn.

- -

Giả sử bạn có các biến sau:

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

Toán tử typeof trả về kết quả lần lượt cho từng biến:

- -
typeof myFun;       // trả về "function"
-typeof shape;       // trả về "string"
-typeof size;        // trả về "number"
-typeof foo;         // trả về "object"
-typeof today;       // trả về "object"
-typeof doesntExist; // trả về "undefined"
-
- -

Với từ khoá truenull, toán tử typeof trả về kết quả sau:

- -
typeof true; // trả về "boolean"
-typeof null; // trả về "object"
-
- -

Với số hoặc chuỗi ký tự, toán tử typeof trả về kết quả sau:

- -
typeof 62;            // trả về "number"
-typeof 'Hello world'; // trả về "string"
-
- -

Với giá trị thuộc tính, toán tử typeof trả về kiểu dữ liệu mà thuộc tính đó bao hàm:

- -
typeof document.lastModified; // trả về "string"
-typeof window.length;         // trả về "number"
-typeof Math.LN2;              // trả về "number"
-
- -

Với phương thức hoặc hàm, toán tử typeof trả về kết quả như sau:

- -
typeof blur;        // trả về "function"
-typeof eval;        // trả về "function"
-typeof parseInt;    // trả về "function"
-typeof shape.split; // trả về "function"
-
- -

Với các object tiền định nghĩa, toán tử typeof trả về kết quả như sau:

- -
typeof Date;     // trả về "function"
-typeof Function; // trả về "function"
-typeof Math;     // trả về "object"
-typeof Option;   // trả về "function"
-typeof String;   // trả về "function"
-
- -

void

- -

Toán tử void operator có thể dùng theo cả hai cách dưới đây:

- -
void (expression)
-void expression
-
- -

Toán tử void xác định biểu thực cần thực hiện mà không trả về giá trị nào. expression là một biểu thức JavaScript cần thực hiện. Dấu ngoặc tròn bao quanh expression là không bắt buộc, nhưng sẽ rất phong cách nếu dùng chúng.

- -

Bạn có thể dùng toán tử void để xác định biểu thức cần thực thi trong một siêu liên kết. Biểu thức sẽ được thực hiện nhưng không văn bản hiện tại sẽ không tải lại tại chỗ.

- -

Đoạn code sau tạo ra một siêu liên kết không thực hiện bất cứ điều gì khi có người dùng nhấn vào. Khi người dùng nhấn vào, void(0) thực hiện thành undefined, vốn không có hiệu ứng gì trong JavaScript.

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

Đoạn code sẽ tiến hành hoàn tất mẫu đơn khi người dùng bấm vào siêu liên kết.

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

Toán tử quan hệ

- -

Toán tử quan hệ so sánh các toán hạng của nó và trả về giá trị Boolean tuỳ thuộc phép so sánh có true hay không.

- -

in

- -

Toán tử in trả về true nếu thuộc tính nhất định có trong object nhất định. Cú pháp là:

- -
propNameOrNumber in objectName
-
- -

với propNameOrNumber là chuỗi ký tự hoặc số đại diện cho tên của thuộc tính hoặc chỉ mục mảng, và objectName là tên của object.

- -

Các ví dụ dưới đây chỉ ra vài cách dùng toán tử in.

- -
// Arrays
-var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
-0 in trees;        // trả về true
-3 in trees;        // trả về true
-6 in trees;        // trả về false
-'bay' in trees;    // trả về false (bạn phải xác định được chỉ mục của mảng,
-                   // không phải giá trị tại vị trí chỉ mục đó)
-'length' in trees; // trả về true (length là một thuộc tính của Array)
-
-// object dựng sẵn
-'PI' in Math;          // trả về true
-var myString = new String('coral');
-'length' in myString;  // trả về true
-
-// object tự tạo
-var mycar = { make: 'Honda', model: 'Accord', year: 1998 };
-'make' in mycar;  // trả về true
-'model' in mycar; // trả về true
-
- -

instanceof

- -

Toán tử instanceof trả về true nếu một object nhất định có kiểu của object nhất định. Cú pháp là:

- -
objectName instanceof objectType
-
- -

với objectName là tên của object để so sánh với objectType, và objectType là kiểu của object, như là {{jsxref("Date")}} hay {{jsxref("Array")}}.

- -

Dùng instanceof khi bạn cần xác nhận kiểu của một object trong runtime (thời gian chạy). Chẳng hạn, khi bắt ngoại lệ, bạn có thể tìm tới từng ngoại lệ riêng biện tuỳ thuộc vào kiểu ngoại lệ được quăng (throw) ra.

- -

Chẳng hạn, đoạn code dưới đây dùng instanceof để xác định xem liệu theDay có phải là một Date object hay không. Bởi vì theDay là một Date object, các lệnh trong sau điều kiện if được thực thi.

- -
var theDay = new Date(1995, 12, 17);
-if (theDay instanceof Date) {
-  // lệnh sẽ được thực thi
-}
-
- -

Thứ tự thực hiện toán tử

- -

Thứ tự thực hiện của toán tử xác định thứ tự thực hiện trong một biểu thức. Bạn có thể vượt quyền ưu tiên bằng cách dùng dấu ngoặc tròn.

- -

Bảng sau chỉ ra thứ tự thực hiện toán tử, từ cao nhất tới thấp nhất.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thứ tự thực hiện các toán tử
?Loại toán tửIndividual operators
member. []
gọi / tạo mới instance() new
phủ định/tăng! ~ - + ++ -- typeof void delete
nhân/chia* / %
cộng/trừ+ -
dịch bit<< >> >>>
quan hệ< <= > >= in instanceof
bằng== != === !==
bitwise-and&
bitwise-xor^
bitwise-or|
logical-and&&
logical-or||
điều kiện?:
gán= += -= *= /= %= <<= >>= >>>= &= ^= |=
?dấu phẩy,
- -

Bảng thứ tự thực hiện chi tiết hơn có thể tìm được trong JavaScript Reference.

- -

Biểu thức

- -

Biểu thức là đơn vị code hợp lệ mà giải được ra một giá trị.

- -

Mọi biểu thức đúng cú pháp đều trả về vài giá trị nào đó nhưng về mặt lý thuyết, có hai kiểu biểu thức: kèm tác dụng phụ (chẳng hạn: những biểu thức gán giá trị cho biến nào đó) và những biểu thức thực hiện gì đấy rồi trả về giá trị.

- -

Biểu thức x = 7 là ví dụ cho kiểu thứ nhất. Biểu thức này dùng toán tử = để gán giá trị cho biến x. Tự biểu thức trả về 7.

- -

Đoạn code 3 + 4 là ví dụ cho kiểu biểu thức thứ hai. Biểu thức này dùng toán tử + để thêm bốn vào ba mà không gán kết quả, bảy, cho một biến nào.
-
- JavaScript có các loại biểu thức sau đây:

- -
    -
  • Số học: tính toán thành một số, chẳng hạn 3.14159. (Thường dùng với toán tử số học.)
  • -
  • Chuỗi ký tự: tính toán thành một chuỗi ký tự, chẳng hạn, "Fred" hoặc "234". (Thường dùng với toán tử chuỗi.)
  • -
  • Logic: tính toán thành true hoặc false. (Thường đi cùng với toán tử luận lý.)
  • -
  • Biểu thức nguyên thuỷ: Từ khoá căn bản và biểu thức chung trong JavaScript.
  • -
  • Biểu thức vế-trái: Giá trị bên trái là đích của phép gán.
  • -
- -

Biểu thức nguyên thuỷ

- -

Từ khoá căn bản và biểu thức chung trong JavaScript.

- -

this

- -

Dùng từ khoá this để trỏ đến object hiện tại. Tổng quát, this trỏ tới object đang gọi trong một phương thức. Có thể dùng this cùng với dấu chấm hoặc dấu ngoặc vuông:

- -
this['propertyName']
-this.propertyName
-
- -

Giả sử hàm validate xác thực thuộc tính value của object, truyền vào cận trên và cận dưới của nó:

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

Bạn có thể gọi validate trong mỗi bộ xử lý sự kiện onChange trong form, dùng this để truyền vào phần tử của form, như trong ví dụ sau:

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

Toán tử nhóm

- -

Toán tử nhóm ( ) kiểm soát thứ tự thực hiện trong biểu thức. Chẳng hạn, bạn có thể cho phép nhân và chia thực hiện sau khi cộng và trừ.

- -
var a = 1;
-var b = 2;
-var c = 3;
-
-// thứ tự mặc định
-a + b * c     // 7
-// mặc định sẽ thực hiện như thế này
-a + (b * c)   // 7
-
-// giờ vượt thứ tự nào
-// cộng trước rồi mới nhân
-(a + b) * c   // 9
-
-// tương tự như
-a * c + b * c // 9
-
- -

Toán tử vế-trái

- -

Giá trị bên trái là đích của phép gán.

- -

new

- -

Bạn có thể dùng toán tử new để tạo ra một instance thuộc kiểu object mà người-dùng-định-nghĩa hoặc một trong những kiểu object dựng-sẵn. Dùng new như sau:

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

super

- -

Từ khoá super được dùng để gọi hàm thuộc cha của object. Thường dùng bởi classes để gọi phương thức khởi tạo của lớp cha, chẳng hạn.

- -
super([arguments]); // gọi phương thức khởi tạo của lớp cha.
-super.functionOnParent([arguments]);
-
- -

Toán tử Spread

- -

Toán tử spread cho phép biểu thức mở rộng tại chỗ khi có nhiều tham số (khi gọi hàm) hoặc nhiều phần tử (với array literal).

- -

Ví dụ: Nếu bạn có một mảng và muốn tạo một mảng mới với mảng cũ là một thành phần trong nó, cú pháp của array literal không bao giờ là đủ và bạn bắt buộc phải code chay, dùng tổ hợp push, splice, concat, vân vân. Với cú pháp spread, việc này súc tích hơn hẳn:

- -
var parts = ['shoulders', 'knees'];
-var lyrics = ['head', ...parts, 'and', 'toes'];
- -

Tương tự, toán tử spread cũng hoạt động với lời gọi hàm:

- -
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/vi/web/javascript/guide/functions/index.html b/files/vi/web/javascript/guide/functions/index.html deleted file mode 100644 index 069a43ef80..0000000000 --- a/files/vi/web/javascript/guide/functions/index.html +++ /dev/null @@ -1,668 +0,0 @@ ---- -title: Functions -slug: Web/JavaScript/Guide/Functions -tags: - - Bắt đầu - - Hướng dẫn - - JavaScript - - hàm -translation_of: Web/JavaScript/Guide/Functions ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}
- -

Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.

- -

See also the exhaustive reference chapter about JavaScript functions to get to know the details.

- -

Định nghĩa hàm

- -

Khai báo hàm

- -

Định nghĩa hàm (hay còn gọi là khai báo hằm, hoặc lệnh hàm) bao gồm từ khóa function, theo sau nó là:

- -
    -
  • Tên của hàm.
  • -
  • Danh sách các tham số truyền vào hàm, được đặt trong ngoặc đơn và cách nhau bởi dấu phẩy.
  • -
  • Các câu lệnh của JavaScript để tạo ra một hàm, được đặt trong ngoặc nhọn {...}.
  • -
- -

Ví dụ, để định nghĩa một hàm có tên là square:

- -
function square(number) {
-  return number * number;
-}
-
- -

Hàm square nhận 1 tham số, có tên là number. Hàm này bao gồm một câu lệnh mà nó sẽ trả về tham số (number) nhân với chính nó. Câu lệnh return chỉ định giá trị được trả lại bới hàm.

- -
return number * number;
-
- -

Các tham số nguyên thủy (primitive parameters - ví dụ như một số) được truyền vào hàm bằng giá trị; giá trị được truyền vào hàm, nhưng nếu hàm thay đổi giá trị của tham số, sự thay đổi này sẽ không ánh xạ trên phạm vi global hoặc trên hàm gọi đến nó (nó sẽ không thay đổi giá trị của tham số được truyền vào ở phạm vi bên ngoài hàm).

- -

Nếu bạn truyền vào hàm một tham số là object (một giá trị non-primitive), ví dụ như một mảng {{jsxref("Array")}} hoặc một object được user tự định nghĩa, và hàm thay đổi các thuộc tính của object, thay đổi đó sẽ có hiệu lực ngay cả ở phạm vi bên ngoài của hàm, giống như ví dụ dưới đây:

- -
function myFunc(theObject) {
-  theObject.make = "Toyota";
-}
-
-var mycar = {make: "Honda", model: "Accord", year: 1998};
-var x, y;
-
-x = mycar.make; // x nhận giá trị "Honda"
-
-myFunc(mycar);
-y = mycar.make; // y nhận giá trị "Toyota"
-                // (thuộc tính make đã bị thay đổi bởi hàm myFunc)
-
- -

Biểu thức hàm (hàm trong biến)

- -

Trong khi việc khai báo hàm ở trên là một câu lệnh về mặt cú pháp, các hàm cũng có thể tạo ra bằng một biểu thức hàm (function expression). Một hàm như vậy có thể nặc danh; nó không cần phải có tên. Ví dụ, hàm square có thể được khai báo như sau:

- -
const square = function(number) { return number * number }; // square lúc này là một hằng giúp nặc danh cho hàm gán cho nó
-var x = square(4) // x nhận giá trị 16
- -

Tuy nhiên, một cái tên có thể được cung cấp trong một biểu thức hàm. Việc cung cấp tên cho phép hàm có thể chạy chính nó, hoặc có thể sử dụng hệ thống debug để nhận dạng hàm trong stack traces.

- -
const factorial = function fac(n) { return n < 2 ? 1 : n * fac(n-1) };
-
-console.log(factorial(3));
-
- -

Các biểu thức hàm rất tiện lợi trong việc truyền một hàm vào một hàm khác dưới vai trò một đối số (argument). Ví dụ sau cho thấy hàm map sẽ nhận một hàm khác là đối số đầu tiên và đối số thứ hai là một mảng.

- -
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;
-}
-
- -

Trong đoạn code dưới đây, hàm map nhận vào một hàm khác đã được định nghĩa bằng một biểu thức hàm, và map sẽ thực thi nó trên mọi phần tử của mảng (được truyền vào như một đối số thứ hai):

- -
map(function(x) {return x * x * x}, [0, 1, 2, 5, 10]);
-
- -

Kết quả trả về: [0, 1, 8, 125, 1000].

- -

Trong JavaScript, một hàm có thể được định nghĩa dựa trên một điều kiện. Ví dụ, việc định nghĩa hàm dưới đây sẽ định nghĩa hàm myFunc chỉ khi num bằng 0.

- -
var myFunc;
-if (num == 0){
-  myFunc = function(theObject) {
-    theObject.make = "Toyota"
-  }
-}
- -

Ngoài các cách định nghĩa hàm đã được mô tả, bạn cũng có thể sử dụng {{jsxref("Function")}} constructor to create functions from a string at runtime, much like {{jsxref("eval", "eval()")}}.

- -

Một phương thức là một hàm mà hàm đó chính là thuộc tính của một object. Xem thêm về object và phương thức tại đây Working with objects.

- -

Gọi hàm

- -

Việc định nghĩa một hàm sẽ không thực thi nó. Định nghĩa một hàm đơn giản chỉ là đặt tên cho hàm và chỉ định những việc cụ thể sẽ làm khi hàm đó được gọi.

- -

Gọi hàm thực chất là thi hành các hành động cụ thể với các tham số được chỉ định. Ví dụ, nếu bạn định nghĩa hàm square, bạn có thể gọi nó như sau:

- -
square(5);
-
- -

Câu lệnh bên trên gọi hàm với một đối số của 5. Hàm thực thi các câu lệnh của nó và trả về giá trị 25.

- -

Các hàm phải đặt trong phạm vi (in scope) khi nó được gọi, nhưng việc khai báo hàm có thể được hoisted (câu lệnh khai báo hàm xuất hiện bên dưới dòng gọi hàm trong đoạn code), như ví dụ này:

- -
console.log(square(5));
-/* ... */
-function square(n) { return n*n }
-
- -

Phạm vi (scope) của một hàm là khoảng không gian bên trong hàm mà nó được khai báo (hoặc là cả chương trình, nếu nó được khai bảo ở top level, tức là nó không nằm trong hàm náo khác).

- -
-

Ghi chú: Điều này chỉ đúng khi định nghĩa một hàm bằng cách sử dụng các cú pháp ở trên (ví dụ function funcName(){}). Đoạn code bên dưới sẽ không hoạt động.

- -

Điều này có nghĩa rằng function hoisting chỉ hoạt động với cách khai báo hàm thông thường (function declarations) - function hoisting không hoạt động đối với hàm được khai báo bằng biểu thức hàm (function expression).

-
- -
console.log(square); // ReferenceError: square is not defined
-console.log(square(5)); // ReferenceError: square is not defined
-square = function (n) {
-  return n * n;
-}
-
- -

Các đối số của một hàm không bị giới hạn trong phạm vi các chuỗi và các số. Bạn có thể truyền các object hoàn chỉnh vào một hàm. Hàm show_props()(được định nghĩa trong Working with objects) là một ví dụ của một hàm mà nó nhận một object như là một đối số.

- -

Một hàm có thể gọi chính nó. Ví dụ, đây là một hàm tính giai thừa đệ quy:

- -
function factorial(n){
-  if ((n == 0) || (n == 1))
-    return 1;
-  else
-    return (n * factorial(n - 1));
-}
-
- -

Bạn có thể tính giai thừa của 1 tới 5 như sau:

- -
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
-
- -

Có những cách khác để gọi hàm. Có nhiều trường hợp mà tại đó một hàm cần phải được gọi một cách tự động, hoặc làm thay đổi số lượng đối số truyền vào một hàm, hoặc trong trường hợp mà việc gọi hàm cần được gắn với một object nhất định được quyết định tại thời điểm runtime.

- -

Điều đó lại hóa ra là các hàm tự bản thân chúng là các object, và kết quả là, những object này có các phương thức. (Xem {{jsxref("Function")}} object). Một trong số chúng, phương thức {{jsxref("Function.apply", "apply()")}}, có thể được dùng để đạt được mục tiêu này.

- -

Phạm vi của hàm (function scope)

- -

Các biến được định nghĩa bên trong một hàm không thể được truy cập từ nơi nào khác bên ngoài hàm, bởi vì biến đó được định nghĩa chỉ trong phạm vi của hàm. Tuy nhiên, một hàm có thể truy cập đến mọi biến và mọi hàm khác trong cùng phạm vi mà nó được định nghĩa.

- -

Nói cách khác, một hàm được định nghĩa trong phạm vi global có thể truy cập tới tất cả các biến đã được định nghĩa trong phạm vi global. Một hàm được định nghĩa bên trong một hàm khác có thể truy cập đến tất cả biến được định nghĩa bên trong hàm cha của nó, và bất cứ biến nào khác mà hàm cha của nó có quyền truy cập đến.

- -
// Các biến sau được định nghĩa trong phạm vi global scope
-var num1 = 20,
-    num2 = 3,
-    name = "Chamahk";
-
-// Hàm này được định nghĩa trong phạm vi global scope
-function multiply() {
-  return num1 * num2;
-}
-
-multiply(); // Returns 60
-
-// Một ví dụ hàm lồng nhau
-function getScore () {
-  var num1 = 2,
-      num2 = 3;
-
-  function add() {
-    return name + " scored " + (num1 + num2);
-  }
-
-  return add();
-}
-
-getScore(); // Returns "Chamahk scored 5"
-
- -

Phạm vi và ngăn xếp của hàm

- -

Recursion

- -

Một hàm có thể tham chiếu và gọi chính nó. Có 3 cách để một hàm có thể tham chiếu đến chính nó:

- -
    -
  1. Dùng tên của hàm
  2. -
  3. arguments.callee
  4. -
  5. Một biến in-scope mà có tham chiếu đến hàm.
  6. -
- -

Ví dụ, xem xét việc định nghĩa hàm sau đây:

- -
var foo = function bar() {
-   // statements go here
-};
-
- -

Bên trong phần body của hàm, các điều sau là tương tự nhau:

- -
    -
  1. bar()
  2. -
  3. arguments.callee()
  4. -
  5. foo()
  6. -
- -

Một hàm mà gọi chính nó được gọi là (hàm đệ quy) recursive function. Trong một số cách hiểu, thì đệ quy (recursion) cũng tương tự như một vòng lặp. Cả hai đều là thực thi một đoạn code lặp đi lặp lại nhiều lần, và cả hai đều yêu cầu điều kiện xác định để chạy (để tránh lặp vô tận, hoặc recursion vô tận). Ví dụ, vòng lặp sau đây... 

- -
var x = 0;
-while (x < 10) { // "x < 10" là điều kiện lặp
-   // thực thi việc sau
-   x++;
-}
-
- -

...có thể được chuyển đổi sang một hàm đệ quy:

- -
function loop(x) {
-  if (x >= 10) // "x >= 10" là điều kiện thoát ra (tương đương với "!(x < 10)")
-    return;
-  // do stuff
-  loop(x + 1); // the recursive call
-}
-loop(0);
-
- -

Tuy nhiên, một số thuật toán không phải là các vòng lặp chỉ đơn giản là được lặp đi lặp lại. Ví dụ, việc lấy tất cả các nodes của một cấu trúc tree (như DOM) sẽ được thực hiện dễ dàng hơn thông qua đệ quy:

- -
function walkTree(node) {
-  if (node == null) //
-    return;
-  // do something with node
-  for (var i = 0; i < node.childNodes.length; i++) {
-    walkTree(node.childNodes[i]);
-  }
-}
-
- -

So với hàm loop, mỗi một lần gọi đệ quy sẽ tạo ra nhiều lần gọi đệ quy tại đây.

- -

Bạn có thể chuyển đổi bất kỳ thuật toán đệ quy nào sang một dạng non-recursive, nhưng logic thường sẽ phức tạp hơn rất nhiều, và làm như vậy cũng đòi hỏi sử dụng một ngăn xếp (a stack).

- -

Thực tế, việc đệ quy bản thân nó khi đệ quy có sử dụng một ngăn xếp: gọi là ngăn xếp hàm (function stack). Lối thực thi dạng ngăn xếp này có thể được tìm thấy trong ví dụ dưới đây:

- -
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
- -

Hàm lồng nhau và các closures

- -

Bạn có thể lồng một hàm bên trong một hàm khác. Hàm con (bên trong) được là private cho hàm chứa nó (hàm bao bên ngoài).

- -

Điều đó cũng định hình nên một closure. Một closure là một biểu thức (thường thì chính là một hàm) mà biểu thức đó có thể có các biến tự do kết hợp với môi trường trói buộc chúng (hay nói cách khác là môi trường giúp "close" biểu thức).

- -

Vì một hàm con là một closure, có nghĩa rằng hàm con có thể "thừa kế" các tham số và các biến của hàm cha. Nói cách khác, một hàm con sẽ chứa scope của hàm cha.

- -

Tóm tắt lại:

- -
    -
  • Hàm con chỉ có thể được truy cập từ các câu lệnh đặt bên trong hàm cha.
  • -
  • Hàm con sẽ định hình nên một closure: hàm con có thể sử dụng các đối số và các biến của hàm cha, trong khi hàm cha không thể sử dụng các đối số và các biến của hàm con.
  • -
- -

Ví dụ sau chỉ ra các hàm được lồng nhau:

- -
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
-
- -

Vì hàm con định hình nên một closure, bạn có thể gọi hàm cha đồng thời chỉ định các đối số cho cả hàm cha và hàm con.

- -
function outside(x) {
-  function inside(y) {
-    return x + y;
-  }
-  return inside;
-}
-fn_inside = outside(3); // Kết quả trả về hàm inside(y)
-result = fn_inside(5); // Trả về 8
-
-result1 = outside(3)(5); // Trả về 8, các đối số được thêm đồng thời cùng lúc
-
- -

Sự bảo tồn của các biến

- -

Để ý cách mà x được bảo tồn sau khi hàm inside returne. Một closure phải bảo tồn các đối số và các biến bên trong mọi scope mà nó tham chiếu. Vì mỗi lần gọi hàm mang đến các tham số đôi khi khác nhau, nên một closure mới sẽ được tạo ra cho mỗi lần gọi hàm outside. Bộ nhớ bảo tồn này chỉ có thể được giải phóng khi hàm inside được return không còn khả dụng.

- -

Điều này không khác gì so với lưu trữ các sự tham chiếu bên trong các object khác, nhưng điều này ít rõ ràng hơn vì nó không thiết lập các sự tham chiếu một cách trực tiếp và cũng không thể kiểm tra được chúng.

- -

Các hàm lồng nhau nhiều cấp

- -

Các hàm có thể được lồng nhau nhiều cấp. Ví dụ:

- -
    -
  • Một hàm (A) chứa một hàm (B), hàm (B) này chứa một hàm (C)
  • -
  • Ở đây, cả hai hàm B và C định hình nên các closures.Vì thế, B có thể truy cập đến A, và C có thể truy cập đến B.
  • -
  • Ngoài ra, vì C có thể truy cập đến B mà B truy cập được đến A, nên C cũng có thể truy cập đến A.
  • -
- -

Do đó, các closures có thể chứa nhiều scope đa cấp; các closures sẽ bao gồm luôn cả phạm vi scope của các hàm chưa nó, việc bao gồm này có hình thức đệ quy. Đây gọi là scope chaining. (Lí do tại sao gọi là "chaining" sẽ giải thích sau).

- -

Cân nhắc ví dụ sau:

- -
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)
-
- -

Trong ví dụ này, C truy cập đến y của  B và x của  A. Điều này có thể đạt được bởi vì: 

- -
    -
  1. B định hình một closure mà closure này bao gồm A, ví dụ B có thể truy cập đến các đối số và biến của A.
  2. -
  3. C định hình nên một closure mà closure này bao gồm B.
  4. -
  5. Vì closure của B bao gồm A, closure của C bao gồm AC có thể truy cập đến biến và đối số của cả hai hàm A và B. Nói cách khác, C chains the scopes của B và A, theo đúng thứ tự đó.
  6. -
- -

Tuy nhiên nếu chạy ngược lại thì không đúng. A không thể truy cập đến C, vì A không thể truy cập đén các đối số và biến của B, mà C chính là một biến của B. Vì vậy C duy trì quyền truy cập private chỉ riêng đối với B.

- -

Xung đột tên gọi

- -

Khi hai đối số hoặc biến trong một scope của một closure có tên giống nhau, sẽ xảy ra xung đột tên gọi, scope nào nằm ở trong sâu hơn thì được ưu tiên. Cho nên, scope trong cùng sẽ mang ưu tiên cao nhất, trong khi scope ngoài cùng ưu tiên thấp nhất. Đây chính là scope chain (chuỗi xích phạm vi). Mắc xích đầu tiên của chain là scope trong cùng, và mắc xích cuối cùng của chain là scope ngoài cùng. Xem xét ví dụ sau:

- -
function outside() {
-  var x = 10;
-  function inside(x) {
-    return x;
-  }
-  return inside;
-}
-result = outside()(20); // returns 20 thay vì 10
-
- -

Xung đột tên gọi xảy ra tại câu lệnh return x giữa tham số x của hàm inside và tham số x của hàm outside. Scope chain ở đây là {inside, outside, global object}. Vì vậy tham số x của inside được ưu tiên hơn x của outside, và 20 (giá trị x của insisde) được trả về thay vì 10.

- -

Closures

- -

Closures là một trong những chức năng quyền lực nhất của JavaScript. JavaScript cho phép lồng các function vào nhau, và cấp quyền cho function con, để function con có toàn quyền truy cập vào tất cả các biến và function được định nghĩa bên trong function cha (và tất cả biến và function mà function cha được cấp quyền truy cập đến).

- -

Tuy nhiên, function cha không có quyền truy cập đến các biến và function được định nghĩa bên trong function con. Điều này tạo nên một dạng bảo mật khép kín cho các biến của function con.

- -

Bên cạnh đó, vì function con có quyền truy cập đến scope của function cha, các biến và function được định nghĩa bên trong function cha sẽ vẫn tồn tại dù việc thực thi function cha đã kết thúc, nếu function con xoay sở để tồn tại lâu hơn thời gian sống của function cha. Một closure được tạo ra khi một function con bằng cách nào đó trở nên khả dụng với bất kỳ scope nào bên ngoài function cha.

- -
var pet = function(name) {   // Function cha định nghĩa một biến tên là "name"
-  var getName = function() {
-    return name;             // Function con có quyền truy cập đến biến "name" của function cha
-  }
-  return getName;            // Trả về function con, theo đó làm function con bị phơi bày ra phạm vi scope bên ngoài (không còn bị giới hạn bên trong function cha nữa)
-},
-myPet = pet("Vivie");
-
-myPet();                     // Returns "Vivie"
-
- -

Thực tế sẽ phức tạp hơn nhiều so với đoạn code bên trên. Nó có thể trả về một object bao gồm các phương thức phục vụ cho việc điều khiển các biến bên trong một function cha.

- -
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
-
- -

Tron đoạn code trên, các function con có thể truy cập vào biến name của function cha, và không có cách nào khác để truy cập vào các biến của function con ngoại trừ thông qua function con. Các biến bên trong của function con đóng vai trò như kho lưu trữ an toàn cho các đối số và biến bên ngoài. Chúng giữ dữ liệu một cách kiên định, và nội bộ, để function con xử lý. Các functions thậm chí không cần phải gán vào bất kỳ biến nào, và cũng không cần tên.

- -
var getCode = (function(){
-  var secureCode = "0]Eal(eh&2";    // Đoạn code chúng ta không muốn những thứ bên ngoài có thể thay đổi nó...
-
-  return function () {
-    return secureCode;
-  };
-})();
-
-getCode();    // Returns the secureCode
-
- -

Lưu ý: Có một vài cạm bẫy cần đề phòng khi sử dụng các closures!

- -

Nếu một function bị bọc kín định nghĩa một biến với tên trùng với tên của function bên ngoài, từ đó sẽ không có cách nào khác để tham chiếu đến biến của function bên ngoài nữa. (Lúc này biến của function bên trong đã ghi đè lên biến bên ngoài, cho đến khi chương trình thoát khỏi scope bên trong.)

- -
var createPet = function(name) {  // Outer function defines a variable called "name"
-  return {
-    setName: function(name) {    // Enclosed function also defines a variable called "name"
-      name = name;               // ??? How do we access the "name" defined by the outer function ???
-    }
-  }
-}
-
- -

The magical this variable is very tricky in closures. They have to be used carefully, as what this refers to depends completely on where the function was called, rather than where it was defined.

- -

Sử dụng arguments object

- -

Các đối số của một function được giữ dưới dạng một object dạng mảng. Trong phạm vi function, bạn có thể định vị các đối số được truyền vào function bằng cách sau:

- -
arguments[i]
-
- -

trong đó i là số thứ tự của đối số, bắt đầu từ 0. Vì vậy, đối số đầu tiên được truyền vào một function sẽ là arguments[0]. Tổng số đối số được xác định bằng arguments.length.

- -

Sử dụng các arguments object, bạn có thể gọi một function với số đối số nhiều hơn số đối số được chấp nhận thông qua khai báo chính thức. Điều này sẽ hữu ích khi bạn không biết trước có bao nhiêu đối số sẽ được truyền vào function. Bạn có thể sử dụng arguments.length để xác định số lượng đối số thực tế được truyền vào function, và sau đó truy cập đến từng đối số bằng cách dùng arguments object. 

- -

Ví dụ, xem xét một function có chức năng nối các string với nhau. Đối số chính thức duy nhất cho function là một string, và string này xác định những ký tự nào sẽ tách các phần tử ra để nối. Function được định nghĩa như sau:

- -
function myConcat(separator) {
-   var result = "", // initialize list
-       i;
-   // iterate through arguments
-   for (i = 1; i < arguments.length; i++) {
-      result += arguments[i] + separator;
-   }
-   return result;
-}
-
- -

Bạn có thể truyền vào bao nhiêu đối số vào function này cũng được, và nó sẽ nối từng đối số với nhau tạo thành một "list" có kiểu string.

- -
// 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");
-
- -
-

Ghi chú: Biến arguments nhìn giống mảng, nhưng nó không phải là một mảng. Nó giống mảng ở chỗ bên trong nó có các index được đánh số và nó có một thuộc tính length. Tuy nhiên, nó không sở hữu bất kỳ phương thức nào để thao tác sử dụng mảng.

-
- -

Xem {{jsxref("Function")}} object trong JavaScript reference để biết thêm.

- -

Các tham số của function

- -

Kể từ ES6, xuất hiện 2 dạng tham số mới: default parameters và rest parameters

- -

Default parameters

- -

Trong JavaScript, các tham số của function được mặc định là undefined. Tuy nhiên, trong một số trường hợp nó có thể hữu ích để thiết lập một giá trị mặc định khác. Đây chính xác là điều mà default parameters sẽ làm.

- -

Khi không có default parameters (trước ES6)

- -

Trong quá khứ, chiến thuật thông thường để thiết lập các giá trị mặc định là kiểm định giá trị của các tham số bên trong body của function và gán giá trị cho nó nếu nó là undefined.

- -

Trong ví dụ sau, nếu không có giá trị nào được truyền cho b, giá trị của nó sẽ là undefined khi thực hiện tính toán a*b, và việc gọi hàm multiply sẽ trả về NaN. Tuy nhiên, điều này bị ngăn chặn bởi dòng thứ 2 trong ví dụ này:

- -
function multiply(a, b) {
-  b = typeof b !== 'undefined' ?  b : 1;
-
-  return a*b;
-}
-
-multiply(5); // 5
-
- -

Khi có default parameters (sau ES6)

- -

Với default parameters, việc kiểm tra thủ công bên trong body của function không còn cần thiết. Bạn có thể đơn giản chỉ là đặt 1 vào làm giá trị mặc định cho b ngay tại head của function:

- -
function multiply(a, b = 1) {
-  return a*b;
-}
-
-multiply(5); // 5
- -

Để chi tiết hơn, xem default parameters trong phần tham khảo.

- -

Rest parameters

- -

Cú pháp rest parameter cho phép chúng ta dùng 1 mảng để đại diện cho số lượng vô hạn các đối số.

- -

Trong ví dụ sau, hàm multiply sử dụng rest parameters để thu thập các đối số kể từ đối số hứ hai trở về đến hết. Hàm này sau đó sẽ nhân những đối số này với đối số đầu tiên.

- -
function multiply(multiplier, ...theArgs) {
-  return theArgs.map(x => multiplier * x);
-}
-
-var arr = multiply(2, 1, 2, 3);
-console.log(arr); // [2, 4, 6]
- -

Arrow functions

- -

Một arrow function expression (trước đây, và hiện tại được biết đến một cách không còn đúng là fat arrow function) có một cú pháp ngắn hơn function expressions và không có thisargumentssuper, or new.target của chính nó. Các arrow function luôn luôn là nặc danh. Xem "ES6 In Depth: Arrow functions".

- -

Có 2 yếu tố dẫn đến việc giới thiệu arrow function: các function ngắn hơn và sự non-binding của this (lexical this).

- -

Các function ngắn hơn

- -

Trong một mẫu function, các function ngắn hơn được khuyến khích. So sánh:

- -
var a = [
-  'Hydrogen',
-  'Helium',
-  'Lithium',
-  'Beryllium'
-];
-
-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]
- -

No separate this (Lexical this)

- -

Trước khi có arrow functions, mọi function mới sẽ tự định nghĩa giá trị this của nó (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). Điều này đã được chứng minh là không lý tưởng đối với phong cách lập trình hướng đối tượng.

- -
function Person() {
-  // Constructor của Person() tự định nghĩa `this`.
-  this.age = 0;
-
-  setInterval(function growUp() {
-    // Trong nonstrict mode, hàm growUp() định nghĩa `this`
-    // như là một global object, và global object này khác với `this`
-    // được định nghĩa bởi Person() constructor.
-    this.age++;
-  }, 1000);
-}
-
-var p = new Person();
- -

Trong ECMAScript 3/5, vấn đề này được sửa chữa bằng cách gán giá trị bên trong this cho một biến mà biến đó có thể được đóng hoàn toàn.

- -
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);
-}
-
-var p = new Person();
-
- -

Predefined functions

- -

JavaScript has several top-level, built-in functions:

- -
-
{{jsxref("Global_Objects/eval", "eval()")}}
-
-

The eval() method evaluates JavaScript code represented as a string.

-
-
{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}
-
-

The uneval() method creates a string representation of the source code of an {{jsxref("Object")}}.

-
-
{{jsxref("Global_Objects/isFinite", "isFinite()")}}
-
-

The global isFinite() function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number.

-
-
{{jsxref("Global_Objects/isNaN", "isNaN()")}}
-
-

The isNaN() function determines whether a value is {{jsxref("Global_Objects/NaN", "NaN")}} or not. Note: coercion inside the isNaN function has interesting rules; you may alternatively want to use {{jsxref("Number.isNaN()")}}, as defined in ECMAScript 6, or you can use typeof to determine if the value is Not-A-Number.

-
-
{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}
-
-

The parseFloat() function parses a string argument and returns a floating point number.

-
-
{{jsxref("Global_Objects/parseInt", "parseInt()")}}
-
-

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

-
-
{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}
-
-

The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or by a similar routine.

-
-
{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}
-
-

The decodeURIComponent() method decodes a Uniform Resource Identifier (URI) component previously created by {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} or by a similar routine.

-
-
{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}
-
-

The encodeURI() method encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

-
-
{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}
-
-

The encodeURIComponent() method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

-
-
{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}
-
-

The deprecated escape() method computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} instead.

-
-
{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}
-
-

The deprecated unescape() method computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The escape sequences might be introduced by a function like {{jsxref("Global_Objects/escape", "escape")}}. Because unescape() is deprecated, use {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} instead.

-
-
- -

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

diff --git a/files/vi/web/javascript/guide/grammar_and_types/index.html b/files/vi/web/javascript/guide/grammar_and_types/index.html deleted file mode 100644 index 910d465526..0000000000 --- a/files/vi/web/javascript/guide/grammar_and_types/index.html +++ /dev/null @@ -1,711 +0,0 @@ ---- -title: Cú pháp lập trình -slug: Web/JavaScript/Guide/Grammar_and_types -translation_of: Web/JavaScript/Guide/Grammar_and_types -original_slug: Web/JavaScript/Guide/cu-phap-lap-trinh ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
- -

Phần này nói về các cú pháp cơ bản của ngôn ngữ JavaScript, các cách khai báo biến, các loại dữ liệu và chính tả (literal).

- -

Cơ bản

- -

Cú pháp của JavaScript (JS) phần lớn được vay mượn từ Java, nhưng JS cũng chịu ảnh hưởng từ cú pháp của các ngôn ngữ lập trình khác như Awk, Perl và Python.

- -

JavaScript là ngôn ngữ lập trình sử dụng chuẩn kí tự Unicode và khi viết cũng cần phải lưu ý phân biệt chữ HOA và chữ thường (case-sensitive). Điều này có nghĩa là các từ như Früh (trong tiếng Đức có nghĩa là "sớm" - early) có thể được sử dụng đặt tên cho biến.

- -
let Früh = "foobar"
-
- -

In JavaScript, instructions are called {{Glossary("Statement", "statements")}} and are separated by a semicolon (;).

- -

Dấu chấm phẩy (;) chỉ cần thiết nếu trên cùng một dòng có từ hai câu lệnh trở lên. Trường hợp câu lệnh nằm riêng một dòng thì không cần dấu chấm phẩy.

- -

ECMAScript cũng có những nguyên tắc để tự động thêm dấu chấm phẩy (ASI) để đánh dấu kết thúc một dòng lệnh. (Để biết thêm, xem tài liệu tham khảo chi tiết tại đây: JavaScript's lexical grammar.)

- -

Thực tế thì nên luôn luôn thêm một dấu chấm phẩy vào cuối mỗi câu lệnh, thậm chí khi điều này là không bắt buộc. Việc làm này sẽ giúp tránh bớt bug.

- -

Các đoạn mã Javascript sẽ được đọc từ trái qua phải và được chuyển thể thành một chuỗi các input elements bao gồm: tokens, control characters, line terminators, comments hoặc {{glossary("whitespace")}}. (Spaces, tabs, và các ký tự đánh dấu dòng mới được xem là whitespace.)

- -

Comments

- -

Cú pháp của comments thì ... giống với C++ và một số ngôn ngữ lập trình khác:

- -
// a one line comment <-- đây là cách comment trên 1 dòng
-
-/* this is a longer, cho những dòng dài hoặc nhiều dòng
-   multi-line comment. hãy sử dụng kiểu comment này
- */
-
-/* You can't, however /* nest comments */ SyntaxError */ <-- Không nên lồng comment trong comment, như đoạn comment này sẽ gây ra lỗi vì "/*" được mở bên trong comment trước đó không có hiệu lực đối với từ SyntaxError nên dấu đóng comment "*/" sẽ gây ra lỗi cú pháp. 
- -

Comments hoạt động như whitespace, và sẽ bị bỏ qua trong quá trình script chạy.

- -

Note: Bạn có thể thấy loại cú pháp comment này trong một số file javascript #!/usr/bin/env node.

- -

Đây là cú pháp hashbang comment, và là một comment đặc biệt sử dụng để chỉ định đường dẫn đến một Javascript interpreter cụ thể có nhiệm vụ sẽ chạy đoạn script. Xem chi tiết Hashbang comments.

- -

Khai báo biến

- -

Có 3 kiểu khai báo biến trong JavaScript.

- -
-
{{jsxref("Statements/var", "var")}}
-
Khai báo một biến, và tùy ý bạn có hoặc không khởi tạo giá trị cho nó.
-
{{jsxref("Statements/let", "let")}}
-
Khai báo một block-scoped, hoặc biến local, chỉ có thể truy cập được trong block bao quanh nó.
-
-
function foo() {
-  var x = 10;
-  if (true) {
-   let x = 20; // x ở đây được khai báo lại nhưng khi ra khỏi block-scoped nó sẽ nhận lại giá trị bên trên là 10
-   console.log(x); // in ra 20
-  }
-   console.log(x); // in ra 10
-}
-
-
{{jsxref("Statements/const", "const")}}
-
Khai báo một hằng block-scoped, read-only.
-
- -

Biến

- -

Bạn sử dụng biến như là tên tượng trưng cho các giá trị trong chương trình. Tên của biến được gọi là {{Glossary("Identifier", "identifier")}}, tuân theo những quy tắc nhất định.

- -

Tên biến phải bắt đầu bằng một 'chữ cái', kí tự gạch dưới (_), hoặc kí tự dollar ($). Các ký tự tiếp theo cũng có thể là các chữ số 0-9.  Vì JavaScript là case sensitive, các chữ các bao gồm các ký tự từ "A" đến "Z" (viết hoa) và "a" đến "z" (viết thường).

- -

Bạn có thể sử dụng chuẩn ISO 8859-1 hoặc các kí tự Unicode như å và ü trong tên biến, thậm chí cả các kí tự dạng Unicode escape sequences.

- -

Ví dụ: Number_hits, temp99, and _name.

- -

Declaring variables

- -

Có hai cách khai báo biến:

- -
    -
  • Sử dụng từ khóa {{jsxref("Statements/var", "var")}}. Ví dụ var x = 42. Cú pháp này dùng khai báo cả 2 loại biến local global, tùy thuộc vào ngữ cảnh thực thi.
  • -
  • Sử dụng từ khóa  {{jsxref("Statements/const", "const")}} hoặc  {{jsxref("Statements/let", "let")}}. Ví dụ let y = 13. Cú pháp này dùng khai báo biến local nhưng chỉ có phạm vi trong block-scoped. (Xem Variable scope bên dưới).
  • -
- -

Bạn cũng có thể khai báo biến mà không dùng các từ khóa trên, ví dụ x = 42. Điều này sẽ tạo ra một biến undeclared global variable. Nó sẽ tạo nên một warning trong JavaScript. Undeclared variables có thể dẫn đến các hành vi không mong muốn. Nên khuyến cáo không nên sử dụng chúng.

- -

Evaluating variables

- -

Một biến được khai báo với cú pháp var hoặc let mà không gán giá trị, sẽ có giá trị mặc định là {{jsxref("undefined")}}.

- -

Truong trường hợp truy cập đến một biến chưa được khai báo, thì exception {{jsxref("ReferenceError")}} sẽ được thrown:

- -
var a;
-console.log('The value of a is ' + a); // The value of a is undefined
-
-console.log('The value of b is ' + b); // The value of b is undefined
-var b;
-// This one may puzzle you until you read 'Variable hoisting' below
-
-console.log('The value of c is ' + c); // Uncaught ReferenceError: c is not defined
-
-let x;
-console.log('The value of x is ' + x); // The value of x is undefined
-
-console.log('The value of y is ' + y); // Uncaught ReferenceError: y is not defined
-let y; 
- -

Bạn có thể sử dụng undefined  để xét xem một biến có đang mang giá trị không. Dưới đây là một ví dụ, biến input chưa được gán giá trị, nên biến input lúc này mang giá trị mặc định undefined vậy câu điều kiện if là return true và không chạy vào else.

- -
var input;
-if(input === undefined){
-  doThis();
-} else {
-  doThat();
-}
-
- -

Giá trị undefined tương đương với fasle khi sử dụng trong bối cảnh boolean, như ví dụ dưới đây, chương trình sẽ chạy function myFunction vì element myArray[0]là undefined trả về false.

- -
var myArray = [];
-if (!myArray[0]) {
-  myFunction();
-}
-
-function myFunction() {
-  alert('return false');
-}
-
- -

Khi biến có giá trị = undefined thực hiện phép toán với biến có giá trị cụ thể hoặc hằng số sẽ cho ra giá trị  = NaN (not a number). 

- -
var a;
-a + 2 = NaN
- -

Null khác với Undefined. Khi biến có giá trị {{jsxref("null")}}, biến sẽ mang giá trị 0 trong các phép toán (numeric) và false trong các ngữ cảnh boolean. Ví dụ:

- -
var n = null;
-console.log(n * 32); // Will log 0 to the console
-
- -

Variable scope

- -

Khi bạn khai báo một biến bên ngoài function, biến đó được gọi là global variable, bởi vì biến đó sẽ có hiệu lực đến bất kì đoạn code nào khác trong document hiện tại. Khi bạn khai báo một biến bên trong một function, nó gọi là local variable, vì nó chỉ có thể dùng được trong phạm vi function đó.

- -

Javascript trước phiên bản ECMAScript 6 không có định nghĩa  block statement scope; thay vào đó, một biến được khai báo trong một block được xem là có giá trị local đối với function (hoặc global scope) mà block đó cư trú.

- -

Ví dụ sau đây sẽ log ra 5, vì scope của x là global context (hoặc function context nếu đoạn code này là một phần của function khác). Scope của x không bị giới hạn vào block câu lệnh if trực tiếp gần nhất.

- -
if (true) {
-  var x = 5;
-}
-console.log(x);  // 5
-
- -

Điều này đã thay đổi khi sử dụng kiểu khai báo let được giới thiệu trong ECMAScript 6.

- -
if (true) {
-  let y = 5;
-}
-console.log(y);  // ReferenceError: y is not defined (y bị giới hạn trực tiếp trong block chứa nó)
-
- -

Variable hoisting

- -

Một thứ không bình thường khác về các biến trong JavaScript là bạn có thể tham chiếu đến một biến tại vị trí phía trước câu lệnh khai báo. Khái niệm này gọi là hoisting; các biến trong JavaScript ở khía cạnh nào đó sẽ được "hoisted" (treo) hoặc lifted (nâng) vào vị trí trên cùng của câu lệnh hoặc hàm gần nó nhất. Tuy nhiên, các variables bị hoisted này sẽ trả về giá trị undefined. Nên cho dù bạn khai báo và khởi tạo sau khi bạn sử dụng hoặc tham chiếu đến biến này, thì trước đó nó vẫn trả về undefined.

- -
/**
- * Example 1
- */
-console.log(x); // undefined
-var x = 3;
-console.log(x); // 3
-
-/**
- * Example 2
- */
-// will return a value of undefined
-var myvar = "my value";
-
-(function() {
-  console.log(myvar); // undefined vì bên dưới có dòng khai báo var myvar, điều này làm biến myvar bị hoisting và nhận giá trị mới là undefined (giá trị 'my value' lúc này không còn hiệu lực vì biến đã bị hoisting)
-  var myvar = "local value";
-})();
-
- -

Ví dụ bên trên có thể được biểu đạt theo cách khác như sau:

- -
/**
- * 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";
-})();
-
- -

Vì vấn đề hoisting này, tất cả các câu lệnh khai báo biến với var bên trong một function nên được đặt gần với đầu của function nhất có thể. Làm điều này giúp gia tăng độ rõ ràng của code (trường hợp dùng var như trong ví dụ 2 ở trên sẽ gây ra hoisting).

- -

Function hoisting

- -

Trong trường hợp của các function, chỉ các function được tạo theo kiểu function declaration là bị hoisted, còn function được tạo theo kiểu function expression thì không. Khác với variable hoisting, hoisted function không trả về giá trị mặc định undefined. Ví dụ:

- -
/* Function declaration */
-
-foo(); // "bar"
-
-function foo() {
-  console.log('bar');
-}
-
-
-/* Function expression */
-
-baz(); // TypeError: baz is not a function
-
-var baz = function() {
-  console.log('bar2');
-};
- -

Biến toàn cục (global variables)

- -

Các global variables trên thực tế là những properties của global object. Trong các web page, global object chính là window, nên bạn có thể set và truy cập đến các global variables bằng cách sử dụng cú pháp window.variable.

- -

Hệ quả  là, bạn có thể truy cập đến các global variables được khai báo trong một window hoặc frame từ một window hoặc frame khác, bằng cách chỉ định rõ tên của window hoặc frame. Ví dụ, nếu một biến có tên phoneNumber được khai báo trong một document, bạn có thể tham chiếu đến biến này từ một iframe như là parent.phoneNumber.

- -

Constants

- -

Bạn có thể tạo các hằng số read-only với từ khóa {{jsxref("Statements/const", "const")}}. Cú pháp đặt tên cho hằng cũng giống như biến, tên hằng phải bắt đầu bằng một chữ cái, hoặc dấu gạch dưới _, hoặc dấu dollar $, và có thể bao gồm mọi ký tự chữ, số, hoặc dấu gạch dưới.

- -
const PI = 3.14;
-
- -

Một hằng số đã khai báo không thể thay đổi giá trị thông qua việc gán lại giá trị hoặc không thể bị khai báo lại trong khi đoạn script đang chạy. Và bắt buộc phải được gán giá trị ngay khi khởi tạo.

- -

Các nguyên tắc về scope cho các hằng số cũng giống như cách các biến block-scoped như let hoạt động.

- -

Bạn không thể khai báo một hằng số với tên trùng với tên function hoặc biến trong cùng một scope. Ví dụ:

- -
// THIS WILL CAUSE AN ERROR
-function f() {};
-const f = 5;
-
-// THIS WILL CAUSE AN ERROR ALSO
-function f() {
-  const g = 5;
-  var g;
-
-  //statements
-}
-
- -

Tuy nhiên, khi gán một object vào một hằng, thì các thuộc tính của object đó là not protected, nên câu lệnh dưới đây sẽ được thực thi mà không lỗi.

- -
const MY_OBJECT = {'key': 'value'};
-MY_OBJECT.key = 'otherValue';
- -

Cũng tương tự, các nội dung trong một mảng cũng là not protected, nên câu lệnh dưới đây sẽ được thực thi mà không lỗi.

- -
const MY_ARRAY = ['HTML','CSS'];
-MY_ARRAY.push('JAVASCRIPT');
-console.log(MY_ARRAY); //logs ['HTML','CSS','JAVASCRIPT'];
- -

Cấu trúc dữ liệu và kiểu dữ liệu

- -

Kiểu dữ liệu

- -

Tiêu chuẩn mới nhất của ECMAScript định nghĩa 8 kiểu dữ liệu:

- -
    -
  • Bảy kiểu dữ liệu nguyên thủy {{Glossary("Primitive", "primitives")}}: -
      -
    1. {{Glossary("Boolean")}}. true và false.
    2. -
    3. {{Glossary("null")}}. Một từ khóa đạc biệt biểu thị giá trị null. Vì JavaScript là case-sensitive, null sẽ không giống với Null, NULL, hoặc bất kỳ biến thể khác.
    4. -
    5. {{Glossary("undefined")}}. Một thuộc tính top-level mà giá trị của nó là không xác định.
    6. -
    7. {{Glossary("Number")}}. Một số nguyên (integer) hoặc số thực dấu chấm động (floating point number) 42 or 3.14159.
    8. -
    9. {{Glossary("BigInt")}}. An integer with arbitrary precision. For example: 9007199254740992n.
    10. -
    11. {{Glossary("String")}}. Một chuỗi các ký tự đại diện cho một giá trị văn bản. Ví dụ: "Howdy".
    12. -
    13. {{Glossary("Symbol")}} (new in ECMAScript 6). Một kiểu dữ liệu mà các instance của nó là duy nhất và bất biến.
    14. -
    -
  • -
  • Và {{Glossary("Object")}}
  • -
- -

Mặc dù những kiểu dữ liệu này tương đối ít, chúng cho phép bạn có thể thể hiện những hàm rất hữu dụng. {{jsxref("Object", "Objects")}} và {{jsxref("Function", "functions")}} là những phần tử nền tảng khác của JavaScript. Bạn có thể xem object như là những vùng chứa được đặt tên (named container) để phục vụ cho các giá trị, và các hàm là những quy trình thủ tục để đoạn script của bạn thi hành.

- -

Chuyển đổi kiểu dữ liệu

- -

JavaScript là dynamically typed language. Điều đó có nghĩa bạn không cần phải chỉ định kiểu dữ liệu của biến khi bạn khai báo biến, và kiểu dữ liệu được tự động chuyển đổi khi cần thiết trong quá trình đoạn script được thực thi.

- -

Cho nên, ví dụ, bạn có thể định nghĩa một biến như sau:

- -
var answer = 42;
-
- -

Và sau đó, bạn có thể gán cùng một biến này với một giá trị chuỗi, ví dụ:

- -
answer = "Thanks for all the fish...";
-
- -

Bởi vì JavaScript là dynamically typed, việc gán giá trị này sẽ không gây ra lỗi.

- -

Các số và toán tử '+'

- -

Trong các biểu thức (expression) có sự liên quan giữa các giá trị numeric và string với toán tử  +, JavaScript sẽ chuyển đổi giá trị số sang chuỗi. Ví dụ:

- -
x = "The answer is " + 42 // "The answer is 42"
-y = 42 + " is the answer" // "42 is the answer"
-
- -

Với tất cả mọi loại toán tử khác, JavaScript sẽ không chuyển đổi giá trị numeric sang string. Ví dụ:

- -
"37" - 7 // 30
-"37" + 7 // "377"
-
- -

Chuyển từ kiểu chuỗi (string) sang kiểu số (number)

- -

Tong trường hợp một giá trị biểu thị một số nhưng lại được lưu trong bộ nhớ như là một chuỗi, có các phương thức để chuyển đổi.

- -
    -
  • {{jsxref("parseInt", "parseInt()")}}
  • -
  • {{jsxref("parseFloat", "parseFloat()")}}
  • -
- -

parseInt sẽ chỉ trả về các số nguyên, nên mục đích của nó là làm giảm bớt giá trị cho các số decimals. Thêm nữa, một thực hành tốt nhất cho parseInt là luôn luôn thêm vào nó tham số radix. Tham số radix được dùng để chỉ định hệ số học nào sẽ được sử dụng.

- -
parseInt('101', 2) // 5
- -

Một phương thức khác để nhận được giá trị số từ một chuỗi là dùng toán tử + 

- -
"1.1" + "1.1" = "1.11.1"
-(+"1.1") + (+"1.1") = 2.2
-// Note: the parentheses are added for clarity, not required.
- -

Literals

- -

Literals (nguyên văn), đại diện cho các giá trị trong JavaScript. Đây là những giá trị cố định - không phải biến - mà bạn cung cấp một cách litterally trong script của bạn. Phần này mô tả những kiểu literals sau đây:

- -
    -
  • {{anch("Array literals")}}
  • -
  • {{anch("Boolean literals")}}
  • -
  • {{anch("Floating-point literals")}}
  • -
  • {{anch("Integers")}}
  • -
  • {{anch("Object literals")}}
  • -
  • {{anch("String literals")}}
  • -
- -

Array literals

- -

Một array literal là một danh sách của không hoặc nhiều biểu thức, mỗi biểu thức trong đó đại diện cho một phần tử của mảng (array element), được bao bọc trong dấu ngoặc vuông ([]). Khi bạn tạo một mảng bằng cách dùng array literal, nó được khởi tạo với những giá trị cụ thể như là các element của mảng, và length của mảng là số lượng đối số (argument).

- -

Ví dụ sau tạo ra mảng coffees với 3 phần tử và một length của 3:

- -
var coffees = ["French Roast", "Colombian", "Kona"];
-
- -

Note: Một array literal là một kiểu của object initializer. Xem Using Object Initializers.

- -

Nếu một mảng được tạo ra sử dụng một literal trong một top-level script, JavaScript sẽ interpret mảng mỗi lần nó đánh giá biểu thức có chứa array literal. Ngoài ra, một literal được sử dụng trong một hàm sẽ được tạo ra mỗi lần function được gọi.

- -

Note: Các array literals cũng là các Array objects. Xem {{jsxref("Array")}} and Indexed collections để biết chi tiết về Array objects.

- -

Dấu phẩy dư trong các array literals

- -

Bạn không cần phải xác định mọi phần tử trong một array literal. Nếu bạn đặt 2 dấu phẩy trên cùng một hàng, mảng sẽ tạo ra một phần tử mang giá trị undefined. Ví dụ sau tạo ra mảng fish.

- -
var fish = ["Lion", , "Angel"];
-
- -

Mảng này gồm 2 phần tử có giá trị và một phần tử rỗng (fish[0] là "Lion", fish[1] là undefined, và fish[2] là "Angel").

- -

Nếu bạn thêm một dấu phẩy theo sau (trailing comma) phần tử cuối cùng của mãng, dấu phẩy này sẽ bị bỏ qua. Trong ví dụ sau, length của mảng là 3. Không có myList[3]. Tất cả dấu phẩy khác trong danh sách ngầm chỉ định là một phần tử mới. (Note: trailing commas có thể xem là lỗi đối với các trình duyệt cũ và tốt nhất là nên xóa chúng đi).

- -
let myList = ['home', , 'school', ];
-
- -

Trong ví dụ bên dưới, length của mảng là 4, myList[0] và myList[2] bị thiếu.

- -
var myList = [ , 'home', , 'school'];
-
- -

Trong ví dụ dưới, length của mảng là 4, myList[1] và myList[3] bị thiếu. Chỉ có dấu phẩy cuối cùng bị bỏ qua.

- -
var myList = ['home', , 'school', , ];
-
- -

Hiểu được hành vi của cac dấu phẩy thêm này rất quan trọng để hiểu được JavaScript như là một ngôn ngữ. Tuy nhiên, khi viết code của riêng bạn, bạn nên khai báo một cách rõ ràng các phần tử bị thiếu (missing elements) là undefined. Làm vậy sẽ gia tăng độ rõ ràng cho code và dễ bảo trì sau này.

- -

Boolean literals

- -

Kiểu Boolean có 2 giá trị literal: truefalse.

- -

Cẩn thận: Đừng nhầm lẫn giá trị Boolean nguyên thủy true và false với true và fales của {{jsxref("Boolean")}} object. Boolean object là một lớp bao bên ngoài kiểu dữ liệu Boolean nguyên thủy. Xem {{jsxref("Boolean")}} để biết thêm.

- -

Numeric literals

- -

Kiểu dữ liệu {{jsxref("Number")}} và {{jsxref("BigInt")}} có thể được biểu diễn bằng hệ decimal (hệ 10), hệ hexadecimal (hệ 16), octal (hệ 8) và binary (base 2 - hệ nhị phân).

- -
    -
  • Một decimal numeric literal là một dãy liên tục của các chữ số mà không dẫn đầu bởi số 0 (zero).
  • -
  • Ký tự số 0 (zero) dẫn đầu trên một numeric literal, hoặc 0o (hoặc 0O) ám chỉ rằng nó nằm trong hệ octal. Octal numerics chỉ gồm các ký tự số từ 0-7.
  • -
  • 0x (hoặc 0X) ám chỉ kiểu dữ liệu hexadecimal numeric. Hexadecimal numerics có thể gồm các ký tự số (0-9) và các chữ cái a-f và A-F. (Việc viết hoa chữ cái sẽ không làm thay đối giá trị của nó. Vì vậy 0xa = 0xA = 10 và 0xf = 0xF = 15).
  • -
  • Một ký tự 0b (hoặc 0B) dẫn đầu ám chỉ hệ nhị phân binary numeric literal. Binary numerics chỉ có thể bao gồm ký tự 0 và 1.
  • -
- -

Một số ví dụ của numeric literals:

- -
0, 117, -345, 123456789123456789n             (decimal, base 10)
-015, 0001 -0o77, 0o777777777777n              (octal, base 8)
-0x1123, 0x00111, -0xF1A7, 0x123456789ABCDEFn  (hexadecimal, "hex" or base 16)
-0b11, 0b0011, -0b11, 0b11101001010101010101n  (binary, base 2)
-
- -

Chi tiết xem thêm tại: Numeric literals in the Lexical grammar reference.

- -

Floating-point literals

- -

Một floating-point literal (literal số thực dấu chấm động) có thể có các bộ phận sau:

- -
    -
  • Một số nguyên hệ 10 decimal integer (có thể thêm vào trước "+" hoặc "-"),
  • -
  • Một dấu chấm hệ 10 ("."), 
  • -
  • Một phần thập phân (một số hệ 10 khác),
  • -
  • Một số mũ.
  • -
- -

Bộ phận số mũ là một ký tự "e" hoặc "E", theo sau nó là một số nguyên integer (số nguyên integer này có thể có thêm phía trước là dấu "+" hoặc "-"). Một floating-point literal phải có ít nhất một ký tự số, và hoặc là một dấu chấm hệ 10 hoặc là ký tự "e" (hoặc "E"). Tóm lại, cú pháp như sau:

- -
[(+|-)][digits][.digits][(E|e)[(+|-)]digits]
-
- -

Ví dụ: 

- -
3.1415926
--.123456789
--3.1E+12
-.1e-23
-
- -

Object literals

- -

Một object literal là một danh sách của không hoặc nhiều cặp property names và associated values (tên thuộc tính và giá trị được liên kết) của một một object, bao bọc bởi cặp dấu ngoặc nhọn ({}).

- -

Lưu ý đừng sử dụng một object literal ngay tại vị trí bắt đầu của một câu lệnh! Điều này sẽ dẫn đến một lỗi (hoặc nó sẽ thực thi theo cách bạn không mong muốn), vì dấu mở ngoặc nhọn { sẽ được interpreted như là bắt đầu của một block.

- -

Ví dụ dưới đây là một ví dụ của object literal. Phần tử đầu tiên của object car định nghĩa là một thuộc tính (property), myCar, và được gán giá trị kiểu chuỗi là "myCar", phần tử thứ 2, thuộc tính getCar, ngay lập tức được gán giá trị là kết quả trả về của việc gọi hàm (CarTypes("Honda")); phần tử thứ 3, thuộc tính special, sử dụng một biến đã tồn tại (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
-
- -

Thêm nữa, bạn có thể sử dụng cả kiểu số hoặc chữ để đặt tên cho thuộc tính của object, hoặc bạn có thể lồng một object bên trong một object khác. Ví dụ:

- -
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
-
-console.log(car.manyCars.b); // Jeep
-console.log(car[7]); // Mazda
-
- -

Các tên thuộc tính của object có thể là bất kỳ chuỗi nào, bao gồm cả chuỗi rỗng ''. Nếu tên thuộc tính không phải là một JavaScript identifier hợp lệ, hoặc nó là số, thì nó phải được bao bọc trong các dấu nháy.

- -

Các tên thuộc tính mà không phải là các identifier hợp lệ không thể được truy cập đến như các thuộc tính thông thường là dùng dấu chấm (.), nhưng có thể được truy cập đến và set giá trị bằng cặp dấu ngoặc vuông giống mảng ("[]").

- -
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!
- -

Please note:

- -
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
-
- -

Enhanced Object literals

- -

Trong ES2015, các object literals được mở rộng từ đó hỗ trợ thêm việc cài đặt các prototype tại construction, shorthand cho việc gán biến foo: foo, các phương thức defining, make super calls, và xử lý các tên thuộc tính với các biểu thức. Cùng nhau, những thứ này cũng mang object listerals và khai báo class đến gần nhau hơn, và cho phép các thiết kế object-based để đạt được lợi ích từ một số tiện nghi giống nhau.

- -
var obj = {
-    // __proto__
-    __proto__: theProtoObj,
-    // Shorthand for ‘handler: handler’
-    handler,
-    // Methods
-    toString() {
-     // Super calls
-     return 'd ' + super.toString();
-    },
-    // Computed (dynamic) property names
-    [ 'prop_' + (() => 42)() ]: 42
-};
- -

RegExp literals

- -

Một regex literal (được định nghĩa chi tiết sau đây) là một mô hình mẫu bao bọc giữa các dấu xuyệt /. Ví dụ:

- -
var re = /ab+c/;
- -

String literals

- -

Một string literal là không có hoặc có nhiều ký tự bao bọc trong dấu (") hoặc ('). Một chuỗi (string) phải được giới hạn trong cặp dấu cùng loại; hoặc là cùng nháy đơn hoặc là cùng nháy kép. Ví dụ:

- -
    -
  • "foo"
  • -
  • 'bar'
  • -
  • "1234"
  • -
  • "one line \n another line"
  • -
  • "John's cat"
  • -
- -

Bạn có thể gọi các phương thức của {{jsxref("String")}} object lên một giá trị string nguyên văn (string literal) - JavaScript tự động chuyển đổi string literal sang một String object tạm, gọi phương thức để chạy, chạy xong hủy bỏ String object tạm đó. Bạn cũng có thể sử dụng thuộc tính String.length với một string literal:

- -
console.log("John's cat".length)
-// Will print the number of symbols in the string including whitespace.
-// In this case, 10.
-
- -

Trong ES2015, template literals cũng được đưa vào sử dụng. Template literals bao bọc trong dấu back-tick (`) (dấu huyền) thay vì dấu nháy đơn hay nháy kép.

- -

Các template strings cung cấp cú pháp đặc biệt (synctactic sugar) để xây dựng các chuỗi (string). (Điều này tương tự với đặc điểm nội suy chuỗi string interpolation trong Perl, Python, v.v...)

- -

Tùy trường hợp, một thẻ tag có thể được thêm vào để cho phép việc xây dựng chuỗi được tùy chỉnh, tránh injection attacks, hoặc xây dựng nên những cấu trúc dữ liệu higher-level từ các nội dung của chuỗi.

- -
// Basic literal string creation
-// `In JavaScript '\n' is a line-feed.`
-
-// Multiline strings
-`In JavaScript, template strings can run
- over multiple lines, but double and single
- quoted strings cannot.`
-
-// String interpolation
-var name = 'Bob', time = 'today';
-`Hello ${name}, how are you ${time}?`
-
-// Construct an HTTP request prefix 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);
-
- -

Bạn nên sử dụng các string literals đơn thuần nếu không cần thiết phải sử dụng đến String object. Xem {{jsxref("String")}} để biết chi tiết về String objects.

- -

Sử dụng các ký tự đặc biệt trong chuỗi

- -

Ngoài các ký tự thông thường, bạn cũng có thể thêm vào các ký tự đặc biệt trong chuỗi, ví dụ:

- -
"one line \n another line"
-
- -

Bảng dưới đây liệt kê danh sách các ký tự đặc biệt có thể sử dụng trong các chuỗi JavaScript.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table: JavaScript special characters
CharacterMeaning
\0Null Byte
\bBackspace - Khoảng cách
\fForm feed -
\nNew line - Dòng mới
\rCarriage return
\tTab - Tab một tab
\vVertical tab - Tab dọc
\'Apostrophe or single quote - trích dẫn đơn
\"Double quote - ngoặc kép.
\\Backslash character
\XXXThe character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXXThe character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXXThe Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See {{anch("Unicode escape sequences")}}.
- -

Escaping characters

- -

Đối với các ký tự không có trong bảng trên, dấu backslash \ được thêm vào trước sẽ bị bỏ qua, nhưng cách dùng này đã không còn nữa và nên được tránh dùng.

- -

Bạn có thể chèn vào một dấu ngoặc kép bên trong một chuỗi bằng cách đặt phía trước nó một dấu backslash \. Điều này tức là escaping dấu trích dẫn. Ví dụ:

- -
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
-console.log(quote);
-
- -

Kết quả của đoạn code trên là:

- -
He read "The Cremation of Sam McGee" by R.W. Service.
-
- -

Để thêm một dấu backslash thật sự vào trong chuỗi, bạn phải escape dấu backslash đó. Ví dụ, để gán dường dẫn file c:\temp vào một chuỗi:

- -
var home = "c:\\temp";
-
- -

Bạn cũng có thể escape các line breaks bằng cách đặt vào trước chúng một dấu backslash. Backslash và line break đều sẽ được remove khỏi giá trị của chuỗi.

- -
var str = "this string \
-is broken \
-across multiple\
-lines."
-console.log(str);   // this string is broken across multiplelines.
-
- -

Mặc dù JavaScript không có cú pháp "heredoc", bạn có thể gần đạt được điều này bằng cách thêm vào một linebreak escape và một escaped linebreak ở cuối mỗi dòng:

- -
var poem =
-"Roses are red,\n\
-Violets are blue.\n\
-I'm schizophrenic,\n\
-And so am I."
-
- -

Thông tin thêm

- -

Chương này tập trung vào cú pháp cơ bản cho các việc khai báo và các kiểu dữ liệu. Để biết rõ hơn về cấu trúc ngôn ngữ JavaScript, xem các chương tiếp theo trong bộ hướng dẫn này:

- - - -

Trong chương tiếp theo, chúng ta sẽ tìm hiểu về control flow constructs và error handling.

- -

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

diff --git a/files/vi/web/javascript/guide/index.html b/files/vi/web/javascript/guide/index.html deleted file mode 100644 index d81ff019a4..0000000000 --- a/files/vi/web/javascript/guide/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: JavaScript Guide -slug: Web/JavaScript/Guide -tags: - - Hướng dẫn - - JavaScript -translation_of: Web/JavaScript/Guide ---- -

{{jsSidebar("JavaScript Guide")}}

- -
-

Tài liệu về JavaScript cung cấp cho bạn cách sử dụng JavaScript và đưa ra cái nhìn tổng quan về ngôn ngữ này. Nếu muốn bắt đầu ngay với Javascript hay lập trình nói chung, hãy tham khảo các bài viết tại learning area.  Nếu cần thông tin đầy đủ về tính năng của ngôn ngữ này, hãy tham khảo JavaScript reference.

-
- - - - - - - - - -

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

diff --git a/files/vi/web/javascript/guide/introduction/index.html b/files/vi/web/javascript/guide/introduction/index.html deleted file mode 100644 index 84ada37f1c..0000000000 --- a/files/vi/web/javascript/guide/introduction/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: Giới thiệu -slug: Web/JavaScript/Guide/Introduction -tags: - - Guide - - JavaScript -translation_of: Web/JavaScript/Guide/Introduction -original_slug: Web/JavaScript/Guide/Gioi-thieu ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
- -

Trong phần này: giới thiệu về JavaScript và thảo luận về một số khái niệm cơ bản của JavaScript.

- -

Kiến thức nền tảng cần có

- -

Để đến với JavaScript, chúng tôi giả sử rằng bạn đã có một số hiểu biết nền tảng:

- -
    -
  • Có hiểu biết chung về Internet và World Wide Web ({{Glossary("WWW")}}).
  • -
  • Đã biết và có thể làm việc được với HyperText Markup Language ({{Glossary("HTML")}}).
  • -
  • Có một số kinh nghiệm về lập trình. Nếu bạn là một người mới tìm hiểu về lập trình, bạn nên đi theo những hướng dẫn có tại trang thông tin chính về JavaScript.
  • -
- -

Bạn có thể tìm thêm thông tin về JavaScript ở đâu?

- -

Tài liệu về JavaScript tại MDN bao gồm:

- -
    -
  • Learning the Web cung cấp cho người mới bắt đầu thông tin và giới thiệu về các khái niệm cơ bản của lập trình và Internet.
  • -
  • JavaScript Guide (là phần hướng dẫn này) cung cấp một cái nhìn tổng quát về ngôn ngữ JavaScript và các Object của nó.
  • -
  • JavaScript Reference cung cấp tài liệu chi tiết về JavaScript.
  • -
- -

Nếu bạn mới tìm hiểu JavaScript, hãy bắt đầu bằng cách đọc các bài viết tại learning areaJavaScript Guide. Một khi bạn đã nắm vững các nền tảng cơ bản, bạn có thể sử dụng JavaScript Reference để lấy những thông tin chi tiết của từng object và các câu lệnh (statements).

- -

JavaScript là gì?

- -

JavaScript là một ngôn ngữ lập trình đa nền tảng (cross-platform), ngôn ngữ lập trình kịch bản, hướng đối tượng. JavaScript là một ngôn ngữ nhỏ và nhẹ (small and lightweight). Khi nằm bên trong một môi trường (host environment), JavaScript có thể kết nối tới các object của môi trường đó và cung cấp các cách quản lý chúng (object).

- -

JavaScript chứa các thư viện tiêu chuẩn cho các object, ví dụ như:  Array, Date, và Math, và các yếu tố cốt lõi của ngôn ngữ lập trình như: toán tử (operators), cấu trúc điều khiển (control structures), và câu lệnh. JavaScript có thể được mở rộng cho nhiều mục đích bằng việc bổ sung thêm các object; ví dụ:

- -
    -
  • Client-side JavaScript - JavaScript phía máy khách, JavaScript được mở rộng bằng cách cung cấp các object để quản lý trình duyệt và Document Object Model (DOM)  của nó. Ví dụ, phần mở rộng phía máy khách cho phép một ứng dụng tác động tới các yếu tố trên một trang HTML và phản hồi giống các tác động của người dùng như click chuột, nhập form, và chuyển trang.
  • -
  • Server-side JavaScript - JavaScript phía Server, JavaScript được mở rộng bằng cách cung cấp thêm các đối tượng cần thiết để để chạy JavaScript trên máy chủ. Ví dụ, phần mở rộng phía server này cho phép ứng dụng kết nối với cơ sở dữ liệu (database), cung cấp thông tin một cách liên tục từ một yêu cầu tới phần khác của ứng dụng, hoặc thực hiện thao tác với các tập tin trên máy chủ.
  • -
- -

JavaScript và Java

- -

JavaScript và Java thì giống nhau ở những cái này nhưng lại khác nhau ở cái khác. Ngôn ngữ JavaScript có lẽ giống giống với ngôn ngữ Java nhưng JavaScript không có khai báo static cũng như không có "tính mạnh về kiểu" (strong type checking) như Java. Cú pháp (syntax) lập trình, đặt tên công thức và xây dựng điều khiển lưu lượng (control-flow) cơ bản của JavaScript phần lớn dựa theo ngôn ngữ lập trình Java, đó cũng là lý do tại sao JavaScript được đổi tên từ LiveScript thành JavaScript.

- -

Ngược lại với hệ thống thời gian biên dịch (compile-time) Java của các lớp được xây dựng bởi các khai báo, JavaScript hỗ trợ nền tảng hệ thống thời gian chạy dựa trên một số lượng nhỏ các loại dữ liệu đại diện cho số, boolean và dữ liệu các chuỗi. JavaScript có một mô hình ít phổ biến hơn là mô hình đối tượng dựa trên nguyên mẫu (prototype-based) thay vì các mô hình đối tượng dựa trên lớp (class-based). Các mô hình dựa trên nguyên mẫu cung cấp khả năng thừa kế năng động; nghĩa là, những gì được kế thừa có thể khác nhau cho các đối tượng khác nhau. JavaScript cũng hỗ trợ các phương thức (function) không khai báo bất cứ gì ở trỏng. Phương thức có thể là một trong các thuộc tính (property) của các đối tượng, thực thi như là một phương thức đã được định kiểu (loosely typed methods).

- -

JavaScript là một ngôn ngữ rất tự do so với Java. Bạn có thể không cần khai báo tất cả biến (variable), lớp (class) và cả phương thức (method). Bạn không cần quan tâm cho dù phương thức đó là public, private hoặc protected, và bạn không cần phải implement interfaces. Biến, tham số (parameters), và kiểu trả về của phương thức (function return) cũng không cần phải rõ ràng.

- -

Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.

- -

In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.

- - - - - - - - - - - - - - - - - - - - - - - -
JavaScript so sánh với Java
JavaScriptJava
Hướng đối tượng (Object-oriented). Không phân biệt giữa kiểu (type) của các đối tượng (object). Tính kế thừa thông qua cơ chế nguyên mẫu (prototype), và các thuộc tính (property) cũng như phương thức có thể thêm vào bất cứ đối tượng nào một cách năng động.Class-based (nền tảng lớp.).Đối tượng được thành các lớp với tất cả kế thừa thông qua hệ thống phân cấp lớp. Các lớp không thể thêm vào các thuộc tính và phương thức mới một cách năng động.
Không khai báo kiểu dữ liệu cho biến (dynamic typing).Phải khai báo kiểu dữ liệu cho biến (static typing).
Không thể tự động ghi vào ổ đĩa cứng.Có thể tự động ghi dữ liệu vào đĩa cứng.
- -

Thêm thông tin về sự khác nhau giữa JavaScript và Java, xem chương: Details of the object model.

- -

JavaScript và tiêu chuẩn ECMAScript

- -

JavaScript được tiêu chuẩn hóa tại Ecma International — the European association for standardizing information and communication systems, Liên kết Châu Âu cho các tiêu chuẩn hóa hệ thống thông tin và truyền thông (ECMA trước đây là viết tắt cho the European Computer Manufacturers Association) cung cấp một tiêu chuẩn hóa, nền tảng ngôn ngữ lập trình mở quốc tế lên JavaScript. Phiên bản đã tiêu chuẩn hóa của JavaScript được gọi là ECMAScript, làm việc giống với cái cách mà tất cả ứng dụng đã được hỗ trợ theo tiêu chuẩn. Các công ty có thể sử dụng tiêu chuẩn ngôn ngữ mở (open standard language) để phát triển các implementation của JavaScript riêng cho họ. Tiêu chuẩn ECMAScript là tài liệu nằm trong tiêu chuẩn ECMA-262 (ECMA-262 specification) . Xem New in JavaScript để biết thêm về sự khác nhau giữa các phiên bản JavaScript cũng như sự khác nhau của phiên bản tiêu chuẩn ECMAScript (ECMAScript specification editions).

- -

Tiêu chuẩn ECMA-262 cũng đã được phê duyệt bởi ISO (International Organization for Standardization) tại ISO-16262. Bạn cũng có thể tìm tiêu chuẩn trên the Ecma International website. Tiêu chuẩn ECMAScript không bao gồm các mô tả cho Document Object Model (DOM), nó được tiêu chuẩn hóa bởi World Wide Web Consortium (W3C). DOM định nghĩa cách mà các đối tượng trong HTML tiếp xúc với các đoạn script của bạn. Để có được một cảm nhận tốt hơn về các công nghệ khác nhau được sử dụng khi lập trình với JavaScript, hãy tham khảo bài viết tổng quan về công nghệ JavaScript.

- -

Tài liệu JavaScript và tiêu chuẩn ECMAScript

- -

Tiêu chuẩn ECMAScript là một tập hợp yêu cầu các việc cần thực hiện khi triển khai ECMAScript; nó rất là hữu ích nếu bạn muốn tạo ra một trình biên dịch tiêu chuẩn các tính năng của ngôn ngữ trong ECMAScript implementation hoặc bộ máy biên dịch của bạn (giống như SpiderMonkey của Firefox, hoặc v8 của Chrome).

- -

Tài liệu ECMAScript được tạo ra không dự định hỗ trợ các lập trình viên script; sử dụng tài liệu JavaScript để lấy thông tin cho việc viết scripts của bạn.

- -

Tiêu chuẩn ECMAScript sử dụng các thuật ngữ và cú pháp có thể các lập trình viên JavaScript chưa được làm quen. Mặc dù sự mô tả của ngôn ngữ có lẽ khác nhau trong ECMAScript, nhưng bản thân ngôn ngữ vẫn giữ nguyên, không thay đổi. JavaScript hỗ trợ tất cả chức năng được nêu trong tiêu chuẩn ECMAScript.

- -

Tài liệu JavaScript mô tả các khía cạnh của ngôn ngữ lập trình JavaScript, thích hợp cho các lập trình viên JavaScript sử dụng.

- -

Bắt đầu với JavaScript

- -

Bắt đầu với JavaScript rất đơn giản: tất cả những gì bạn cần là một trình duyệt Web hiện đại. Trong các bài hướng dẫn có kèm theo một số tính năng JavaScript, mà nó chỉ chạy được ở các phiên bản trình duyệt mới nhất của Firefox, hoặc... cách tốt nhất là sử dụng một số phiên bản trình duyệt gần đây nhất của Firefox..

- -

Có 2 công cụ được xây dựng trong Firefox, nó rất hữu ích để chạy các 'thí nghiệm' với JavaScript, đó là: Web ConsoleScratchpad.

- -

Web Console

- -

Web Console cho phép bạn thấy thông tin về trang Web đang chạy, và kèm theo một command line, với nó bạn có thể sử dụng để chạy một đoạn lệnh JavaScript trên trang Web hiện tại.

- -

Mở Web Console bằng cách chọn "Web Console" từ menu "Web Developer" (Ctrl + Shift + I),  "Web Developer" nằm trong Menu chính của Firefox, nó có hình cờ lê, tên: Developer (nếu vẫn không thấy nó, bạn có thể mở menu và nhấn Customize để kéo nó ra ngoài). Sau khi mở lên, nó sẽ là 1 bảng hiển thị nằm phía dưới của cửa sổ trình duyệt. Có 1 ô nhập chạy dài dưới cùng của cửa sổ Web Console (khoanh vùng màu đỏ trong mình), nó chính là command line, với nó bạn có thể nhập vào đoạn JavaScript mà bạu muốn thực thi, và sau khi Enter thì trình duyệt sẽ chạy và trả về kết quả lên bảng Web Console nằm trên nó:

- -

- -

Scratchpad

- -

Web Console có thể rất hiệu quả cho việc chạy đơn lẻ từng dòng lệnh của JavaScript, bạn cũng có thể chạy những đoạn lệnh nhiều dòng với nó (Ctrl + Enter)... Nhưng có vẻ nó không được tiện lợi cho lắm! Bạn không thể lưu lại code khi sử dụng Web Console. Với các 'thí nghiệm' dài và phức tạp thì Scratchpad là một công cụ hiệu quả.

- -

Để mở Scratchpad, chọn "Scratchpad" từ menu "Web Developer" (Ctrl + Shift + I),  "Web Developer" nằm trong Menu chính của Firefox, nó có hình cờ lê, tên: Developer (nếu vẫn không thấy nó, bạn có thể mở menu và nhấn Customize để kéo nó ra ngoài).  Nó sẽ mở lên trong một cửa sổ window riêng với trình duyệt và là một trình soạn thảo mà bạn có thể sử dụng để viết và chạy JavaScript trong trình duyệt. Bạn cũng có thế lưu lại hoặc mở lên các đoạn script đó lên từ ổ đĩa.

- -

Nếu bạn chọn "Inspect", đoạn code trong cửa sổ nãy sẽ chạy trong trình duyệt và xuất kết quả trở về bảng dưới dạng comment:

- -

- -

Hello world

- -

Bắt đầu với JavaScript, mở Web Console hoặc Scarthpad và viết code JavaScript hiển thị "Hello world" đầu tiên của bạn:

- -
function greetMe(user) {
-  return "Hi " + user;
-}
-
-greetMe("Alice"); // "Hi Alice"
-
- -

Trong trang tiếp theo, chúng tôi sẽ giới thiệu cho bạn về cú pháp và các đặc tính của ngôn ngữ JavaScript, với nó, bạn sẽ có thể viết các ứng dụng phức tạp.

- -

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

diff --git a/files/vi/web/javascript/guide/iterators_and_generators/index.html b/files/vi/web/javascript/guide/iterators_and_generators/index.html deleted file mode 100644 index e283bbb21d..0000000000 --- a/files/vi/web/javascript/guide/iterators_and_generators/index.html +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: Iterators and generators -slug: Web/JavaScript/Guide/Iterators_and_Generators -translation_of: Web/JavaScript/Guide/Iterators_and_Generators ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Using_promises", "Web/JavaScript/Guide/Meta_programming")}}
- -

Việc xử lý mỗi phần tử trong một tập hợp là thao tác rất phổ biến. JavaScript cung cấp một số cách để duyệt qua một tập hợp, từ đơn giản với lệnh lặp {{jsxref("Statements/for","for")}} đến {{jsxref("Global_Objects/Array/map","map()")}} và {{jsxref("Global_Objects/Array/filter","filter()")}}. Iterators và Generators đem đến khái niệm của iteration vào nhân của ngôn ngữ và cung cấp cách để tùy biến cơ chế của vòng lặp {{jsxref("Statements/for...of","for...of")}}.

- -

Tham khảo thêm:

- -
    -
  • Iteration protocols
  • -
  • {{jsxref("Statements/for...of","for...of")}}
  • -
  • {{jsxref("Statements/function*","function*")}} and {{jsxref("Generator")}}
  • -
  • {{jsxref("Operators/yield","yield")}} and {{jsxref("Operators/yield*","yield*")}}
  • -
- -

Iterators

- -

Trong JavaScript một iterator là một object mà nó định nghĩa một trình tự và giá trị có thể trả về tiếp theo trước khi kết thúc. Một cách cụ thể hơn một iterator là một object bất kỳ mà nó cài đặt giao thức Iterator với việc cài đặt phương thức next() mà trả về một object với thuộc tính:  value, giá trị kế tiếp in chuỗi giá trị; và done, mà là true nếu giá trị  cuối cùng trong chuỗi giá trị đã được sử dụng. Nếu value trả về cùng với thuộc tính done, nó là giá trị trả về bởi lệnh return trong iterator đó.

- -

Mỗi lần được tạo, một iterator có thể được duyệt tường minh bởi việc gọi lại nhiều lần phương thức next(). Việc duyệt qua iterator được gọi là sử dụng iterator, bởi vì nó chỉ có thể làm một lần. Sau khi giá trị kết thúc được trả về thì lần gọi next() luôn trả về {done: true}.
-
- Iterator thông dụng nhất trong JavaScript là iterator mãng, mà đơn giản là trả về mỗi giá trị trong associated array theo thứ tự. Trong khi nó thì dễ dàng tưởng tượng rằng tất cả iterators được biểu diễn như mãng, điều này không đúng. Mảng phải được cấp phát toàn bộ, nhưng iterators được sử dụng chỉ khi cần thiết và vì vậy có thể biểu diễn một chuỗi không có giới hạn kích thước, như là một dãy các số nguyên từ 0 cho đến vô cực.
-
- Sau đây là một ví dụ minh họa cho điều đó. Bạn có thể tạo ra một iterator khoảng giá trị đơn giản mà nó định nghĩa một dãy các số nguyên từ start (đã bao gồm) đến end (không bao gồm) với bước nhảy step. Giá trị trả về cuối cùng là kích thước của dãy giá trị mà nó đã tạo, ghi nhận trong biến iterationCount.

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

Việc sử dụng iterator được minh họa như trong đoạn mã sau:

- -
let it = makeRangeIterator(1, 10, 2);
-
-let result = it.next();
-while (!result.done) {
- console.log(result.value); // 1 3 5 7 9
- result = it.next();
-}
-
-console.log("Iterated over sequence of size: ", result.value); // 5
-
-
- -
-

Bạn không biết chắc một đối tượng cụ thể là một iterator hay không. Nếu bạn cần làm điều này, thì hãy dùng Iterables.

-
- -

Generator functions

- -

Iterator tùy biến là công cụ hữu ích, tuy nhiên việc tạo chúng đòi hỏi sự cẩn thận vì chúng ta cần phải tự quản lý trạng thái của chúng. Hàm Generator cung cấp một cách thức tốt hơn để thay thế việc đó: chúng cho phép bạn định nghĩa giải thuật duyệt bằng cách viết một hàm đơn mà sự thực thi của nó không diễn ra liên tục. Hàm Generator được viết bằng cách sử dụng cú pháp {{jsxref("Statements/function*","function*")}}. Khi gọi lần đầu, hàm generator không thực thi bất kỳ đoạn mã nào bên trong, thay vào đó nó trả về kiểu của iterator được gọi là generator. Khi một giá trị được dùng để trả về bởi lời gọi phương thức next() của generator, hàm generator thực thi cho đến khi nó bắt gặp từ khóa  yield.

- -

Hàm có thể được gọi bao nhiêu lần cũng được và nó trả về một generator cho mỗi lần gọi, tuy nhiên generator có thể chỉ được duyệt một lần.
-
- Chúng ta có thể điều chỉnh ví dụ trên. Chúng ta thấy đoạn mã sau cũng thực thi cùng chức năng, nhưng nó dễ viết và dễ đọc hơn.

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

Iterables

- -

Một đối tượng là khả duyệt nếu nó định nghĩa cơ chế duyệt của nó, chẳng hạn như giá trị gì được duyệt qua trong hàm dựng {{jsxref("Statements/for...of", "for...of")}}. Một vài kiểu dựng sẳn, như  {{jsxref("Array")}} hoặc {{jsxref("Map")}}, có cơ chế duyệt mặc định, trong khi những kiểu khác (như là {{jsxref("Object")}}) thì không có.

- -

Để có thể khả duyệt, một object phải cái đặt phương thức của @@iterator, nghĩa là object (hoặc đối tượng cha trong chuỗi  prototype) phải có một thuộc tính {{jsxref("Symbol.iterator")}}.
- It may be possible to iterate over an iterable more than once, or only once. It is up to the programmer to know which is the case. Iterables which can iterate only once (e.g. Generators) customarily return this from their @@iterator method, where those which can be iterated many times must return a new iterator on each invocation of @@iterator.
- Bạn có thể cho phép duyệt qua nhiều lần, hoặc chỉ một lần. Điều này phụ thuộc vào theo yêu cầu của mỗi ứng dụng. Đối tượng khả duyệt mà chỉ duyệt qua một lần (ví dụ Generators) đơn giản là nó chỉ trả về this từ phương thức  @@iterator, trong khi để khả duyệt nhiều lần bạn phải trả về một iterator mới cho mỗi lần gọi @@iterator.

- -

Tự định nghĩa đối tượng khả duyệt

- -

Chúng ta có thể tự tạo đối tượng khả duyệt như sau:

- -
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]
-
- -

Những iterable tạo sẵn

- -

{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}} and {{jsxref("Set")}} là những iterable đã được tạo sẵn, bởi vì đối tượng prototype của chúng đã có phương thức {{jsxref("Symbol.iterator")}}.

- -

Cú pháp đòi hỏi đối tượng khả duyệt

- -

Một vài câu lệnh và biểu thức đòi hỏi toán hạng hoặc đối số phải là đối tượng khả duyệt, ví dụ lệnh lặp {{jsxref("Statements/for...of","for-of")}}, {{jsxref("Operators/yield*","yield*")}}

- -
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 Cao Cấp

- -

Generator tính toán giá trị trả ra tùy biến theo nhu cầu, nó cho phép biển diễn chuỗi giá trị một cách hiệu quả mà tốn kém để tính toán, hoặc thậm chí cho phép chuỗi giá trị vô tận như đã minh họa ở trên.
-  

- -

The {{jsxref("Global_Objects/Generator/next","next()")}} method also accepts a value which can be used to modify the internal state of the generator. A value passed to next() will be treated as the result of the last yield expression that paused the generator.
- Phương  thức {{jsxref("Global_Objects/Generator/next","next()")}} cũng chấp nhận một đối số mà được sử dụng để thay đổi trạng thái bên trong của generator. Một giá trị được truyền vào next() sẽ được dùng như kết quả của biểu thức yield cuối cùng khi tạm dừng generator.

- -

Here is the fibonacci generator using next(x) to restart the sequence:

- -
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
- -

Bạn có thể ép một generator phát sinh lỗi bằng cách gọi phương thức {{jsxref("Global_Objects/Generator/throw","throw()")}} của generator và chỉ định giá trị lỗi mà nó cần phát sinh. Lỗi này sẽ được phát sinh từ ngữ cảnh hiện tại của generator, tạo điểm mà yield đang tam dừng, thay vì lệnh throw value như cách thông thường.

- -

Nếu lỗi không được bắt từ bên trong generator, nó sẽ được đẩy lên cấp cao hơn thông qua lời gọi hàm throw(), khi đó lời gọi tiếp theo tới next() sẽ trả về done với giá trị true.

- -

Generator có một phương thức {{jsxref("Global_Objects/Generator/return","return(value)")}} mà giá trị được truyền vào và kết thúc chính nó.

- -

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

diff --git a/files/vi/web/javascript/guide/keyed_collections/index.html b/files/vi/web/javascript/guide/keyed_collections/index.html deleted file mode 100644 index 491efcf1da..0000000000 --- a/files/vi/web/javascript/guide/keyed_collections/index.html +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: Keyed collections -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")}}
- -

Chương này sẽ giới thiệu về bộ sưu tập dữ liệu được sắp xếp theo key; Map và Set objects chứa các phần tử có thể được lặp lại theo thứ tự được thêm vào.

- -

Maps

- -

Map object

- -

ECMAScript 2015 giới thiệu một cấu trúc dữ liệu mới để ánh xạ giá trị thành giá trị. Một đối tượng {{jsxref("Map")}} là một ánh xạ đơn giản key/value và có thể lặp lại các phần tử theo thứ tự thêm vào.

- -

Đoạn code bên dưới sẽ thể hiện các thao tác cơ bản với Map. Xem thêm {{jsxref("Map")}} để có thêm nhiều ví dụ và toàn bộ API. Bạn có thể sử dụng một vòng lặp {{jsxref("Statements/for...of","for...of")}} để trả về một mảng của [key, value] trong mỗi lần lặp.

- -
let 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');
-sayings.has('dog'); // false
-
-for (let [key, value] of sayings) {
-  console.log(key + ' goes ' + value);
-}
-// "cat goes meow"
-// "elephant goes toot"
-
-sayings.clear();
-sayings.size; // 0
-
- -

Object and Map compared

- -

Thông thường, {{jsxref("Object", "objects", "", 1)}} được sử dụng để ánh xạ string thành value. Objects cũng cho phép bạn đặt key thành values, truy xuất các value, xóa các key, và kiểm tra xe có dữ liệu nào được lưu trữ trong một key. Tuy nhiên Map objects có một vài lợi thế hơn giúp chúng tốt hơn trong việc ánh xạ.

- -
    -
  • Các key trong một Object là {{jsxref("Global_Objects/String","Strings")}} hoặc {{jsxref("Global_Objects/Symbol","Symbols")}}, trong khi chúng có thể là bất kỳ giá trị nào trong một Map.
  • -
  • Bạn có thể lấy được size của một Map dễ dàng, trong khi bạn sẽ phải xử lý thủ công để lấy được kích thước của một Object.
  • -
  • Vòng lặp của các ánh xạ sẽ theo thứ tự được thêm vào của  các phần tử.
  • -
  • Một Object có một prototype, vì thế có các giá trị mặc định của key trong ánh xạ. (Điều này có thể bỏ qua bằng cách sử dụng map = Object.create(null).)
  • -
- -

Ba mẹo dưới đây có thể giúp bạn quyết định khi nào thì sử dụng Map hoặc Object:

- -
    -
  • Sử dụng các object khi các key không được xác định cho đến khi chạy, và khi tất cả các key có cùng kiểu và tất cả các value cũng cùng kiểu.
  • -
  • Sử dụng các map nếu cần lưu trữ các giá trị có kiểu nguyên thủy làm key vì các object coi mỗi key là một string cho dù nó là một giá trị số, boolean hoặc bất kỳ giá trị có kiểu nguyên thủy nào.
  • -
  • Sử dụng các object khi có logic hoạt động trên các yếu tố riêng lẻ.
  • -
- -

WeakMap object

- -

Đối tượng {{jsxref("WeakMap")}} là một bộ sưu tập của cặp key/value trong đó các key chỉ là các đối tượng và các value có thể là bất kỳ giá trị nào. Tham chiếu đối tượng trong các key được giữ yếu ớt (weakly), có nghĩa là chúng là mục tiêu của garbage collection (GC) nếu không có tham chiếu nào khác đến đối tượng nữa. Các WeakMap API giống với các Map API.

- -

Một điểm khác biệt so với các Map objects là các key của WeakMap không đếm được (tức là không có phương thức nào cung cấp cho bạn danh sách các key). Nếu có, danh sách key sẽ phụ thuộc vào trạng thái của garbage collection, đưa ra tính không xác định.

- -

Một số thông tin và ví dụ khác, xem tại "Why WeakMap?" trong tài liệu tham khảo {{jsxref("WeakMap")}}.

- -

Một trường hợp sử dụng các WeakMap objec là lưu trữ dữ liệu riêng tư cho một đối tượng hoặc ấn chi tiết thực hiện. Ví dụ sau đây từ bài đăng trên blog của Nick Fitzgerald's  "Hiding Implementation Details with ECMAScript 6 WeakMaps". Các dữ liệu và phương thức riêng bên trong object sẽ được lưu trữ trong đối tượng privates. Tất cả các instance và prototype lộ ra được công khai; mọi thứ khác không thể truy cập từ bên ngoài bởi vì privates không được xuất từ mô-đun.

- -
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

- -

Các {{jsxref("Set")}} object là bộ sưu tập các giá trị. Bạn có thể lặp các phần tử theo thứ tự được thêm vào. Một giá trị trong một Set chỉ có thể xuất hiện một lần; nó là duy nhất trong Set.

- -

Đoạn code dưới đây là các thao tác cơ bản với Set. Xem thêm tại tài liệu tham khảo {{jsxref("Set")}} để có thêm nhiều ví dụ và toàn bộ các API.

- -
let 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"
-
- -

Converting between Array and Set

- -

Bạn có thể tạo một {{jsxref("Array")}} từ một Set bằng cách sử dụng {{jsxref("Array.from")}} hoặc spread operator. Ngoài ra, hàm khởi tạo Set cho phép chuyển đổi một Array theo một hướng khác.

- -
-

Note: Hãy nhớ rằng các Set object lưu trữ các giá trị duy nhất—vì thế bất kỳ phần tử nào trùng lặp trong Array sẽ bị loại bỏ khi chuyển đổi!

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

Array and Set compared

- -

Thông thường, một tập hợp các phần tử được lưu trữ trong mảng trong JavaScript trong nhiều tính huống. Tuy nhiên, Set object có một vài điểm lợi thế sau:

- -
    -
  • Xóa bỏ các phẩn tử trong mảng theo giá trị (arr.splice(arr.indexOf(val), 1)) rất chậm.
  • -
  • Set object cho phép bạn xóa bỏ các phần tử theo giá trị của chúng. Trong khi đó một mảng, bạn sẽ phải dùng phương thức splice dựa theo index của phần tử.
  • -
  • Giá trị {{jsxref("NaN")}} không thể được tìm thất với indexOf trong một mảng.
  • -
  • Các Set object lưu trữ các giá trị duy nhất. Bạn không cần phải thao tác thủ công để theo dõi các giá trị bị trùng lặp.
  • -
- -

WeakSet object

- -

Các {{jsxref("WeakSet")}} object là bộ sưu tập các đối tượng. Một đối tượng trong WeakSet chỉ xuất hiện một lần. Nó là duy nhất trong bộ sưu tập WeakSet, và các đối tượng đó không thể đếm được.

- -

Những điểm khác biệt chính so với {{jsxref("Set")}} object:

- -
    -
  • Khác với Sets, WeakSets là bộ sưu tập các đối tượng và không phải bất kỳ giá trị của bất kỳ kiểu nào. 
  • -
  • WeakSet là yếu ớt (weak): Tham chiếu tới đối tượng trong bộ sưu tập được tổ chức yếu ớt (weakly). Nếu không có tham chiếu nào khác tới đối tượng được lưu trữ trong WeakSet, chúng có thể bị thu thập bởi garbage collected. Điều này có nghĩa là không có danh sách các đối tượng đang được lưu trữ trong bộ sưu tập. WeakSets không thể đếm được.
  • -
- -

Các trường hợp sử dụng các  WeakSet object bị hạn chế. Chúng sẽ không rò rỉ bộ nhớ, vì thế nó có thể an toàn khi sử dụng các phần tử DOM làm khóa và đánh dấu chúng cho mục đích theo dõi.

- -

Key and value equality of Map and Set

- -

So sánh bằng nhau của các key của các Map object và value của các Set object dựa trên "same-value-zero algorithm":

- -
    -
  • So sánh bằng nhau làm việc giống như so sánh bằng toán tử ===.
  • -
  • -0+0 được coi là bằng nhau.
  • -
  • {{jsxref("NaN")}} được coi là bằng chính nó (trái với ===).
  • -
- -

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

diff --git a/files/vi/web/javascript/guide/loops_and_iteration/index.html b/files/vi/web/javascript/guide/loops_and_iteration/index.html deleted file mode 100644 index 5ad3581fba..0000000000 --- a/files/vi/web/javascript/guide/loops_and_iteration/index.html +++ /dev/null @@ -1,348 +0,0 @@ ---- -title: Loops and iteration -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")}}
- -

Vòng lặp giúp thực hiện một hành động nhiều lần một cách nhanh chóng và đơn giản. Chương Hướng dẫn JavaScript này giới thiệu về các câu lệnh lặp trong JavaScript.

- -

Hãy tưởng tượng vòng lặp giống như phiên bản vi tính của trò chơi mà bạn bảo một người đi X bước sang một hướng rồi đi Y bước sang một hướng khác; chẳng hạn, ý tưởng trò "Tiến 5 bước về phía Đông" có thể được biểu diễn dưới dạng vòng lặp như sau:

- -
var step;
-for (let step = 0; step < 5; step++) {
-  // Chạy 5 lần, với giá trị chạy từ 0 đến 4.
-  console.log('Walking east one step');
-}
-
- -

Có nhiều kiểu vòng lặp khác nhau, nhưng tất cả đều thực hiện cùng một việc: làm lại một hành động trong số lần nhất định (số lần đó có thể là 0). Mỗi vòng lặp có các cơ chế khác nhau, tương ứng với đó là sự khác nhau giữa cách xác định điểm bắt đầu và kết thúc của vòng lặp. Tuỳ theo trường hợp xác định mà lựa kiểu vòng lặp cho phù hợp..

- -

Các lệnh lặp trong JavaScript là:

- -
    -
  • {{anch("for statement")}}
  • -
  • {{anch("do...while statement")}}
  • -
  • {{anch("while statement")}}
  • -
  • {{anch("labeled statement")}}
  • -
  • {{anch("break statement")}}
  • -
  • {{anch("continue statement")}}
  • -
  • {{anch("for...in statement")}}
  • -
  • {{anch("for...of statement")}}
  • -
- -

Lệnh for

- -

Vòng lặp {{jsxref("statements/for","for")}} thực hiện liên tục cho tới khi điều kiện ban đầu trả về false. Vòng for trong JavaScript tương tự như vòng for trong Java hoặc C. Lệnh for có dạng như sau:

- -
for ([biểu_thức_khởi_tạo]; [điều_kiện]; [biểu_thức_tăng_tiến])
-  lệnh
-
- -

Vòng lặp for thực thi như sau:

- -
    -
  1. Biểu thức khởi tạo (biểu_thức_khởi_tạo), nếu có, được thực thi. Biểu thức này thường khởi tạo một hoặc nhiều biến đếm cho vòng lặp, nhưng cú pháp của nó vẫn có thể tạo ra biểu thức có độ phức tạp. Biểu thức này còn có thể khai báo biến.
  2. -
  3. Biểu thức điều kiện (điều_kiện) được tính toán. Nếu giá trị của điều_kiện trả về true, các lệnh trong vòng lặp được thực thi. Nếu giá trị của điều_kiện trả về false, vòng lặp for bị dừng lại. Nếu biểu thức điều_kiện bị khuyết (bỏ qua không đặt), điều kiện sẽ được gán giả định là true.
  4. -
  5. lệnh sẽ được thực thi. Để thực thi nhiều lệnh, dùng khối lệnh ({ ... }) để gom nhóm các lệnh này.
  6. -
  7. Nếu không có lỗi nào xảy ra sau khi thực thi lệnh, biểu thức cập nhật (biểu_thức_tăng_tiến) được thực thi.
  8. -
  9. Quay lại bước 2.
  10. -
- -

Ví dụ

- -

Hàm dưới đây chứa lệnh for đếm số option được chọn trong danh sách cuộn (phần tử {{HTMLElement("select")}} cho phép chọn nhiều). Lệnh for khai báo biến i và khởi tạo cho nó là 0. Điều kiện kiểm tra i có nhỏ hơn số option mà phần tử <select> sở hữu hay không, nếu thoả mãn điều kiện, chương trình sẽ chạy vào lệnh if, và tăng i thêm một.

- -
<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>
-
-
- -

Lệnh do...while

- -

Lệnh {{jsxref("statements/do...while", "do...while")}} thực hiện liên tục cho tới khi điều kiện xác định trả về false. Lệnh do...while có dạng như sau:

- -
do
-  lệnh
-while (điều_kiện);
-
- -

lệnh luôn được thực thi một lần trước khi kiểm tra điều kiện (và rồi cứ thế cho tới khi điều kiện trả về false). Để thực thi nhiều lệnh, dùng khối lệnh ({ ... }) để gom nhóm các câu lệnh. Nếu điều_kiện trả về true, lệnh lại được thực thi một lần nữa. Sau mỗi lần thực thi, chương trình kiểm tra lại điều kiện. Khi điều kiện trả về false, chương trình dừng thực thi vòng lặp và truyền điều khiển xuống lệnh liền sau vòng do...while.

- -

Ví dụ

- -

Trong ví dụ sau, lặp do lặp ít nhất một lần và tái duyệt cho tới khi i không nhỏ hơn 5.

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

Lệnh while

- -

Lệnh {{jsxref("statements/while","while")}} thực thi các lệnh bên trong nó ngay khi điều kiện xác định trả về true. Lệnh while có dạng như sau:

- -
while (điều_kiện)
-  lệnh
-
- -

Nếu điều kiện trả về false, chương trình sẽ ngừng thực thi lệnh bên trong vòng lặp và truyền điều khiển xuống lệnh liền sau vòng lặp.

- -

Chương trình kiểm tra điều kiện trước khi thực thi lệnh bên trong. Nếu điều kiện trả về true, lệnh sẽ được thực thi và kiểm tra lại điều kiện. Nếu điều kiện trả về false, ngừng thực thi và truyền điều khiển xuống lệnh liền sau vòng lặp while.

- -

Để thực thi nhiều lệnh, dùng khối lệnh ({ ... }) để gom nhóm các câu lệnh.

- -

Ví dụ 1

- -

Vòng while lặp lại cho tới khi n nhỏ hơn 3:

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

Ứng với mỗi lần lặp, tăng n thêm một và cộng giá trị đó vào x. Bởi vậy, xn có giá trị như sau:

- -
    -
  • Sau lần lặp thứ nhất: n = 1 và x = 1
  • -
  • Sau lần lặp thứ hai: n = 2 và x = 3
  • -
  • Sau lần lặp thứ ba: n = 3 và x = 6
  • -
- -

Sau khi hoàn thành lần lặp thứ ba, điều kiện n < 3 không còn trả về true nữa nên vòng lặp bị kết thúc.

- -

Ví dụ 2

- -

Hãy tránh lặp vô hạn. Hãy đảm bảo rằng điều kiện của vòng lặp sẽ dần trả về false; bằng không, vòng lặp sẽ không bao giờ kết thúc. Lệnh trong vòng lặp while dưới đây được thực thi mãi mãi vì điều kiện không bao giờ trả về false:

- -
while (true) {
-  console.log('Hello, world!');
-}
- -

Lệnh gán nhãn

- -

{{jsxref("statements/label","label")}} tạo ra một lệnh đi kèm với một định danh, thông qua định danh giúp bạn tham chiếu tới nó từ những nơi khác trong chương trình của bạn. Chẳng hạn, bạn có thể dùng nhãn để định danh một vòng lặp, rồi dùng lệnh break hoặc continue để chương trình xác định có nên dừng hay tiếp tục thực thi vòng lặp hay không.

- -

Cú pháp của lệnh gán nhãn có dạng như sau:

- -
nhãn :
-   lệnh
-
- -

Giá trị của nhãn có thể là định danh JavaScript bất kỳ nhưng không phải từ dành riêng (tên biến, tên hàm hoặc nhãn khác). lệnh được gán với nhãn có thể là bất kỳ lệnh nào.

- -

Ví dụ

- -

Trong ví dụ này, nhãn markLoop giúp định danh cho một vòng lặp while.

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

Lệnh break

- -

Dùng lệnh {{jsxref("statements/break","break")}} để kết thúc vòng lặp, kết thúc switch, hoặc liên hợp với một lệnh được gán nhãn.

- -
    -
  • Khi dùng break không kèm với nhãn, chương trình kết thúc ngay tức thì vòng while, do-while, for, hoặc switch trong cùng bọc lệnh break và truyền điều khiển xuống lệnh liền sau.
  • -
  • Khi dùng break kèm với nhãn, nó sẽ chấm dứt việc thực thi lệnh được gắn nhãn đó.
  • -
- -

Cú pháp lệnh break có dạng như sau:

- -
break;
-break [nhãn];
-
- -

Kiểu cú pháp đầu tiên kết thúc vòng lặp trong cục bao bọc hoặc switch; kiểu thứ hai kết thúc lệnh gắn với nhãn.

- -

Ví dụ 1

- -

Trong ví dụ sau, lệnh lặp sẽ lặp qua từng phần tử của mảng (thông qua chỉ mục của từng phần tử) cho tới khi gặp phần tử có giá trị bằng theValue:

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

Ví dụ 2: Áp dụng break cho nhãn

- -
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;
-    }
-  }
-}
-
- -

Lệnh continue

- -

Lệnh {{jsxref("statements/continue","continue")}} có thể dùng để tái duyệt các vòng while, do-while, for, hoặc label.

- -
    -
  • Khi dùng continue không kèm theo label, chương trình ngừng thực thi lần lặp hiện tại của vòng while, do-while, hoặc for gần nhất bọc lệnh continue và tiếp tục thực thi lần lặp tiếp theo. Trái với lệnh break, continue không dừng vòng lặp hoàn toàn. Trong vòng lặp while, chương trình nhảy về đoạn xét điều kiện. Trong vọng lặp for, chương trình nhảy tới biểu_thức_tăng_tiến.
  • -
  • Khi dùng continue có kèm theo label, lệnh continue sẽ áp dụng cho vòng lặp được gán nhãn đó.
  • -
- -

Cú pháp của lệnh continue có dạng như sau:

- -
continue [label];
-
- -

Ví dụ 1

- -

Trong ví dụ sau, vòng while với lệnh continue thực thi khi giá trị của i bằng 3. Thế nên, n sẽ có giá trị là 1, 3, 7 và 12.

- -
var i = 0;
-var n = 0;
-while (i < 5) {
-  i++;
-  if (i == 3) {
-    continue;
-  }
-  n += i;
-  console.log(n);
-}
-//1,3,7,12
-
-
-var i = 0;
-var n = 0;
-while (i < 5) {
-  i++;
-  if (i == 3) {
-     // continue;
-  }
-  n += i;
-  console.log(n);
-}
-// 1,3,6,10,15
-
- -

Ví dụ 2

- -

Lệnh nhãn checkiandj chứa nhãn checkj. Nếu chương trình chạy tới continue, chương trình sẽ ngừng thực hiện lần lặp hiện tại của checkj và bắt đầu thực hiện lần lặp kế tiếp. Mỗi khi chạy tới continue, checkj tái duyệt cho tới khi biểu thức điều kiện của nó trả về false. Khi false được trả về, phần còn lại của lệnh checkiandj được hoàn thành, và checkiandj tái duyệt cho tới khi điều kiện của nó trả về false. Khi false được trả về, chương trình tiếp tục thực thi lệnh liền sau checkiandj.

- -

Nếu continue gắn với nhãn checkiandj, chương trình sẽ tiếp tục ở đầu lệnh checkiandj .

- -
var i = 0;
-var j = 10;
-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);
-  }
- -

Lệnh for...in

- -

Lệnh {{jsxref("statements/for...in","for...in")}} lặp một biến (variable) đã được xác định trước, qua mọi thuộc tính có thể đếm được (enumerable properties) của đối tượng (object). Với từng phần tử riêng biệt, JavaScript thực thi các câu lệnh mà bạn định sẵn. Lệnh for...in có dạng như sau:

- -
for (variable in object)
-  statement
-
- -

Ví dụ

- -

Hàm sau nhận vào tham số là một object và tên của object đó. Sau đó nó lặp qua mọi thuộc tính của object, với mỗi lần lặp nó trả về một chuỗi ký tự liệt kê các tên thuộc tính và giá trị của chúng.

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

Chẳng hạn với object car có thuộc tính là makemodel, result sẽ là:

- -
car.make = Ford
-car.model = Mustang
-
- -

Mảng

- -

Mặc dù có thể dùng cách này để lặp qua từng phần tử của mảng {{jsxref("Array")}}, lệnh for...in sẽ trả về tên của thuộc tính mà người dùng tự định nghĩa kèm theo chỉ mục của mảng.

- -

Bởi vậy, tốt hơn hết hãy sử dụng cách truyền thống là dùng vòng lặp {{jsxref("statements/for","for")}} với chỉ mục dạng số để lặp qua từng phần tử của mảng, bởi lệnh for...in còn lặp qua cả thuộc tính mà người dùng tự định nghĩa (chẳng hạn như khi thêm một thuộc tính vào mảng, sẽ có ví dụ ở phía dưới).

- -

for...of statement

- -

Lệnh {{jsxref("statements/for...of","for...of")}} tạo ra một vòng lặp, áp dụng với các đối tượng khả duyệt (iterable object) (bao gồm {{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("functions/arguments","arguments")}} object, v.v...), và gọi lên một hook lặp tùy chỉnh (custom iteration hook) với các câu lệnh sẽ được thực thi cho giá trị của từng thuộc tính.

- -
for (variable of object)
-  statement
-
- -

Ví dụ sau chỉ ra sự khác biệt giữa hai vòng lặp: for...of và {{jsxref("statements/for...in","for...in")}}. Trong khi for...in lặp qua tên thuộc tính, for...of lặp qua giá trị thuộc tính:

- -
var arr = [3, 5, 7];
-arr.foo = 'hello';
-
-for (var i in arr) {
-   console.log(i); // logs "0", "1", "2", "foo"
-}
-
-for (var 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/vi/web/javascript/guide/numbers_and_dates/index.html b/files/vi/web/javascript/guide/numbers_and_dates/index.html deleted file mode 100644 index a48afbbb89..0000000000 --- a/files/vi/web/javascript/guide/numbers_and_dates/index.html +++ /dev/null @@ -1,385 +0,0 @@ ---- -title: Numbers and dates -slug: Web/JavaScript/Guide/Numbers_and_dates -translation_of: Web/JavaScript/Guide/Numbers_and_dates ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}
- -

Chương này giới thiệu những khái niệm, đối tượng và hàm được sử dụng để làm việc và tính toán với giá trị số và ngày tháng trong JavaScript. Nó bao gồm việc sử dụng những con số được viết dưới dạng những hệ cơ số khác nhau như là hệ thập phân, hệ nhị phân và hệ thập lục phân, cũng như việc sử dụng đối tượng toàn cục {{jsxref("Math")}} để thực hiện các phép toán số học.

- -

Con Số (Numbers)

- -

Trong JavaScript, tất cả các con số được cài đặt theo double-precision 64-bit binary format IEEE 754 (ví dụ: một số bắt đầu từ ±2−1022 and ±2+1023, hoặc là khoảng ±10−308 to ±10+308, với độ chính xác 53 bits sau dấu phẩy). Số nguyên lớn nhất có thể là ±253 − 1. Để có thể biểu diễn số thực dấu chấm động, ta có thể dùng ba ký hiệu +{{jsxref("Infinity")}}, -{{jsxref("Infinity")}}, and {{jsxref("NaN")}} (not-a-number). Xem thêm trong JavaScript data types and structures về những kiểu sơ cấp trong JavaScript.

- -
-

Lưu Ý: Không có kiểu cụ thể cho số nguyên trong JavaScript, mặc dù kiểu {{jsxref("BigInt")}} cho phép biểu diễn số nguyên mà có giá trị rất lớn. Nhưng cần cẩn thận khi dùng BigInt, ví dụ, bạn có không thể kết hợp giá trị BigInt và {{jsxref("Number")}} trong cùng một biểu thức, và bạn cũng không thể sử dụng {{jsxref("Math")}} với giá trị BigInt.

-
- -

Bạn có thể sử dụng bốn loại literal để tạo số: thập phân, nhị phân, bát phân và thập lục phân.

- -

Số thập phân

- -
1234567890
-42
-
-// Cẩn thận với số bắt đầu bằng số không:
-
-0888 // 888 trong hệ thập phân
-0777 // được xem như là số bát phân trong chế độ non-strict (và có giá trị là 511 trong hệ thập phân)
-
- -

Lưu ý literal thập phân có thể bắt đầu bằng số zero (0) được theo sau là những số thập phân, nhưng nếu mọi chữ số sau số 0 nhỏ hơn 8, thì nó hiểu nhầm như là hệ bát phân.

- -

Số nhị phân

- -

Cú pháp của hệ nhị phân bắt đầu bằng chữ số 0 theo sau là "B" hoặc "b" (0b or 0B). Nếu các chữ số theo sau 0b không phải là 0 hoặc 1, thì lỗi  SyntaxError sẽ phát sinh như sau "Missing binary digits after 0b".

- -
var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
-var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
-var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
- -

Số bát phân

- -

Số bát phân bắt đầu bằng số 0. Nếu chữ số theo sau số 0 không nắm trong khoảng từ 0 đến 7, thì số đó sẽ được hiểu là số thập phân.

- -
var n = 0755; // 493
-var m = 0644; // 420
-
- -

Trong chế độ strict trong ECMAScript 5 ngăn cấm cú pháp hệ bát phân. Cú pháp hệ bát phân không nằm trong đặc tả của ECMAScript 5, nhưng nó được hỗ trợ bởi tất cả các trình duyệt bằng cách đặt tiền tố 0:  0644 === 420 and"\045" === "%". Trong ECMAScript 2015 (ES6), số bát phân được hỗ trợ nếu chúng bắt đầu bằng 0o, ví dụ:

- -
var a = 0o10; // ES2015: 8
-
- -

Số thập lục phân

- -

Cú pháp của số thập lục phân được bắt đầu bằng 0 và theo sau là "x" hoặc "X" (0x or 0X). Nếu các chữ số theo sau 0x nằm ngoài khoảng giá trị  (0123456789ABCDEF), Lỗi  SyntaxError sẽ phát sinh: "Identifier starts immediately after numeric literal".

- -
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
-0x123456789ABCDEF   // 81985529216486900
-0XA                 // 10
-
- -

Số mũ

- -
1E3   // 1000
-2e6   // 2000000
-0.1e2 // 10
- -

Number object

- -

{{jsxref("Number")}} object có những thuộc tính có giá trị là những hằng kiểu số, như giá trị lớn nhất, not-a-number, và vô cực. Bạn không thể thay đổi những giá trị của những thuộc tính này và bạn sử dụng nó như sau:

- -
var biggestNum = Number.MAX_VALUE;
-var smallestNum = Number.MIN_VALUE;
-var infiniteNum = Number.POSITIVE_INFINITY;
-var negInfiniteNum = Number.NEGATIVE_INFINITY;
-var notANum = Number.NaN;
-
- -

Bạn luôn phải tham chiếu đến những thuộc tính được định nghĩa sẳn của Number object như trên, và không thể truy xuất qua giá trị số mà bạn tạo ra.

- -

Bảng sau tổng hợp những thuộc tính của Number object.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thuộc tính của Number
Thuộc tínhMô tả
{{jsxref("Number.MAX_VALUE")}}Số lớn nhất có thể gán (±1.7976931348623157e+308)
{{jsxref("Number.MIN_VALUE")}}Số nhỏ nhất có thể gán (±5e-324)
{{jsxref("Number.NaN")}}Special "not a number" value
- Giá trị đặc biệt để mô tả "không phải là số"
{{jsxref("Number.NEGATIVE_INFINITY")}}Giá trị số âm vô định; được về khi vượt quá giá trị có thể tính toán
{{jsxref("Number.POSITIVE_INFINITY")}}Giá trị số dương vô định; được về khi vượt quá giá trị có thể tính toán
{{jsxref("Number.EPSILON")}}Sự khác nhau giữa 1 và giá trị nhỏ nhất lớn hơn 1 mà có thể được biểu diễn là một số
- {{jsxref("Number")}} (2.220446049250313e-16)
{{jsxref("Number.MIN_SAFE_INTEGER")}}Số nguyên được an toàn nhỏ nhất trong JavaScript (−253 + 1, or −9007199254740991)
{{jsxref("Number.MAX_SAFE_INTEGER")}}Số nguyên dương an toàn lớn nhất trong JavaScript (+253 − 1, or +9007199254740991)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Phương thức của Number
Phương thứcMô tả
{{jsxref("Number.parseFloat()")}}Phân tích giá trị chuỗi và trả vể một giá trị số thực.
- Giống như hàm toàn cục {{jsxref("parseFloat", "parseFloat()")}}.
{{jsxref("Number.parseInt()")}}Phân tích giá trị kiểu chuỗi và trả về giá trị số nguyên dựa trên cơ số chỉ định.
- Cũng giống như hàm toàn cục {{jsxref("parseInt", "parseInt()")}} function.
{{jsxref("Number.isFinite()")}}Xác định giá trị được truyền vào có phải là một số xác đinh.
{{jsxref("Number.isInteger()")}}Xác định giá trị truyền vào có phải là một số nguyên.
{{jsxref("Number.isNaN()")}}Xác định giá trị truyền vào là {{jsxref("Global_Objects/NaN", "NaN")}}. Đây là phiên bản cải tiến của {{jsxref("Global_Objects/isNaN", "isNaN()")}}.
{{jsxref("Number.isSafeInteger()")}}Xác định giá trị truyền vào là một số nguyên an toàn.
- -

Number prototype cung cấp những phương thức để lấy thông tin từ những đối tượng Number dưới nhiều định dạng. Bảng sau đây tổng hợp những phương thức của Number.prototype.

- - - - - - - - - - - - - - - - - - - - - - - -
Những phương thức của Number.prototype
Phương thứcMô tả
{{jsxref("Number.toExponential", "toExponential()")}}Trả về một chuỗi biểu diễn một số theo dạng lũy thừa.
{{jsxref("Number.toFixed", "toFixed()")}}Trả về một chuỗi biểu diễn một số theo dạng số thập phân, với phần thập phân cố định.
{{jsxref("Number.toPrecision", "toPrecision()")}}Trả về một chuỗi biểu diễn một số thập phân với độ chính xác được chỉ định.
- -

Math object

- -

{{jsxref("Math")}} object cung cấp thuộc tính và những phương thức để lấy giá trị của các hằng số và những hàm toán học. Ví dụ, thuộc tính PI của Math có giá trị pi (3.141...), mà bạn có thể sử dụng trong ứng dụng như

- -
Math.PI
-
- -

Tương tự, những hàm chuẩn của toán học là phương thức của Math. Bao gồm lượng giác, logarit, hàm mũ, và những hàm khác nữa. Ví dụ, nếu bạn muốn sử dụng hàm lượng giác sine, bạn có thể viết như sau

- -
Math.sin(1.56)
-
- -

Lưu ý rằng phương thức lượng giác của Math nhận đổi số kiểu radians.

- -

Bảng sau tóm tắt những phương thức của đối tượng Math.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Phương thức của Math
Phương thứcMô tả
{{jsxref("Math.abs", "abs()")}}Giá trị tuyệt đối
{{jsxref("Math.sin", "sin()")}}, {{jsxref("Math.cos", "cos()")}}, {{jsxref("Math.tan", "tan()")}}Những hàm lượng giác chuẩn, với đối số đơn vị radians.
{{jsxref("Math.asin", "asin()")}}, {{jsxref("Math.acos", "acos()")}}, {{jsxref("Math.atan", "atan()")}}, {{jsxref("Math.atan2", "atan2()")}}Những hàm lượng giác ngược; trả về giá trị theo đơn vị radians.
{{jsxref("Math.sinh", "sinh()")}}, {{jsxref("Math.cosh", "cosh()")}}, {{jsxref("Math.tanh", "tanh()")}}Hàm Hyperbolic; đối số là giá trị theo đơn vị hyperbolic.
-  
{{jsxref("Math.asinh", "asinh()")}}, {{jsxref("Math.acosh", "acosh()")}}, {{jsxref("Math.atanh", "atanh()")}}Nghịch đảo của hàm hyperbolic; đối số là giá trị theo đơn vị hyperbolic.
-

{{jsxref("Math.pow", "pow()")}}, {{jsxref("Math.exp", "exp()")}}, {{jsxref("Math.expm1", "expm1()")}}, {{jsxref("Math.log10", "log10()")}}, {{jsxref("Math.log1p", "log1p()")}}, {{jsxref("Math.log2", "log2()")}}

-
Hàm mũ và hàm logarit
{{jsxref("Math.floor", "floor()")}}, {{jsxref("Math.ceil", "ceil()")}}Trả về số nguyên lớn nhất và nhỏ nhất mà nhỏ hơn hoặc lớn hơn hoặc bằng đối số truyền vào.
{{jsxref("Math.min", "min()")}}, {{jsxref("Math.max", "max()")}}Trả về giá trị lớn nhất hoặc nhỏ nhất trong dãy các giá trị truyền vào.
{{jsxref("Math.random", "random()")}}Trả về số ngẫu nhiên trong khoảng 0 và 1.
{{jsxref("Math.round", "round()")}}, {{jsxref("Math.fround", "fround()")}}, {{jsxref("Math.trunc", "trunc()")}},Những hàm làm tròn hoặc cắt bớt.
{{jsxref("Math.sqrt", "sqrt()")}}, {{jsxref("Math.cbrt", "cbrt()")}}, {{jsxref("Math.hypot", "hypot()")}} -

Căn bậc hai, cube root, căn bậc hai của tổng đối số bình phương.

-
{{jsxref("Math.sign", "sign()")}}Xác dịnh số âm hay số dương hay số không
{{jsxref("Math.clz32", "clz32()")}},
- {{jsxref("Math.imul", "imul()")}}
Số bit 0 ở đầu trong số nhị phân 32 bit. Kết quả của phép nhân 32 bit.
- -

Không giống như những object khác, bạn không bao giờ tạo Math riêng. Bạn luôn dùng đối tượng Math có sẳn

- -

Date object

- -

JavaScript không có kiểu dữ liệu ngày tháng. Tuy nhiên, bạn có thể sử dụng {{jsxref("Date")}} object và phương thức của nó để làm việc với ngày giờ trong ứng dụng của mình. Date object cung cấp nhiều phương thức trực tiếp để thao tác trên trên giá trị ngày giờ. Nó không có bất kỳ thuộc tính nào.

- -

JavaScript xử lý ngày giờ tương tự Java. Hai ngôn ngữ có nhiều tên phương thức giống nhau, và cả hai ngôn ngữ đều lưu trữ ngày giờ như là một số theo mili giây tính từ ngày 1 tháng 1 năm 1970, 00:00:00, với một Unix Timestamp là một số theo giây tính từ ngày 1 tháng 1, 1970, 00:00:00.

- -

Dãy giá trị của Date object là -100,000,000 ngày đến 100,000,000 ngày so với 01 tháng 1, 1970 UTC.

- -

Để tạo một Date object:

- -
var dateObjectName = new Date([parameters]);
-
-
- -

dateObjectName là biến lưu trữ Date object được  tạo;

- -

Nếu chúng ta bỏ qua từ khóa new, giá trị nhận được là một chuỗi biểu diễn giá trị kiểu ngày giờ.

- -

parameters trong cú pháp trên có thể là một trong những giá trị sau:

- -
    -
  • Không truyền gì vào: tạo ngày giờ hiện hành. Ví dụ: today = new Date();.
  • -
  • Một chuỗi biểu diễn ngày giờ theo định dạng: "Tháng ngày, năm giờ:phút:giây". Ví dụ: var Xmas95 = new Date("December 25, 1995 13:30:00"). Nếu bạn bỏ sót giờ, phút, giây, giá trị mặc định sẽ là 0.
  • -
  • Một tập các số nguyên cho năm, tháng, và ngày. Ví dụ, var Xmas95 = new Date(1995, 11, 25).
  • -
  • Một tập các số nguyên cho năm, tháng, ngày, giờ, phút, và giây. Ví dụ var Xmas95 = new Date(1995, 11, 25, 9, 30, 0);.
  • -
- -

Những phương thức của Date object

- -

Những phương thức của Date object để xử lý thuộc một trong những loại sau:

- -
    -
  • phương thức "set", để gán giá trị ngày giờ cho Date objects.
  • -
  • phương thức "get", để nhận giá trị ngày giờ từ Date objects.
  • -
  • phương thức "to", để nhận về giá trị kiểu chuỗi cho Date objects.
  • -
  • phương thức phân giải (parse) và UTC, để phân giải chuỗi Date .
  • -
- -

Với phương thức "get" và "set" bạn có thể nhận và gán giây, phút, giờ và ngày của tháng, ngày của tuần, tháng, và năm. Phương thức getDay trả về ngày của tuần, tháng, nhưng không có phương thức setDay tương ứng, bởi vì ngày của tuần được xác định tự động. Những phương thức này sử dụng số nguyên để biểu diễn những giá trị sau:

- -
    -
  • Giây và phúc: 0 đến 59
  • -
  • Giờ: 0 đến 23
  • -
  • Thứ: 0 (Chủ nhật) đến 6 (Thứ bảy)
  • -
  • Ngày: 1 đến 31 (ngày của tháng)
  • -
  • Tháng: 0 (Tháng 1) to 11 (Tháng 12)
  • -
  • Năm: năm tính từ 1900
  • -
- -

Ví dụ, giả sử bạn định nghĩa giá trị ngày như sau:

- -
var Xmas95 = new Date('December 25, 1995');
-
- -

Phương thức Xmas95.getMonth() trả về 11, và Xmas95.getFullYear() trả về 1995.

- -

Phương thức getTimesetTime dùng để so sánh hai giá trị ngày. Phương thức getTime trả về số milli giây tính từ 0 giờ 0 phút 0 giây ngày 1 tháng 1 năm 1970.

- -

Ví dụ đoạn mã sau hiển thị số ngày còn lại trong năm hiện tại:

- -
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
-
- -

Đầu tiên một Date object được tạo ra với tên là today chứ giá trị là ngày hiện tại. Sau đó, một Date object nữa được tạo ra với tên là endYear và được gán giá trị của ngày cuối cùng của năm 1995. Nhưng sau đó endYear được gán lại với năm hiện tại cho đồng nhất về năm. Rồi ta tính toán độ chênh lệch theo ngày giữa endYeartoday giá trị phải được làm tròn.

- -

Phương thức parse dùng để chuyển đổi chuỗi kiểu  Date thành Date object. Ví dụ, Đoạn mã sau sử dụng parsesetTime để gán giá trị ngày cho biến IPOdate:

- -
var IPOdate = new Date();
-IPOdate.setTime(Date.parse('Aug 9, 1995'));
-
- -

Ví dụ

- -

Trong ví dụ sau, hàm JSClock() trả về thời gian trong định dạng của đồng hồ số.

- -
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;
-}
-
- -

Hàm JSClock đầu tiên tạo ra Date object với tên time; vì không có đối số được cung cấp, time được tạo ra có giá trị là ngày giờ hiện tại. Sau đó các hàm getHours, getMinutes, và getSeconds để gán giá trị giờ, phút, giây hiện tai cho các biến hour, minute, và second.

- -

Bốn câu lệnh kế tiếp tạo giá trị chuỗi từ thời gian. Câu lệnh đầu tiên tạo một biến temp, dùng biểu thức điều kiện để gán 1 giá trị cho temp; nếu hour lớn hơn 12, thì gán (hour - 12), ngược lại thì gán giá trị của hour.  Nếu giá trị của hour là 0, thì giá trị 12 cho temp.

- -

Câu lệnh tiếp theo chèn gía trị minute cho temp. Nếu giá trị của minute kém hơn 10, ta thêm ':0' vào trước giá trị chuỗi; ngược lại ta chỉ thêm ':'. Sau đó chèn giá trị giây vào temp với cùng cách trên.

- -

Cuối cùng, chèn "P.M" vào temp nếu hour lớn hơn 12, ngược lại ta chèn "A.M.".

- -

{{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}

diff --git a/files/vi/web/javascript/guide/regular_expressions/index.html b/files/vi/web/javascript/guide/regular_expressions/index.html deleted file mode 100644 index acddfd5184..0000000000 --- a/files/vi/web/javascript/guide/regular_expressions/index.html +++ /dev/null @@ -1,666 +0,0 @@ ---- -title: Biểu thức chính quy -slug: Web/JavaScript/Guide/Regular_Expressions -tags: - - Guide - - Intermediate - - JavaScript - - Regular Expression -translation_of: Web/JavaScript/Guide/Regular_Expressions ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}}
- -

Biểu thức chính quy (regular expressions ) là các mẫu dùng để tìm kiếm các bộ kí tự được kết hợp với nhau trong các chuỗi kí tự. Trong JavaScript thì biểu thức chính quy cũng đồng thời là các đối tượng, tức là khi bạn tạo ra một biểu thức chính quy là bạn có một đối tượng tương ứng. Các mẫu này được sử dụng khá nhiều trong JavaScript như phương thức exec và test của RegExp, hay phương thức match, replace, search, và split của String. Trong chương này, ta cùng tìm hiểu chi tiết hơn về biểu thức chính quy trong JavaScript.

- -

Tạo một biểu thức chính quy

- -

Bạn có thể tạo ra một biểu thức chính quy bằng 1 trong 2 cách sau:

- -
    -
  • Sử dụng cách mô tả chính quy thuần (regular expression literal) như sau: -
    var re = /ab+c/;
    -
    - -

    Các đoạn mã chứa các mô tả chính quy thuần sau khi được nạp vào bộ nhớ sẽ dịch các đoạn mô tả đó thành các biểu thức chính quy. Các biểu thức chính quy được dịch ra này sẽ được coi như các hằng số, tức là không phải tạo lại nhiều lần, điều này giúp cho hiệu năng thực hiện tốt hơn.

    -
  • -
  • Tạo một đối tượng RegExp như sau: -
    var re = new RegExp("ab+c");
    -
    - -

    Với cách này, các biểu thức chính quy sẽ được dịch ra lúc thực thi chương trình nên hiệu năng không đạt được như với việc sử dụng cách mô tả chính quy thuần. Nhưng ưu điểm là nó có thể thay đổi được, nên ta thường sử dụng chúng khi ta muốn nó có thể thay đổi được, hoặc khi ta chưa chắc chắn về các mẫu chính quy (pattern) như nhập từ bàn phím chẳng hạn.

    -
  • -
- -

Cách viết một mẫu biểu thức chính quy

- -

Một mẫu biểu thức chính quy là một tập các kí tự thường, như /abc/, hay một tập kết hợp cả kí tự thường và kí tự đặc biệt như /ab*c/ hoặc /Chapter (\d+)\.\d*/. Trong ví dụ cuối, ta thấy rằng nó chứa cả các dấu ngoặc đơn( () )được sử dụng như các thiết bị nhớ, tức là các mẫu trong phần () này sau khi được tìm kiếm có thể được nhớ lại để sử dụng cho các lần sau. Bạn có thể xem chi tiết hơn tại:  Sử dụng dấu ngoặc đơn tìm xâu con.

- -

Sử dụng mẫu đơn giản

- -

Các mẫu đơn giản là các mẫu có thể được xây dựng từ các kí tự có thể thể tìm kiếm một cách trực tiếp. Ví dụ, mẫu /abc/ sẽ tìm các các đoạn 'abc' theo đúng thứ tự đó trong các chuỗi. Mẫu này sẽ khớp được với  "Hi, do you know your abc's?" và "The latest airplane designs evolved from slabcraft.", vì cả 2 chuỗi này đều chứa đoạn 'abc'. Còn với  chuỗi 'Grab crab', nó sẽ không khớp vì chuỗi này không chứa 'abc' theo đúng thứ tự, mà chỉ chứa 'ab c'.

- -

Sử dụng các kí tự đặc biệt

- -

Các mẫu có thể chứa các kí tự đặc biệt cho các mục đích tìm kiếm nâng cao mà tìm kiếm trực tiếp sẽ khó khăn như tìm một đoạn chứa một hoặc nhiều hơn một kí tự b, hay tìm một hoặc nhiều kí tự dấu cách (while space). Ví dụ, mẫu /ab*c/ có thể tìm các đoạn có chứa: một kí tự 'a', theo sau là không có hoặc có một hoặc có nhiều kí tự 'b', cuối cùng là một kí tự 'c' như chuỗi "cbbabbbbcdebc," sẽ được khớp với xâu con 'abbbbc'.

- -

Bảng dưới đây mô tả đầy đủ các kí tự đặc biệt có thể dùng với biểu thức chính quy.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Bảng 4.1 Các kí tự đặc biệt trong biểu thức chính quy.
Kí tự (kí hiệu, cờ)Ý nghĩa
\ -

Tìm với luật dưới đây:
-
- Một dấu gạch chéo ngược sẽ biến một kí tự thường liền kế phía sau thành một kí tự đặc biệt, tức là nó không được sử dụng để tìm kiếm thông thường nữa. Ví dụ,  trường hợp kí tự 'b' không có dấu gạch chéo ngược này sẽ được khớp với các kí tự 'b' in thường, nhưng khi nó có thêm dấu gạch chéo ngược, '\b' thì nó sẽ không khớp với bất kì kí tự nào nữa, lúc này nó trở thành kí tự đặc biệt. Xem thêm phần word boundary character để biết thêm chi tiết.
-
- Tuy nhiên nếu đứng trước một kí tự đặc biệt thì nó sẽ biến kí tự này thành một kí tự thường, tức là bạn có thể tìm kiếm kí tự đặc biệt này trong xâu chuỗi của bạn như các kí tự thường khác. Ví dụ, mẫu /a*/ có '*' là kí tự đặc biệt và mẫu này sẽ bị phụ thuộc vào kí tự này, nên được hiểu là sẽ tìm khớp  với 0 hoặc nhiều kí tự a. Nhưng, với mẫu /a\*/ thì kí tự '*' lúc này được hiểu là kí tự thường nên mẫu này sẽ tìm kiếm xâu con là 'a*'.

- -

Đừng quên \ cũng là một kí tự đặc biệt, khi cần so khớp chính nó ta cũng phải đánh dấu nó là kí tự đặc biệt bằng cách đặt \ ở trước (\\).

-
^ -

Khớp các kí tự đứng đầu một chuỗi. Nếu có nhiều cờ này thì nó còn khớp được cả các kí tự đứng đầu của mỗi dòng (sau kí tự xuống dòng).
-
- Ví dụ, /^A/ sẽ không khớp được với 'A' trong "an A" vì 'A' lúc này không đứng đầu chuỗi, nhưng nó sẽ khớp "An E" vì lúc này 'A' đã đứng đầu chuỗi.

- -

Ý nghĩa của '^' sẽ thay đổi khi nó xuất hiện như một kí tự đầu tiên trong một lớp kí tự, xem phần complemented character sets để biết thêm chi tiết.

-
$ -

So khớp ở cuối chuỗi. Nếu gắn cờ multiline (đa dòng), nó sẽ khớp ngay trước kí tự xuống dòng.

- -

Ví dụ, /t$/ không khớp với 't' trong chuỗi "eater" nhưng lại khớp trong chuỗi "eat".

-
* -

Cho phép kí tự trước nó lặp lại 0 lần hoặc nhiều lần. Tương đương với cách viết {0,}.

- -

Ví dụ, /bo*/ khớp với 'boooo' trong chuỗi "A ghost booooed" nhưng không khớp trong chuỗi "A birth warbled".

-
+ -

Cho phép kí tự trước nó lặp lại 1 lần hoặc nhiều lần. Tương đương với cách viết {1,}.

- -

Ví dụ, /a+/ khớp với 'a' trong chuỗi "candy" và khớp với tất cả kí tự a liền nhau trong chuỗi "caaaaaaandy".

-
? -

Cho phép kí tự trước nó lặp lại 0 lần hoặc 1 lần duy nhất. Tương đương với cách viết {0,1}.

- -

Ví dụ, /e?le?/ khớp với 'el' trong chuỗi "angel" và 'le' trong chuỗi "angle" hay 'l' trong "oslo".

- -

Nếu sử dụng kí tự này ngay sau bất kì kí tự định lượng nào trong số *,+,? hay {}, đều làm bộ định lượng "chán ăn" (dừng so khớp sau ngay khi tìm được kí tự phù hợp), trái ngược với đức tính "tham lam" vốn sẵn của chúng (khớp tất cả kí tự chúng tìm thấy). Ví dụ, áp dụng biểu mẫu /\d+/ cho "123abc" ta được "123". Nhưng áp /\d+?/ cho chính chuỗi trên ta chỉ nhận được kết quả là "1".

- -

Bạn có thể đọc thêm trong mục x(?=y) và x(?!y) của bảng này.

-
. -

Dấu . khớp với bất kì kí tự đơn nào ngoại trừ kí tự xuống dòng.

- -

Ví dụ, /.n/ khớp với 'an' và 'on' trong chuỗi "no, an apple is on the tree", nhưng không khớp với 'no'.

-
(x) -

Khớp 'x' và nhớ kết quả so khớp này, như ví dụ ở dưới. Các dấu ngoặc tròn được gọi là các dấu ngoặc có nhớ.

- -

Biểu mẫu /(foo) (bar) \1 \2/ khớp với 'foo' và 'bar' trong chuỗi "foo bar foo bar". \1\2 trong mẫu khớp với 2 từ cuối.

- -

Chú ý rằng \1, \2, \n được sử dụng để so khớp các phần trong regex, nó đại diện cho nhóm so khớp đằng trước. Ví dụ: /(foo) (bar) \1 \2/ tương đương với biểu thức /(foo) (bar) foo bar/. 

- -

Cú pháp $1, $2, $n còn được sử dụng trong việc thay thế các phần của một regex. Ví dụ: 'bar foo'.replace(/(...) (...)/, '$2 $1') sẽ đảo vị trí 2 từ 'bar' và 'foo' cho nhau.

-
(?:x) -

Khớp 'x' nhưng không nhớ kết quả so khớp. Những dấu ngoặc tròn được gọi là những dấu ngoặc không nhớ, nó cho phép bạn định nghĩa những biểu thức con cho những toán tử so khớp. Xem xét biểu thức đơn giản /(?:foo){1,2}/. Nếu biểu thức này được viết là /foo{1,2}/{1,2} sẽ chỉ áp dụng cho kí tự 'o' ở cuối chuỗi 'foo'. Với những dấu ngoặc không nhớ, {1,2} sẽ áp dụng cho cả cụm 'foo'.

-
x(?=y) -

Chỉ khớp 'x' nếu 'x' theo sau bởi 'y'.

- -

Ví dụ, /Jack(?=Sprat)/ chỉ khớp với 'Jack' nếu đằng sau nó là 'Sprat'. /Jack(?=Sprat|Frost)/ chỉ khớp 'Jack' nếu theo sau nó là 'Sprat' hoặc 'Frost'. Tuy nhiên, cả 'Sprat' và 'Frost' đều không phải là một phần của kết quả so khớp trả về.

-
x(?!y) -

Chỉ khớp 'x' nếu 'x' không được theo sau bởi 'y'.

- -

Ví dụ: /\d+(?!\.)/ chỉ khớp với số không có dấu . đằng sau. Biểu thức /\d+(?!\.)/.exec("3.141")​ cho kết quả là '141' mà không phải '3.141'.

-
x|y -

Khớp 'x' hoặc 'y'

- -

Ví dụ, /green|red/ khớp với 'green' trong chuỗi "green apple" và 'red' trong chuỗi "red apple".

-
{n} -

Kí tự đứng trước phải xuất hiện n lần. n phải là một số nguyên dương.

- -

Ví dụ, /a{2}/ không khớp với 'a' trong "candy", nhưng nó khớp với tất cả kí tự 'a' trong "caandy", và khớp với 2 kí tự 'a' đầu tiên trong "caaandy".

-
{n,m} -

Kí tự đứng trước phải xuất hiện từ n đến m lần. n và m là số nguyên dương và n <= m. Nếu m bị bỏ qua, nó tương đương như ∞.

- -

Ví dụ, /a{1,3}/ không khớp bất kì kí tự nào trong "cndy", kí tự 'a' trong "candy", 2 kí tự 'a' đầu tiên trong "caandy", và 3 kí tự 'a' đầu tiên trong "caaaaaaandy". Lưu ý là "caaaaaaandy" chỉ khớp với 3 kí tự 'a' đầu tiên mặc dù chuỗi đó chứa 7 kí tự 'a'.

-
[xyz] -

Lớp kí tự. Loại mẫu này dùng để so khớp với một kí tự bất kì trong dấu ngoặc vuông, bao gồm cả escape sequences. Trong lớp kí tự, dấu chấm (.) và dấu hoa thị (*) không còn là kí tự đặc biệt nên ta không cần kí tự thoát đứng trước nó. Bạn có thể chỉ định một khoảng kí tự bằng cách sử dụng một kí tự gạch nối (-) như trong ví dụ dưới đây:

- -

Mẫu [a-d] so khớp tương tự như mẫu [abcd], khớp với 'b' trong "brisket" và 'c' trong "city". Mẫu /[a-z.]+/ và /[\w.]+/ khớp với toàn chuỗi "test.i.ng".

-
[^xyz] -

Lớp kí tự phủ định. Khi kí tự ^ đứng đầu tiên trong dấu ngoặc vuông, nó phủ định mẫu này.

- -

Ví dụ, [^abc] tương tự như [^a-c], khớp với 'r' trong "brisket" và 'h' trong "chop" là kí tự đầu tiên không thuộc khoảng a đến c.

-
[\b] -

Khớp với kí tự dịch lùi - backspace (U+0008). Bạn phải đặt trong dấu ngoặc vuông nếu muốn so khớp một kí tự dịch lùi. (Đừng nhầm lẫn với mẫu \b).

-
\b -

Khớp với kí tự biên. Kí tự biên là một kí tự giả, nó khớp với vị trí mà một kí tự không được theo sau hoặc đứng trước bởi một kí tự khác. Tương đương với mẫu (^\w|\w$|\W\w|\w\W). Lưu ý rằng một kí tự biên được khớp sẽ không bao gồm trong kết quả so khớp. Nói cách khác, độ dài của một kí tự biên là 0. (Đừng nhầm lẫn với mẫu [\b])

- -

Ví dụ:
- /\bm/ khớp với 'm' trong chuỗi "moon";
- /oo\b/ không khớp  'oo' trong chuỗi "moon", bởi vì 'oo' được theo sau bởi kí tự 'n';
-  /oon\b/ khớp với 'oon' trong chuỗi "moon", bởi vì 'oon' ở cuối chuỗi nên nó không được theo sau bởi một kí tự; 
- /\w\b\w/ sẽ không khớp với bất kì thứ gì, bởi vì một kí tự không thể theo sau một kí tự biên và một kí tự thường.

- -
-

Chú ý: Engine biên dịch biểu thức chính quy trong Javascript định nghĩa một lớp kí tự là những kí tự thường. Bất kỳ kí tự nào không thuộc lớp kí tự bị xem như một kí tự ngắt. Lớp kí tự này khá hạn chế: nó bao gồm bộ kí tự La-tinh cả hoa và thường, số thập phân và kí tự gạch dưới. Kí tự có dấu, như "é" hay "ü", không may, bị đối xử như một kí tự ngắt.

-
-
\B -

Khớp với kí tự không phải kí tự biên. Mẫu này khớp tại vị trí mà kí tự trước và kí tự sau nó cùng kiểu: hoặc cả hai là kí tự hoặc cả hai không phải là kí tự. Bắt đầu và kết thúc chuỗi không được xem là những kí tự.

- -

Ví dụ, /\B../ khớp với 'oo' trong "noonday", và /y\B./ khớp với 'ye' trong "possibly yesterday."

-
\cX -

X là một kí tự trong khoảng A tới Z. Mẫu này khớp với một kí tự điều khiển trong một chuỗi.

- -

Ví dụ: /\cM/ khớp với control-M (U+000D) trong chuỗi.

-
\d -

Khớp với một kí tự số. Tương đương với mẫu [0-9].

- -

Ví dụ: /\d/ hoặc /[0-9]/ khớp với '2' trong chuỗi "B2 is the suite number."

-
\D -

Khớp với một kí tự không phải là kí tự số. Tương đương với mẫu [^0-9].

- -

Ví dụ; /\D/ hoặc /[^0-9]/ khớp với 'B' trong "B2 is the suite number."

-
\fKhớp với kí tự phân trang - form feed (U+000C).
\nKhớp với kí tự xuống dòng - line feed (U+000A).
\rKhớp với kí tự quay đầu dòng -  carriage return (U+000D).
\s -

Khớp với một kí tự khoảng trắng, bao gồm trống - space, tab, phân trang - form feed, phân dòng - line feed. Tương đương với [ \f\n\r\t\v​\u00a0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​\u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​​\u202f\u205f​\u3000].

- -

Ví dụ: /\s\w*/ khớp với ' bar' trong "foo bar."

-
\S -

Khớp với một kí tự không phải khoảng trắng. Tương đương với [^ \f\n\r\t\v​\u00a0\u1680​\u180e\u2000​\u2001\u2002​\u2003\u2004​\u2005\u2006​\u2007\u2008​\u2009\u200a​\u2028\u2029​\u202f\u205f​\u3000].

- -

Ví dụ: /\S\w*/ khớp với 'foo' trong chuỗi "foo bar."

-
\tKhớp với kí tự tab (U+0009).
\vKhớp với kí tự vertical tab (U+000B).
\w -

Khớp với tất cả kí tự là chữ, số và gạch dưới. Tương đương với mẫu [A-Za-z0-9_].

- -

ví dụ, /\w/ khớp với 'a' trong "apple," '5' trong "$5.28," và '3' trong "3D."

-
\W -

Khớp với tất cả kí tự không phải là chữ. Tương đương với mẫu [^A-Za-z0-9_].

- -

ví dụ, /\W/ hoặc /[^A-Za-z0-9_]/ khớp với '%' trong "50%."

-
\n -

Trong đó, n là một số nguyên dương, một tham chiếu ngược tới chuỗi khớp thứ n trong biểu thức (đếm từ trái sang, bắt đầu bằng 1).

- -

ví dụ, /apple(,)\sorange\1/ hay /apple(,)\sorange,/ khớp với 'apple, orange,' trong chuỗi "apple, orange, cherry, peach."

-
\0Khớp với kí tự NULL (U+0000). Lưu ý: không được thêm bất kì một kí tự số nào sau 0, vì \0<các-kí-tự-số> là một biểu diễn hệ bát phân escape sequence.
\xhhKhớp với kí tự với mã code là hh (2 số trong hệ thập lục phân)
\uhhhhKhớp với kí tự có mã hhhh (4 số trong hệ thập lục phân).
- -

Mã hóa escapse chuỗi người dùng nhập vào bằng một hàm thay thế đơn giản sử dụng biểu thức chính quy:

- -
function escapeRegExp(string){
-  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-}
- -

Sử dụng ngoặc tròn

- -

Ngoặc tròn bao quanh bất kỳ phần nào của biểu thức chính quy sẽ khiến phần kết quả so khớp được nhớ. Mỗi lần nhớ, chuỗi con có thể được gọi lại để sử dụng, mô tả trong Using Parenthesized Substring Matches.

- -

Ví dụ, mẫu /Chapter (\d+)\.\d*/ khớp đúng với 'Chapter ' theo sau bởi một hoặc nhiều kí tự số, sau nữa là một dấu chấm thập phân, cuối cùng có thể là 0 hoặc nhiều kí tự số. Bên cạnh đó, dấu ngoặc tròn được sử dụng để nhớ một hoặc nhiều kí tự số đầu tiên được khớp.

- -

Mẫu này được tìm thấy trong chuỗi "Open Chapter 4.3, paragraph 6", nhớ '4' nhưng không được tìm thấy trong chuỗi "Chapter 3 and 4", bởi vì chuỗi đó không có dấu chấm sau kí tự số '3'.

- -

Để so khớp một chuỗi con không nhớ, đặt ?: ở vị trí đầu tiên trong ngoặc. Ví dụ, (?:\d+) khớp với một hoặc nhiều kí tự số nhưng không nhớ kết quả so khớp.

- -

Làm việc với biểu thức chính quy

- -

Biểu thức chính quy được sử dụng với phương thức test và exec của lớp RegExp hoặc phương thức match, replace, search và split của chuỗi. Những phương thức này được giải thích chi tiết trong JavaScript Reference.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Bảng 4.2 Những phương thức được sử dụng trong biểu thức chính quy
Phương thứcMô tả
execMột phương thức của RegExp dùng để tìm kiếm chuỗi phù hợp với mẫu so khớp. Nó trả về một mảng chứa kết quả tìm kiếm.
testMột phương thức của RegExp dùng để kiểm tra mẫu có khớp với chuỗi hay không. Nó trả về giá trị true hoặc false.
matchMột phương thức của chuỗi dùng để tìm kiếm chuỗi phù hợp với mẫu so khớp. Nó trả về một mảng chứa kết quả tìm kiếm hoặc null nếu không tìm thấy.
searchMột phương thức của chuỗi dùng để tìm kiếm chuỗi phù hợp với mẫu so khớp và trả về vị trí của chuỗi đó hoặc -1 nếu không tìm thấy.
replaceMột phương thức của chuỗi dùng để tìm kiếm một chuỗi theo mẫu so khớp và thay thế chuỗi con được khớp với một chuỗi thay thế.
splitMột phương thức của chuỗi dùng một biểu mẫu chính quy hoặc một chuỗi bất biến để ngắt chuỗi đó thành một mảng các chuỗi con.
- -

Khi bạn muốn biết một mẫu có được tìm thấy trong chuỗi hay không, sử dụng phương thức test hoặc search; để lấy nhiều thông tin hơn (nhưng chậm hơn) sử dụng phương thức exec hoặc match.

- -

Như ví dụ dưới đây, phương thức exec được dùng để tìm chuỗi phù hợp theo mẫu so khớp.

- -
var myRe = /d(b+)d/g;
-var myArray = myRe.exec("cdbbdbsbz");
-
- -

Nếu bạn không cần truy cập những thuộc tính khác của biểu thức chính quy, sử dụng cách sau:

- -
var myArray = /d(b+)d/g.exec("cdbbdbsbz");
-
- -

Nếu bạn muốn khởi tạo một biểu thức chính quy từ một chuỗi:

- -
var myRe = new RegExp("d(b+)d", "g");
-var myArray = myRe.exec("cdbbdbsbz");
-
- -

Với những mã này, so khớp thành công và trả về một mảng kết quả với những thuộc tính được liệt kê trong bảng dưới đây.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Bảng 4.3 Kết quả so khớp
Đối tượngThuộc tính hoặc chỉ sốMô tảTrong vd này
myArray Chuỗi kết quả so khớp và toàn bộ chuỗi con được nhớ.["dbbd", "bb"]
indexVị trí của chuỗi tìm thấy, đếm từ 01
inputChuỗi gốc được nhập vào"cdbbdbsbz"
[0]Những kí tự cuối cùng được khớp."dbbd"
myRelastIndexVị trí nơi mà bắt đầu so khớp lần sau. (Thuộc tính này chỉ được gán nếu biểu thức chính quy sử dụng lựa chọn g, được mô tả trong Advanced Searching With Flags ).5
sourceChuỗi biểu thức chính quy, được cập nhật tại thời điểm biểu thức được tạo, không phải tại lúc thực thi."d(b+)d"
- -

Như dạng thứ 2 của ví dụ trên, bạn có thể dùng một biểu thức chính quy được khởi tạo mà không gán nó tới một biến. Tuy nhiên, nếu bạn làm thế, mỗi lần xuất hiện là một biểu thức chính quy mới. Vì lí do này, nếu bạn không gán nó vào một biến, bạn sẽ không thể truy cập các thuộc tính của biểu thức chính quy đó nữa. Ví dụ bạn có đoạn script sau:

- -
var myRe = /d(b+)d/g;
-var myArray = myRe.exec("cdbbdbsbz");
-console.log("The value of lastIndex is " + myRe.lastIndex);
-
- -

Kết quả hiển thị là:

- -
The value of lastIndex is 5
-
- -

Tuy nhiên nếu bạn chạy:

- -
var myArray = /d(b+)d/g.exec("cdbbdbsbz");
-console.log("The value of lastIndex is " + /d(b+)d/g.lastIndex);
-
- -

Thì kết quả hiển thị sẽ là:

- -
The value of lastIndex is 0
-
- -

Sự xuất hiện của /d(b+)d/g trong 2 lệnh trên là những đối tượng biểu thức chính quy khác nhau và vì thế có những giá trị khác nhau cho thuộc tính lastIndex. Nếu bạn cần truy cập những thuộc tính của một biểu thức chính quy, bạn nên gán nó tới một biến.

- -

Sử dụng nhiều dấu ngoặc tròn

- -

Sử dụng nhiều ngoặc tròn trong một biểu thức chính quy cho ta nhiều kết quả so khớp tương ứng được nhớ. Cho ví dụ, /a(b)c/ khớp với 'abc' và nhớ 'b'. Để gọi lại những kết quả so khớp, sử dụng những phần tử của mảng [1]..., [n].

- -

Số lượng các chuỗi con trong những ngoặc tròn là không giới hạn. Mảng trả về giữ lại tất cả mọi thứ được tìm thấy.

- -

Ví dụ

- -

Đoạn mã JavaScript dưới đây sử dụng phương thức replace() để giao hoán các từ trong chuỗi. Trong chuỗi thay thế, ta dùng $1 và $2 để chỉ các chuỗi khớp với mẫu trong ngoặc ở vị trí thứ 1 và 2.

- -
var re = /(\w+)\s(\w+)/;
-var str = "John Smith";
-var newstr = str.replace(re, "$2, $1");
-console.log(newstr);
-
- -

Kết quả hiển thị là: "Smith, John".

- -

Tìm kiếm nâng cao với cờ

- -

Biểu thức chính quy có 4 cờ cho phép tìm kiếm toàn cục và hoa thường. Những cờ này có thể được đứng riêng hoặc đứng gần nhau, và được coi như một phần của biểu thức chính quy.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Bảng 4.4 Cờ của biểu thức chính quy
CờMô tả
gTìm kiếm toàn cục.
iTìm kiếm không phân biệt hoa thường.
mTìm đa dòng.
yThực thi một tìm kiếm "dính" - so khớp được bắt đầu ở vị trí hiện tại trong chuỗi mục tiêu.
- -

{{ Fx_minversion_note(3, "Từ Firefox 3 đã hỗ trợ cờ y. Cờ y thất bại nếu so khớp không thành công ở vị trí hiện tại trong chuỗi mục tiêu.") }}

- -

Để sử dụng cờ trong biểu thức chính quy, dùng cú pháp này:

- -
var re = /pattern/flags;
-
- -

hoặc

- -
var re = new RegExp("pattern", "flags");
-
- -

Lưu ý rằng cờ là một phần hợp thành một biểu thức chính quy. Chúng không thể được thêm hoặc gỡ bỏ sau đó.

- -

Ví dụ, re = /\w+\s/g tạo một biểu thức chính quy dùng để tìm kiếm một hoặc nhiều kí tự theo sau bởi một khoảng trắng, và nó tìm kiếm tổ hợp này xuyên suốt chuỗi mục tiêu.

- -
var re = /\w+\s/g;
-var str = "fee fi fo fum";
-var myArray = str.match(re);
-console.log(myArray);
-
- -

Kết quả hiển thị là ["fee ", "fi ", "fo "].

- -

Trong ví dụ này, bạn cũng có thể thay thế dòng này:

- -
var re = /\w+\s/g;
-
- -

bằng:

- -
var re = new RegExp("\\w+\\s", "g");
-
- -

và nhận được cùng một kết quả giống nhau.

- -

Cờ m được sử dụng để xác định rằng một chuỗi đầu vào nên được đối xử như nhiều dòng. Nếu dùng cờ này, so khớp ^ và $ ở đầu và cuối ở mọi dòng trong chuỗi đầu vào thay vì ở đầu và cuỗi của toàn bộ chuỗi.

- -

Ví dụ minh họa

- -

Các ví dụ sau đây cho thấy một số cách sử dụng các biểu thức chính quy.

- -

Thay đổi thứ tự trong một chuỗi

- -

Ví dụ sau đây minh họa sự cấu thành các biểu thức chính quy và việc sử dụng các phương thức string.split()string.Replace(). Nó làm sạch một chuỗi đầu vào được định dạng có chứa tên (first name ở vị trí đầu tiên) cách nhau bởi khoảng trống, các tab và chỉ một dấu chấm phẩy duy nhất. Cuối cùng, nó đảo ngược thứ tự tên (last name ở vị trí đầu tiên) và sắp xếp lại danh sách.

- -
// 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"));
-
- -

Sử dụng những kí tự đặc biệt để xác thực đầu vào

- -

Trong ví dụ dưới đây, ta mong chờ người dùng nhập một số điện thoại. Khi người dùng ấn nút "Check", đoạn script sẽ kiểm tra tính xác thực của số vừa nhập. Nếu số đó hợp lệ (khớp với chuỗi kí tự được xác định bởi biểu thức chính quy), website sẽ hiển thị một tin nhắn cảm ơn người dùng và xác nhận số đó. Nếu số đó không hợp lệ, website sẽ thông báo người dùng rằng số điện thoại vừa nhập không hợp lệ.

- -

var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;

- -

Trong mẫu ngoặc tròn không nhớ (?:, biểu thức chính quy tìm 3 kí tự số \d{3}  hoặc | 3 kí tự số trong cặp ngoặc tròn, (kết thúc mẫu ngoặc tròn không nhớ), sau đó là một kí tự gạch ngang, dấu chéo ngược, hoặc dấu chấm thập phân, và khi tìm thấy, nhớ kí tự vừa tìm được, tìm tiếp 3 kí tự số, theo sau là một so khớp được nhớ ở lần đầu tiên ([-\/\.]), cuối cùng là 4 kí tự số.

- -

Sự kiện change được kích hoạt khi người dùng nhấp Enter.

- -
<!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/vi/web/javascript/guide/text_formatting/index.html b/files/vi/web/javascript/guide/text_formatting/index.html deleted file mode 100644 index c3a09c6617..0000000000 --- a/files/vi/web/javascript/guide/text_formatting/index.html +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Text formatting -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")}}
-

Chương này giới thiệu cách làm việc với các chuỗi và văn bản trong JavaScript.

- -

Dây

- -

Kiểu chuỗi của JavaScript được sử dụng để thể hiện dữ liệu văn bản. Nó là một tập hợp các "phần tử" của các giá trị nguyên không dấu 16 bit (đơn vị mã UTF-16). Mỗi phần tử trong Chuỗi chiếm một vị trí trong Chuỗi. Phần tử đầu tiên là ở chỉ số 0, phần tử tiếp theo ở chỉ số 1, v.v. Độ dài của Chuỗi là số phần tử trong đó. Bạn có thể tạo chuỗi bằng cách sử dụng chuỗi ký tự hoặc chuỗi đối tượng.

- - - -

Chuỗi ký tự

- -

Bạn có thể tạo các chuỗi đơn giản bằng cách sử dụng dấu ngoặc đơn hoặc dấu ngoặc kép:

- -
'foo'
-"quán ba"
- -

Các chuỗi nâng cao hơn có thể được tạo bằng các chuỗi thoát:

- -

Trình tự thoát thập lục phân

- -

The number after \x is interpreted as a hexadecimal number.

- -
'\xA9' // "©"
-
- -

Unicode escape sequences

- -

The Unicode escape sequences require at least four hexadecimal digits following \u.

- -
'\u00A9' // "©"
- -

Unicode code point escapes

- -

New in ECMAScript 2015. With Unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use Unicode code points up to 0x10FFFF. With simple Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result.

- -

See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}.

- -
'\u{2F804}'
-
-// the same with simple Unicode escapes
-'\uD87E\uDC04'
- -

String objects

- -

The {{jsxref("String")}} object is a wrapper around the string primitive data type.

- -
const foo = new String('foo'); // Creates a String object
-console.log(foo); // Displays: [String: 'foo']
-typeof foo; // Returns 'object'
-
- -

You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal.

- -

You should use string literals unless you specifically need to use a String object, because String objects can have counterintuitive behavior. For example:

- -
const firstString = '2 + 2'; // Creates a string literal value
-const secondString = new String('2 + 2'); // Creates a String object
-eval(firstString); // Returns the number 4
-eval(secondString); // Returns the string "2 + 2"
- -

A String object has one property, length, that indicates the number of UTF-16 code units in the string. For example, the following code assigns helloLength the value 13, because "Hello, World!" has 13 characters, each represented by one UTF-16 code unit. You can access each code unit using an array bracket style. You can't change individual characters because strings are immutable array-like objects:

- -
const hello = 'Hello, World!';
-const helloLength = hello.length;
-hello[0] = 'L'; // This has no effect, because strings are immutable
-hello[0]; // This returns "H"
-
- -

Characters whose Unicode scalar values are greater than U+FFFF (such as some rare Chinese/Japanese/Korean/Vietnamese characters and some emoji) are stored in UTF-16 with two surrogate code units each. For example, a string containing the single character U+1F600 "Emoji grinning face" will have length 2. Accessing the individual code units in such a string using brackets may have undesirable consequences such as the formation of strings with unmatched surrogate code units, in violation of the Unicode standard. (Examples should be added to this page after MDN bug 857438 is fixed.) See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}.

- -

A String object has a variety of methods: for example those that return a variation on the string itself, such as substring and toUpperCase.

- -

The following table summarizes the methods of {{jsxref("String")}} objects.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Methods of String

-
MethodDescription
{{jsxref("String.charAt", "charAt")}}, {{jsxref("String.charCodeAt", "charCodeAt")}}, {{jsxref("String.codePointAt", "codePointAt")}}Return the character or character code at the specified position in string.
{{jsxref("String.indexOf", "indexOf")}}, {{jsxref("String.lastIndexOf", "lastIndexOf")}}Return the position of specified substring in the string or last position of specified substring, respectively.
{{jsxref("String.startsWith", "startsWith")}}, {{jsxref("String.endsWith", "endsWith")}}, {{jsxref("String.includes", "includes")}}Returns whether or not the string starts, ends or contains a specified string.
{{jsxref("String.concat", "concat")}}Combines the text of two strings and returns a new string.
{{jsxref("String.fromCharCode", "fromCharCode")}}, {{jsxref("String.fromCodePoint", "fromCodePoint")}}Constructs a string from the specified sequence of Unicode values. This is a method of the String class, not a String instance.
{{jsxref("String.split", "split")}}Splits a String object into an array of strings by separating the string into substrings.
{{jsxref("String.slice", "slice")}}Extracts a section of a string and returns a new string.
{{jsxref("String.substring", "substring")}}, {{jsxref("String.substr", "substr")}}Return the specified subset of the string, either by specifying the start and end indexes or the start index and a length.
{{jsxref("String.match", "match")}}, {{jsxref("String.matchAll", "matchAll")}}, {{jsxref("String.replace", "replace")}}, {{jsxref("String.search", "search")}}Work with regular expressions.
{{jsxref("String.toLowerCase", "toLowerCase")}}, {{jsxref("String.toUpperCase", "toUpperCase")}} -

Return the string in all lowercase or all uppercase, respectively.

-
{{jsxref("String.normalize", "normalize")}}Returns the Unicode Normalization Form of the calling string value.
{{jsxref("String.repeat", "repeat")}}Returns a string consisting of the elements of the object repeated the given times.
{{jsxref("String.trim", "trim")}}Trims whitespace from the beginning and end of the string.
- -

Multi-line template literals

- -

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

- -

Template literals are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template literals can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}).

- -

Multi-lines

- -

Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings:

- -
console.log('string text line 1\n\
-string text line 2');
-// "string text line 1
-// string text line 2"
- -

To get the same effect with multi-line strings, you can now write:

- -
console.log(`string text line 1
-string text line 2`);
-// "string text line 1
-// string text line 2"
- -

Embedded expressions

- -

In order to embed expressions within normal strings, you would use the following syntax:

- -
const five = 5;
-const ten = 10;
-console.log('Fifteen is ' + (five + ten) + ' and not ' + (2 * five + ten) + '.');
-// "Fifteen is 15 and not 20."
- -

Now, with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:

- -
const five = 5;
-const ten = 10;
-console.log(`Fifteen is ${five + ten} and not ${2 * five + ten}.`);
-// "Fifteen is 15 and not 20."
- -

For more information, read about Template literals in the JavaScript reference.

- -

Internationalization

- -

The {{jsxref("Intl")}} object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The constructors for {{jsxref("Collator")}}, {{jsxref("NumberFormat")}}, and {{jsxref("DateTimeFormat")}} objects are properties of the Intl object.

- -

Date and time formatting

- -

The {{jsxref("DateTimeFormat")}} object is useful for formatting date and time. The following formats a date for English as used in the United States. (The result is different in another time zone.)

- -
const msPerDay = 24 * 60 * 60 * 1000;
-
-// July 17, 2014 00:00:00 UTC.
-const july172014 = new Date(msPerDay * (44 * 365 + 11 + 197));
-
-const options = { year: '2-digit', month: '2-digit', day: '2-digit',
-                hour: '2-digit', minute: '2-digit', timeZoneName: 'short' };
-const americanDateTime = new Intl.DateTimeFormat('en-US', options).format;
-
-console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT
-
- -

Number formatting

- -

The {{jsxref("NumberFormat")}} object is useful for formatting numbers, for example currencies.

- -
const gasPrice = new Intl.NumberFormat('en-US',
-                        { style: 'currency', currency: 'USD',
-                          minimumFractionDigits: 3 });
-
-console.log(gasPrice.format(5.259)); // $5.259
-
-const hanDecimalRMBInChina = new Intl.NumberFormat('zh-CN-u-nu-hanidec',
-                        { style: 'currency', currency: 'CNY' });
-
-console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五
-
- -

Collation

- -

The {{jsxref("Collator")}} object is useful for comparing and sorting strings.

- -

For example, there are actually two different sort orders in German, phonebook and dictionary. Phonebook sort emphasizes sound, and it’s as if “ä”, “ö”, and so on were expanded to “ae”, “oe”, and so on prior to sorting.

- -
const names = ['Hochberg', 'Hönigswald', 'Holzman'];
-
-const 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"
-
- -

Some German words conjugate with extra umlauts, so in dictionaries it’s sensible to order ignoring umlauts (except when ordering words differing only by umlauts: schon before schön).

- -
const 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"
-
- -

For more information about the {{jsxref("Intl")}} API, see also Introducing the JavaScript Internationalization API.

- -
{{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}
diff --git a/files/vi/web/javascript/guide/using_promises/index.html b/files/vi/web/javascript/guide/using_promises/index.html deleted file mode 100644 index 8ed6befe37..0000000000 --- a/files/vi/web/javascript/guide/using_promises/index.html +++ /dev/null @@ -1,329 +0,0 @@ ---- -title: Sử dụng Promise -slug: Web/JavaScript/Guide/Using_promises -tags: - - Hướng dẫn - - JavaScript - - Promise - - bất đồng bộ - - trình độ trung cấp -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")}} là một đối tượng thể hiện cho sự hoàn thành hoặc thất bại của một tiến trình bất đồng bộ. Vì đa số chúng ta là người sử dụng Promise được tạo sẵn, bài viết này sẽ hướng dẫn cách sử dụng Promise trước khi hướng dẫn cách tạo ra chúng.

- -

Về cơ bản, một promise là một đối tượng trả về mà bạn gắn callback vào nó thay vì truyền callback vào trong một hàm.

- -

Giả sử chúng ta có một hàm, createAudioFileAsync(), mà nó sẽ tạo ra một file âm thanh từ config object và hai hàm callback một cách bất đồng bộ, một hàm sẽ được gọi khi file âm thanh được tạo thành công, và một hàm được gọi khi có lỗi xảy ra.

- -

Sau đây là code ví dụ sử dụng 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);
-
- -

Thay vì như trên, các hàm bất đồng bộ hiện đại sẽ trả về đối tượng promise mà bạn sẽ gắn callback vào nó:

- -

Nếu hàm createAudioFileAsync() được viết lại sử dụng promise, thì việc sử dụng nó sẽ chỉ đơn giản như sau:

- -
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);
- -

Nếu viết dài dòng hơn thì sẽ là:

- -
const promise = createAudioFileAsync(audioSettings);
-promise.then(successCallback, failureCallback);
- -

Chúng ta gọi đây là một lời gọi hàm bất đồng bộ (asynchronous function call). Cách tiếp cận này có nhiều ưu điểm, mà chúng ta sẽ lần lượt xem xét bên dưới.

- -

Sự đảm bảo

- -

Không như cách truyền callback kiểu cũ, một promise có những đảm bảo như sau:

- -
    -
  • Callback sẽ không bao giờ được gọi trước khi hoàn tất lượt chạy của một JavaScript event loop.
  • -
  • Callback được thêm vào then() sau khi tiến trình bất đồng bộ đã hoàn thành vẫn được gọi, và theo nguyên tắc ở trên.
  • -
  • Nhiều callback có thể được thêm vào bằng cách gọi then() nhiều lần. Mỗi callback sẽ được gọi lần lượt, theo thứ tự mà chúng được thêm vào.
  • -
- -

Một trong những đặc tính tuyệt vời của promise là chaining (gọi nối).

- -

Chaining (gọi nối)

- -

Có một nhu cầu phổ biến đó là thực thi hai hay nhiều tiến trình bất đồng độ liên tiến nhau, cái sau bắt đầu ngay khi cái trước hoàn tất, với giá trị truyền vào là kết quả từ bước trước đó. Mục tiêu này có thể đạt được với một chuỗi promise (promise chain).

- -

Sau đây là cách nó hoạt động: hàm then() trả về một promise mới, khác với hàm ban đầu:

- -
const promise = doSomething();
-const promise2 = promise.then(successCallback, failureCallback);
-
- -

hoặc

- -
const promise2 = doSomething().then(successCallback, failureCallback);
-
- -

Promise thứ hai (promise2) không chỉ đại diện cho việc hoàn thành doSomething() mà còn cho cả successCallback hoặc failureCallback mà bạn đưa vào, mà chúng có thể là những hàm bất đồng bộ khác trả về promise. Trong trường hợp đó, bất kỳ callback nào được thêm vào cho promise2 cũng sẽ được xếp phía sau promise trả về bởi một trong hai successCallback hoặc failureCallback.

- -

Tóm lại, mỗi promise đại diện cho việc hoàn tất của một bước bất đồng bộ trong chuỗi.

- -

Trước khi có promise, kết quả của việc thực hiện một chuỗi các thao tác bất đồng bộ theo cách cũ là một "thảm họa" kim tự tháp callback:

- -
doSomething(function(result) {
-  doSomethingElse(result, function(newResult) {
-    doThirdThing(newResult, function(finalResult) {
-      console.log('Got the final result: ' + finalResult);
-    }, failureCallback);
-  }, failureCallback);
-}, failureCallback);
-
- -

Thay vào đó, với cách tiếp cận hiện đại, chúng ta sẽ gắn các callback vào các promise trả về, tạo thành một chuỗi promise:

- -
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);
-
- -

Tham số cho then là không bắt buộc, và catch(failureCallback) là cách viết gọn của then(null, failureCallback). Bạn có thể thấy chuỗi promise dùng với arrow function như sau:

- -
doSomething()
-.then(result => doSomethingElse(result))
-.then(newResult => doThirdThing(newResult))
-.then(finalResult => {
-  console.log(`Got the final result: ${finalResult}`);
-})
-.catch(failureCallback);
-
- -

Quan trọng: hãy nhớ luôn trả về kết quả, nếu không, callback sẽ không nhận được kết quả từ promise trước đó (với arrow functions () => x được rút gọn từ () => { return x; })

- -

Gọi nối sau hàm catch

- -

Bạn có thể tiếp tục gọi chuỗi then sau một hàm bắt lỗi catch. Điều này cho phép code của bạn luôn thực hiện một thao tác nào đó cho dù đã có lỗi xảy ra ở một bước nào đó trong chuỗi. Hãy xem ví dụ sau:

- -
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, no matter what happened before');
-});
-
- -

Đoạn code này sẽ log ra những dòng sau:

- -
Initial
-Do that
-Do this, no matter what happened before
-
- -

Ghi chú: Dòng text Do this không hiển thị bởi vì Error Something failed đã xảy ra trước và gây lỗi trong chuỗi promise.

- -

Xử lý lỗi tập trung

- -

Bạn hãy nhớ lại đoạn code kim tự tháp thảm họa ở trên, có đến 3 lần hàm failureCallback được sử dụng. Trong khi đó, bạn chỉ cần khai báo một lần vào cuối chuỗi promise:

- -
doSomething()
-.then(result => doSomethingElse(result))
-.then(newResult => doThirdThing(newResult))
-.then(finalResult => console.log(`Got the final result: ${finalResult}`))
-.catch(failureCallback);
-
- -

Về căn bản, một chuỗi promise sẽ dừng lại nếu có lỗi xảy ra, và nó sẽ truy xuống dưới cuối chuỗi để tìm và gọi hàm xử lý lỗi catch. Cách hoạt động này khá giống với cách thức hoạt động của try catch của code đồng bộ:

- -
try {
-  const result = syncDoSomething();
-  const newResult = syncDoSomethingElse(result);
-  const finalResult = syncDoThirdThing(newResult);
-  console.log(`Got the final result: ${finalResult}`);
-} catch(error) {
-  failureCallback(error);
-}
-
- -

Và vì lý do trên, try catch cũng được sử dụng để bắt lỗi cho code bất đồng bộ khi viết với cú pháp async/await của ECMAScript 2017.

- -
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);
-  }
-}
-
- -

Cú pháp trên được xây dựng từ Promise, VD: doSomething() chính là hàm được viết với Promise ở trên. Bạn có thể đọc thêm về cú pháp đó ở đây.

- -

Promise giúp giải quyết một hạn chế cơ bản của kim tự tháp callback, đó là cho phép bắt được tất cả các loại lỗi, từ những lỗi throw Error cho đến lỗi về cú pháp lập trình. Điều này rất cần thiết cho việc phối hợp các hàm xử lý bất đồng bộ.

- -

Tạo Promise từ API có kiểu callback cũ

- -

Một {{jsxref("Promise")}} có thể được tạo mới từ đầu bằng cách sử dụng hàm constructor. Tuy nhiên cách này thường chỉ dùng để bọc lại API kiểu cũ.

- -

Trong môi trường lý tưởng, tất cả các hàm bất đồng bộ đều trả về promise. Tuy nhiên vẫn còn nhiều API yêu cầu hàm callback được truyền vào theo kiểu cũ. Ví dụ điển hình nhất chính là hàm {{domxref("WindowTimers.setTimeout", "setTimeout()")}}:

- -
setTimeout(() => saySomething("10 seconds passed"), 10000);
-
- -

Trộn lẫn callback và promise có nhiều vấn đề tiềm ẩn. Nếu hàm saySomething() xảy ra lỗi bên trong nó, sẽ không có gì bắt được lỗi này. setTimeout là để đổ lỗi cho điều này.

- -

May mắn là chúng ta có thể bọc setTimeout lại với promise. Cách làm tốt nhất là bọc hàm có vấn đề ở cấp thấp nhất, để rồi sau đó chúng ta không phải gọi nó trực tiếp nữa:

- -
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
-
-wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback);
-
- -

Về căn bản, constructor của Promise nhận vào một hàm thực thi với hai tham số hàm resolve và reject để chúng ta có thể giải quyết hoặc từ chối promise một cách thủ công. Bởi vì hàm setTimeout() không bao giờ gây ra lỗi, chúng ta bỏ qua reject trong trường hợp này.

- -

Phối hợp các Promise

- -

{{jsxref("Promise.resolve()")}} và {{jsxref("Promise.reject()")}} là những phương thức để lấy nhanh một promise đã được giải quyết hoặc từ chối sẵn. Những phương thức này có thể hữu dụng trong một số trường hợp.

- -

{{jsxref("Promise.all()")}} và {{jsxref("Promise.race()")}} là hai hàm tiện ích dùng để phối hợp các thao tác bất đồng bộ chạy song song.

- -

Chúng ta có thể cho các tiến trình bất đồng bộ bắt đầu song song và chờ cho đến khi tất cả đều hoàn tất như sau:

- -
Promise.all([func1(), func2(), func3()])
-.then(([result1, result2, result3]) => { /* use result1, result2 and result3 */ });
-
- -

Việc phối hợp các tiến trình bất đồng bộ diễn ra tuần tự không có sẵn tiện ích nhưng có thể viết mẹo với reduce như sau:

- -
[func1, func2, func3].reduce((p, f) => p.then(f), Promise.resolve())
-.then(result3 => { /* use result3 */ });
-
- -

Về cơ bản, chúng ta đang rút gọn (reduce, tạm dịch) một mảng các hàm bất đồng bộ thành một chuỗi promise: Promise.resolve().then(func1).then(func2).then(func3);

- -

Thao tác trên có thể được viết thành một hàm dùng lại được, như cách chúng ta hay làm trong functional programming:

- -
const applyAsync = (acc,val) => acc.then(val);
-const composeAsync = (...funcs) => x => funcs.reduce(applyAsync, Promise.resolve(x));
- -

Hàm composeAsync() sẽ nhận vào tham số là các hàm xử lý bất đồng bộ với số lượng bất kỳ, và trả và một hàm mới mà khi gọi, nó nhận vào một giá trị ban đầu mà giá trị này sẽ được truyền vào tuần tự qua các hàm xử lý bất đồng bộ:

- -
const transformData = composeAsync(func1, func2, func3);
-const result3 = transformData(data);
-
- -

Trong ECMAScript 2017, việc phối hợp tuần tự các promise có thể thực hiện đơn giản hơn với async/await:

- -
let result;
-for (const f of [func1, func2, func3]) {
-  result = await f(result);
-}
-/* use last result (i.e. result3) */
-
- -

Thời điểm thực thi

- -

Để nhất quán và tránh những bất ngờ, các hàm truyền vào cho then() sẽ không bao giờ được thực thi đồng bộ, ngay với  cả những promíe đã được giải quyết:

- -
Promise.resolve().then(() => console.log(2));
-console.log(1); // 1, 2
-
- -

Thay vì chạy ngay lập tức, promise callback được đặt vào hàng đợi microtask, điều này có nghĩa là nó sẽ chỉ được thực thi khi hàng đợi được làm rỗng ( các promise đều được giải quy) cuối event loop hiện tại của JavaScript:

- -
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
-
- -

Lồng cấp

- -

Chuỗi Promise đơn giản chỉ nên có một cấp và không lồng vào nhau, vì lồng cấp sẽ dẫn đến những tổ hợp phức tạp dễ gây ra lỗi. Xem các sai lầm thường gặp.

- -

Lồng nhau là một cấu trúc kiểm soát để giới hạn phạm vi của các câu lệnh catch. Cụ thể, một câu lệnh catch lồng bên trong chỉ có thể bắt được những lỗi trong phạm vi của nó và bên dưới, không phải là lỗi phía bên trên của chuỗi bên ngoài phạm vi lồng nhau. Khi được sử dụng một cách hợp lý, nó mang lại độ chính xác cao hơn trong việc khôi phục lỗi:

- -
doSomethingCritical()
-.then(result => doSomethingOptional()
-  .then(optionalResult => doSomethingExtraNice(optionalResult))
-  .catch(e => {})) // Ignore if optional stuff fails; proceed.
-.then(() => moreCriticalStuff())
-.catch(e => console.log("Critical failure: " + e.message));
-
- -

Lưu ý rằng các bước tuỳ chọn ở đây được lồng vào trong, không phải từ việc thụt đầu dòng, mà từ vị trí đặt dấu ( và ) xung quanh chúng.

- -

Câu lệnh catch bên trong chỉ bắt lỗi từ doSomethingOptional() và doSomethingExtraNice(), sau đó nó sẽ tiếp tục với moreCriticalStuff(). Điều quan trọng là nếu doSomethingCritical() thất bại, lỗi của nó chỉ bị bắt bởi catch cuối cùng (bên ngoài).

- -

Một số sai lầm phổ biến

- -

Dưới đây là một số lỗi phổ biến cần chú ý khi sử dụng chuỗi promise. Một số trong những sai lầm này biểu hiện trong ví dụ sau:

- -
// Một ví dụ có đến 3 sai lầm!
-doSomething().then(function(result) {
-  doSomethingElse(result) // Quên trả về promise từ chuỗi lồng bên trong + lồng nhau không cần thiết
-  .then(newResult => doThirdThing(newResult));
-}).then(() => doFourthThing());
-// Quên kết thúc chuỗi bằng một hàm catch!
-
- -

Sai lầm đầu tiên là không kết nối mọi thứ với nhau đúng cách. Điều này xảy ra khi chúng ta tạo ra một promise mới nhưng quên trả lại. Hậu quả là chuỗi bị hỏng, hay đúng hơn, chúng ta có hai chuỗi độc lập cùng chạy. Có nghĩa là doFourthThing() sẽ không đợi doSomethingElse() hoặc doThirdThing() kết thúc và sẽ chạy song song với chúng, có khả năng ngoài ý muốn. Các chuỗi riêng biệt cũng sẽ xử lý lỗi riêng biệt, dẫn đến khả năng lỗi không được xử lý.

- -

Sai lầm thứ hai là làm lồng nhau không cần thiết, cho phép sai lầm đầu tiên. Lồng nhau cũng giới hạn phạm vi của các trình xử lý lỗi bên trong, điều mà nếu không cố ý thì có thể dẫn đến các lỗi chưa được xử lý. Một biến thể của điều này là​ ​​​​​​promise constructor anti-pattern, kết hợp lồng với việc sử dụng dự phòng của promise constructor để bọc mã đã sử dụng promise.

- -

Sai lầm thứ ba là quên chấm dứt chuỗi với catch. Chuỗi promise không kết thúc bằng catch, khi bị reject sẽ gây ra lỗi "uncaught promise rejection" trong hầu hết các trình duyệt.

- -

Một nguyên tắc tốt là luôn luôn trả lại hoặc chấm dứt chuỗi promise, và ngay khi bạn nhận được một promise mới, hãy trả lại ngay lập tức:

- -
doSomething()
-.then(function(result) {
-  return doSomethingElse(result);
-})
-.then(newResult => doThirdThing(newResult))
-.then(() => doFourthThing())
-.catch(error => console.log(error));
-
- -

Lưu ý rằng () => x được rút gọn từ () => { return x; }.

- -

Bây giờ chúng ta có một chuỗi xác định duy nhất với xử lý lỗi thích hợp.

- -

Sử dụng async/await sẽ khắc phục hầu hết, nếu không muốn nói là tất cả các vấn đề trên đây — với một hạn chế cũng là một lỗi thường gặp với cú pháp này đó là việc quên từ khoá await.

- -

Xem thêm

- - - -

{{PreviousNext("Web/JavaScript/Guide/Details_of_the_Object_Model", "Web/JavaScript/Guide/Iterators_and_Generators")}}

diff --git a/files/vi/web/javascript/guide/working_with_objects/index.html b/files/vi/web/javascript/guide/working_with_objects/index.html deleted file mode 100644 index 6fdc2dba69..0000000000 --- a/files/vi/web/javascript/guide/working_with_objects/index.html +++ /dev/null @@ -1,500 +0,0 @@ ---- -title: Working with objects -slug: Web/JavaScript/Guide/Working_with_Objects -translation_of: Web/JavaScript/Guide/Working_with_Objects ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}
- -

JavaScript được thiết kế trên mô hình đối tượng đơn giản. Một object là một tập hợp các thuộc tính, và một thuộc tính là sự liên kết giữa một cái tên và giá trị. Giá trị của một thuộc tính có thể là một hàm. Ngoài những đối tượng được định nghĩa trước trong trình duyệt, bạn có thể định nghĩa những đối tượng của riêng bạn. Chương này mô tả cách sử dụng những đối tượng, những thuộc tính, những hàm, và phương thức, cũng như cách thức để tạo đối tượng riêng của mình.

- -

Tổng quan về Objects

- -

Objects trong JavaScript, cũng tương tự như những ngôn ngữ khác, có thể so sánh như đối tượng trong đời thường. Khái niệm của objects trong JavaScript có thể được hiểu như những đối tượng thực tế trong đời thực.

- -

Trong JavaScript, một object là một thực thể độc lập, với thuộc tính và kiểu. Lấy cái tách làm ví dụ. Cái tách là một object có những thuộc tính của riêng nó. Một cái tách có màu sắc, thiết kế, trọng lượng, chất liệu tạo ra nó, vân vân... Tương tự như vậy, JavaScript objects có thể có những thuộc tính định nghĩa nên đặc tính của nó.

- -

Objects and thuộc tính

- -

Một JavaScript object có những thuộc tính liên kết với nó. Một thuộc tính của một object có thể được giải thích như là một biến mà được gắn vào object đó. Những thuộc tính của object cơ bản cũng là những biến JavaScript bình thường, chỉ đặc biệt là được gắn lên object. Thuộc tính của object định nghĩa đặc tính của object. Chúng ta truy xuất thuộc tính của object với ký hiệu ".":

- -
objectName.propertyName
-
- -

Giống như những biến JavaScript, cả tên của object (có thể được xem như là 1 biến thông thường) và tên thuộc tính thì cũng phân biệt hoa thường. Bạn có thể định nghĩa một thuộc tính bằng cách gán giá trị cho nó. Ví dụ hãy tạo đối tượng myCar và gắn thuộc tính cho nó như make, model, and year như sau:

- -
var myCar = new Object();
-myCar.make = 'Ford';
-myCar.model = 'Mustang';
-myCar.year = 1969;
-
- -

Những thuộc tính không được gán giá trị sẽ có giá trị {{jsxref("undefined")}} (lưu ý nó là không {{jsxref("null")}}).

- -
myCar.color; // undefined
- -

Thuộc tính của JavaScript object có thể được truy xuất hoặc thiết lập bằng cách dùng dấu ngoặc vuông (xem property accessors để tham khảo chi tiết). Objects thỉnh thoảng cũng được gọi là mảng liên kết, vì mỗi thuộc tính được liên kết với một giá trị kiểu chuỗi mà có thể được dùng để truy xuất thuộc tính đó. Ví dụ bạn có thể truy xuất những thuộc tính của myCar object như sau:

- -
myCar['make'] = 'Ford';
-myCar['model'] = 'Mustang';
-myCar['year'] = 1969;
-
- -

Tên thuộc tính của một object có thế là chuỗi ký tự hợp lệ bất kỳ, hoặc bất kỳ thứ gì có thể chuyển đổi được thành chuỗi, bao gồm cả chuỗi rỗng. Tuy nhiên, bất kỳ tên thuộc tính nào mà không phải là 1 định danh hợp lệ trong JavaScript (ví dụ, một thuộc tính mà tên có khoảng trắng hoặc gạch ngang, hoặc bắt đầu bằng số) chỉ có thể truy xuất bằng cách dùng dấu ngoặc vuông []. Ký pháp này cũng rất hữu dụng khi tên thuộc tính được xác định động (khi tên thuộc tính chỉ được xác định lúc thực thi). Như trong ví dụ sau:

- -
// Khởi tạo 4 biến và gán giá trị cho chúng trên cùng một dòng lệnh
-// phân cách bởi dấu ","
-var myObj = new Object(),
-    str = 'myString',
-    rand = Math.random(),
-    obj = new Object();
-
-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);
-
- -

Chú ý tất cả biểu thức được làm khóa trong dấu ngoặc vuông đều được chuyển đổi thành kiểu chuỗi, bởi vì objects trong JavaScript chỉ chấp nhận khóa là kiểu chuỗi. Ví dụ trong đoạn mã trên khi khóa obj được thêm vào myObj, JavaScript sẻ gọi phương thức obj.toString(), và lấy kết quả đó làm khóa.

- -

Bạn cũng có thể truy xuất thuộc tính bằng cách dùng giá trị chuỗi mà nó được lưu trong một biến:

- -
var propertyName = 'make';
-myCar[propertyName] = 'Ford';
-
-propertyName = 'model';
-myCar[propertyName] = 'Mustang';
-
- -

Bạn có thể sử dụng dấu ngoặc vuông với for...in để duyệt qua tất cả thuộc tính có thể đếm của object. Để minh họa cách nó hoạt động, hãy xem xét hàm sau đây, nó sẽ hiển thị những thuộc tính của đối tượng dựa vào 2 đối số gồm đối tượng (obj) và tên (objName) của đối tượng truyền vào cho hàm:

- -
function showProps(obj, objName) {
-  var result = '';
-  for (var i in obj) {
-    // obj.hasOwnProperty() is used to filter out properties from the object's prototype chain
-    if (obj.hasOwnProperty(i)) {
-      result += objName + '.' + i + ' = ' + obj[i] + '\n';
-    }
-  }
-  return result;
-}
-
- -

Như vậy, khi ta gọi showProps(myCar, "myCar") thì kết quả được trả về như sau:

- -
myCar.make = Ford
-myCar.model = Mustang
-myCar.year = 1969
- -

Liệt kê những thuộc tính của một object

- -

Bắt đầu từ ECMAScript 5, có 3 cách để liệt kê/duyệt danh sách thuộc tính của object:

- -
    -
  • Câu lệnh lặp  for...in
    - Cách này duyệt qua tất cả thuộc tính có thể duyệt của một object và chuỗi prototype của nó
  • -
  • {{jsxref("Object.keys", "Object.keys(o)")}}
    - Phương thức này trả về một mảng tất cả tên những thuộc tính có thể liệt kê mà gắn trực tiếp trên object o (không phải từ chuỗi prototype)
  • -
  • {{jsxref("Object.getOwnPropertyNames", "Object.getOwnPropertyNames(o)")}}
    - Phương thức này trả về một mảng tất cả tên những thuộc tính (có thể liệt kê hoặc không) mà gắn trực tiếp trên object o (không phải từ chuỗi prototype)
  • -
- -

Trước ECMAScript 5, không có cách thức có sẵn để liệt kê tất cả thuộc tính của một object. Tuy nhiên, chúng ta có thực hiện việc  đó bằng hàm sau:

- -
function listAllProperties(o) {
-	var objectToInspect;
-	var result = [];
-
-	for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)) {
-      result = result.concat(Object.getOwnPropertyNames(objectToInspect));
-	}
-
-	return result;
-}
-
- -

Cách này rất hữu ích khi chúng ta muốn hiển thị những thuộc tính ẩn (những thuộc tính trong chuỗi prototype mà không thể truy xuất thông qua object, bởi vì một thuộc tính khác có cùng tên ở lớp trước của chuỗi prototype đã đè lên nó). Việc liệt kê những thuộc tính có thể truy xuất chỉ có thể dễ dàng hoàn thành bằng cách xóa bỏ trùng lặp trong mảng.

- -

Tạo những object mới

- -

JavaScript có một số object được định nghĩa sẵn. Ngoài ra, bạn có thể tạo định nghĩa những object mới. Bạn có thể tạo một object sử dụng bộ khởi tạo object (object initializer). Cách khác, bạn có thể tạo hàm dựng và rồi khởi tạo đối tượng bằng cách gọi hàm đó với toán tử new đặt trước.

- -

Sử dụng bộ khởi tạo object

- -

Ngoài việc khởi tạo object bằng cách dùng hàm dựng, bạn có thể tạo object bằng cách sử dụng bộ khởi tạo (object initializer). Sử dụng bộ khởi tạo thỉnh thoảng cũng được hiểu là cách khởi tạo bằng cách dùng literal. "Bộ khởi tạo" ("Object initializer") thì đồng nhất với thuật ngữ được sử dụng trong C++.

- -

Cú pháp cho việc tạo một object bằng bộ khởi tạo la:

- -
var obj = { property_1:   value_1,   // property_# may be an identifier...
-            2:            value_2,   // or a number...
-            // ...,
-            'property n': value_n }; // or a string
-
- -

Trong đó obj là tên của object mới, mỗi property_i là một định danh (hoặc là một tên, một số, hoặc một chuỗi dạng literal), và mỗi value_i là một biểu thức mà giá trị được gán cho property_i . obj và phép gán là không bắt buộc; nếu bạn không cần tham chiếu đến object đó ở chổ khác, bạn không cần assign nó cho một biến. (lưu ý bạn có thể cần bao object literal lại bằng dấu ngoặc nếu nó xuất hiện ở chổ cần như là một câu lệnh, làm như vậy để tránh gây nhầm lẩn với câu lệnh khối.)

- -

Bộ khởi tạo object là những biểu thức, và mỗi bộ khởi tạo object sẽ tạo ra object mỗi khi biểu thức đó được tính toán. Bộ khởi tạo object tạo ra những đối tượng riêng biệt và chúng không bằng nhau khi so sánh bằng ==. Những đối tượng được tạo ra bằng cách new Object() cũng như những đối tượng được tạo ra bằng object literal đều là thực thể (instance) của Object.

- -

Câu lệnh sau tạo một đối tượng và gán nó cho biến x khi và chỉ khi biểu thức cond là true:

- -
if (cond) var x = {greeting: 'hi there'};
-
- -

Đoạn mã sau tạo đối tượng myHonda với ba thuộc tính. Lưu ý thuộc tính engine cũng là một object và nó có những thuộc tính riêng của nó.

- -
var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}};
-
- -

Bạn cũng có thể dùng bộ khởi tạo object để tạo mảng. Tham khảo array literals.

- -

Sử dụng hàm dựng

- -

Ngoài ra, bạn có thể tạo một object với hai bước sau đây:

- -
    -
  1. Định nghĩa kiểu cho object bằng cách khai báo một hàm dựng. Bạn nên đặt tên hàm với chữ hoa cho ký tự đầu tiên.
  2. -
  3. Tạo một thực thể của đối tượng với toán tử new.
  4. -
- -

Để định nghĩa một kiểu dữ liệu object, tạo một hàm cho kiểu dữ liệu đó rồi chỉ định tên, những thuộc tính và phương thưc. Ví dụ, giả sử bạn muốn tạo một kiểu dữ liệu cho cars. Bạn đặt tên cho kiểu dữ liệu đó là Car, và bạn muốn nó có những thuộc tính như make, model, và year. Để làm được điểu này, bạn sẽ viết hàm sau:

- -
function Car(make, model, year) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-}
-
- -

Lưu ý cách sử dụng this để gán trị giá trị cho những thuộc tính của object dựa vào giá trị được truyền vào cho hàm.

- -

Bây giờ bạn có thể tạo một object tên mycar như sau:

- -
var mycar = new Car('Eagle', 'Talon TSi', 1993);
-
- -

Câu lệnh này tạo mycar gán những giá trị cụ thể cho những thuộc tính của nó. Giá trị của mycar.make là chuỗi "Eagle", mycar.year là số 1993, và tiếp tuc như thế.

- -

Bạn có thể tạo bao nhiêu Car object đều được bằng toán tử new. Như ví dụ sau:

- -
var kenscar = new Car('Nissan', '300ZX', 1992);
-var vpgscar = new Car('Mazda', 'Miata', 1990);
-
- -

Một object có thể có một thuộc tính mà giá trị là một object khác. Ví dụ như, giả sử bạn định nghĩa một object tên person như sau:

- -
function Person(name, age, sex) {
-  this.name = name;
-  this.age = age;
-  this.sex = sex;
-}
-
- -

và sau đó khởi tạo hai object person mới như sau:

- -
var rand = new Person('Rand McKinnon', 33, 'M');
-var ken = new Person('Ken Jones', 39, 'M');
-
- -

Và rồi, bạn có thể viết lại định nghĩa của Car để thêm thuộc tính owner mà nhận giá trị là một đối tượng kiểu person, như sau:

- -
function Car(make, model, year, owner) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-  this.owner = owner;
-}
-
- -

Để khởi tạo object mới, bạn viết những câu lệnh sau:

- -
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
-var car2 = new Car('Nissan', '300ZX', 1992, ken);
-
- -

Lưu ý rằng thay vì truyền vào một hằng chuỗi hoặc giá trị số khi tạo những object mới, câu lệnh trên truyền vào những đối tượng randken như là đối số cho owner. Sau đó nếu bạn muốn tìm tên của owner của car2, bạn có thể truy xuất như sau:

- -
car2.owner.name
-
- -

Lưu ý rằng bạn có thể luôn luôn thêm một thuộc tính mới vào những object đã được tạo ra. Như ví dụ câu lệnh sau:

- -
car1.color = 'black';
-
- -

thêm vào thuộc tính color cho car1, và gán giá trị cho nó là "black". Tuy nhiên, việc này không ảnh hưởng lên những object khác. Để thêm thuộc tính cho tất cả object của cùng một kiểu, bạn phải thêm thuộc tính đó khi định nghĩa kiểu đối tượng Car.
-  

- -

Sử dụng Object.create

- -

Những object có thể được tạo ra bằng phương thức {{jsxref("Object.create()")}}. Phương thức này có thể rất hữu ích, bởi vì nó cho phép bạn chọn prototype cho object bạn muốn tạo ra, mà không cần phải định nghĩa hàm dựng.

- -
// 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
- -

Sự Kế  Thừa

- -

Tất cả object trong JavaScript kế thừa từ ít nhất một object khác. Object mà được kế thừa từ nó thì được xem như là prototype, và những thuộc tính được kế thừa có thể được tìm thấy trong đối tượng prototype của hàm dựng. Xem thêm Inheritance and the prototype chain

- -

Đánh chỉ mục thuộc tính object

- -

Bạn có thể tham chiếu tới một object hoặc là bằng tên thuộc tính hoặc là bằng chỉ mục. Nếu bạn định nghĩa thuộc tính bằng tên, thì sau đó bạn phải dùng tên để truy xuất thuộc tính đó, còn nếu bạn định nghĩa thuộc tính bằng chỉ mục (một số), bạn phải dùng chỉ mục để truy xuất.

- -

Giới hạn này áp dụng khi bạn tạo một object và thuộc tính của nó với hàm dựng (như chúng  ta đã làm với kiểu Car) và khi bạn định nghĩa những thuộc tính riêng lẻ một cách tường minh (ví dụ như , myCar.color = "red"). Nếu bạn định nghĩa thuộc tính với một chỉ mục, chẳng hạn như myCar[5] = "25 mpg", thì bạn phải tham chiếu đến thuộc tính đó với chỉ mục myCar[5].

- -

Ngoại trừ nếu đó là object giống mảng (array-like), ví dụ như những object tạo ra từ HTML như forms object. Bạn có thể tham chiếu đến những object đó bằng cách hoặc là dùng số (dựa vào thứ tự nó xuất hiện trong document) hoặc là tên (nếu được định nghĩa). Ví dụ, nếu thẻ <FORM> thứ hai trong document có thuộc tính NAME là "myForm", bạn có thể tham chiếu đến form bằng cách document.forms[1] hoặc document.forms["myForm"] hoặc document.forms.myForm.

- -

Định nghĩa những thuộc tính cho kiểu dữ liệu object

- -

Bạn có thể thêm một thuộc tính cho một object đã định nghĩa trước đó bằng cách sử dụng thuộc tính prototype. Điều này định nghĩa một thuộc tính mà sẽ được chia sẻ bởi tất các các thuộc tính của cùng kiểu dữ liệu đó, không riêng cho một thực thể nào của kiểu đó. Đoạn mã sau sẽ thêm thuộc tính color cho tất cả các object của kiểu Car, và rồi gán giá trị cho thuộc tính color của object car1.

- -
Car.prototype.color = null;
-car1.color = 'black';
-
- -

Xem thêm prototype property của object Function trong JavaScript reference.

- -

Định nghĩa phương thức

- -

Một phương thức là một hàm liên kết với một object, hoặc, có thể nói phương thức là một thuộc tính của object có giá trị là một hàm. Phương thức được định nghĩa giống như cách định nghĩa hàm, ngoài trừ việc chúng phải được gán như là thuộc tính của một object. Xem thêm method definitions. Ví dụ:

- -
objectName.methodname = functionName;
-
-var myObj = {
-  myMethod: function(params) {
-    // ...do something
-  }
-
-  // OR THIS WORKS TOO
-
-  myOtherMethod(params) {
-    // ...do something else
-  }
-};
-
- -

objectName là một object đã được tạo trước đó, methodname là tên mà bạn đang gán cho phương thức, và functionName là tên của hàm.

- -

Sau đó bạn có thể gọi hàm trong ngữ cảnh của object như sau:

- -
object.methodname(params);
-
- -

Bạn có thể định nghĩa phương thức của một kiểu object bằng cách thêm định nghĩa phương thức vào trong hàm dựng. Bạn có thể định nghĩa một hàm mà sẽ định dạng và hiển thị những thuộc tính của những đối tượng kiểu Car đã được định nghĩa trước, ví dụ:

- -
function displayCar() {
-  var result = 'A Beautiful ' + this.year + ' ' + this.make
-    + ' ' + this.model;
-  pretty_print(result);
-}
-
- -

trong đó pretty_print được giả định là một hàm đã được định nghĩa trước để hiển thị đường kẻ ngang và chuỗi kết quả. Lưu ý tham chiếu this đang trỏ đến đối tượng mà phương thức đang gắn trên đó.

- -

Bạn có thể tạo hàm này thành phương thức của lớp Car bằng câu lệnh sau:

- -
this.displayCar = displayCar;
-
- -

khi định nghĩa kiểu object Car. Cài đặt đầy đủ của Car bây giờ sẽ là:

- -
function Car(make, model, year, owner) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-  this.owner = owner;
-  this.displayCar = displayCar;
-}
-
- -

Rồi sau đó bạn có thể gọi phương thức displayCar trên mỗi đối tượng như sau:

- -
car1.displayCar();
-car2.displayCar();
-
- -

Sử dụng this để tham chiếu đối tượng

- -

JavaScript có từ khóa đặc biệt, this, mà bạn có thể sử dụng bên trong phương thức để tham chiếu đến object hiện tại. Ví dụ, giả sử bạn có một hàm tên là validate để kiểm tra giá trị của thuộc tính của một object là giá trị cao hay thấp:

- -
function validate(obj, lowval, hival) {
-  if ((obj.value < lowval) || (obj.value > hival)) {
-    alert('Invalid Value!');
-  }
-}
-
- -

Sau đó, bên trong hàm handler của event onchange của mỗi phần tử của form bạn có thể gọi hàm validate như ví dụ sau:

- -
<input type="text" name="age" size="3"
-  onChange="validate(this, 18, 99)">
-
- -

Nói chúng, this trỏ đến object đang gọi bên trong hàm.

- -

Khi kết hợp với thuộc tính form, this có thể tham chiếu đến form cha của object hiện tại. Trong ví dụ sau, form myForm chứa đối tượng Text và một nút. Khi user nhấp lên cái nút, giá trị của đối tượng Text được gán bằng tên của form. Hàm thực thi của sự kiện onclick của cái nút sử dụng this.form để tham chiếu đến form cha, myForm.

- -
<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>
- -

Định nghĩa getters và setters

- -

Một getter là một phương thức mà nhận giá trị của một thuộc tính cụ thể. Một setter là một phương thức thiết lập giá trị cho một thuộc tính cụ thể. Bạn có thể định nghĩa getters và setters cho bất kỳ object nào có thể là do runtime tạo sẵn hoặc do người dùng định nghĩa. Chúng ta dùng cú pháp của object literal để tạo getter và setter.

- -

Đoạn mã sau minh họa cách định nghĩa và thao tác trên getter và setter.

- -
var o = {
-  a: 7,
-  get b() {
-    return this.a + 1;
-  },
-  set c(x) {
-    this.a = x / 2;
-  }
-};
-
-console.log(o.a); // 7
-console.log(o.b); // 8
-o.c = 50;
-console.log(o.a); // 25
-
- -

Những thuộc tính của object o là:

- -
    -
  • o.a — một số
  • -
  • o.b — một getter trả về kết quả của o.a cộng 1
  • -
  • o.c — một setter thiết lập giá trị cho o.a với giá trị là một nửa giá trị của đối số được truyền vào
  • -
- -

Lưu ý ta dùng hàm để định nghĩa getter và setter, nhưng chúng ta truy xuất nó như một thuộc tính. Để định nghĩa một getter hoặc setter ta dùng cú pháp "[gs]et property()", Hoặc chúng ta một cách khác để định nghĩa getter hoặc setter là dùng Object.defineProperty  (hoặc dùng cách cũ với Object.prototype.__defineGetter__).

- -

Đoạn mã sau minh họa cách dùng getter và setter mở rộng prototype của {{jsxref("Date")}} để thêm thuộc tính year cho tất cả thực thể được tạo ra từ lớp Date. Và dùng phương thức getFullYear and setFullYear để hỗ trợ getter và setter year.

- -

Những câu lệnh sau định nghĩa getter và setter cho thuộc tính year:
-  

- -
var d = Date.prototype;
-Object.defineProperty(d, 'year', {
-  get: function() { return this.getFullYear(); },
-  set: function(y) { this.setFullYear(y); }
-});
-
- -

Những câu lệnh sau sử dụng getter và setter trong đối tượng Date:
-  

- -
var now = new Date();
-console.log(now.year); // 2000
-now.year = 2001; // 987617605170
-console.log(now);
-// Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001
-
- -

Điều cần ghi nhớ là, getter vad setter có thể:

- -
    -
  • hoặc được định nghĩa bằng cách sứ dụng bộ khởi tạo object
  • -
  • hoặc được thêm vào sau đó cho bất kỳ object nào tại bất kỳ thời điểm nào bằng cách sử dụng phương thức tạo getter & setter (Object.defineProperty).
  • -
- -

Khi tạo getters và settes sử dụng bộ khởi tạo object điều bạn cần làm là đặt từ khóa  get trước tên phương thức getter và từ khóa set trước phương thức setter. Tất nhiên là phương thức getter không cần bất kỳ tham số nào, còn phương thức setter cần đúng một tham số. Như ví dụ sau:

- -
var o = {
-  a: 7,
-  get b() { return this.a + 1; },
-  set c(x) { this.a = x / 2; }
-};
-
- -

Getters and setters có thể được thêm vào một object bất kỳ khi nào sau khi được tạo bằng cách dùng phương thức Object.defineProperties. Tham số đầu tiên của phương thức này là object mà bạn muốn định nghĩa getter và setter. Tham số thứ hai là một object mà tên của thuộc tính là tên của getter và setter, giá trị của thuộc tính là object định nghĩa hàm getter và setter. Sau đây là ví dụ minh họa cách định nghĩa getter và 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
-
- -

Việc lựa chọn cách nào để định nghĩa getter và setter tùy thuộc vào phong cách lập trình và công việc cụ thể. Nếu bạn luôn dùng bộ khởi tạo object khi định nghĩa một prototype thì bạn nên chọn cách thứ nhất. Cách này đơn giản và tự nhiên. Tuy nhiên, nếu bạn cần thêm getters và setters sau đó — bởi vì bạn không viết prototype hoặc object cụ thể — bạn phải sử dụng cách thứ hai. Cách thứ hai thể hiện tính chất "động" tự nhiên của JavaScript — nhưng nó làm cho code khó đọc và khó hiểu.

- -

Việc xóa bỏ thuộc tính

- -

Bạn có thể xóa bỏ một thuộc tính không kế thừa bằng toán tử  delete. Câu lệnh sau chỉ bạn cách để xóa bỏ một thuộc tính.

- -
// Creates a new object, myobj, with two properties, a and b.
-var myobj = new Object;
-myobj.a = 5;
-myobj.b = 12;
-
-// Removes the a property, leaving myobj with only the b property.
-delete myobj.a;
-console.log ('a' in myobj); // yields "false"
-
- -

Bạn cũng có thể dùng delete để xóa bỏ biến toàn cục nếu bạn không dùng từ khóa var khi định nghĩa biến.

- -
g = 17;
-delete g;
-
- -

So sánh objects

- -

Trong JavaScript những object là kiểu tham chiếu. Hai đối tượng tách biệt không bao giờ bằng nhau, thậm chí nếu chúng có cùng những thuộc tính. Chỉ khi nó so sánh với chính nó thì kết quả mới là true.

- -
// Two variables, two distinct objects with the same properties
-var fruit = {name: 'apple'};
-var fruitbear = {name: 'apple'};
-
-fruit == fruitbear; // return false
-fruit === fruitbear; // return false
- -
// Two variables, a single object
-var fruit = {name: 'apple'};
-var fruitbear = fruit;  // assign fruit object reference to fruitbear
-
-// here fruit and fruitbear are pointing to same object
-fruit == fruitbear; // return true
-fruit === fruitbear; // return true
-
- -
fruit.name = 'grape';
-console.log(fruitbear);    // yields { name: "grape" } instead of { name: "apple" }
-
- -

Chi tiết về toán tử so sánh, xem thêm tại Comparison operators.

- -

See also

- - - -

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

diff --git a/files/vi/web/javascript/index.html b/files/vi/web/javascript/index.html deleted file mode 100644 index bc5593df24..0000000000 --- a/files/vi/web/javascript/index.html +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: JavaScript -slug: Web/JavaScript -tags: - - Học javascript - - JavaScript - - Landing -translation_of: Web/JavaScript ---- -
{{JsSidebar()}}
- -
-

JavaScript® (viết tắt là JS) là một ngôn ngữ lập trình gọn nhẹ, được thông dịch hoặc biên dịch trong thời gian với đặc tính hàm đối tượng (first-class functions). JavaScript được biết tới như một ngôn ngữ lập trình dành cho các trang Web - tức là được thực thi trên trình duyệt, rất nhiều môi trường phi trình duyệt khác cũng sử dụng ngôn ngữ này, như là Node.js hay Apache CouchDB và Adobe Acrobat. Ngôn ngữ này có đặc điểm là một ngôn ngữ lập trình dựa trên nguyên mẫu (prototype-based), đa hình (multi-paradigm), đơn luồng nên khá linh động và hỗ trợ được cả các phong cách lập trình hướng đối tượng, lập trình mệnh lệnh và lập trình hàm. Bạn có thể đọc thêm về JavaScript ở đây.

-
- -

ECMAScript là tiêu chuẩn chung cho JavaScript và tính tới thời điểm năm 2012 thì tất cả các trình duyện hiện đại đều đã hỗ trợ đầy đủ các tiêu chuẩn ECMAScript 5.1, còn một số trình duyệt cũ thì cũng hỗ trợ ít nhất ở phiên bản ECMAScript 3. Vào ngày 17 tháng 06 năm 2015, phiên bản chính thức thứ 6 của ECMAScript đã được phát hành với tên gọi chính thức là ECMAScript 2015, nhưng nó cũng hay được gọi với tên là ECMAScript 6 hoặc ES6.

- -

Phần này dành riêng cho việc hướng dẫn về ngôn ngữ JavaScript chứ không mô tả cụ thể cho từng môi trường như Web hay cho các môi trường máy chủ. Về các API dành riêng cho Web, bạn có thể xem ở phần Web APIs và DOM.

- -

Lưu ý rằng JavaScript khác với ngôn ngữ lập trình Java nên đừng nhầm lẫn với Java. Cả "Java" và "JavaScript" là các nhãn hiệu được đăng kí bởi Oracle tại Mĩ và các quốc gia khác. Tuy nhiên, hai ngôn ngữ lập trình này có cú pháp, ngữ nghĩa và cách dùng rất khác nhau.

- -

Bạn đang muốn trờ thành một người phát triển website (front-end web developer)?

- -

Chúng tôi đã tổng hợp một khóa học bao gồm tất cả thông tin cần thiết mà bạn cần để hướng tới mục tiêu của mình.

- -

Cùng bắt đầu

- -
-
-

Hướng dẫn

- -

Học cách lập trình bằng JavaScript.

- -

Mở đầu

- -
-
Dẫn nhập về JavaScript
-
Bạn chưa biết về JavaScript? Tốt, phần này sẽ dẫn bạn đi một vòng qua ngôn ngữ này.
-
Tổng quan về các công nghệ JavaScript
-
Giới thiệu về hiện trạng của JavaScript ở các trình duyệt Web.
-
Nhập môn hướng đối tượng với JavaScript
-
Giới thiệu các khái niệm về lập trình hướng đối tượng trong JavaScript.
-
- -

Căn bản

- -
-
Giới thiệu lại về JavaScript
-
Một bản tổng quan dành cho người đã biết về JavaScript.
-
- -
-
Cấu trúc dữ liệu trong JavaScript
-
Tổng quan về các cấu trúc dữ liệu trong JavaScript.
-
Các phép so sánh bằng và cách sử dụng
-
JavaScript cung cấp 3 kiểu so sánh giá trị khác nhau là: so sánh bằng chặt chẽ với === và so sánh bằng lỏng lẻo với ==.
-
- -

Nâng cao

- -
-
Kế thừa và chuỗi nguyên mẫu
-
Giải thích về sự hiểu lầm và đánh giá không chuẩn về kế thừa dựa trên nguyên mẫu (prototype-based inheritance)
-
Chế độ nghiêm ngặt (strict mode)
-
Một biến thể bị giới hạn của JavaScript.
-
Các kiểu dữ liệu mảng của JavaScript
-
Các mảng của JavaScript cung cấp cơ chế truy cậ dữ liệu nhị phân gốc (raw binary data).
-
Quản lý bộ nhớ
-
Về vòng đời bộ nhớ và bộ dọn rác trong JavaScript.
-
-
- -
-

Tài liệu

- -

Xem bộ tài liệu tham chiếu JS đầy đủ.

- -
-
Các đối tượng tiêu chuẩn
-
Hướng dẫn về một số đối tượng chuẩn được xây dựng sẵn như {{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")}} ...
-
Các biểu thức và toán tử
-
Học thêm về các xử lý của các toán tử trong JavaScript như {{jsxref("Operators/instanceof", "instanceof")}}, {{jsxref("Operators/typeof", "typeof")}}, {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}} ...
-
Các câu lệnh và khai báo
-
Học về các câu lệnh và cách khai báo cũng như các từ khóa trong JavaScirpt như {{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")}} ...
-
Hàm
-
Học cách làm việc với các hàm trong JS để phát triển các ứng dụng của bạn.
-
- -

Công cụ & tài nguyên

- -

Các công cụ hữu dụng để viết mã và gỡ lỗi với JavaScript.

- -
-
Các công cụ phát triển của Firefox
-
Scratchpad, Web Console, JavaScript Profiler, Debugger...
-
Firebug
-
Chỉnh sửa, gỡ lỗi, và theo dõi các mã CSS, HTML, và JavaScript trực tiếp với bất kì trang web nào.
-
JavaScript Shells
-
A JavaScript shell cho phép bạn kiểm tra nhanh chóng các đoạn mã JavaScript.
-
TogetherJS
-
-

Hợp tác để giải quyết các vấn đề dễ hơn.

-
-
Stack Overflow
-
Các câu hỏi được đánh thẻ "JavaScript" trên hệ thống giải đáp Stack Overflow.
-
Các phiên bản JavaScript và các chú thích phát hành
-
Xem thêm về lịch sử của JavaScript cùng với các chú thích của nó.
-
-
-
diff --git a/files/vi/web/javascript/memory_management/index.html b/files/vi/web/javascript/memory_management/index.html deleted file mode 100644 index 3c3da3771d..0000000000 --- a/files/vi/web/javascript/memory_management/index.html +++ /dev/null @@ -1,183 +0,0 @@ ---- -title: Memory Management -slug: Web/JavaScript/Memory_Management -translation_of: Web/JavaScript/Memory_Management ---- -
{{JsSidebar("Advanced")}}
- -

Giới thiệu

- -

Ngôn ngữ bậc thấp như C, có các nguyên hàm quản lý bộ nhớ theo cách thủ công như làmalloc()free(). Trái lại, JavaScript tự động cấp phát bộ nhớ khi object được khởi tạo và giải phóng khi object đó không còn được dùng nữa (bộ thu thập rác). Sự tự động này có thể gây ra bối rối: khiến cho nhà phát triển tưởng rằng họ không cần lo về vấn đề quản lý bộ nhớ.

- -

Vòng đời bộ nhớ

- -

Với mọi ngôn ngữ lập trình, vòng đời bộ nhớ khá giống nhau:

- -
    -
  1. Cấp phát bộ nhớ mà bạn cần
  2. -
  3. Sử dụng bộ nhớ đã cấp phát (đọc, ghi)
  4. -
  5. Giải phóng bộ nhớ đã cấp phát khi chúng không còn được sử dụng
  6. -
- -

Phần thứ hai tường minh trên mọi ngôn ngữ. Phần đầu và cuối tường minh trên họ ngôn ngữ bậc thấp nhưng ngầm trên ngôn ngữ bậc cao như JavaScript.

- -

Cấp phát trong JavaScript

- -

Khởi tạo giá trị

- -

Để không khiến lập trình viên phải bận tâm với việc cấp phát, JavaScript thực hiện điều đó khi khởi tạo giá trị.

- -
var n = 123; // cấp phát bộ nhớ cho một số
-var s = 'azerty'; // cấp phát bộ nhớ cho một xâu ký tự
-
-var o = {
-  a: 1,
-  b: null
-}; // cấp phát bộ nhớ cho object và giá trị bên trong
-
-// (giống như object) cấp phát bộ nhớ cho mảng
-// và giá trị bên trong
-var a = [1, null, 'abra'];
-
-function f(a) {
-  return a + 2;
-} // cấp phát cho hàm (là object khả gọi)
-
-// biểu thức function cũng được cấp phát như object
-someElement.addEventListener('click', function() {
-  someElement.style.backgroundColor = 'blue';
-}, false);
-
- -

Cấp phát thông qua lời gọi hàm

- -

Kết quả của vài lời gọi hàm là việc cấp phát cho object.

- -
var d = new Date(); // cấp phát cho Date object
-
-var e = document.createElement('div'); // cấp phát cho phần tử DOM
- -

Một số phương thức cấp phát giá trị hoặc object mới:

- -
var s = 'azerty';
-var s2 = s.substr(0, 3); // s2 is a new string
-// Vì xâu ký tự là giá trị không thể biến đổi
-// JavaScript có thể sẽ không cấp phát thêm bộ nhớ
-// mà chỉ lưu trữ đoạn [0, 3].
-
-var a = ['ouais ouais', 'nan nan'];
-var a2 = ['generation', 'nan nan'];
-var a3 = a.concat(a2);
-// mảng mới với 4 phần tử
-// là kết quả của phép nối các phần tử của a và a2
-
- -

Sử dụng giá trị

- -

Sử dụng giá trị về cơ bản nghĩa là đọc và ghi trên bộ nhớ đã cấp phát. Việc này có thể được thực hiện thông qua đọc hoặc ghi giá trị của một biến hoặc một thuộc tính của object hay thậm chí là truyền tham số vào một hàm.

- -

Giải phóng khi bộ nhớ không còn cần tới

- -

Hầu hết các vấn đề về quản lý bộ nhớ đều xảy ra ở bước này. Nhiệm vụ khó nhất lúc này là tìm "bộ nhớ đã cấp phát không còn cần tới nữa". Thường lúc này nhà phát triển sẽ phải xác định phần bộ nhớ nào trong chương trình không còn cần tới nữa và giải phóng chúng.

- -

Ngôn ngữ bậc cao nhúng phần mềm có tên là "bộ thu thập rác" có nhiệm vụ dò theo việc cấp phát và sử dụng bộ nhớ để tìm ra "bộ nhớ đã cấp phát không còn cần tới nữa", nó sẽ tự động giải phóng phần bộ nhớ đó. Công cuộc này chỉ gần đúng bởi vì vấn đề chung để biết được liệu phần bộ nhớ đó có cần tới hay không là không thể quyết định (không thể giải quyết bằng thuật toán).

- -

Bộ thu thập rác

- -

Như đã nhấn mạnh ở trên, vấn đề chung để tự động tìm ra phần bộ nhớ "không còn cần tới nữa" là không thể quyết định được. Vì vậy, bộ thu thập rác sử dụng tập hạn chế để giải quyết vấn đề chung đó. Phần này sẽ giải thích khái niệm cần thiết để hiểu được các thuật toán thu thập rác và hạn chế của chúng.

- -

Tham chiếu

- -

Thuật toán thu thập rác chủ yếu phụ thuộc vào khái niệm tham chiếu. Trong ngữ cảnh quản lý bộ nhớ, object này được gọi là tham chiếu tới object khác nếu cái trước truy xuất tới cái sau (cả ngầm lẫn tường minh). Chẳng hạn, một JavaScript object tham chiếu tới prototype (tham chiếu ngầm) và tới giá trị thuộc tính của nó (tham chiếu tường minh).

- -

Trong ngữ cảnh này, khái niệm "object" được hiểu rộng ra hơn với định nghĩa object của JavaScript và còn bao gồm phạm vi hàm (hoặc phạm vi lexical toàn cục).

- -

Đếm tham chiếu

- -

Đây là thuật toán thu thập rác thô sơ nhất. Thuật toán rút gọn định nghĩa từ "một object không cần tới nữa" thành "một object không có tham chiếu nào tới nó". Một object được coi như là khả thu nếu không có tham chiếu nào trỏ tới nó.

- -

Ví dụ

- -
var o = {
-  a: {
-    b: 2
-  }
-};
-// 2 object được khởi tạo. object này tham chiếu tới object kia như là thuộc tính của nó.
-// The other is referenced by virtue of being assigned to the 'o' variable.
-// Obviously, none can be garbage-collected
-
-
-var o2 = o; // the 'o2' variable is the second thing that
-            // has a reference to the object
-o = 1;      // now, the object that was originally in 'o' has a unique reference
-            // embodied by the 'o2' variable
-
-var oa = o2.a; // reference to 'a' property of the object.
-               // This object now has 2 references: one as a property,
-               // the other as the 'oa' variable
-
-o2 = 'yo'; // The object that was originally in 'o' has now zero
-           // references to it. It can be garbage-collected.
-           // However its 'a' property is still referenced by
-           // the 'oa' variable, so it cannot be freed
-
-oa = null; // The 'a' property of the object originally in o
-           // has zero references to it. It can be garbage collected.
-
- -

Hạn chế: vòng

- -

Phát sinh hạn chế khi xét tới vòng. Trong ví dụ sau, hai object được khởi tạo và tham chiếu tới nhau, tạo ra vòng. Chúng sẽ không còn được dùng tới nữa sau lời gọi hàm, nên chúng sẽ trở thành vô dụng và khả thu. Tuy nhiên, thuật toán đếm tham chiếu vẫn xét là hai object tham chiếu lần lượt tới nhau, nên cả hai bất khả thu.

- -
function f() {
-  var o = {};
-  var o2 = {};
-  o.a = o2; // o tham chiếu tới o2
-  o2.a = o; // o2 tham chiếu tới o
-
-  return 'azerty';
-}
-
-f();
-
- -

Ví dụ thực-tiễn

- -

Internet Explorer 6 và 7 đều dùng thuật toán đếm tham chiếu cho DOM object. Vòng là lỗi thường gặp mà có thể gây ra rò rỉ bộ nhớ:

- -
var div;
-window.onload = function() {
-  div = document.getElementById('myDivElement');
-  div.circularReference = div;
-  div.lotsOfData = new Array(10000).join('*');
-};
-
- -

Trong ví dụ trên, phần tử DOM "myDivElement" có tham chiếu vòng tới chính nó trong thuộc tính "circularReference". Nếu thuộc tính đó không được loại bỏ hoặc gán giá trị null một cách tường minh, bộ thu thập rác (đếm tham chiếu) sẽ luôn có ít nhất một tham chiếu không bị thay đổi và sẽ giữ phần tử DOM trong bộ nhớ thậm chí khi nó đã bị loại bỏ khỏi cây DOM. Nếu phần tử DOM mang nhiều dữ liệu (thể hiện trong thuộc tính "lotsOfData"), bộ nhớ tiêu tốn bởi đống dữ liệu này sẽ không bao giờ được giải phóng.

- -

Thuật toán Mark-and-sweep

- -

Thuật toán này rút gọn định nghĩa từ "object không cần tới nữa" thành "object không thể tới được".

- -

Thuật toán này sử dụng tập các object gọi là root (Trong JavaScript, root là object toàn cục). Theo chu kỳ, bộ thu thập rác sẽ bắt đầu từ root, tìm tất cả object được tham chiếu tới từ root, rồi tới tất cả objects được tham chiếu từ các object trên, tương tự tới hết. Bắt đầu từ root, bộ thu thập rác sẽ tìm tất cả object có thể tới được và thu thập mọi object không thể tới được.

- -

Thuật toán này tốt hơn thuật toán trước bởi "object có không tham chiếu" dẫn tới object đó không thể tới được. Điều ngược lại không đúng như ví dụ về truy xuất vòng.

- -

Đến năm 2012, tất cả trình duyệt hiện đại đều hỗ trợ bộ thu thập rác mark-and-sweep. Mọi cải tiến trong bộ thu thập rác của JavaScript (generational/incremental/concurrent/parallel garbage collection) trong nhiều năm qua đều được áp dụng vào thuật toán này, nhưng không cải tiến thẳng vào thuật toán hay là rút gọn định nghĩa khi "object không cần tới nữa".

- -

Vòng không còn là mối lo

- -

Trong ví dụ đầu tiên, sau khi hàm gọi tới lệnh return, sẽ không còn object toàn cục nào tới được 2 object trong hàm. Vì thế, bộ thu thập rác sẽ xác định là chúng không thể tới được.

- -

Hạn chế: object cần phải được bất khả tới một cách tường minh

- -

Dù được đánh dấu là hạn chế, nhưng trên thực tế trường hợp này hiếm khi xảy ra nên không ai bận tâm tới bộ thu thập rác cả.

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/classes/constructor/index.html b/files/vi/web/javascript/reference/classes/constructor/index.html deleted file mode 100644 index dddb2555f3..0000000000 --- a/files/vi/web/javascript/reference/classes/constructor/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: constructor -slug: Web/JavaScript/Reference/Classes/constructor -translation_of: Web/JavaScript/Reference/Classes/constructor ---- -
{{jsSidebar("Classes")}}
- -

Phương thức constructor là một phương thức đặc biệt dùng để khởi tạo 1 object và được tạo ở trong class.

- -
{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}
- - - -

Cú pháp

- -
constructor([arguments]) { ... }
- -

Mô tả

- -

Chỉ có duy nhất 1 phương thức đặc biệt tên là "constructor" ở trong class. Có nhiều hơn 1 phương thức constructor ở trong class thì sẽ gây ra lỗi{{jsxref("SyntaxError")}}.

- -

Một constructor có thể sử dụng từ khóa {{jsxref("Operators/super", "super")}} để gọi đến constructor của class cha.

- -

Nếu bạn không chỉ định 1 phương thức constructor thì constructor mặc định sẽ được sử dụng

- -

Ví dụ

- -

Sử dụng phương thức constructor 

- -

Đoạn code này được lấy từ classes sample (live demo).

- -
class Square extends Polygon {
-  constructor(length) {
-    // Here, it calls the parent class' constructor with lengths
-    // provided for the Polygon's width and height
-    super(length, length);
-    // Note: In derived classes, super() must be called before you
-    // can use 'this'. Leaving this out will cause a reference error.
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-
-  set area(value) {
-    this.area = value;
-  }
-}
- -

Ví dụ khác

- -

Hãy xem đoạn code sau

- -
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
- -

Ở đây prototype của class Square đã bị thay đổi nhưng constructor kế thừa từ class Polygon vẫn được gọi khi tạo ra 1 thực thể mới.

- -

Default constructors

- -

Như đã nói ởi trước, nếu bạn không chỉ đỉnh 1 phương thức constructor thì default constructor sẽ được sử dụng. Với những class cơ bản thì default contructor sẽ là:

- -
constructor() {}
-
- -

Với những class dẫn xuất, default constructor sẽ là:

- -
constructor(...args) {
-  super(...args);
-}
- -

Thông số kĩ thuật

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.classes.constructor")}}

- -

Bài viết liên quan

- - diff --git a/files/vi/web/javascript/reference/classes/extends/index.html b/files/vi/web/javascript/reference/classes/extends/index.html deleted file mode 100644 index a7a2438965..0000000000 --- a/files/vi/web/javascript/reference/classes/extends/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: extends(Thừa kế) -slug: Web/JavaScript/Reference/Classes/extends -translation_of: Web/JavaScript/Reference/Classes/extends ---- -
{{jsSidebar("Classes")}}
- -

Từ khóa extends được sử dụng trong khai báo class hoặc trong class expressions để tạo ra 1 class con là con của class khác

- -
{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}
- - - -

Cú pháp

- -
class ChildClass extends ParentClass { ... }
- -

Mô tả

- -

Từ khó extends có thể được sử dụng để tạo ra class con từ những class mà chúng ta tạo ra hoặc những class sẵn có

- -

Thuộc tính .prototype của lớp được kế thừa phải trả về giá trị là  {{jsxref("Object")}} hoặc {{jsxref("null")}}.

- -

Ví dụ

- -

Sử dụng extends

- -

Ở ví dụ đầu tiên tạo ra 1 class Square từ class Polygon. Ví dụ này được lấy từ  đây (source).

- -
class Square extends Polygon {
-  constructor(length) {
-    // Ở đây, gọi 1 constructor từ class cha với tham số truyền vào là length
-    // cung cấp chiều rộng vào chiều cao của class Polygon
-    super(length, length);
-    // Chú ý: trong những class con, super()  phải được gọi trước khi
-    // bạn có thể sử dụng từ khóa 'this'. Nếu không sẽ gây ra lỗi tham chiếu
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-}
- -

Sử dụng extends với những object có sẵn

- -

Trong ví dụ này chúng ta thừa kế từ object có sẵn là {{jsxref("Date")}} . Ví dụ này được lấy từ đây(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();
-  }
-}
- -

Thừa kế từ null

- -

Thừa kế từ {{jsxref("null")}} cũng giống như class thông thường, ngoại trừ rằng các prototype của object sẽ không được thừa kế từ {{jsxref("Object.prototype")}}.

- -
class nullExtends extends null {
-  constructor() {}
-}
-
-Object.getPrototypeOf(nullExtends); // Function.prototype
-Object.getPrototypeOf(nullExtends.prototype) // null
-
-new nullExtends(); //ReferenceError: this is not defined
-
- -

Thông số kĩ thuật

- - - - - - - - - - - - - - - - - - - -
Thông sốTrạng tháiBình luận
{{SpecName('ES2015', '#sec-class-definitions', 'extends')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt tương thích

- - - -

{{Compat("javascript.classes.extends")}}

- -

Bài viết liên quan

- - diff --git a/files/vi/web/javascript/reference/classes/index.html b/files/vi/web/javascript/reference/classes/index.html deleted file mode 100644 index 02a693e6fc..0000000000 --- a/files/vi/web/javascript/reference/classes/index.html +++ /dev/null @@ -1,410 +0,0 @@ ---- -title: Classes -slug: Web/JavaScript/Reference/Classes -tags: - - Class trong ES6 - - JavaScript - - biểu thức class - - class declarations - - class expressions - - class trong javasript - - khai báo class - - thừa kế -translation_of: Web/JavaScript/Reference/Classes ---- -
{{JsSidebar("Classes")}}
- -
Lớp (class) trong JavaScript được giới thiệu trong ECMAScript 2015 chủ yếu là cú pháp cải tiến (syntactical sugar) dựa trên nền tảng thừa kế nguyên mẫu (prototypal inheritance) sẵn có trong JavaScript. Cú pháp class không giới thiệu mô hình thừa kế hướng đối tượng mới cho JavaScript.
- -

Định nghĩa class

- -

Thực tế các class giống như các "function đặc biệt", và cũng giống như bạn có thể định nghĩa hàm biểu thức (function expressions)  và khai báo hàm (function declarations), cú pháp class có hai thành phần: biểu thức class (class expressions) và khai báo class (class declarations).

- -

Khai báo class

- -

Một cách để định nghĩa class là sử dụng khai báo lớp class declaration. Để khai báo một class, bạn sử dụng từ khóa class  với tên của class đằng sau (ví dụ "Rectangle" như dưới đây).

- -
class Rectangle {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-}
- -

Hoisting (sự kéo lên)

- -

Một sự khác biệt quan trọng giữa khai báo hàmkhai báo class mà các bạn cần chú ý đó là khai báo hàm được kéo lên đầu ({{Glossary("Hoisting", "hoisted")}}), và khai báo class thì không. Bạn cần khai báo class của bạn trước tiên sau đó mới có thể gọi và sử dụng nó, ngược lại nếu viết code giống như phía dưới đây thì sẽ xảy ra lỗi {{jsxref("ReferenceError")}}:

- -
var p = new Rectangle(); // ReferenceError
-
-class Rectangle {}
-
- -

Biểu thức class

- -

Một biểu thức class là một cách khác để khai báo một class. Biểu thức class có thể có tên hoặc không tên. Biểu thức class nếu có tên, thì tên đó chỉ được nhìn thấy bên trong thân class. (Tuy nhiên từ bên ngoài nó có thể được lấy ra thông qua thuộc tính {{jsxref("Function.name", "name")}} của class (không phải instance)).

- -
// biểu thức class không tên
-var Rectangle = class {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-
-console.log(Rectangle.name);
-// output: "Rectangle" (tên của biến được gán)
-
-// biểu thức class có tên
-var Rectangle = class Rectangle2 {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-
-console.log(Rectangle.name);
-// output: "Rectangle2" (tên phía sau từ khóa class)
-
- -
-

Lưu ý: Các biểu thức class cũng theo quy luật hoisting như của {{anch("Class declarations")}} đề cập ở trên.

-
- -

Thân class và định nghĩa phương thức

- -

Phần thân của một class là phần nằm trong dấu ngoặc nhọn {}. Tại đó bạn có thể định nghĩa các thành phần của class như phương thức (method) hoặc hàm khởi tạo (constructor).

- -

Strict mode

- -

Các phần tử khai báo trong class declarations và class expressions đã được thực hiện ở chế độ strict mode như constructor, static tương tự đối với prototype methods, setter, getter functions. (Nếu bạn chưa hiểu chế độ strict mode thì hãy tìm hiểu thêm tại đây).

- -

Constructor (hàm khởi tạo)

- -

Hàm khởi tạo (constructor) là một hàm đặc biệt, nhiệm vụ của nó là khởi tạo một đối tượng cho một class. Trong một class chỉ có thể tồn tại duy nhất một hàm khởi tạo, nghĩa là bạn chỉ có thể khai báo duy nhất một hàm với tên "constructor". Nếu bạn cố gắng làm ngược lại (khai báo nhiều hơn một hàm constructor) thì sẽ xuất hiện lỗi {{jsxref("SyntaxError")}}.

- -

Một constructor có thể sử dụng từ khóa super để gọi tới hàm constructor của class cha.

- -

Phương thức Prototype

- -

Xem thêm định nghĩa hàm.

- -
class Rectangle {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-
-  get area() {
-    return this.calcArea();
-  }
-
-  calcArea() {
-    return this.height * this.width;
-  }
-}
-
-const square = new Rectangle(10, 10);
-
-console.log(square.area);
- -

Phương thức Static (phương thức tĩnh)

- -

Từ khóa static định nghĩa một hàm static (hàm tĩnh) trong một class. Nếu muốn gọi hàm static này thì bạn không cần gọi chúng thông qua các instantiating của class đó và bạn cũng không thể gọi chúng thông qua cách khởi tạo class. Hàm static thường được sử dụng vào mục đích tạo ra một hàm tiện ích (có thể gọi là hàm dùng chung) cho cả một ứng dụng.

- -
class Point {
-  constructor(x, y) {
-    this.x = x;
-    this.y = y;
-  }
-
-  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);
-
-console.log(Point.distance(p1, p2));
- -

Boxing với phương thức prototype và static

- -

Khi hai hàm static và prototype được gọi trực tiếp (không cần tạo đối tượng có giá trị "this") thì bây giờ bên trong hàm gọi, giá trị this sẽ là undefine. Autoboxing sẽ không xảy ra. Hành vi này sẽ giống nhau ngay cả khi chúng ta viết code ở strict mode bởi vì tất cả các hàm, phương thức, hàm khởi tạo, setter và getter đều thực thi mặc định ở strict mode. Chính vì vậy nếu chúng ta không chỉ định giá trị "this" thì giá trị của "this" sẽ là undefined.

- -
class Animal {
-  speak() {
-    return this;
-  }
-  static eat() {
-    return this;
-  }
-}
-
-let obj = new Animal();
-obj.speak(); // Animal {}
-let speak = obj.speak;
-speak(); // undefined
-
-Animal.eat() // class Animal
-let eat = Animal.eat;
-eat(); // undefined
-
- -

Nếu chúng ta chỉnh sửa code như trên bằng cách sửa dụng prototype thì autoboxing sẽ tự động hiểu rằng giá trị this bấy giờ là dựa trên cái hàm được gọi. Tham khảo code bên dưới.

- -
function Animal() { }
-
-Animal.prototype.speak = function() {
-  return this;
-}
-
-Animal.eat = function() {
-  return this;
-}
-
-let obj = new Animal();
-let speak = obj.speak;
-speak(); // global object
-
-let eat = Animal.eat;
-eat(); // global object
-
- -

Tạo lớp con với extends

- -

Từ khóa extends được sử dụng trong class declarations hoặc class expressions để tạo ra một class con kế thừa từ một class sẵn có (class cha).

- -
class Animal {
-  constructor(name) {
-    this.name = name;
-  }
-
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-}
-
-class Dog extends Animal {
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak(); // Mitzie barks.
-
- -

Nếu có một constructor trong lớp con (sub-class), nó cần gọi hàm super() trước khi có thể sử dụng "this".

- -

Một cách khác cũng có thể gọi và mở rộng hàm có sẵn là dùng prototype:

- -
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.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak(); // Mitzie barks.
-
- -

Cần lưu ý rằng các class không thể extend một object bình thường trong javascript (regular object). Do đó nếu bạn muốn kế thừa một hàm từ object bình thường này, bạn cần thay thế và sử dụng {{jsxref("Object.setPrototypeOf()")}}:

- -
var Animal = { // regular object
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-};
-
-class Dog { //
-  constructor(name) {
-    this.name = name;
-  }
-}
-
-Object.setPrototypeOf(Dog.prototype, Animal);// Nếu bạn không làm điều này khi gọi hàm speak thì sẽ sinh ra lỗi
-
-var d = new Dog('Mitzie'); // đối tượng của class Dog
-d.speak(); // Mitzie makes a noise.
-
- -

Species

- -

Bạn có thể muốn trả về các đối tượng {{jsxref("Array")}} trong mảng của class MyArray. Mô hình species sẽ cho phép bạn ghi đè lên các hàm khởi tạo mặc định.

- -

Ví dụ, khi sử dụng những phương thức như là {{jsxref("Array.map", "map()")}} điều đó sẽ trả về giá trị khởi tạo mặc định, bạn muốn những phương thức đó trả về một mảng đối tượng của Array, thay vì đối tượng của MyArray. {{jsxref("Symbol.species")}}  sẽ cho phép bạn thực hiện điều này:

- -
class MyArray extends Array {
-  // Overwrite species to the parent Array constructor
-  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
-
- -

Gọi class cha sử dụng super

- -

Từ khóa super dùng để gọi một hàm có sẵn ở đối tượng cha.

- -
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.');
-  }
-}
-
-var l = new Lion('Fuzzy');
-l.speak();
-// Fuzzy makes a noise.
-// Fuzzy roars.
-
-
- -

Mix-ins

- -

Abstract subclasses or mix-ins are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.

- -

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:

- -

Tập hợp các class con hoặc mix-ins được gọi là khuôn mẫu cho các class. Trong ECMAScript một class chỉ có thể có một lớp cha, vì vậy để thừa kế từ tập hợp các class (kế thừa nhiều class) là điều không thể. Các chức năng phải được cung cấp bởi lớp mà nó kế thừa (cung cấp bởi lớp cha).

- -

Một hàm mà đã được định nghĩa ở lớp cha và lớp con muốn kế thừa và mở rộng hàm đó ra thì có thể sự dụng các lệnh mix-ins trong  ECMAScript như sau:

- -
var calculatorMixin = Base => class extends Base {
-  calc() { }
-};
-
-var randomizerMixin = Base => class extends Base {
-  randomize() { }
-};
-
- -

Một class để sử dụng mix-ins này có thể viết code như thế này:

- -
class Foo { }
-class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
- -

Đặc điểm kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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')}}
- -

Tính tương thích với các trình duyệt

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}[1]
- {{CompatChrome(49.0)}}
{{CompatGeckoDesktop(45)}}13{{CompatNo}}{{CompatOpera(43.0)}}{{CompatSafari(9.0)}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}9{{CompatChrome(56.0)}}
-
- -

[1] Yêu cầu chế độ strict (luôn chạy javascript ở chế độ này). Tắt strict mode trong flag "Enable Experimental JavaScript", mặc định flag này bị vô hiệu hóa.

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/errors/index.html b/files/vi/web/javascript/reference/errors/index.html deleted file mode 100644 index c295fccea6..0000000000 --- a/files/vi/web/javascript/reference/errors/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: JavaScript error reference -slug: Web/JavaScript/Reference/Errors -tags: - - Debugging - - Error - - Errors - - Exception - - JavaScript - - NeedsTranslation - - TopicStub - - exceptions -translation_of: Web/JavaScript/Reference/Errors ---- -

{{jsSidebar("Errors")}}

- -

Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a name and a message.

- -

Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.

- -

List of errors

- -

In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!

- -

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

- -

See also

- - diff --git a/files/vi/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/vi/web/javascript/reference/errors/missing_semicolon_before_statement/index.html deleted file mode 100644 index 2e5e606618..0000000000 --- a/files/vi/web/javascript/reference/errors/missing_semicolon_before_statement/index.html +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: 'Lỗi cú pháp: Thiếu dấu ; trước câu lệnh' -slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement -tags: - - JavaScript - - Lỗi - - Lỗi cú pháp -translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement ---- -
{{jsSidebar("Errors")}}
- -

Thông điệp

- -
SyntaxError: missing ; before statement
-
- -

Kiểu lỗi

- -

{{jsxref("Lỗi cú pháp")}}.

- -

Sai ở đâu?

- -

Bạn đang thiếu dấu (;) ở đâu đó. Câu lệnh JavaScript phải được kết thúc bằng một dấu "chấm phẩy". Một vài trong số đó được thêm tự động bởi tính năng automatic semicolon insertion (ASI), nhưng trong tình huống này bạn cần thêm thủ công để JavaScript có thể hiểu câu lệnh của bạn chính xác.

- -

Tuy nhiên, thi thoảng lỗi này lại là kết quả của một vài lỗi khác, ví dụ như không kết thúc chuỗi ký tự một cách chính xác, hoặc sử dụng từ khoá var không đúng. Cũng có thể bạn đã thêm quá nhiều dấu ngoặc tròn ở đâu đó. Nếu bạn nhìn thấy lỗi này, trước hết hãy kiểm tra cẩn thận các lỗi cú pháp.

- -

Ví dụ

- -

Không kết thúc chuỗi

- -

Lỗi này có thể xảy ra khi bạn quên kết thúc chuỗi, còn JavaScrip thì đang mong đợi điều ấy:

- -
var foo = 'Tom's bar';
-// SyntaxError: missing ; before statement
- -

Bạn có thể sử dụng dấu nháy kép hoặc sử dụng dấu  \ cho những ký tự đặc biệt thế này:

- -
var foo = "Tom's bar";
-var foo = 'Tom\'s bar';
-
- -

Khai báo thuộc tính với từ khoá var

- -

Bạn KHÔNG THỂ khai báo thuộc tính của một đối tượng hoặc một mảng bằng từ khoá var:

- -
var obj = {};
-var obj.foo = 'hi'; // SyntaxError missing ; before statement
-
-var array = [];
-var array[0] = 'there'; // SyntaxError missing ; before statement
-
- -

Thay vào đó, hãy cứ bỏ qua từ khoá var như thế này:

- -
var obj = {};
-obj.foo = 'hi';
-
-var array = [];
-array[0] = 'there';
-
- -

Xem thêm:

- - diff --git a/files/vi/web/javascript/reference/errors/more_arguments_needed/index.html b/files/vi/web/javascript/reference/errors/more_arguments_needed/index.html deleted file mode 100644 index 4cf87a8b6d..0000000000 --- a/files/vi/web/javascript/reference/errors/more_arguments_needed/index.html +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: 'TypeError: More arguments needed' -slug: Web/JavaScript/Reference/Errors/More_arguments_needed -translation_of: Web/JavaScript/Reference/Errors/More_arguments_needed ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
TypeError: tham số không phải là một đối tượng và không phải là null (Edge)
-TypeError: Object.create requires cần ít nhất 1 tham số, nhưng chỉ có 0 được thông qua
-TypeError: Object.setPrototypeOf requires cần ít nhất 2 tham số nhưng chỉ có 0 được thông qua
-TypeError: Object.defineProperties requires cần ít nhất một tham số, nhưng chỉ có 0 được thông qua
-
- -

Loại lỗi

- -

{{jsxref("Lỗi")}}.

- -

Chuyện gì đã xảy ra?

- -

Đã có một lỗi với hàm được gọi. Cần cung cấp nhiều tham số hơn

- -

VÍ dụ

- -

Phương thức {{jsxref("Object.create()")}} cần ít nhất 1 tham số và phương thức {{jsxref("Object.setPrototypeOf()")}} cần ít nhất 2 tham số:

- -
var obj = Object.create();
-// TypeError: Object.create requires cần ít nhất là 1 tham số, nhưng chỉ có 0 được thông qua
-
-var obj = Object.setPrototypeOf({});
-// TypeError: Object.setPrototypeOf requires cần ít nhât 2 tham số, nhưng chỉ có 1 được thông qua
-
- -

Bạn có thể khắc phục bằng cách đặt {{jsxref("null")}} về nguyên mẫu, ví dụ:

- -
var obj = Object.create(null);
-
-var obj = Object.setPrototypeOf({}, null);
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/errors/not_a_function/index.html b/files/vi/web/javascript/reference/errors/not_a_function/index.html deleted file mode 100644 index a267a8bc74..0000000000 --- a/files/vi/web/javascript/reference/errors/not_a_function/index.html +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: 'TypeError: "x" is not a function' -slug: Web/JavaScript/Reference/Errors/Not_a_function -tags: - - JavaScript - - Lỗi - - Lỗi đánh máy -translation_of: Web/JavaScript/Reference/Errors/Not_a_function ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
TypeError: "x" is not a function
-
- -

Thể loại sai:

- -

{{jsxref("TypeError")}}.

- -

Chuyện gì đã xảy ra?

- -

Dự định gọi 1 giá trị như 1 chức năng, nhưng giá trị đó không thật sự là 1 chức năng. Một số đoạn mã chờ bạn cung cấp 1 chức năng, nhưng điều đó không xảy ra.

- -

Có lẽ là do bạn đánh sai tên chức năng chăng? Có lẽ object mà bạn định gọi method cho không có chức năng này? Ví dụ như những object của Javascript không có chức năng map, nhưng object của Javascript xâu (Array) thì có.

- -

Có rất nhiều chức năng có sẵn khi cần dùng lại 1 chức năng. Bạn sẽ phải cung cấp 1 chức năng để những method này hoạt động 1 cách chính xác.

- -
    -
  • Khi sử dụng những object {{jsxref("Array")}} hoặc {{jsxref("TypedArray")}}: -
      -
    • {{jsxref("Array.prototype.every()")}}, {{jsxref("Array.prototype.some()")}}, {{jsxref("Array.prototype.forEach()")}}, {{jsxref("Array.prototype.map()")}}, {{jsxref("Array.prototype.filter()")}},  {{jsxref("Array.prototype.reduce()")}}, {{jsxref("Array.prototype.reduceRight()")}}, {{jsxref("Array.prototype.find()")}}
    • -
    -
  • -
  • Khi sử dụng những object {{jsxref("Map")}} và {{jsxref("Set")}} : -
      -
    • {{jsxref("Map.prototype.forEach()")}} and {{jsxref("Set.prototype.forEach()")}}
    • -
    -
  • -
- -

Ví dụ

- -

Lỗi đánh máy trong tên chức năng

- -

Trong trường hợp này, xảy ra rất thường xuyên, có 1 lỗi đánh máy trong tên method:

- -
var x = document.getElementByID('foo');
-// TypeError: document.getElementByID is not a function
-
- -

Tên đúng là getElementById:

- -
var x = document.getElementById('foo');
-
- -

Chức năng bị gọi sai trên object

- -

Đối với 1 số method nhất định, bạn phải cung cấp 1 chức năng (để gọi trở lại) và nó sẽ hoạt động trên những object nhất định đó thôi. Ví dụ khi {{jsxref("Array.prototype.map()")}} được sử dụng, thì sẽ chỉ chạy với object {{jsxref("Array")}} này mà thôi.

- -
var obj = {a: 13, b: 37, c: 42};
-
-obj.map(function(num) {
-  return num * 2;
-});
-
-// TypeError: obj.map is not a function
- -

Thay vào đó, sử dụng 1 xâu:

- -
var numbers = [1, 4, 9];
-
-numbers.map(function(num) {
-  return num * 2;
-});
-
-// Array [2, 8, 18]
-
- -

Liên kết:

- - diff --git a/files/vi/web/javascript/reference/errors/too_much_recursion/index.html b/files/vi/web/javascript/reference/errors/too_much_recursion/index.html deleted file mode 100644 index 32084a7de0..0000000000 --- a/files/vi/web/javascript/reference/errors/too_much_recursion/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: 'InternalError: Quá nhiều đệ quy' -slug: Web/JavaScript/Reference/Errors/Too_much_recursion -tags: - - JavaScript - - Lỗi - - Lỗi bên trong -translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion -original_slug: Web/JavaScript/Reference/Errors/qua_nhieu_de_quy ---- -
{{jsSidebar("Errors")}}
- -

Thông điệp

- -
InternalError: too much recursion
-
- -

Loại lỗi

- -

{{jsxref("InternalError")}}.

- -

Lỗi phát sinh ra khi nào?

- -

Một hàm gọi chính nó được gọi là hàm đệ quy . Trong một số trường hợp, đệ quy tương tự như một vòng lặp. Cả hai đều thực hiện cùng một mã nhiều lần, Và cả hai đều yêu cầu một điều kiện ( Để tránh một vòng lặp vô hạn, hoặc đúng hơn, đệ quy vô hạn trong trường hợp này ). Khi có quá nhiều hoặc vô hạn đệ quy, JavaScript sẽ ném lỗi này.

- -

Ví dụ

- -

Chức năng đệ quy này chạy 10 lần, theo điều kiện x >= 10 .

- -
function loop(x) {
-  if (x >= 10) // "x >= 10" là điều kiện dừng
-    return;
-  // do stuff
-  loop(x + 1); // gọi lại chính nó (đệ quy)
-}
-loop(0);
- -

Đặt điều kiện này lên một giá trị rất cao, sẽ không hoạt động:

- -
function loop(x) {
-  if (x >= 1000000000000)
-    return;
-  // do stuff
-  loop(x + 1);
-}
-loop(0);
-
-// InternalError: too much recursion
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/functions/arguments/index.html b/files/vi/web/javascript/reference/functions/arguments/index.html deleted file mode 100644 index ffcb00b472..0000000000 --- a/files/vi/web/javascript/reference/functions/arguments/index.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: The arguments object -slug: Web/JavaScript/Reference/Functions/arguments -translation_of: Web/JavaScript/Reference/Functions/arguments ---- -

{{JSSidebar("Functions")}}

- -

arguments là object giống Array khả truy cập bên trong hàm, chứa các giá trị của đối số truyền vào trong hàm đó.

- -
-

Ghi chú: Nếu bạn viết mã tương thích cho ES6, thì bạn nên tham khảo rest parameters.

-
- -
-

Ghi chú: “Giống Array” tức là arguments có thuộc tính {{jsxref("Functions/arguments/length", "length")}} và đánh chỉ mục từ không (0), nhưng nó không có phương thức dựng sẵn của {{JSxRef("Array")}} như {{jsxref("Array.forEach", "forEach()")}} và {{jsxref("Array.map", "map()")}}. Xem §Mô tả để biết thêm chi tiết.

-
- -
{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}
- - - -

Cú pháp

- -
arguments
- -

Mô tả

- -

Object arguments là biến cục bộ có sẵn cho mọi hàm không phải hàm mũi tên. Bạn có thể tham chiếu tới đối số của một hàm bên trong hàm đó bằng cách sử dụng object arguments. Nó chứa từng đối số mà hàm đó được gọi cùng, với chỉ mục bắt đầu từ 0.

- -

Chẳng hạn, nếu một hàm được truyền vào 3 đối số, bạn có thể truy cập nó theo cách sau:

- -
arguments[0] // đối số thứ nhất
-arguments[1] // đối số thứ hai
-arguments[2] // đối số thứ ba
-
- -

Mỗi đối số đều có thể thiết lập hoặc gán lại:

- -
arguments[1] = 'new value';
-
- -

Object arguments không phải là {{jsxref("Array")}}. Nó tương tự nhưng không có thuộc tính của Array ngoài {{jsxref("Array.length", "length")}}. Chẳng hạn, nó không có phương thức {{jsxref("Array.pop", "pop()")}}. Tuy nhiên, nó có thể ép kiểu về Array:

- -
var args = Array.prototype.slice.call(arguments);
-// Using an array literal is shorter than above but allocates an empty array
-var args = [].slice.call(arguments);
-
- -

Như có thể làm với mọi object giống-Array, bạn có thể dùng phương thức {{jsxref("Array.from()")}} của ES2015 hoặc cú pháp spread để ép kiểu arguments thành Array:

- -
var args = Array.from(arguments);
-var args = [...arguments];
-
- -

Object arguments có ích đối với hàm được truyền nhiều đối số hơn so với khởi tạo ban đầu. Kỹ thuật này có ích với hàm cần được truyền nhiều biến, như là {{jsxref("Math.min()")}}. Hàm ví dụ dưới đây chấp nhật mọi xâu ký tự và trả về xâu dài nhất:

- -
function longestString() {
-  var longest = '';
-  for (var i=0; i < arguments.length; i++) {
-    if (arguments[i].length > longest.length) {
-      longest = arguments[i];
-    }
-  }
-  return longest;
-}
-
- -

Bạn có thể dùng {{jsxref("Functions/arguments/length", "arguments.length")}} để đếm số lượng đối số được truyền vào khi hàm được gọi. Thay vì thế, nếu bạn muốn đếm số lượng tham số chính quy mà hàm chấp nhận khi khởi tạo, hãy tham khảo thuộc tính {{jsxref("Function.length", "length")}} của hàm.

- -

Sử dụng typeof với Arguments

- -

Toán tử {{jsxref("Operators/typeof", "typeof")}} trả về 'object' khi dùng với arguments

- -
console.log(typeof arguments); // 'object' 
- -

Kiểu của từng đối số có thể xác định lần lượt bằng cách chỉ đích danh trong object arguments:

- -
console.log(typeof arguments[0]); // trả về kiểu của đối số thứ nhất
- -

Thuộc tính

- -
-
{{jsxref("Functions/arguments/callee", "arguments.callee")}}
-
Tham chiếu tới hàm đang được thực thi sở hữu arguments.
-
{{jsxref("Functions/arguments/caller", "arguments.caller")}} {{Obsolete_Inline}}
-
Reference to the function that invoked the currently executing function.
-
{{jsxref("Functions/arguments/length", "arguments.length")}}
-
Số lượng đối số được truyền vào hàm.
-
{{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}}
-
Returns a new {{jsxref("Array/@@iterator", "Array iterator", "", 0)}} object that contains the values for each index in the arguments.
-
- -

Ví dụ

- -

Định nghĩa hàm nối xâu ký tự

- -

Ví dụ sau đây định nghĩa một hàm nối các xâu ký tự với nhau. Tham số chính quy mà hàm nhận là một xâu chứa các ký tự ngăn cách các xâu với nhau sau khi được nối.

- -
function myConcat(separator) {
-  var args = Array.prototype.slice.call(arguments, 1);
-  return args.join(separator);
-}
- -

Bạn có thể truyền vào bao nhiêu xâu ký tự tuỳ ý. Giá trị trả về là một xâu chứa tất cả các đối số được truyền vào:

- -
// trả về "red, orange, blue"
-myConcat(', ', 'red', 'orange', 'blue');
-
-// trả về "elephant; giraffe; lion; cheetah"
-myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');
-
-// trả về "sage. basil. oregano. pepper. parsley"
-myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
- -

Định nghĩa hàm sinh danh sách HTML

- -

Ví dụ sau đây định nghĩa một hàm sinh ra một xâu ký tự chứa các thẻ HTML để tạo thành một danh sách. Tham số chính quy duy nhất mà hàm nhận là một ký tự như "u" nếu danh sách không có thứ tự (đánh dấu chấm), hay "o" nếu danh sách có thứ tự (đánh số). Hàm đó được định nghĩa như sau:

- -
function list(type) {
-  var html = '<' + type + 'l><li>';
-  var args = Array.prototype.slice.call(arguments, 1);
-  html += args.join('</li><li>');
-  html += '</li></' + type + 'l>'; // end list
-
-  return html;
-}
- -

Bạn có thể truyền bao nhiêu đối số tuỳ ý, và nó sẽ thêm từng đối số vào danh sách có kiểu xác định trước. Chẳng hạn:

- -
var listHTML = list('u', 'One', 'Two', 'Three');
-
-/* listHTML is:
-"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
-*/
- -

Tham số rest, default và destructured

- -

Object arguments có thể dùng cùng lúc với các tham số như rest, default, và destructured.

- -
function foo(...args) {
-  return args;
-}
-foo(1, 2, 3); // [1,2,3]
-
- -

Tuy trong strict-mode, tham số rest, default, hoặc destructured parameters không can thiệp vào hành vi của object arguments, nhưng trong non-strict mode vẫn có không ít khác biệt.

- -

Nếu một hàm non-strict không chứa tham số rest, default, hay destructured, thì giá trị trong object arguments thay đổi đồng bộ với giá trị của tham số truyền vào. Hãy xem đoạn mã dưới đây:

- -
function func(a) {
-  arguments[0] = 99; // cập nhật arguments[0] cũng cập nhật a
-  console.log(a);
-}
-func(10); // 99
-
- -

- -
function func(a) {
-  a = 99; // cập nhật a cũng cập nhật arguments[0]
-  console.log(arguments[0]);
-}
-func(10); // 99
-
- -

Khi hàm non-strict chứa tham số rest, default hoặc destructured, thì giá trị trong object arguments không theo dõi giá trị của đối số. Thay vì vậy, chúng ánh xạ đến đối số truyền vào khi hàm được gọi:

- -
function func(a = 55) {
-  arguments[0] = 99; // updating arguments[0] does not also update a
-  console.log(a);
-}
-func(10); // 10
- -

- -
function func(a = 55) {
-  a = 99; // updating a does not also update arguments[0]
-  console.log(arguments[0]);
-}
-func(10); // 10
-
- -

- -
// An untracked default parameter
-function func(a = 55) {
-  console.log(arguments[0]);
-}
-func(); // undefined
- -

Đặc tả kĩ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1
{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES2015', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ESDraft')}} 
- -

Tương thích trình duyệt

- - - -

{{Compat("javascript.functions.arguments")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/functions/arrow_functions/index.html b/files/vi/web/javascript/reference/functions/arrow_functions/index.html deleted file mode 100644 index 6da70e4205..0000000000 --- a/files/vi/web/javascript/reference/functions/arrow_functions/index.html +++ /dev/null @@ -1,426 +0,0 @@ ---- -title: Hàm mũi tên (hàm rút gọn) -slug: Web/JavaScript/Reference/Functions/Arrow_functions -translation_of: Web/JavaScript/Reference/Functions/Arrow_functions ---- -
{{jsSidebar("Functions")}}
- -

Biểu thức hàm mũi tên là một thay thế rút gọn cho hàm biểu thức truyền thống, nhưng bị hạn chế và không thể sử dụng trong mọi trường hợp.

- -

Sự khác biệt & Hạn chế:

- -
    -
  • Không hỗ trợ binddings đến con trỏ  this hoặc super, và không nên dùng ở methods.
  • -
  • Không có arguments, hoặc từ khóa new.target.
  • -
  • Không phù hợp với các phương thức callapply và bind, thường dựa vào thiết lập scope.
  • -
  • Không sử dụng để constructors.
  • -
  • Không thể dùng yield, trong nội dung (body).
  • -
- -

{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}

- -

So sánh hàm truyền thống và hàm mũi tên

- -

Hãy phân tách "hàm truyền thống" thành "hàm mũi tên" đơn giản nhất theo từng bước:
- LƯU Ý: Mỗi bước là một "hàm mũi tên" hợp lệ.

- -
// Hàm truyền thống
-function (a){
-  return a + 100;
-}
-
-// Phân rã thành hàm mũi tên
-
-// 1. Xóa từ khóa "function" và thay thế bằng mũi tên ở giữa đối số và dấu ngoặc nhọn bắt đầu nội dung hàm
-(a) => {
-  return a + 100;
-}
-
-// 2. Xóa dấu ngoặc nhọn và từ khóa "return" sự trả về đã bao hàm (mặc định) khi sử dụng hàm mũi tên.
-(a) => a + 100;
-
-// 3. Xóa luôn dấu ngoặc đơn của đối số
-a => a + 100;
- -

Như bạn thấy ở bên trên, dấu { ngoặc nhọn } và dấu (ngoặc tròn ở đối ố) và "return" là tùy chọn, nhưng đôi khi có thể bắt buộc phải có.

- -

Ví dụ, nếu bạn có nhiều đối số hoặc không có đối số, bạn cần phải thêm dấu ngoặc tròn vào xung quanh các đối số:

- -
// Hàm Truyền thống
-function (a, b){
-  return a + b + 100;
-}
-
-// Hàm mũi tên
-(a, b) => a + b + 100;
-
-// Hàm truyền thống (không đối số)
-let a = 4;
-let b = 2;
-function (){
-  return a + b + 100;
-}
-
-// Hàm mũi tên (không đối số)
-let a = 4;
-let b = 2;
-() => a + b + 100;
- -

Tương tự như vậy, nếu nội dung (body) hàm cần thêm nhiều dòng để xử lý thì bạn cần thêm vào dấu ngoặc nhọn CỘNG thêm "return" (hàm mũi tên không có kỳ diệu đến mức biết khi nào bạn muốn "return"):

- -
// Hàm truyền thống
-function (a, b){
-  let chuck = 42;
-  return a + b + chuck;
-}
-
-// Hàm mũi tên
-(a, b) => {
-  let chuck = 42;
-  return a + b + chuck;
-}
- -

Và cuối cùng, với các hàm được đặt tên chúng tôi xử lý các biểu thức mũi tên như các biến

- -
// Hàm truyền thống
-function bob (a){
-  return a + 100;
-}
-
-// Hàm mũi tên
-let bob = a => a + 100;
- -

Cú pháp

- -

Cú pháp cơ bản

- -
(param1, param2, …, paramN) => { statements }
-(param1, param2, …, paramN) => expression
-// tương đương với: (param1, param2, …, paramN) => { return expression; }
-
-// Dấu ngoặc đơn không bắt buộc khi chỉ có một tham số truyền vào:
-(singleParam) => { statements }
-singleParam => { statements }
-
-// Hàm khi không có tham số truyền vào bắt buộc phải là dấu ():
-() => { statements }
-() => expression // tương đương: () => { return expression; }
-
- -

Cú pháp nâng cao

- -
// Bên trong dấu ngoặc đơn là một đối tượng:
-params => ({foo: bar})
-
-// Rest parameters và default parameters được hỗ trợ
-(param1, param2, ...rest) => { statements }
-(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }
-
-// Destructuring within the parameter list is also supported
-var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
-f();  // 6
-
- -

Chi tiết các ví dụ bạn có thể xem ở đây.

- -

Mô tả

- -

Xem thêm "ES6 Chuyên sâu: Những hàm arrow" trên hacks.mozilla.org.

- -

Two factors influenced the introduction of arrow functions: shorter functions and non-binding of this.

- -

Hàm ngắn

- -

Một vài ví dụ, cú pháp hàm rút gọn luôn được coder yêu thích, cùng so sánh:

- -
var materials = [
-  'Hydrogen',
-  'Helium',
-  'Lithium',
-  'Beryllium'
-];
-
-// thông thường
-var materialsLength1 = materials.map(function(material) {
-  return material.length;
-});
-
-// ngắn hơn (như mùa đông 5 độ vậy)
-var materialsLength2 = materials.map((material) => {
-  return material.length;
-});
-
-// ngắn hơn nữa (và -2 độ, bạn còn bao nhiêu cm ?)
-var materialsLength3 = materials.map(material => material.length);
-
- -

Không ràng buộc this

- -

Cho tới khi hàm rút gọn xuất hiện, mọi hàm mới đều tự định nghĩa giá trị this của riêng hàm (là object vừa được khởi tạo nếu dùng constructor, là undefined nếu đặt strict mode khi gọi hàm, là context object nếu hàm được gọi như một "object method", vân vân.). This trở nên khá khó chịu khi làm việc với phong cách lập trình hướng đối tượng.

- -
function Person() {
-  // constructor của Person() định nghĩa `this` như một biến.
-  this.age = 0;
-
-  setInterval(function growUp() {
-    // Khi dùng non-strict mode, hàm growUp() định nghĩa `this`
-    // như một đối tượng toàn cục, khác hoàn toàn so với `this`
-    // được định nghĩa bởi constructor của Person().
-    this.age++;
-  }, 1000);
-}
-
-var p = new Person();
- -

Theo ECMAScript 3/5, vấn đề của this có thể sửa được bằng cách gán this cho một biến gần nhất.

- -
function Person() {
-  var that = this;
-  that.age = 0;
-
-  setInterval(function growUp() {
-    // Hàm callback trỏ tới biến `that`với
-    // giá trị là đối tượng mong đợi.
-    that.age++;
-  }, 1000);
-}
- -

Nói cách khác, tạo ra một hàm ràng buộc để truyền giá trị của this vào hàm ràng buộc đích (chẳng hạn như hàm growUp() phía trên).

- -

Hàm rút gọn không tạo ra ngữ cảnh this của riêng hàm, thế nên this có ý nghĩa trong ngữ cảnh bọc quanh nó. Đoạn code phía dưới là một ví dụ:

- -
function Person(){
-  this.age = 0;
-
-  setInterval(() => {
-    this.age++; // |this| ở đây trỏ tới đối tượng person
-  }, 1000);
-}
-
-var p = new Person();
- -

Mối liên hệ với strict mode

- -

Giả sử this bị bó buộc trong thân hàm, strict mode sẽ khiến cho this bị bỏ qua.

- -
var f = () => { 'use strict'; return this; };
-f() === window; // hoặc đối tượng toàn cục
- -

Các strict mode khác được áp dụng như bình thường.

- -

Gọi thông qua call hoặc apply

- -

Vì this không bị ràng buộc bên trong hàm rút gọn, các phương thức call() hoặc apply() chỉ có thể truyền tham số. this bị bỏ qua.

- -
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));         // Sẽ trả ra 2
-console.log(adder.addThruCall(1)); // Vẫn sẽ trả ra 2
- -

Không ràng buộc arguments

- -

Hàm rút gọn không ràng buộc arguments object. Do đó, trong ví dụ sau, arguments chỉ đơn giản là một tham chiếu đến đối tượng cùng tên trong phạm vi bao quanh:

- -
var arguments = 42;
-var arr = () => arguments;
-
-arr(); // 42
-
-function foo() {
-  var f = (i) => arguments[0] + i; // foo's implicit arguments binding
-  return f(2);
-}
-
-foo(1); // 3
- -

Trong nhiều trường hợp, sử dụng rest parameters là một cách thay thế tốt để dùng đối tượng arguments.

- -
function foo() {
-  var f = (...args) => args[0];
-  return f(2);
-}
-
-foo(1); // 2
- -

Dùng hàm rút gọn như một phương thức

- -

Như đã nói phía trên, biểu thức hàm rút gọn cực kì hợp với các hàm non-method. Hãy xem chuyện gì sẽ xảy ra khi ta dùng chúng như phương thức trong ví dụ bên dưới nhé:

- -
'use strict';
-var obj = {
-  i: 10,
-  b: () => console.log(this.i, this),
-  c: function() {
-    console.log(this.i, this);
-  }
-}
-obj.b(); // in ra undefined, Object {...}
-obj.c(); // in ra 10, Object {...}
- -

Hàm rút gọn không định nghĩa ("ràng buộc") this của hàm.  Một ví dụ khác đối với {{jsxref("Object.defineProperty()")}}:

- -
'use strict';
-var obj = {
-  a: 10
-};
-
-Object.defineProperty(obj, 'b', {
-  get: () => {
-    console.log(this.a, typeof this.a, this);
-    return this.a + 10; // đại diện cho đối tượng toàn cục 'Window', bởi vậy 'this.a' trả về 'undefined'
-  }
-});
-
- -

Dùng toán tử new

- -

Hàm rút gọn không thể dùng như phương thức khởi tạo và sẽ báo lỗi nếu dùng toán tử new.

- -
var Foo = () => {};
-var foo = new Foo(); // TypeError: Foo is not a constructor
- -

Dùng thuộc tính prototype

- -

Hàm rút gọn không có thuộc tính prototype.

- -
var Foo = () => {};
-console.log(Foo.prototype); // undefined
-
- -

Dùng từ khoá yield

- -

Từ khoá yield có thể sẽ không dùng được trong thân hàm rút gọn (trừ khi được gọi trong hàm lồng trong hàm rút gọn). Tức là, hàm rút gọn không thể dùng như là generator (hàm sinh).

- -

Phần thân hàm

- -

Hàm rút gọn vừa có thể có "concise body" hoặc dạng thường thấy "block body".

- -

Trong concise body, chỉ cần biểu thức, return sẽ được gán ngầm. Còn với block body, bạn phải có return.

- -
var func = x => x * x;                  // concise syntax, implied "return"
-var func = (x, y) => { return x + y; }; // with block body, explicit "return" needed
-
- -

Trả về object literals

- -

Không thể dùng cú pháp params => {object:literal} nếu muốn trả về object literal.

- -
var func = () => { foo: 1 };               // Calling func() returns undefined!
-var func = () => { foo: function() {} };   // SyntaxError: function statement requires a name
- -

Bởi vì đoạn code bên trong ({}) được phân giải thành một chuỗi các trình tự nối tiếp (ví dụ foo được coi như một nhãn, thay vì một key trong object literal).

- -

Thế nên hãy bao object literal trong ngoặc tròn.

- -
var func = () => ({foo: 1});
- -

Kí tự xuống dòng

- -

Hàm rút gọn không thể chứa bất cứ kí tự rút gọn nào giữa phần truyền tham số và dấu mũi tên.

- -
var func = ()
-           => 1; // SyntaxError: expected expression, got '=>'
- -

Parsing order

- -

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

- -
let callback;
-
-callback = callback || function() {}; // ok
-callback = callback || () => {};      // SyntaxError: invalid arrow-function arguments
-callback = callback || (() => {});    // ok
-
- -

Một số ví dụ khác

- -
// An empty arrow function returns undefined
-let empty = () => {};
-
-(() => 'foobar')(); // IIFE, returns "foobar"
-
-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]
-
-// More concise promise chains
-promise.then(a => {
-  // ...
-}).then(b => {
-   // ...
-});
-
-// Parameterless arrow functions that are visually easier to parse
-setTimeout( () => {
-  console.log('I happen sooner');
-  setTimeout( () => {
-    // deeper code
-    console.log('I happen later');
-  }, 1);
-}, 1);
-
- -

Đặc điểm kĩ thuật

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ESDraft')}}
- -

Tương thích trình duyệt

- -
{{Compat("javascript.functions.arrow_functions")}}
- -

Firefox-specific notes

- -
    -
  • The initial implementation of arrow functions in Firefox made them automatically strict. This has been changed as of Firefox 24. The use of "use strict"; is now required.
  • -
  • Arrow functions are semantically different from the non-standard {{jsxref("Operators/Expression_Closures", "expression closures", "", 1)}} added in Firefox 3 (details: JavaScript 1.8), for {{jsxref("Operators/Expression_Closures", "expression closures", "", 1)}} do not bind this lexically.
  • -
  • Prior to Firefox 39, a line terminator (\n) was incorrectly allowed after arrow function arguments. This has been fixed to conform to the ES2015 specification and code like () \n => {} will now throw a {{jsxref("SyntaxError")}} in this and later versions.
  • -
- -

Tìm đọc

- - diff --git a/files/vi/web/javascript/reference/functions/default_parameters/index.html b/files/vi/web/javascript/reference/functions/default_parameters/index.html deleted file mode 100644 index 11ae77dab7..0000000000 --- a/files/vi/web/javascript/reference/functions/default_parameters/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Default parameters -slug: Web/JavaScript/Reference/Functions/Default_parameters -translation_of: Web/JavaScript/Reference/Functions/Default_parameters ---- -
{{jsSidebar("Functions")}}
- -

Các tham số của hàm mặc định cho phép khởi tạo với các giá trị mặc định khi không truyền giá trị vào đó.

- -
{{EmbedInteractiveExample("pages/js/functions-default.html")}}
- - - -

Cú pháp

- -
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
-   statements
-}
-
- -

Mô tả

- -

Trong JavaScript, tham số của hàm mặc định {{jsxref("undefined")}}. Tuy nhiên, chúng thường hữu ích hơn khi tạo giá trị mặc định khác. 

- -

Trước đây, quy tắc chung khi tạo giá trị mặc định là kiểm tra các giá trị tham số trong thân hàm và gán vào tham số nếu nó không xác định.

- -

Trong ví dụ sau, nếu không cung cấp giá trị cho b khi gọi hàm multiply, b sẽ không xác định trong phép tính a * b và hàm multiply sẽ trả về NaN.

- -
function multiply(a, b) {
-  return a * b;
-}
-
-multiply(5, 2); // 10
-multiply(5);    // NaN !
-
- -

Để tránh điều này, ta sẽ dùng một dòng code xác định b=1 nếu hàm chỉ được gọi với 1 đối số.

- -
function multiply(a, b) {
-  b = (typeof b !== 'undefined') ?  b : 1;
-  return a * b;
-}
-
-multiply(5, 2); // 10
-multiply(5);    // 5
-
- -

Với các tham số mặc định trong ES2015, việc kiểm tra thân hàm không còn cần thiết. Bạn có thể gán 1 cho b ở đầu hàm:

- -
function multiply(a, b = 1) {
-  return a * b;
-}
-
-multiply(5, 2); // 10
-multiply(5);    // 5
-
- -

Ví dụ

- -

Truyền giá trị undefined với giá trị ảo

- -

Trong lời gọi thứ hai, ngay cả khi đối số thứ nhất không xác định (không phải null hay giá trị ảo), đối số num vẫn mặc định.

- -

function test(num = 1) { console.log(typeof num); } test(); // 'number' (num is set to 1) test(undefined); // 'number' (num is set to 1 too) // test with other falsy values: test(''); // 'string' (num is set to '') test(null); // 'object' (num is set to null)

- -

Xét tại thời điểm gọi

- -

Đối số mặc định được xét tại thời điểm gọi. Trong khi Python, một đối tượng mới được tạo ra mỗi khi hàm được gọi.

- -

function append(value, array = []) { array.push(value); return array; } append(1); //[1] append(2); //[2], not [1, 2]

- -

Áp dụng cho cả hàm và biến:

- -
function callSomething(thing = something()) {
- return thing;
-}
-
-let numberOfTimesCalled = 0;
-function something() {
-  numberOfTimesCalled += 1;
-  return numberOfTimesCalled;
-}
-
-callSomething(); // 1
-callSomething(); // 2
- -

Các tham số mặc định có sẵn cho các tham số mặc định sau:

- -

Các tham số được xác định trước (bên trái) có sẵn cho các tham số mặc định sau:

- -

function greet(name, greeting, message = greeting + ' ' + name) {     return [name, greeting, message]; } greet('David', 'Hi');  // ["David", "Hi", "Hi David"] greet('David', 'Hi', 'Happy Birthday!');  // ["David", "Hi", "Happy Birthday!"]

- -

This functionality can be aChức năng này sử dụng cho nhiều trường hợp xảy ra:

- -
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, "=^_^="]
-
- -

Định nghĩa hàm trong thân hàm

- -

Giới thiệu trong Gecko 33 {{geckoRelease(33)}}. Các hàm được khai báo trong thân hàm không thể được tham chiếu bên trong với các tham số mặc định của hàm ngoài. Nếu bạn thử, {{jsxref("ReferenceError")}} sẽ bị loại bỏ. Các tham số mặc định luôn được thực thi trước, hàm khai báo bên trong thân hàm sẽ thực thi sau.

- -
// Doesn't work! Throws ReferenceError.
-function f(a = go()) {
-  function go() { return ':P'; }
-}
-
- -

Tham số không mặc định

- -

Trước Gecko 26 {{geckoRelease(26)}}, đoạn code sau cho kết quả {{jsxref("SyntaxError")}}. Sau đó được sửa lại {{bug(777060)}}. Các tham số vẫn xuất hiện từ trái qua phải, ghi đè lên các tham số mặc định kể cả các tham số sau không mặc định.

- -
function f(x = 1, y) {
-  return [x, y];
-}
-
-f(); // [1, undefined]
-f(2); // [2, undefined]
-
- -

Tham số bị hủy gán với giá trị mặc định

- -

Có thể dùng giá trị mặc định với kí hiệu destructuring assignment:

- -
function f([x, y] = [1, 2], {z: z} = {z: 3}) {
-  return x + y + z;
-}
-
-f(); // 6
- -

Đặc điểm

- - - - - - - - - - - - - - - - - - - -
Đặc điểmTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ES2015')}}Định nghĩa ban đầu
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ESDraft')}}
- -

Trình duyệt tương thích

- -
- - -

{{Compat("javascript.functions.default_parameters")}}

-
- -

Liên quan

- - diff --git a/files/vi/web/javascript/reference/functions/index.html b/files/vi/web/javascript/reference/functions/index.html deleted file mode 100644 index e7935d3318..0000000000 --- a/files/vi/web/javascript/reference/functions/index.html +++ /dev/null @@ -1,657 +0,0 @@ ---- -title: Functions -slug: Web/JavaScript/Reference/Functions -tags: - - Constructor - - Function - - Functions - - JavaScript - - NeedsTranslation - - Parameter - - TopicStub - - parameters -translation_of: Web/JavaScript/Reference/Functions ---- -
{{jsSidebar("Functions")}}
- -

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

- -

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

- -

For more examples and explanations, see also the JavaScript guide about functions.

- -

Description

- -

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

- -

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

- -

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

- -
/* Declare the function 'myFunc' */
-function myFunc(theObject) {
-   theObject.brand = "Toyota";
- }
-
- /*
-  * Declare variable 'mycar';
-  * create and initialize a new Object;
-  * assign reference to it to 'mycar'
-  */
- var mycar = {
-   brand: "Honda",
-   model: "Accord",
-   year: 1998
- };
-
- /* Logs 'Honda' */
- console.log(mycar.brand);
-
- /* Pass object reference to the function */
- myFunc(mycar);
-
- /*
-  * Logs 'Toyota' as the value of the 'brand' property
-  * of the object, as changed to by the function.
-  */
- console.log(mycar.brand);
-
- -

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

- -

Defining functions

- -

There are several ways to define functions:

- -

The function declaration (function statement)

- -

There is a special syntax for declaring functions (see function statement for details):

- -
function name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The function expression (function expression)

- -

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

- -
function [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

Here is an example of an anonymous function expression (the name is not used):

- -
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 benefit of creating a named function expression is that in case we encounted 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 example do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

- -

When function are used only once, a common pattern is an IIFE (Immediately Invokable Function Expressions).

- -
(function() {
-    statements
-})();
- -

IIFE are function expression that are invoked as soon as the function is declared.

- -

The generator function declaration (function* statement)

- -

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

- -
function* name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The generator function expression (function* expression)

- -

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

- -
function* [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

The arrow function expression (=>)

- -

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

- -
([param[, param]]) => {
-   statements
-}
-
-param => expression
-
- -
-
param
-
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
-
statements or expression
-
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
-
- -

The Function constructor

- -
-

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

- -
new Function (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function body.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

The GeneratorFunction constructor

- -
-

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

-
- -
-

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

- -
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function definition.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

Function parameters

- -

Default parameters

- -

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

- -

Rest parameters

- -

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

- -

The arguments object

- -

You can refer to a function's arguments within the function by using the arguments object. See arguments.

- -
    -
  • arguments: An array-like object containing the arguments passed to the currently executing function.
  • -
  • arguments.callee {{Deprecated_inline}}: The currently executing function.
  • -
  • arguments.caller {{Obsolete_inline}} : The function that invoked the currently executing function.
  • -
  • arguments.length: The number of arguments passed to the function.
  • -
- -

Defining method functions

- -

Getter and setter functions

- -

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

- -
-
get
-
-

Binds an object property to a function that will be called when that property is looked up.

-
-
set
-
Binds an object property to a function to be called when there is an attempt to set that property.
-
- -

Method definition syntax

- -

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

- -
var obj = {
-  foo() {},
-  bar() {}
-};
- -

Function constructor vs. function declaration vs. function expression

- -

Compare the following:

- -

A function defined with the Function constructor assigned to the variable multiply:

- -
var multiply = new Function('x', 'y', 'return x * y');
- -

A function declaration of a function named multiply:

- -
function multiply(x, y) {
-   return x * y;
-} // there is no semicolon here
-
- -

A function expression of an anonymous function assigned to the variable multiply:

- -
var multiply = function(x, y) {
-   return x * y;
-};
-
- -

A function expression of a function named func_name assigned to the variable multiply:

- -
var multiply = function func_name(x, y) {
-   return x * y;
-};
-
- -

Differences

- -

All do approximately the same thing, with a few subtle differences:

- -

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

- -
var y = function x() {};
-alert(x); // throws an error
-
- -

The function name also appears when the function is serialized via Function's toString method.

- -

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.

- -

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

- -

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

- -
function anonymous() {
-}
-
- -

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

- -
var foo = new Function("alert(anonymous);");
-foo();
-
- -

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

- -
foo(); // alerts FOO!
-function foo() {
-   alert('FOO!');
-}
-
- -

A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

- -

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

- -

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

- -
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
-foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
- -

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

- -
    -
  • becomes part of an expression
  • -
  • is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body:
  • -
- -
var x = 0;               // source element
-if (x == 0) {            // source element
-   x = 10;               // not a source element
-   function boo() {}     // not a source element
-}
-function foo() {         // source element
-   var y = 20;           // source element
-   function bar() {}     // source element
-   while (y == 10) {     // source element
-      function blah() {} // not a source element
-      y++;               // not a source element
-   }
-}
-
- -

Examples

- -
// function declaration
-function foo() {}
-
-// function expression
-(function bar() {})
-
-// function expression
-x = function hello() {}
-
-
-if (x) {
-   // function expression
-   function world() {}
-}
-
-
-// function declaration
-function a() {
-   // function declaration
-   function b() {}
-   if (0) {
-      // function expression
-      function c() {}
-   }
-}
-
- -

Block-level functions

- -

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

- -
'use strict';
-
-function f() {
-  return 1;
-}
-
-{
-  function f() {
-    return 2;
-  }
-}
-
-f() === 1; // true
-
-// f() === 2 in non-strict mode
-
- -

Block-level functions in non-strict code

- -

In a word: Don't.

- -

In non-strict code, function declarations inside blocks behave strangely. For example:

- -
if (shouldDefineZero) {
-   function zero() {     // DANGER: compatibility risk
-      console.log("This is zero.");
-   }
-}
-
- -

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

- -

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

- -

A safer way to define functions conditionally is to assign a function expression to a variable:

- -
var zero;
-if (0) {
-   zero = function() {
-      console.log("This is zero.");
-   };
-}
-
- -

Examples

- -

Returning a formatted number

- -

The following function returns a string containing the formatted representation of a number padded with leading zeros.

- -
// This function returns a string padded with leading zeros
-function padZeros(num, totalLen) {
-   var numStr = num.toString();             // Initialize return value as string
-   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
-   for (var i = 1; i <= numZeros; i++) {
-      numStr = "0" + numStr;
-   }
-   return numStr;
-}
-
- -

The following statements call the padZeros function.

- -
var result;
-result = padZeros(42,4); // returns "0042"
-result = padZeros(42,2); // returns "42"
-result = padZeros(5,4);  // returns "0005"
-
- -

Determining whether a function exists

- -

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

- -
 if ('function' == typeof window.noFunc) {
-   // use noFunc()
- } else {
-   // do something else
- }
-
- -

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator functions39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow functions{{CompatChrome(45.0)}}{{CompatGeckoDesktop("22.0")}}{{CompatNo}}{{CompatOpera(32)}}10
Block-level functions{{CompatUnknown}}{{CompatGeckoDesktop("46.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator functions{{CompatUnknown}}39{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow functions{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Block-level functions{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("46.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- -
    -
  • {{jsxref("Statements/function", "function statement")}}
  • -
  • {{jsxref("Operators/function", "function expression")}}
  • -
  • {{jsxref("Statements/function*", "function* statement")}}
  • -
  • {{jsxref("Operators/function*", "function* expression")}}
  • -
  • {{jsxref("Function")}}
  • -
  • {{jsxref("GeneratorFunction")}}
  • -
  • {{jsxref("Functions/Arrow_functions", "Arrow functions")}}
  • -
  • {{jsxref("Functions/Default_parameters", "Default parameters")}}
  • -
  • {{jsxref("Functions/rest_parameters", "Rest parameters")}}
  • -
  • {{jsxref("Functions/arguments", "Arguments object")}}
  • -
  • {{jsxref("Functions/get", "getter")}}
  • -
  • {{jsxref("Functions/set", "setter")}}
  • -
  • {{jsxref("Functions/Method_definitions", "Method definitions")}}
  • -
  • Functions and function scope
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/concat/index.html b/files/vi/web/javascript/reference/global_objects/array/concat/index.html deleted file mode 100644 index f19a1b981b..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/concat/index.html +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Array.prototype.concat() -slug: Web/JavaScript/Reference/Global_Objects/Array/concat -translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat ---- -
{{JSRef}}
- -

Phương thức concat() dùng để kết nối 2 hay nhiều mảng với nhau. Phương thức này  không làm thay đổi các mảng đã có mà thay vào đó sẽ trả về 1 mảng mới.

- -
{{EmbedInteractiveExample("pages/js/array-concat.html")}}
- - - -

Cú pháp

- -
var newArray = oldArray.concat(value1[, value2[, ...[, valueN]]])
- -

Tham số

- -
-
valueN
-
Các giá trị hay mảng dùng để nối lại với nhau trong mảng mới .
-
- -

Giá trị trả về

- -

Một mảng {{jsxref("Array")}} mới.

- -

Mô tả

- -

Phương thức concat tạo ra 1 mảng mới bao gồm các phần tử trong đối tượng mà nó được gọi thực thi, và theo thứ tự lần lượt, với mỗi tham số truyền vào là các phần tử của tham số đó (nếu tham số truyền vào là 1 mảng) hoặc là chính tham số đó (nếu tham số truyền vào không  phải là 1 mảng). Phương thức này sẽ không thực thi 1 cách đệ quy cho các tham số là mảng lồng nhau.

- -

Phương thức concat không thay đổi this (mảng được gọi thực thi)  hay bất cứ mảng được truyền vào làm tham số mà thay vào đó nó sẽ trả về 1 bản sao tham chiếu (shallow copy) bao gồm các bản sao của cùng 1 phần tử được kết hợp từ các mảng ban đầu. Các phần từ của mảng ban đầu được sao chép vào mảng mới như sau: 

- -
    -
  • Đối với tham chiếu đối tượng (và không phải đối tượng thực tế): concat sao chép tham chiếu đối tượng vào mảng mới.  Cả mảng ban đầu và mảng mới đều tham chiếu tới cùng 1 đối tượng. Nghĩa là nếu đối tượng được tham chiếu tới bị thay đổi thì việc thay đổi đó sẽ ảnh hưởng trong cả mảng ban đầu và mảng mới. Điều này bao gồm các phần tử của các mảng làm tham số cũng đều là mảng. 
  • -
  • Đối với dữ liệu kiểu chuỗi(strings), số(numbers), và booleans (không phải là các đối tượng kiểu {{jsxref("Global_Objects/String", "String")}}, {{jsxref("Global_Objects/Number", "Number")}}, và {{jsxref("Global_Objects/Boolean", "Boolean")}}): concat sẽ sao chép giá trị của chuỗi, số vào mảng mới.
  • -
- -
-

Chú ý: Việc ghép nối các mảng hay giá trị sẽ không "đụng chạm" tới các giá trị ban đầu. Hơn nữa, bất cứ thao tác nào trên mảng trả về (ngoại trừ các thao tác trên các phần từ là tham chiếu đối tượng) sẽ không ảnh hưởng tới các mảng ban đầu, và ngược lại.

-
- -

Ví dụ

- -

Nối 2 mảng

- -

Đoạn mã dưới đây sẽ nối 2 mảng lại với nhau:

- -
var alpha = ['a', 'b', 'c'];
-var numeric = [1, 2, 3];
-
-alpha.concat(numeric);
-// result in ['a', 'b', 'c', 1, 2, 3]
-
- -

Nối 3 mảng

- -

Đoạn mã dưới đây sẽ nối 3 mảng lại với nhau

- -
var num1 = [1, 2, 3],
-    num2 = [4, 5, 6],
-    num3 = [7, 8, 9];
-
-var nums = num1.concat(num2, num3);
-
-console.log(nums);
-// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
-
- -

Nối các giá trị vào 1 mảng

- -

Đoạn mã sau đây sẽ nối 3 giá trị vào 1 mảng:

- -
var alpha = ['a', 'b', 'c'];
-
-var alphaNumeric = alpha.concat(1, [2, 3]);
-
-console.log(alphaNumeric);
-// results in ['a', 'b', 'c', 1, 2, 3]
-
- -

Nối mảng lồng nhau

- -

Đoạn mã sau đây sẽ nối các mảng lồng nhau và thể hiện sự lưu trữ tham chiếu:

- -
var num1 = [[1]];
-var num2 = [2, [3]];
-
-var nums = num1.concat(num2);
-
-console.log(nums);
-// results in [[1], 2, [3]]
-
-// modify the first element of num1
-num1[0].push(4);
-
-console.log(nums);
-// results in [[1, 4], 2, [3]]
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa lần đầu. Hiện thực trong 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')}} 
- -

Tương thích trình duyệt

- -
- - -

{{Compat("javascript.builtins.Array.concat")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.push", "push")}} / {{jsxref("Array.pop", "pop")}} — thêm/xóa phần tử từ cuối mảng
  • -
  • {{jsxref("Array.unshift", "unshift")}} / {{jsxref("Array.shift", "shift")}} — thêm/xóa các phần tử từ đầu mảng
  • -
  • {{jsxref("Array.splice", "splice")}} — thêm/xóa các phần tử tại vị trí xác định trong mảng
  • -
  • {{jsxref("String.prototype.concat()")}}
  • -
  • {{jsxref("Symbol.isConcatSpreadable")}} – control flattening.
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/copywithin/index.html b/files/vi/web/javascript/reference/global_objects/array/copywithin/index.html deleted file mode 100644 index fd216cbc54..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/copywithin/index.html +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: Array.prototype.copyWithin() -slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin -translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin ---- -
{{JSRef}}
- -

 copyWithin()  là một phương thức sao chép cạn một phần của mảng tới một vị trí khác trong mảng đó và trả về giá trị mà không thay đổi độ dài của mảng

- -
{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}
- - - -

Cú pháp

- -
arr.copyWithin(target[, start[, end]])
-
- -

Parameters

- -
-
target
-
Zero-based index at which to copy the sequence to. If negative, target will be counted from the end.
-
If target is at or greater than arr.length, nothing will be copied. If target is positioned after start, the copied sequence will be trimmed to fit arr.length.
-
start {{optional_inline}}
-
Zero-based index at which to start copying elements from. If negative, start will be counted from the end.
-
If start is omitted, copyWithin will copy from index 0
-
end {{optional_inline}}
-
Zero-based index at which to end copying elements from. copyWithin copies up to but not including end. If negative, end will be counted from the end.
-
If end is omitted, copyWithin will copy until the last index (default to arr.length).
-
- -

Return value

- -

The modified array.

- -

Description

- -

The copyWithin works like C and C++'s memmove, and is a high-performance method to shift the data of an {{jsxref("Array")}}. This especially applies to the {{jsxref("TypedArray/copyWithin", "TypedArray")}} method of the same name. The sequence is copied and pasted as one operation; pasted sequence will have the copied values even when the copy and paste region overlap.

- -

The copyWithin function is intentionally generic, it does not require that its this value be an {{jsxref("Array")}} object.

- -

The copyWithin method is a mutable method. It does not alter the length of this, but it will change its content and create new properties, if necessary.

- -

Polyfill

- -
if (!Array.prototype.copyWithin) {
-  Object.defineProperty(Array.prototype, 'copyWithin', {
-    value: 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;
-  },
-  configurable: true,
-  writable: true
-  });
-}
- -

Examples

- -

Using copyWithin

- -
[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 Typed Arrays are subclasses of Array
-var i32a = new Int32Array([1, 2, 3, 4, 5])
-
-i32a.copyWithin(0, 2)
-// Int32Array [3, 4, 5, 4, 5]
-
-// On platforms that are not yet ES2015 compliant:
-[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
-// Int32Array [4, 2, 3, 4, 5]
-
- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.copyWithin")}}

-
- -

See also

- -
    -
  • {{jsxref("Array")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/entries/index.html b/files/vi/web/javascript/reference/global_objects/array/entries/index.html deleted file mode 100644 index 6be2131071..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/entries/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Array.prototype.entries() -slug: Web/JavaScript/Reference/Global_Objects/Array/entries -translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries ---- -
{{JSRef}}
- -

Phương thức entries() trả về một mảng đối tượng Array Iterator chứa cặp key/value cho mỗi chỉ mục trong mảng.

- -
{{EmbedInteractiveExample("pages/js/array-entries.html")}}
- - - -

Syntax

- -
array.entries()
- -

Return value

- -

Một {{jsxref("Array")}} đối tượng iterator.

- -

Examples

- -

Iterating with index and element

- -
const a = ['a', 'b', 'c'];
-
-for (const [index, element] of a.entries())
-  console.log(index, element);
-
-// 0 'a'
-// 1 'b'
-// 2 'c'
-
- -

Using a for…of loop

- -
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')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.entries")}}

-
- -

See also

- -
    -
  • {{jsxref("Array.prototype.keys()")}}
  • -
  • {{jsxref("Array.prototype.values()")}}
  • -
  • {{jsxref("Array.prototype.forEach()")}}
  • -
  • {{jsxref("Array.prototype.every()")}}
  • -
  • {{jsxref("Array.prototype.some()")}}
  • -
  • for...of
  • -
  • Iteration protocols
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/every/index.html b/files/vi/web/javascript/reference/global_objects/array/every/index.html deleted file mode 100644 index efeaa2deca..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/every/index.html +++ /dev/null @@ -1,236 +0,0 @@ ---- -title: Array.prototype.every() -slug: Web/JavaScript/Reference/Global_Objects/Array/every -translation_of: Web/JavaScript/Reference/Global_Objects/Array/every ---- -
{{JSRef}}
- -

Phương thức every() sẽ kiểm tra xem mọi phần tử bên trong một array được truyền vào có vượt qua được bài kiểm tra khi thực hiện với function được cung cấp không. every() sẽ return về một kết quả Boolean.

- -
{{EmbedInteractiveExample("pages/js/array-every.html","shorter")}}
- - - -

Cú pháp

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

Parameters

- -
-
callback
-
Một function với chức năng là kiểm tra từng phần tử trong mảng được cung cấp cho every(), nhận vào 3 đối số: -
-
element
-
Là phần tử hiện tại của mảng đang được function xử lý.
-
index {{Optional_inline}}
-
Index của phần tử trên.
-
array {{Optional_inline}}
-
Mảng mà every() gọi.
-
-
-
thisArg {{Optional_inline}}
-
A value to use as this when executing callback.
-
- -

Return value

- -

true if the callback function returns a truthy value for every array element. Otherwise, false.

- -

Description

- -

The every method executes the provided callback function once for each element present in the array until it finds the one where callback returns a falsy value. If such an element is found, the every method immediately returns false. Otherwise, if callback returns a truthy value for all elements, every returns true.

- -
-

Caution: Calling this method on an empty array will return true for any condition!

-
- -

callback is invoked only for array indexes which have assigned values. It is not invoked for indexes which have been deleted, or which have never been assigned values.

- -

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

- -

If a thisArg parameter is provided to every, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value.  The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

- -

every does not mutate the array on which it is called.

- -

The range of elements processed by every is set before the first invocation of callback. Therefore, callback will not run on elements that are appended to the array after the call to every begins. If existing elements of the array are changed, their value as passed to callback will be the value at the time every visits them. Elements that are deleted are not visited.

- -

every acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true. (It is vacuously true that all elements of the empty set satisfy any given condition.)

- -

Polyfill

- -

every was added to the ECMA-262 standard in the 5th edition, and it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of every in implementations which do not natively support it.

- -

This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object and TypeError have their original values, and that callbackfn.call evaluates to the original value of {{jsxref("Function.prototype.call")}}.

- -
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' && Object.prototype.toString.call(callbackfn) !== '[object 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) {
-        var testResult;
-        // 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 if T is not undefined
-        // else is the result of calling callbackfn
-        // and argument list containing kValue, k, and O.
-        if(T) testResult = callbackfn.call(T, kValue, k, O);
-        else testResult = callbackfn(kValue,k,O)
-
-        // iii. If ToBoolean(testResult) is false, return false.
-        if (!testResult) {
-          return false;
-        }
-      }
-      k++;
-    }
-    return true;
-  };
-}
-
- -

Examples

- -

Testing size of all array elements

- -

The following example tests whether all elements in the array are bigger than 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
-
- -

Using arrow functions

- -

Arrow functions provide a shorter syntax for the same test.

- -
[12, 5, 8, 130, 44].every(x => x >= 10);   // false
-[12, 54, 18, 130, 44].every(x => x >= 10); // true​
- -

Affecting Initial Array (modifying, appending, and deleting)

- -

The following examples tests the behaviour of the every method when the array is modified.

- -
// ---------------
-// Modifying items
-// ---------------
-let arr = [1, 2, 3, 4];
-arr.every( (elem, index, arr) => {
-  arr[index+1] -= 1
-  console.log(`[${arr}][${index}] -> ${elem}`)
-  return elem < 2
-})
-
-// Loop runs for 3 iterations, but would
-// have run 2 iterations without any modification
-//
-// 1st iteration: [1,1,3,4][0] -> 1
-// 2nd iteration: [1,1,2,4][1] -> 1
-// 3rd iteration: [1,1,2,3][2] -> 2
-
-// ---------------
-// Appending items
-// ---------------
-arr = [1, 2, 3];
-arr.every( (elem, index, arr) => {
-  arr.push('new')
-  console.log(`[${arr}][${index}] -> ${elem}`)
-  return elem < 4
-})
-
-// Loop runs for 3 iterations, even after appending new items
-//
-// 1st iteration: [1, 2, 3, new][0] -> 1
-// 2nd iteration: [1, 2, 3, new, new][1] -> 2
-// 3rd iteration: [1, 2, 3, new, new, new][2] -> 3
-
-// ---------------
-// Deleting items
-// ---------------
-arr = [1, 2, 3, 4];
-arr.every( (elem, index, arr) => {
-  arr.pop()
-  console.log(`[${arr}][${index}] -> ${elem}`)
-  return elem < 4
-})
-
-// Loop runs for 2 iterations only, as the remaining
-// items are `pop()`ed off
-//
-// 1st iteration: [1,2,3][0] -> 1
-// 2nd iteration: [1,2][1] -> 2
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.every")}}

-
- -

See also

- -
    -
  • {{jsxref("Array.prototype.forEach()")}}
  • -
  • {{jsxref("Array.prototype.some()")}}
  • -
  • {{jsxref("Array.prototype.find()")}}
  • -
  • {{jsxref("TypedArray.prototype.every()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/fill/index.html b/files/vi/web/javascript/reference/global_objects/array/fill/index.html deleted file mode 100644 index e7e8201c46..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/fill/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: Array.prototype.fill() -slug: Web/JavaScript/Reference/Global_Objects/Array/fill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill ---- -
{{JSRef}}
- -

Phương thức fill() điền (sửa đổi) tất cả các phần tử của một mảng từ một chỉ mục bắt đầu (số không mặc định) đến một chỉ mục kết thúc (độ dài mảng mặc định) với một giá trị tĩnh. Nó trả về mảng đã sửa đổi

- -
{{EmbedInteractiveExample("pages/js/array-fill.html")}}
- - - -

Syntax

- -
arr.fill(value[, start[, end]])
-
- -

Parameters

- -
-
value
-
Value to fill an array.
-
start {{optional_inline}}
-
Start index, defaults to 0.
-
end {{optional_inline}}
-
End index, defaults to this.length.
-
- -

Return value

- -

The modified array.

- -

Description

- -

The fill method takes up to three arguments value, start and end. The start and end arguments are optional with default values of 0 and the length of the this object.

- -

If start is negative, it is treated as length+start where length is the length of the array. If end is negative, it is treated as length+end.

- -

fill is intentionally generic, it does not require that its this value be an Array object.

- -

fill is a mutable method, it will change this object itself, and return it, not just return a copy of it.

- -

When fill gets passed an object, it will copy the reference and fill the array with references to that object.

- -

Examples

- -
[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" }]
-
- -

Polyfill

- -
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;
-    }
-  });
-}
-
- -

If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable.

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
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')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.fill")}}

-
- -

See also

- -
    -
  • {{jsxref("Array")}}
  • -
  • {{jsxref("TypedArray.prototype.fill()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/filter/index.html b/files/vi/web/javascript/reference/global_objects/array/filter/index.html deleted file mode 100644 index 900c22a1ac..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/filter/index.html +++ /dev/null @@ -1,232 +0,0 @@ ---- -title: Array.prototype.filter() -slug: Web/JavaScript/Reference/Global_Objects/Array/filter -translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter ---- -
{{JSRef}}
- -

Phương thức filter() dùng để tạo một mảng mới với tất cả các phần tử thỏa điều kiện của một hàm test.

- -
{{EmbedInteractiveExample("pages/js/array-filter.html")}}
- - - -

Cú pháp

- -
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
- -

Tham số

- -
-
callback
-
Đây là hàm thử, dùng để kiểm tra từng phần tử của mảng.  Trả về true để giữ lại phần tử, hoặc false để loại nó ra. Nó được gọi với ba tham số:
-
-
-
element
-
Phần tử đang được xử lý trong mảng.
-
index{{optional_inline}}
-
Chỉ mục (index) của phần tử đang được xử lý.
-
array{{optional_inline}}
-
Mảng nguồn mà hàm filter đang xử lý.
-
-
-
thisArg {{optional_inline}}
-
Không bắt buộc. Giá trị của this bên trong hàm callback.
-
- -

Giá trị trả về

- -

Một mảng mới với các phần tử đã thỏa điều kiện của hàm test. Nếu không có phần tử nào thỏa điều kiện, một mảng rỗng sẽ được trả về.

- -

Mô tả

- -

filter() sẽ thực thi hàm callback trên từng phần tử của mảng, và xây dựng một mảng mới với các phần tử mà giá trị trả về của callback nếu ép kiểu sẽ mang giá trị true. callback chỉ được thực thi tại những chỉ mục (index) của mảng mà chúng được gán giá trị; nó không được thực thi tại chỉ mục đã bị xóa hoặc chưa từng được gán giá trị. Những phần tử không thỏa điều kiện tại hàm thử callback sẽ bị bỏ qua, không được cho vào mảng mới.

- -

callback được gọi với ba tham số:

- -
    -
  1. giá trị của phần tử
  2. -
  3. chỉ mục (index) của phần tử
  4. -
  5. mảng ban đầu mà hàm thử đang được gọi lên
  6. -
- -

Nếu tham số thisArg được truyền cho hàm filter, nó sẽ được thay vào giá trị của từ khóa this trong hàm callback. Nếu không, giá trị undefined sẽ được dùng cho this. Tóm lại, giá trị của từ khóa this trong hàm callback được xác định tuân theo các quy tắc thông thường để xác định this trong một hàm.

- -

filter() không làm thay đổi mảng mà nó được gọi.

- -

Các phần tử được filter() chạy qua được xác định từ đầu trước khi callback được gọi lần đầu tiên. Những phần tử mới được thêm vào sau khi filter() bắt đầu chạy sẽ không được truyền vào callback. Trong lúc filter() đang chạy, nếu những phần tử hiện tại của mảng bị thay đổi, thì giá trị của chúng khi được truyền cho callback  là giá trị tại thời điểm filter() chạy qua; những phần tử đã xóa sẽ bị bỏ qua.

- -

Ví dụ

- -

Lọc bỏ các giá trị nhỏ

- -

Ví dụ sau sẽ dùng filter() để tạo một mảng lọc không có các phần tử nào nhỏ hơn 10.

- -
function isBigEnough(value) {
-  return value >= 10;
-}
-
-var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
-// filtered is [12, 130, 44]
-
- -

Lọc các giá trị không hợp lệ khỏi JSON

- -

Ví dụ sau sẽ dùng hàm filter() để lọc lại các phần tử của JSON chỉ chứa id có giá trị số và khác 0.

- -
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
-
- -

Tìm kiếm trong mảng

- -

Ví dụ sau dùng filter() để lọc ra phần tử có nội dung thỏa chuỗi tìm kiếm

- -
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
-
-/**
- * Array filters items based on search criteria (query)
- */
-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']
- -

Ví dụ ở trên với ES2015

- -
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
-
-/**
- * Array filters items based on search criteria (query)
- */
-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']
-
-
- -

Polyfill

- -

filter() chỉ được thêm vào đặc tả ECMA-262 phiên bản thứ 5; cho nên nó có thể không tồn tại trong một số hiện thực (implementation) của đặc tả. Bạn có thể xoay sở bằng cách thêm vào đoạn code bên dưới vào đầu script của bạn, cho phép sử dụng filter() tại những nơi mà nó không được hỗ trợ sẵn. Giải thuật trong hàm polyfill này chính xác với đặc tả trong ECMA-262, 5th edition, với yêu cầu fn.call trả về giá trị ban đầu của {{jsxref("Function.prototype.bind()")}}, và {{jsxref("Array.prototype.push()")}} không bị thay đổi.

- -
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;
-  };
-}
- -

 

- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}Định nghĩa lần đầu. Được hiện thực trong JavaScript 1.6.
{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}} 
- -

Tương thích trình duyệt

- -
- - -

{{Compat("javascript.builtins.Array.filter")}}

-
- -

Tương tự

- -
    -
  • {{jsxref("Array.prototype.forEach()")}}
  • -
  • {{jsxref("Array.prototype.every()")}}
  • -
  • {{jsxref("Array.prototype.some()")}}
  • -
  • {{jsxref("Array.prototype.reduce()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/find/index.html b/files/vi/web/javascript/reference/global_objects/array/find/index.html deleted file mode 100644 index ba4631a924..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/find/index.html +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Array.prototype.find() -slug: Web/JavaScript/Reference/Global_Objects/Array/find -translation_of: Web/JavaScript/Reference/Global_Objects/Array/find ---- -
{{JSRef}}
- -

Phương thức find() sẽ trả về giá trị đầu tiên tìm thấy ở trong mảng được cung cấp. Hoặc có thể trả về {{jsxref("undefined")}} .

- -
{{EmbedInteractiveExample("pages/js/array-find.html")}}
- - - -

Xem thêm phương thức {{jsxref("Array.findIndex", "findIndex()")}} , sẽ trả về index của phần tử tìm thấy trong mảng thay vì giá trị của nó.

- -

Nếu bạn muốn tìm vị trí của phần tử hoặc tìm phần tử đó có tồn tại trong mảng hay không, hãy thử sử dụng  {{jsxref("Array.prototype.indexOf()")}} or {{jsxref("Array.prototype.includes()")}}.

- -

Cú Pháp

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

Parameters ( thông số đầu vào )

- -
-
callback
-
Hàm thực thi với mỗi giá trị trong mảng, chuyền vào 3 giá trị : -
-
element
-
Phần tử hiện tại đang được xử lý trong mảng.
-
index {{optional_inline}}
-
Thứ tự của phần tử hiện tại đang được xử lý trong mảng..
-
array {{optional_inline}}
-
Mảng được gọi.
-
-
-
thisArg {{optional_inline}}
-
Đối tượng tùy chọn để sử dụng như thế này khi thực hiện callback.
-
- -

Return value ( giá trị trả về )

- -

Giá trị ( value ) của phần tử đầu tiên ( first element ) trong mảng thỏa mãn chức năng kiểm tra được cung cấp. Nếu không, sẽ trả về {{jsxref("undefined")}}.

- -

Mô Tả

- -

Phương thức find thực thi hàm  callback với mỗi giá trị trong mảng cho đến khi tìm được giá trị mà hàm callback trả về giá trị. Nếu phần tử đó được tìm thấy, phương thức find sẽ trả về giá trị của phần tử đó. Nếu không tìm thấy, find sẽ trả về {{jsxref("undefined")}}. callback được gọi cho mọi index có trong mảng từ 0 đếnlength - 1 và cho tất cả các indexes, không chỉ những giá trị đã được gán. Điều này chỉ ra rằng nó có thể kém hiệu quả hơn so với các phương thức khác chỉ truy cập các indexes có giá trị được gán.

- -

callback được gọi với ba arguments: giá trị của phần tử ( the value of the element ), biến đếm của phần tử ( the index of the element ) và đối tượng mảng cần tìm ( the Array object being traversed ).

- -

Nếu thisArg tham số ( parameter ) cung cấp cho phương thức find, nó sẽ được sử dụng như là giá trị this cho mỗi lần gọi callback. Nếu không được cung cấp tham số, thì {{jsxref("undefined")}} sẽ được thay thế.

- -

Phương thức find sẽ không làm thay đổi mảng mà nó được gọi hoặc sử dụng.

- -

Phạm vi của các phần tử được xử lý bởi find sẽ được gán trước ghi gọi hàm callback. Vì thế, callback sẽ không truy cập các phần tử được gắn vào mảng sau khi phương thức find được bắt đầu. Các phần tử bị xóa vẫn có thể truy cập được.

- -

Ví Dụ

- -

Tìm một đối tượng trong một mảng bằng một trong các thuộc tính

- -
const inventory = [
-    {name: 'apples', quantity: 2},
-    {name: 'bananas', quantity: 0},
-    {name: 'cherries', quantity: 5}
-];
-
-function isCherries(fruit) {
-    return fruit.name === 'cherries';
-}
-
-console.log(inventory.find(isCherries));
-// { name: 'cherries', quantity: 5 }
- -

Sử dụng arrow function ( 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 }
- -

Tìm số nguyên tố trong mảng

- -

Theo ví dụ sau đây tìm thấy một phần tử trong mảng là số nguyên tố (hoặc sẽ trả về {{jsxref("undefined")}} nếu trong mảng không có số nguyên tố nào).

- -
function isPrime(element, index, array) {
-  let 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
-
- -

Ví dụ sau đây cho thấy các phần tử không tồn tại và bị xóa vẫn được truy cập và giá trị được chuyển cho callback lại là giá trị của chúng khi được truy cập.

- -
// Declare array with no element at index 2, 3 and 4
-const array = [0,1,,,,5,6];
-
-// Shows all indexes, not just those that have been assigned values
-array.find(function(value, index) {
-  console.log('Visited index ' + index + ' with value ' + value);
-});
-
-// Shows all indexes, including deleted
-array.find(function(value, index) {
-
-  // Delete element 5 on first iteration
-  if (index == 0) {
-    console.log('Deleting array[5] with value ' + array[5]);
-    delete array[5];
-  }
-  // Element 5 is still visited even though deleted
-  console.log('Visited index ' + index + ' with value ' + value);
-});
-// expected output:
-// Deleting array[5] with value 5
-// Visited index 0 with value 0
-// Visited index 1 with value 1
-// Visited index 2 with value undefined
-// Visited index 3 with value undefined
-// Visited index 4 with value undefined
-// Visited index 5 with value undefined
-// Visited index 6 with value 6
-
- -

Polyfill

- -

Phương pháp này đã được thêm vào ECMAScript 2015 và có thể không có sẵn trong tất cả các phiên bản JavaScript. Tuy nhiên, bạn có thể sử dụng Array.prototype.find với cú pháp :

- -
// 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
-  });
-}
-
-
- -

Đặc Điểm

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ESDraft')}}
- -

Tính Tương Thích Với Trình Duyệt Web

- -
- - -

{{Compat("javascript.builtins.Array.find")}}

-
- -

Những Phương Thức Liên Quan

- -
    -
  • {{jsxref("Array.prototype.findIndex()")}} – find and return an index
  • -
  • {{jsxref("Array.prototype.includes()")}} – test whether a value exists in the array
  • -
  • {{jsxref("Array.prototype.filter()")}} – find all matching elements
  • -
  • {{jsxref("Array.prototype.every()")}} – test all elements together
  • -
  • {{jsxref("Array.prototype.some()")}} – test at least one element
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/findindex/index.html b/files/vi/web/javascript/reference/global_objects/array/findindex/index.html deleted file mode 100644 index 3c8d822f07..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/findindex/index.html +++ /dev/null @@ -1,207 +0,0 @@ ---- -title: Array.prototype.findIndex() -slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex -translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex ---- -
{{JSRef}}
- -

Phương thức findIndex() trả về chỉ số (index) của phần tử đầu tiên trong mảng thỏa mãn hàm truyền vào. Nếu không phần tử nào thỏa mãn, phương thức trả lại -1.

- -
function isBigEnough(element) {
-  return element >= 15;
-}
-
-[12, 5, 8, 130, 44].findIndex(isBigEnough); // Trả về 3, phần tử thứ 4.
- -

Xem thêm phương thức {{jsxref("Array.find", "find()")}}, trả về giá trị (value) của phần tử được tìm thấy thay vì chỉ số.

- -

Cú pháp

- -
arr.findIndex(callback[, thisArg])
- -

Tham số

- -
-
callback
-
Hàm kiểm tra, được thực thi cho mỗi phần tử của mảng, có thể chứa 3 tham số: -
-
element
-
Phần tử đang xét.
-
index
-
Chỉ số của phần tử đang xét.
-
array
-
Mảng được gọi.
-
-
-
thisArg
-
Optional. Object to use as this when executing callback.
-
- -

Giá trị trả về

- -

Một chỉ số của mảng nếu tìm được phần tử đầu tiên thỏa mãn hàm kiểm tra; otherwise, -1.

- -

Mô tả

- -

Phương thức findIndex thực thi hàm callback từng lần cho toàn bộ chỉ số mảng từ  0..length-1 (bao gồm hai nút) trong mảng cho tới khi tìm thấy chỉ số mà phần tử tại đó làm cho callback trả về một giá trị đúng (a value that coerces to true). Nếu một phần tử được tìm thấy, findIndex lập tức trả về chỉ số của phần tử này. Nếu hàm callback luôn nhận giá trị không đúng hoặc số phần tử của mảng bằng 0, findIndex trả về -1. Không giống như cách phương thức về mảng khác như Array#some, trong mảng thưa thớt hàm callback được gọi là ngay cả đối với các chỉ mục của mục không có trong mảng đó.

- -

callback được gọi với 3 đối số: giá trị của phần tử, chỉ số của phần tử, và mảng đang được xét.

- -

Nếu tham số thisArg được đưa vào findIndex, Nó sẽ được sử dụng như là this cho mỗi lần gọi callback. Nếu nó không được đưa vào, thì {{jsxref("undefined")}} sẽ được sử dụng.

- -

findIndex không làm thay đổi mảng mà nó được gọi.

- -

The range of elements processed by findIndex is set before the first invocation of callback. Elements that are appended to the array after the call to findIndex begins will not be visited by callback. If an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that findIndex visits that element's index; elements that are deleted are not visited.

- -

Ví dụ

- -

Tìm chỉ số của một số nguyên tố trong mảng

- -

Ví dụ dưới đây tìm chỉ số của một phần tử trong mảng mà là số nguyên tố (trả về -1 nếu không tìm thấy).

- -
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
-
- -

Polyfill

- -
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
-if (!Array.prototype.findIndex) {
-  Object.defineProperty(Array.prototype, 'findIndex', {
-    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 k.
-        var kValue = o[k];
-        if (predicate.call(thisArg, kValue, k, o)) {
-          return k;
-        }
-        // e. Increase k by 1.
-        k++;
-      }
-
-      // 7. Return -1.
-      return -1;
-    }
-  });
-}
-
- -

If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable.

- -

Các thông số

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.findindex', 'Array.prototype.findIndex')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}{{Spec2('ESDraft')}} 
- -

Tương thích trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatChrome(45.0)}}{{CompatGeckoDesktop("25.0")}}{{CompatNo}}YesYes{{CompatSafari("7.1")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25.0")}}{{CompatNo}}{{CompatNo}}8.0
-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.find()")}}
  • -
  • {{jsxref("Array.prototype.indexOf()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/flat/index.html b/files/vi/web/javascript/reference/global_objects/array/flat/index.html deleted file mode 100644 index 065a92a7a5..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/flat/index.html +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: Array.prototype.flat() -slug: Web/JavaScript/Reference/Global_Objects/Array/flat -tags: - - Array - - JavaScript - - Method - - Prototype - - Reference - - flat -translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat ---- -
{{JSRef}}
- -
Phương thức flat()  trả về một mảng mới. Trong đó, tất cả các phần tử của mảng con được gán ngược vào nó bằng  cách đệ quy lên đến độ sâu đã chỉ định.
- - - -

{{EmbedInteractiveExample("pages/js/array-flat.html")}}

- - - -

Syntax

- -
var newArray = arr.flat([depth]);
- -

Parameters

- -
-
depth {{optional_inline}}
-
Chỉ định độ sâu của mảng kết quả cuối cùng. Mặc định là 1
-
- -

Return value

- -

Một mảng mới với các phần tử của mảng con được nối với nó.

- -

Alternatives

- -

reduce and concat

- -
const arr = [1, 2, [3, 4]];
-
-// Trả về mảng chỉ có 1 level
-arr.flat();
-
-// Nó ngang với việc sử dụng reduce
-arr.reduce((acc, val) => acc.concat(val), []);
-// [1, 2, 3, 4]
-
-// hoặc decomposition syntax
-const flattened = arr => [].concat(...arr);
-
- -

reduce + concat + isArray + recursivity

- -
const arr = [1, 2, [3, 4, [5, 6]]];
-
-// ?Sử dụng reduce, concat và deep level
-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]
-
- -

Use a stack

- -
// Sử dụng stack để đệ quy không cần báo deep level
-
-function flatten(input) {
-  const stack = [...input];
-  const res = [];
-  while(stack.length) {
-    // Lấy gía trị ra khỏi stack
-    const next = stack.pop();
-    if(Array.isArray(next)) {
-      // Gán trở lại arry, không thay đổi giá trị của item đó
-      stack.push(...next);
-    } else {
-      res.push(next);
-    }
-  }
-  // Đảo ngược array để trả về đúng order ban đầu
-  return res.reverse();
-}
-
-const arr = [1, 2, [3, 4, [5, 6]]];
-flatten(arr);
-// [1, 2, 3, 4, 5, 6]
-
- -

Use Generator function

- -
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]
-
- - - -

Examples

- -

Flattening nested arrays

- -
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]
-
- -

Flattening and array holes

- -

The flat method removes empty slots in arrays:

- -
const arr5 = [1, 2, , 4, 5];
-arr5.flat();
-// [1, 2, 4, 5]
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-array.prototype.flat', 'Array.prototype.flat')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.flat")}}

-
- -

See also

- -
    -
  • {{jsxref("Array.prototype.flatMap()")}}
  • -
  • {{jsxref("Array.prototype.map()")}}
  • -
  • {{jsxref("Array.prototype.reduce()")}}
  • -
  • {{jsxref("Array.prototype.concat()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/foreach/index.html b/files/vi/web/javascript/reference/global_objects/array/foreach/index.html deleted file mode 100644 index 6121f40a83..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/foreach/index.html +++ /dev/null @@ -1,303 +0,0 @@ ---- -title: Array.prototype.forEach() -slug: Web/JavaScript/Reference/Global_Objects/Array/forEach -translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach ---- -
{{JSRef}}
- -

Phương thức forEach() sẽ thực thi một hàm khi duyệt qua từng phần tử của mảng.

- -
{{EmbedInteractiveExample("pages/js/array-foreach.html")}}
- - - -

Cú pháp

- -
arr.forEach(function callback(currentValue[, index[, array]]) {
-    //your iterator
-}[, thisArg]);
- -

Parameters

- -
-
callback
-
Hàm sẽ thực thi lên từng phần tử của mảng được gọi, hàm này nhận 3 tham số: -
-
currentValue{{optional_inline}}
-
Giá trị của phần tử đang được duyệt.
-
index{{optional_inline}}
-
Chỉ mục của phần tử đang được duyệt.
-
array{{optional_inline}}
-
Mảng mà hàm forEach() đang duyệt.
-
-
-
thisArg {{Optional_inline}}
-
-

Giá trị được gán cho từ khóa this bên trong hàm callback khi được thực thi.

-
-
- -

Giá trị trả về

- -

{{jsxref("undefined")}}.

- -

Mô tả chi tiết

- -

forEach() thực thi hàm callback trong lúc duyệt tới từng phần tử của mảng theo thứ tự tăng dần. Nó sẽ không được gọi cho vị trí index đã bị xóa hoặc không được khởi tạo (đối với mảng thưa - sparse arrays).

- -

callback được gọi với 3 tham số:

- -
    -
  • giá trị của phần tử
  • -
  • index của phần tử
  • -
  • mảng đang được duyệt
  • -
- -

Nếu tham số thisArg được truyền vào cho forEach(), nó sẽ được dùng cho từ khóa this trong hàm callback. Nếu không, giá trị {{jsxref("undefined")}} sẽ được dùng cho từ khóa this. Tóm lại, giá trị của từ khóa this trong hàm callback được xác định tuân theo các quy tắc thông thường để xác định this trong một hàm.

- -

Khoảng các phần tử được xử lý bởi forEach() được thiết lập trước lần gọi đầu tiên của callback. Phần tử được thêm vào mảng sau khi gọi forEach() sẽ không được callback bắt gặp. Nếu giá trị của các phần tử sẵn có trong mảng thay đổi, thì giá trị truyền vào callback sẽ là giá trị lúc forEach() gặp chúng; phần tử bị xoá trước khi bắt gặp sẽ không tính. Nếu phần tử đã gặp rồi bị loại đi (ví dụ dùng {{jsxref("Array.prototype.shift()", "shift()")}}) trong quá trình lặp, các phần tử sau sẽ bị bỏ qua - xem ví dụ phía dưới.

- -

forEach() executes the callback function once for each array element; unlike {{jsxref("Array.prototype.map()", "map()")}} or {{jsxref("Array.prototype.reduce()", "reduce()")}} it always returns the value {{jsxref("undefined")}} and is not chainable. The typical use case is to execute side effects at the end of a chain.

- -

forEach() does not mutate the array on which it is called (although callback, if invoked, may do so).

- -
-

Khác với cú pháp lặp truyền thống, không có cách nào để ngừng vòng lặp forEach ngoài việc ném ra một ngoại lệ. Nếu vì một mục đích nào đó mà bạn cần ngừng vòng lặp thì nên dùng cách khác thay vì dùng forEach

- -

Một số cách có thể dùng trong trường hợp đó:

- -
    -
  • Vòng lặp for đơn giản
  • -
  • Vòng lặp for...of 
  • -
  • {{jsxref("Array.prototype.every()")}}
  • -
  • {{jsxref("Array.prototype.some()")}}
  • -
  • {{jsxref("Array.prototype.find()")}}
  • -
  • {{jsxref("Array.prototype.findIndex()")}}
  • -
- -

Một số hàm khác trên kiểu mảng: {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, and {{jsxref("Array.prototype.findIndex()", "findIndex()")}} test the array elements with a predicate returning a truthy value to determine if further iteration is required.

-
- -

Ví dụ

- -

Converting a for loop to forEach

- -

before

- -
const items = ['item1', 'item2', 'item3'];
-const copy = [];
-
-for (let i=0; i<items.length; i++) {
-  copy.push(items[i])
-}
-
- -

after

- -
const items = ['item1', 'item2', 'item3'];
-const copy = [];
-
-items.forEach(function(item){
-  copy.push(item)
-});
-
-
- -

Printing the contents of an array

- -

The following code logs a line for each element in an array:

- -
function logArrayElements(element, index, array) {
-  console.log('a[' + index + '] = ' + element);
-}
-
-// Notice that index 2 is skipped since there is no item at
-// that position in the array.
-[2, 5, , 9].forEach(logArrayElements);
-// logs:
-// a[0] = 2
-// a[1] = 5
-// a[3] = 9
-
- -

Using thisArg

- -

The following (contrived) example updates an object's properties from each entry in the array:

- -
function Counter() {
-  this.sum = 0;
-  this.count = 0;
-}
-Counter.prototype.add = function(array) {
-  array.forEach(function(entry) {
-    this.sum += entry;
-    ++this.count;
-  }, this);
-  // ^---- Note
-};
-
-const obj = new Counter();
-obj.add([2, 5, 9]);
-obj.count;
-// 3
-obj.sum;
-// 16
-
- -

Since the thisArg parameter (this) is provided to forEach(), it is passed to callback each time it's invoked, for use as its this value.

- -
-

If passing the function argument using an arrow function expression the thisArg parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.

-
- -

An object copy function

- -

The following code creates a copy of a given object. There are different ways to create a copy of an object; the following is just one way and is presented to explain how Array.prototype.forEach() works by using ECMAScript 5 Object.* meta property functions.

- -
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
-
- -

If the array is modified during iteration, other elements might be skipped.

- -

The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. forEach() does not make a copy of the array before iterating.

- -
var words = ['one', 'two', 'three', 'four'];
-words.forEach(function(word) {
-  console.log(word);
-  if (word === 'two') {
-    words.shift();
-  }
-});
-// one
-// two
-// four
-
- -

Polyfill

- -

forEach() was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of forEach() in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that callback.call() evaluates to the original value of {{jsxref("Function.prototype.call()")}}.

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.18
-// Reference: http://es5.github.io/#x15.4.4.18
-if (!Array.prototype.forEach) {
-
-  Array.prototype.forEach = function(callback/*, thisArg*/) {
-
-    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(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 = arguments[1];
-    }
-
-    // 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. Call the Call internal method of callback with T as
-        // the this value and argument list containing kValue, k, and O.
-        callback.call(T, kValue, k, O);
-      }
-      // d. Increase k by 1.
-      k++;
-    }
-    // 8. return undefined.
-  };
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}{{Spec2('ESDraft')}}
- -

Trình duyệt tương thích

- -
- - -

{{Compat("javascript.builtins.Array.forEach")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.find()")}}
  • -
  • {{jsxref("Array.prototype.findIndex()")}}
  • -
  • {{jsxref("Array.prototype.map()")}}
  • -
  • {{jsxref("Array.prototype.every()")}}
  • -
  • {{jsxref("Array.prototype.some()")}}
  • -
  • {{jsxref("Map.prototype.forEach()")}}
  • -
  • {{jsxref("Set.prototype.forEach()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/from/index.html b/files/vi/web/javascript/reference/global_objects/array/from/index.html deleted file mode 100644 index cee1cc84f7..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/from/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: Array.from() -slug: Web/JavaScript/Reference/Global_Objects/Array/from -tags: - - Array - - ECMAScript 2015 - - JavaScript - - Phương Thức - - Tham khảo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/from ---- -
{{JSRef}}
- -

Phương thức Array.from() tạo ra một thực thể Array mới được sao chép cạn (shallow-copied) từ các đối tượng giống mảng hoặc các đối tượng khả duyệt.

- -
{{EmbedInteractiveExample("pages/js/array-from.html")}}
- - - -

Cú pháp

- -
Array.from(arrayLike[, mapFn[, thisArg]])
-
- -

Tham số

- -
-
arrayLike
-
Đối tượng có tính chất giống mảng hoặc khả duyệt
-
mapFn{{Optional_inline}}
-
Hàm Map được gọi khi thực thi trên từng phần tử.
-
thisArg{{Optional_inline}}
-
Giá trị được sử dụng như this, thường là tham chiếu đến phạm vi của đối tượng gọi hàm mapFn.
-
- -

Giá trị trả về

- -

Một thực thể {{jsxref("Array")}} mới.

- -

Mô tả

- -

Array.from() cho phép tạo Array từ:

- -
    -
  • Các đối tượng giống mảng (một đối tượng giống mảng sẽ có thuộc tính mô tả chiều dài length  và các phần tử được đánh chỉ mục) 
  • -
  • iterable objects  - đối tượng khả duyệt (là các đối tượng mà các phần tử của nó có thể được duyệt ví dụ như {{jsxref("Map")}} và  {{jsxref("Set")}}).
  • -
- -

Array.from() còn cung cấp thêm một tham số tuỳ chọn là mapFn, vốn là một hàm được tự động thực thi khi duyệt qua từng phần tử của {{jsxref("Array.prototype.map", "map")}}. Điểm khác biệt quan trọng của Array.from(obj, mapFn, thisArg) so với Array.from(obj).map(mapFn, thisArg) là nó không tạo ra mảng trung gian. Đây là điểm quan trọng cho các mảng kế thừa như typed arrays vì mảng trung gian nhất thiết sẽ có các giá trị được cắt ngắn để vừa với loại thích hợp.

- -

Thuộc tính length của phương thức from() là 1.

- -

Với ES2015 thì cú pháp class cho phép kế thừa từ cả các lớp có sẵn hoặc do người dùng định nghĩa, tất nhiên kể cả các phương thức tĩnh như Array.from cũng được kế thừa trong subclass, và kết quả trả về của from trong subclass là thực thể của subclass, không phải Array.

- -

Ví dụ

- -

Tạo mảng từ chuỗi

- -
Array.from('foo');
-// ["f", "o", "o"]
- -

Tạo mảng từ tập hợp Set

- -
var s = new Set(['foo', window]);
-Array.from(s);
-// ["foo", window]
- -

Tạo mảng từ một Map

- -
var m = new Map([[1, 2], [2, 4], [4, 8]]);
-Array.from(m);
-// [[1, 2], [2, 4], [4, 8]]
-
-var mapper = new Map([['1', 'a'], ['2', 'b']]);
-Array.from(mapper.values());
-// ['a', 'b'];
-
-Array.from(mapper.keys());
-// ['1', '2'];
-
- -

Tạo mảng từ một đối tượng có tính chất giống mảng (arguments)

- -
function f() {
-  return Array.from(arguments);
-}
-
-f(1, 2, 3);
-
-// [1, 2, 3]
- -

Hàm arrow trong 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]
-
- -

Polyfill

- -

Array.from đã được thêm vào tiêu chuẩn ECMA-262 trong ấn bản thứ 6 (ES2015); như vậy nó có thể không có mặt trong các bản hiện thực khác của ECMA-262 khác. Bạn có thể giải quyết vấn đề này bằng cách chèn đoạn mã sau vào đầu các đoạn mã JavaScript cho phép sử dụng Array.from trong các bản thực thi không hỗ trợ Array.from.

- -
// 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;
-    };
-  }());
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-array.from', 'Array.from')}}{{Spec2('ES2015')}}Khởi tạo.
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- -
- - -

{{Compat("javascript.builtins.Array.from")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array")}}
  • -
  • {{jsxref("Array.prototype.map()")}}
  • -
  • {{jsxref("TypedArray.from()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/includes/index.html b/files/vi/web/javascript/reference/global_objects/array/includes/index.html deleted file mode 100644 index bc4b1980f4..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/includes/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Array.prototype.includes() -slug: Web/JavaScript/Reference/Global_Objects/Array/includes -tags: - - JavaScript - - Mảng - - Phương Thức - - Pollyfill - - Prototype - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes ---- -
{{JSRef}}
- -

Phương thức includes() kiểm tra xem phần tử đã cho có tồn tại trong mảng hay không, trả về kết quả true hoặc false.

- -
{{EmbedInteractiveExample("pages/js/array-includes.html")}}
- - - -

Cú pháp

- -
arr.includes(valueToFind[, fromIndex])
-
- -

Các tham số

- -
-
valueToFind
-
-

Giá trị muốn kiểm tra.

- -
-

Lưu ý: Khi kiểm tra chuỗi hoặc kí tự, includes() sẽ phân biệt hoa thường.

-
-
-
fromIndex {{optional_inline}}
-
Vị trí trong mảng để bắt đầu tìm kiếm valueToFind; đầu tìm kiếm tại fromIndex khi fromIndex mang giá trị dương, hoặc tại array.length + fromIndex khi fromIndex  mang giá trị âm (sử dụng {{interwiki("wikipedia", "absolute value", "giá trị tuyệt đối")}} của fromIndex làm số lượng kí tự tính từ cuối mảng làm vị trí bắt đầu). Giá trị mặc định là 0.
-
- -

Giá trị trả về

- -

Có kiểu {{jsxref("Boolean")}}, trả về true nếu valueToFind được tìm thấy trong mảng (hoặc một phần của mảng được xác định bởi fromIndex nếu có). Các giá trị "không" được coi là bằng nhau (-0 sẽ bằng 0 và +0), nhưng false thì không bằng 0.

- -
-

Lưu ý: Về mặt kĩ thuật, includes() sử dụng thuật toán sameValueZero để kiểm tra phần tử đã cho có tìm thấy hay không.

-
- -

Ví dụ

- -
[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 lớn hơn hoặc bằng độ dài mảng

- -

Nếu fromIndex lớn hơn hoặc bằng độ dài mảng, trả về kết quả false

- -
var arr = ['a', 'b', 'c'];
-
-arr.includes('c', 3);   // false
-arr.includes('c', 100); // false
- -

Computed index nhỏ hơn 0

- -

Nếu fromIndex là số âm, computed index sẽ được dùng làm vị trí bắt đầu để tìm kiếm valueToFind. Nếu computed index nhỏ hơn hoặc bằng -1 * array.length, phần tử đã cho sẽ được tìm kiếm trong toàn bộ mảng (tương tự như fromIndex bằng 0).

- -
// độ dài mảng là 3
-// fromIndex là -100
-// computed index là 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() used as a generic method

- -

includes() method is intentionally generic. It does not require this value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). The example below illustrates includes() method called on the function's arguments object.

- -
(function() {
-  console.log([].includes.call(arguments, 'a')); // true
-  console.log([].includes.call(arguments, 'd')); // false
-})('a','b','c');
- - - -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ESDraft')}}
{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ES7')}}Initial definition.
- -

Khả năng tương thích của trình duyệt

- -
- - -

{{Compat("javascript.builtins.Array.includes")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("TypedArray.prototype.includes()")}}
  • -
  • {{jsxref("String.prototype.includes()")}}
  • -
  • {{jsxref("Array.prototype.indexOf()")}}
  • -
  • {{jsxref("Array.prototype.find()")}}
  • -
  • {{jsxref("Array.prototype.findIndex()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/index.html b/files/vi/web/javascript/reference/global_objects/array/index.html deleted file mode 100644 index 151242e596..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/index.html +++ /dev/null @@ -1,433 +0,0 @@ ---- -title: Array -slug: Web/JavaScript/Reference/Global_Objects/Array -tags: - - Array - - JavaScript -translation_of: Web/JavaScript/Reference/Global_Objects/Array ---- -
{{JSRef}}
- -

Đối tượng Array trong JavaScript là đối tượng toàn cục được dùng để xây dựng nên các mảng; là những đối tượng cấp cao và giống một dạng danh sách.

- -

Tạo một Mảng

- -
var fruits = ['Apple', 'Banana'];
-
-console.log(fruits.length);
-// 2
-
- -

Truy cập (bằng chỉ mục) đến một phần tử của Mảng

- -
var first = fruits[0];
-// Apple
-
-var last = fruits[fruits.length - 1];
-// Banana
-
- -

Lặp qua một Mảng

- -
fruits.forEach(function(item, index, array) {
-  console.log(item, index);
-});
-// Apple 0
-// Banana 1
-
- -

Thêm phần tử vào cuối Mảng

- -
var newLength = fruits.push('Orange');
-// ["Apple", "Banana", "Orange"]
-
- -

Xóa phần tử từ cuối Mảng

- -
var last = fruits.pop(); // xoá bỏ Orange (từ vị trí cuối)
-// ["Apple", "Banana"];
-
- -

Xóa phần tử từ đầu Mảng

- -
var first = fruits.shift(); // xoá bỏ Apple từ vị trí đầu
-// ["Banana"];
-
- -

Thêm phần tử vào đầu Mảng

- -
var newLength = fruits.unshift('Strawberry') // thêm vào vị trí đầu
-// ["Strawberry", "Banana"];
-
- -

Tìm chỉ mục của một phần tử trong Mảng

- -
fruits.push('Mango');
-// ["Strawberry", "Banana", "Mango"]
-
-var pos = fruits.indexOf('Banana');
-// 1
-
- -

Xóa một phần tử bằng chỉ mục của nó

- -
var removedItem = fruits.splice(pos, 1); // đây là cách để xoá bỏ một phần tử
-
-// ["Strawberry", "Mango"]
- -

Xóa các phần tử bắt đầu từ vị trí của chỉ mục

- -
var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
-console.log(vegetables);
-// ["Cabbage", "Turnip", "Radish", "Carrot"]
-
-var pos = 1, n = 2;
-
-var removedItems = vegetables.splice(pos, n);
-// đây là cách để xoá các phần tử, n định nghĩa số phần tử cần xoá bỏ,
-// từ vị trí đó (pos) trở đi đến cuối mảng.
-
-console.log(vegetables);
-// ["Cabbage", "Carrot"] (mảng ban đầu đã bị thay đổi)
-
-console.log(removedItems);
-// ["Turnip", "Radish"]
- -

Sao chép một Mảng

- -
var shallowCopy = fruits.slice(); // đây là cách để tạo một bản sao
-// ["Strawberry"]
-
- -

Cú pháp

- -
[ element0 , element1 , ..., elementN ]
-new Array(element0 , element1 [, ... [, elementN ]])
-new Array(arrayLength)
- -
-
nguyên tố N
-
Một mảng JavaScript được khởi tạo với các yếu tố nhất định, ngoại trừ trong trường hợp một đối số duy nhất được truyền vào mảng xây dựng và lập luận đó là một con số. (Xem bên dưới). Lưu ý rằng trường hợp đặc biệt này chỉ áp dụng cho các mảng JavaScript tạo ra với các mảng xây dựng, không mảng literals tạo ra với cú pháp khung.
-
arrayLength
-
Nếu đối số duy nhất được truyền cho các mảng constructor là một số nguyên giữa 0 và 2 32 -1 (bao gồm), điều này trả về một mảng JavaScript mới với chiều dài thiết lập để con số đó. Nếu đối số là số nào khác, một {{jsxref ("Global_Objects / RangeError", "RangeError")}} ngoại lệ được ném ra.
-
- -

Miêu tả

- -

Mảng là đối tượng danh sách giống như nguyên mẫu mà có phương pháp để thực hiện traversal và đột biến hoạt động. Cả chiều dài của một mảng JavaScript hay các loại của các yếu tố của nó được cố định. Vì chiều dài kích thước của một mảng lớn hoặc thu nhỏ bất cứ lúc nào, các mảng JavaScript là không đảm bảo được dày đặc. Nói chung, đây là những đặc điểm thuận tiện; nhưng nếu các tính năng này không được mong muốn sử dụng cụ thể của bạn, bạn có thể xem xét sử dụng các mảng gõ.

- -

Một số người nghĩ rằng bạn không nên sử dụng một mảng như là một mảng kết hợp . Trong mọi trường hợp, bạn có thể sử dụng đồng bằng {{jsxref ("Global_Objects / Object", "đối tượng")}} thay vào đó, mặc dù làm như vậy đi kèm với hãy cẩn thận của mình. Xem các bài viết từ điển JavaScript nhẹ với các phím tùy ý như là một ví dụ.

- -

Truy cập vào các phần tử mảng

- -

Mảng JavaScript được zero-lập chỉ mục: phần tử đầu tiên của mảng là lúc chỉ số 0 , và các yếu tố cuối cùng là chỉ số tương đương với giá trị của của mảng {{jsxref ("Array.length", "chiều dài")}} tài sản trừ đi 1.

- -
var arr = ['đây là yếu tố đầu tiên "," đây là yếu tố thứ hai'];
-console.log(arr[0]); // Nhật ký này là yếu tố đầu tiên '
-console.log(arr[1]); // Nhật ký này là yếu tố thứ hai '
-console.log(arr[arr.length - 1]); // Nhật ký này là yếu tố thứ hai '
-
- -

Các phần tử mảng là thuộc tính đối tượng trong cùng một cách mà toString là một thuộc tính, nhưng cố gắng để truy cập vào một phần tử của mảng như sau ném một lỗi cú pháp, bởi vì tên sở hữu là không hợp lệ:

- -
console.log(arr.0); // Một lỗi cú pháp
-
- -

Có gì đặc biệt về mảng JavaScript và các thuộc tính gây ra điều này là. Tính JavaScript bắt đầu bằng một chữ số không thể được tham chiếu với ký hiệu dấu chấm; và phải được truy cập bằng cách sử dụng ký hiệu khung. Ví dụ, nếu bạn đã có một đối tượng với một thuộc tính có tên '3D' , nó chỉ có thể được tham chiếu bằng cách sử dụng ký hiệu khung. Ví dụ như:

- -
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
-console.log(years.0); // Một lỗi cú pháp
-console.log(years[0]); // Đúng cú pháp
-
- -
renderer.3d.setTexture (model, 'character.png'); // Một lỗi cú pháp
-renderer['3D']setTexture (model, 'character.png.'); // Đúng cú pháp
-
- -

Lưu ý rằng trong ví dụ 3d , '3D' đã được trích dẫn. Có thể trích dẫn các chỉ số mảng JavaScript cũng như (ví dụ, năm ['2'] thay vì năm [2] ), mặc dù nó không cần thiết. 2 trong năm [2] là bị cưỡng chế vào một chuỗi các công cụ JavaScript thông qua một tiềm ẩn toString chuyển đổi. Chính vì lý do này mà '2''02' sẽ chỉ đến hai khe cắm khác nhau trên năm đối tượng và các ví dụ sau đây có thể là sự thật :

- -
console.log(years['2'] = years['02']!);
-
- -

Tương tự, thuộc tính đối tượng đó xảy ra để được dành riêng chỉ có thể được truy cập như các chuỗi trong ký hiệu khung:

- -
var promise = {
-  'Var': 'text',
-  'Array': [1, 2, 3, 4]
-};
-
-console.log(promise['Array']);
-
- -

Mối quan hệ giữa chiều dài và số thuộc tính

- -

Một mảng của JavaScript {{jsxref ("Array.length", "chiều dài")}} tài sản và tính toán được kết nối. Một số phương pháp mảng xây dựng trong (ví dụ, {{jsxref ("Array.join", "tham gia")}}, {{jsxref ("Array.slice", "lát cắt")}}, {{jsxref (" Array.indexOf "," indexOf ")}}, vv) có tính đến các giá trị của một mảng {{jsxref (" Array.length "," chiều dài ")}} tài sản khi chúng được gọi. Các phương pháp khác (ví dụ, {{jsxref ("Array.push", "đẩy")}}, {{jsxref ("Array.splice", "mối nối")}}, vv) cũng cho kết quả trong bản cập nhật tới một mảng của { {jsxref ("Array.length", "chiều dài")}} thuộc tính.

- -
var fruits = [];
-fruits.push('banana', 'apple', 'peach');
-
-console.log(fruits.length); // 3
- -

Khi thiết lập một thuộc tính trên một mảng JavaScript khi tài sản là một chỉ số mảng hợp lệ và chỉ số đó là ngoài giới hạn hiện tại của mảng, engine sẽ cập nhật thuộc tính {{jsxref ("Array.length", "chiều dài")}} của mảng cho phù hợp:

- -
fruits[5] = 'mango';
-console.log(fruits[5]); // 'mango'
-console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
-console.log(fruits.length); // 6
- -

Tăng {{jsxref ("Array.length", "chiều dài")}}.

- -
fruits.length = 10;
-console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
-console.log(fruits.length); // 10
-
- -

Giảm thuộc tính {{jsxref ("Array.length", "chiều dài")}} , tuy nhiên, xóa các phần tử.

- -
fruits.length = 2;
-console.log(Object.keys(fruits)); // ['0', '1']
-console.log(fruits.length); // 2
-
- -

Điều này được giải thích thêm về {{jsxref ("Array.length")}} trang.

- -

Tạo một mảng bằng cách sử dụng kết quả của một trận đấu

- -

Kết quả của một trận đấu giữa một biểu hiện thường xuyên và một chuỗi có thể tạo ra một mảng JavaScript. Mảng này có các tính chất và các yếu tố trong đó cung cấp thông tin về trận đấu. Một mảng đó được trả về bởi {{jsxref ("RegExp.exec")}}, {{jsxref ("String.match")}} và {{jsxref ("string.Replace")}}. Để giúp giải thích các thuộc tính và các yếu tố, nhìn vào ví dụ sau đây và sau đó tham khảo bảng dưới đây:

- -
// Trận đấu một d theo sau bởi một hoặc nhiều b theo sau bởi một d
-// Ghi phù hợp của b và d sau
-// Bỏ qua trường hợp
-
-var Myre = / d (b +) (d) / i;
-var myArray = myRe.exec('cdbBdbsbz');
-
- -

Các tính chất và các yếu tố trở về từ trận đấu này như sau:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Bất động sản / tửMiêu tảThí dụ
đầu vàoMột thuộc tính chỉ đọc phản ánh các chuỗi ban đầu dựa vào đó các biểu thức chính quy được kết hợp.cdbBdbsbz
mục lụcMột thuộc tính chỉ đọc mà là chỉ số không dựa trên các trận đấu trong chuỗi.1
[0]Một yếu tố chỉ đọc mà xác định các ký tự tương ứng cuối cùng.dbBd
[1], ... [n]Chỉ đọc các yếu tố đó chỉ định các trận đấu substring parenthesized, nếu có trong các biểu hiện thường xuyên. Số lượng các chuỗi con trong ngoặc có thể là không giới hạn.[1]: bB
- [2]: d
- -

Thuộc tính

- -
-
{{Jsxref ("Array.length")}}
-
Thuộc tính chiều dài của Array trong constructor (hàm dựng) có giá trị là 1.
-
{{Jsxref ("Array.prototype")}}
-
Cho phép bổ sung các thuộc tính cho tất cả các đối tượng mảng.
-
- -

Phương thức

- -
-
{{Jsxref ("Array.from()")}} {{experimental_inline}}
-
Tạo ra một Mảng mới từ một đối tượng giống mảng hoặc iterable.
-
{{Jsxref ("Array.isArray()")}}
-
Trả về true nếu một biến là một mảng, ngược lại false nếu không phải là mảng.
-
{{Jsxref ("Array.of()")}} {{experimental_inline}}
-
Tạo ra một Array mới với một số lượng các đối số, bất kể số hoặc loại của các đối số.
-
- -

Array instances

- -

Tất cả instance Array kế thừa từ {{jsxref ("Array.prototype")}}. Các đối tượng nguyên mẫu của Array constructor có thể được sửa đổi để ảnh hưởng đến tất cả các instance Array.

- -

Thuộc tính

- -
{{Page ('/ en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Properties')}}
- -

Phương thức

- -

Phương thức mutator

- -
{{Page ('en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Mutator_methods')}}
- -

Phương thức accessor

- -
{{Page ('en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Accessor_methods')}}
- -

Phương thức lặp đi lặp lại

- -
{{Page ('en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Iteration_methods')}}
- -

Array phương thức chung

- -

Đôi khi bạn muốn áp dụng phương thức mảng các chuỗi hoặc các đối tượng mảng giống khác (chẳng hạn như chức năng {{jsxref ("Chức năng / lập luận", "lý luận", "", 1)}}). Bằng cách này, bạn đối xử với một chuỗi như là một mảng kí tự (hoặc nếu không điều trị một phi mảng như là một mảng). Ví dụ, để kiểm tra xem tất cả các nhân vật trong biến str là một lá thư, bạn có thể viết:

- -
function isLetter (person) {
-  return person >= 'a' && person <= 'z';
-}
-
-if (Array.prototype.every.call (str, isLetter)) {
-  console.log("The string " + str + " contains only letters!");
-}
-
- -

Ký hiệu này là khá lãng phí và JavaScript 1.6 giới thiệu một cách viết tắt chung:

- -
if (Array.every (str, isLetter)) {
-  console.log("The string " + str + " contains only letters!");
-}
-
- -

{{Jsxref ("Global_Objects / String", "Generics", "#String_generic_methods", 1)}} cũng có sẵn trên {{jsxref ("Global_Objects / String", "String")}}.

- -

Đây không phải là một phần của tiêu chuẩn ECMAScript và chúng không được hỗ trợ bởi các trình duyệt không phải là Gecko. Như một thay thế tiêu chuẩn, bạn có thể chuyển đổi đối tượng của bạn thành một mảng bằng cách sử dụng ({{jsxref ("Array.from ()")}}, mặc dù phương pháp này có thể không được hỗ trợ trong các trình duyệt cũ:

- -
if (Array.from(str).every(isLetter)) {
-  console.log("The string " + str + " contains only letters!");
-}
- -

Ví dụ

- -

Tạo một mảng

- -

Ví dụ sau tạo một mảng, msgArray , với chiều dài 0, sau đó gán giá trị cho [0] msgArraymsgArray [99] , thay đổi độ dài của mảng đến 100.

- -
var msgArray = [];
-msgArray [0] = "Hello";
-msgArray [99] = 'World';
-
-if (msgArray.length === 100) {
-  console.log('Chiều dài là 100');
-}
-
- -

Tạo một mảng hai chiều

- -

Sau đây tạo ra một bàn cờ như là một mảng hai chiều của chuỗi. Động thái đầu tiên được thực hiện bằng cách sao chép 'p' trong (6,4) đến (4,4). Các vị trí cũ (6,4) được làm trống.

- -
var 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');
-
-// Di chuyển King's Pawn về phía trước 2
-board[4][4] = board[6][4];
-board[6][4] = ' ';
-console.log(board.join('\n'));
- -

Đây là kết quả:

- -
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
-
- -

Sử dụng một mảng để sắp xếp một tập các giá trị

- -
values = [];
-for (var x = 0; x < 10; x++){
- values.push([
-  2 ** x,
-  2 * x ** 2
- ])
-};
-console.table(values)
- -

Kết quả là:

- -
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
- -

(Cột đầu tiên là index (chỉ mục))

- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc điểm kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu.
{{SpecName("ES5.1", "#sec-15.4", "Array")}}{{Spec2("ES5.1")}}Phương thức mới được thêm vào: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf ")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array. prototype.forEach","forEach")}}, {{jsxref("Array.prototype.map","map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName("ES6", "#sec-array-objects", "Array")}}{{Spec2 ("ES6")}}Phương thức mới được thêm vào: {{jsxref ("Array.from")}}, {{jsxref ("Array.of")}}, {{jsxref ("Array.prototype.find", "find")}}, {{jsxref ("Array.prototype.findIndex", "findIndex")}}, {{jsxref ("Array.prototype.fill", "fill")}}, {{jsxref ("Array.prototype.copyWithin", "copyWithin")}}
- -

Khả năng tương thích trình duyệt

- -
{{Compat("javascript.builtins.Array")}}
- -
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/indexof/index.html b/files/vi/web/javascript/reference/global_objects/array/indexof/index.html deleted file mode 100644 index 1ac4ea6321..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/indexof/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: Array.prototype.indexOf() -slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf -translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf ---- -
{{JSRef}}
- -

Phương thức indexOf() sẽ trả về giá trị index đầu tiên của mảng, nơi mà nó đc tìm thấy trong mảng, hoặc trả về -1 nếu không tồn tại trong mảng.

- -
-

Chú ý: sử dụng indexOf() cho String, xem ở đây {{jsxref("String.prototype.indexOf()")}}.

-
- -
{{EmbedInteractiveExample("pages/js/array-indexof.html")}}
- - - -

Cú pháp

- -
arr.indexOf(searchElement[, fromIndex])
- -

Các tham số

- -
-
searchElement
-
Phần tử cần tìm trong mảng.
-
fromIndex {{optional_inline}}
-
Vị trí index nơi bắt đầu tìm kiếm. Nếu index lớn hơn hoặc bằng số phần tử trong mảng, -1 sẽ được trả về, việc tìm kiếm sẽ không xảy ra. Nếu giá trị fromIndex là một số âm, vị trí index được tính từ cuối mảng. Lưu ý: cho dù fromIndex là số âm, kết quả tìm kiếm vẫn tính từ đầu mảng trở về sau. Nếu index bằng 0, cả mảng sẽ được tìm kiếm. Mặc định: 0 (cả mảng sẽ được tìm kiếm)
-
- -

Giá trị trả về

- -

Index đầu tiên của phần tử tìm thấy trong mảng; -1 nếu không tìm thấy.

- -

Mô tả

- -

indexOf() sẽ so sánh giá trị searchElement với các phần tử của mảng sử dụng so sánh chặt (tương đương với việc so sánh toán tử ba-dấu-bằng ===)

- -

Ví dụ

- -

Sử dụng indexOf()

- -

Ví dụ sau sẽ dùng indexOf() để tìm vị trí của giá trị trong một mảng.

- -
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
-
- -

Tìm tất cả các lần xuất hiện của phần tử

- -
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]
-
- -

Xác định phần tử đã tồn tại trong mảng hay chưa và cập nhật lại mảng

- -
function updateVegetablesCollection (veggies, veggie) {
-    if (veggies.indexOf(veggie) === -1) {
-        veggies.push(veggie);
-        console.log('New veggies collection is : ' + veggies);
-    } else if (veggies.indexOf(veggie) > -1) {
-        console.log(veggie + ' already exists in the veggies collection.');
-    }
-}
-
-var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
-
-updateVegetablesCollection(veggies, 'spinach');
-// New veggies collection is : potato,tomato,chillies,green-pepper,spinach
-updateVegetablesCollection(veggies, 'spinach');
-// spinach already exists in the veggies collection.
-
- -

Polyfill

- -

indexOf() được thêm vào đặc tả ECMA-262, phiên bản 5; nên có thể nó không có sẵn trong tất cả trình duyệt. Bạn có thể work around bằng cách thêm vào đoạn code bên dưới vào đầu script. Polyfill này sẽ giúp bạn vẫn sử dụng được indexOf dù trình duyệt nào đó vẫn chưa hỗ trợ sẵn. Giải thuật của polyfill này tương đương với đặc tả của indexOf trong ECMA-262, 5th edition, với yêu cầu {{jsxref("Global_Objects/TypeError", "TypeError")}} và {{jsxref("Math.abs()")}} không bị thay đổi.
-  

- -
// This version tries to optimize by only checking for "in" when looking for undefined and
-// skipping the definitely fruitless NaN search. Other parts are merely cosmetic conciseness.
-// Whether it is actually faster remains to be seen.
-if (!Array.prototype.indexOf)
-  Array.prototype.indexOf = (function(Object, max, min) {
-    "use strict"
-    return function indexOf(member, fromIndex) {
-      if (this === null || this === undefined)
-        throw TypeError("Array.prototype.indexOf called on null or undefined")
-
-      var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len)
-      if (i < 0) i = max(0, Len + i)
-      else if (i >= Len) return -1
-
-      if (member === void 0) {        // undefined
-        for (; i !== Len; ++i) if (that[i] === void 0 && i in that) return i
-      } else if (member !== member) { // NaN
-        return -1 // Since NaN !== NaN, it will never be found. Fast-path it.
-      } else                          // all else
-        for (; i !== Len; ++i) if (that[i] === member) return i
-
-      return -1 // if the value was not found, then return -1
-    }
-  })(Object, Math.max, Math.min)
- -

Tuy nhiên, nếu bạn muốn hiểu rõ mọi chi tiết của đặc tả ECMA, và không mấy quan tâm đến performance hay cần phải ngắn gọn, thì bạn nên tham khảo đoạn polyfill bên dưới:

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.14
-// Reference: http://es5.github.io/#x15.4.4.14
-if (!Array.prototype.indexOf) {
-  Array.prototype.indexOf = function(searchElement, fromIndex) {
-
-    var k;
-
-    // 1. Let o be the result of calling ToObject passing
-    //    the this value as the argument.
-    if (this == null) {
-      throw new TypeError('"this" is null or not defined');
-    }
-
-    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 len is 0, return -1.
-    if (len === 0) {
-      return -1;
-    }
-
-    // 5. If argument fromIndex was passed let n be
-    //    ToInteger(fromIndex); else let n be 0.
-    var n = fromIndex | 0;
-
-    // 6. If n >= len, return -1.
-    if (n >= len) {
-      return -1;
-    }
-
-    // 7. If n >= 0, then Let k be n.
-    // 8. Else, n<0, Let k be len - abs(n).
-    //    If k is less than 0, then let k be 0.
-    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
-
-    // 9. Repeat, while k < len
-    while (k < len) {
-      // 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
-      //    i.  Let elementK be the result of calling the Get
-      //        internal method of o with the argument ToString(k).
-      //   ii.  Let same be the result of applying the
-      //        Strict Equality Comparison Algorithm to
-      //        searchElement and elementK.
-      //  iii.  If same is true, return k.
-      if (k in o && o[k] === searchElement) {
-        return k;
-      }
-      k++;
-    }
-    return -1;
-  };
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}{{Spec2('ES5.1')}}Định nghĩa lần đầu. Được hiện thực trong 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')}}
- -

Tương thích trình duyệt

- -
- - -

{{Compat("javascript.builtins.Array.indexOf")}}

-
- -

Lưu ý về tương thích

- -
    -
  • Kể từ Firefox 47 {{geckoRelease(47)}}, phương thức này không còn trả về -0. Ví dụ: [0].indexOf(0, -0) sẽ luôn trả về +0 ({{bug(1242043)}}).
  • -
- -

Tương tự

- -
    -
  • {{jsxref("Array.prototype.lastIndexOf()")}}
  • -
  • {{jsxref("TypedArray.prototype.indexOf()")}}
  • -
  • {{jsxref("String.prototype.indexOf()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/isarray/index.html b/files/vi/web/javascript/reference/global_objects/array/isarray/index.html deleted file mode 100644 index 9f34413842..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/isarray/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: Array.isArray() -slug: Web/JavaScript/Reference/Global_Objects/Array/isArray -tags: - - Array - - ECMAScript 5 - - JavaScript - - Phương Thức - - Tham khảo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray ---- -
{{JSRef}}
- -

Array.isArray() là một phương thức để xác định liệu giá trị truyền vào có phải là một mảng kiểu {{jsxref("Array")}}.

- -
Array.isArray([1, 2, 3]);  // true
-Array.isArray({foo: 123}); // false
-Array.isArray('foobar');   // false
-Array.isArray(undefined);  // false
-
- -

Cú pháp

- -
Array.isArray(value)
- -

Tham Số

- -
-
value
-
Giá trị được kiểm tra.
-
- -

Giá trị trả về

- -

true nếu giá trị là kiểu mảng {{jsxref("Array")}}; false nếu không phải mảng.

- -

Mô tả

- -

Nếu giá trị là {{jsxref("Array")}}, trả về true, nếu không thì trả về false.

- -

Xem bài viết “Determining with absolute accuracy whether or not a JavaScript object is an array” để có thêm chi tiết. Giả sử ta có một {{jsxref("TypedArray")}} instance, false sẽ luôn được trả về.

- -

Ví dụ

- -
// all following calls return true
-Array.isArray([]);
-Array.isArray([1]);
-Array.isArray(new Array());
-// Little known fact: Array.prototype itself is an array:
-Array.isArray(Array.prototype);
-
-// all following calls return 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

- -

Để kiểm tra kiểu Array, nên dùng Array.isArray hơn là instanceof bởi vì nó vẫn ra đúng khi giá trị kiểm tra được truyền qua iframes.

- -
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]
-
-// Correctly checking for Array
-Array.isArray(arr);  // true
-// Considered harmful, because doesn't work through iframes
-arr instanceof Array; // false
-
- -

Polyfill

- -

Chạy mã dưới đây đầu tiên trước các mã khác sẽ tạo Array.isArray() nếu nó không có sẵn.

- -
if (!Array.isArray) {
-  Array.isArray = function(arg) {
-    return Object.prototype.toString.call(arg) === '[object Array]';
-  };
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Định nghĩa lần đầu. Được hiện thực trong JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- -
- - -

{{Compat("javascript.builtins.Array.isArray")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/join/index.html b/files/vi/web/javascript/reference/global_objects/array/join/index.html deleted file mode 100644 index 12e5286a98..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/join/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Array.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/Array/join -tags: - - JavaScript - - Mảng - - Phương Thức - - Prototype - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/join ---- -
{{JSRef}}
- -

Phương thức join() tạo ra một chuỗi mới bằng cách nối tất cả các phần tử của mảng (hoặc một array-like object), ngăn cách chúng bởi dấu phẩy hoặc một chuỗi ký tự xác định. Nếu mảng chỉ có một phần tử, kết quả sẽ trả về chính phần tử đó.

- -
{{EmbedInteractiveExample("pages/js/array-join.html")}}
- - - -

Cú pháp

- -
arr.join([chuỗi_ngăn_cách])
- -

Các tham số

- -
-
chuỗi_ngăn_cách {{optional_inline}}
-
Là một chuỗi xác định dùng để ngăn cách các phần tử liền kề của mảng. Nếu bỏ qua, các phần tử sẽ được ngăn cách bởi dấu phẩy (","). Nếu là một chuỗi rỗng, các phần tử sẽ nối với nhau mà không có bất kì ký tự nào ngăn cách chúng.
-
- -

Giá trị trả về

- -

Trả về một chuỗi với giá trị là các phần tử đã được nối với nhau. Nếu arr.length bằng 0, sẽ trả về một chuỗi rỗng.

- -

Mô tả

- -

Chuyển giá trị của tất cả các phần tử mảng thành chuỗi và nối chúng lại thành một chuỗi.

- -
-

Nếu phần tử mảng là undefined hoặc null, sẽ trả về một chuỗi rỗng.

-
- -

Ví dụ

- -

Nối chuỗi với 4 cách khác nhau

- -

Tạo một mảng a với ba phần tử, sau đó nối chúng lại với 4 cách khác nhau: dùng chuỗi_ngăn_cách mặc định, với dấu phẩy và khoảng cách, với dấu cộng và một chuỗi rỗng.

- -
var a = ['Wind', 'Water', 'Fire'];
-a.join();      // 'Wind,Water,Fire'
-a.join(', ');  // 'Wind, Water, Fire'
-a.join(' + '); // 'Wind + Water + Fire'
-a.join('');    // 'WindWaterFire'
- -

Nối một array-like object

- -

Nối array-like object (arguments), bằng cách gọi {{jsxref("Function.prototype.call")}} Array.prototype.join.

- -
function f(a, b, c) {
-  var s = Array.prototype.join.call(arguments);
-  console.log(s); // '1,a,true'
-}
-f(1, 'a', true);
-//expected output: "1,a,true"
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Được đưa vào lần đầu trong 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')}}
{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ESDraft')}}
- -

Khả năng tương thích của trình duyệt

- - - -

{{Compat("javascript.builtins.Array.join")}}

- -

Xem thêm các mục tương tự

- -
    -
  • {{jsxref("String.prototype.split()")}}
  • -
  • {{jsxref("Array.prototype.toString()")}}
  • -
  • {{jsxref("TypedArray.prototype.join()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/map/index.html b/files/vi/web/javascript/reference/global_objects/array/map/index.html deleted file mode 100644 index fe3b6c1c37..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/map/index.html +++ /dev/null @@ -1,316 +0,0 @@ ---- -title: Array.prototype.map() -slug: Web/JavaScript/Reference/Global_Objects/Array/map -translation_of: Web/JavaScript/Reference/Global_Objects/Array/map ---- -
{{JSRef}}
- -

Phương thức map() giúp tạo ra một mảng mới với các phần tử là kết quả từ việc thực thi một hàm lên từng phần tử của mảng được gọi.

- -
{{EmbedInteractiveExample("pages/js/array-map.html")}}
- - - -

Cú pháp

- -
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
-    // Trả về element mới cho new_array
-}[, thisArg])
- -

Tham số

- -
-
callback
-
Hàm để tạo ra phần tử cho mảng mới, nhận vào ba tham số: -
-
 
-
currentValue
-
Giá trị của phần tử trong mảng đang được xử lý
-
index{{optional_inline}}
-
Index của phần tử trong mảng đang được xử lý
-
array{{optional_inline}}
-
Mảng đang được gọi với map
-
-
-
thisArg{{optional_inline}}
-
Giá trị gán cho từ khóa this bên trong callback.
-
- -

Giá trị trả về

- -

Một mảng mới với phần tử là kết quả của hàm callback.

- -

Mô tả

- -

map sẽ gọi hàm callback lên từng phần tử của mảng, theo thứ tự trong mảng, và tạo ra một mảng mới chứa các phần tử kết quả. callback chỉ được gọi cho những vị trí index của mảng được gán giá trị, bao gồm cả undefined. Nó không được gọi cho những vị trí index trống (là các index của mảng chưa bao giờ được khởi tạo, bao gồm index chưa được gán giá trị hoặc đã bị xóa bằng delete).

- -

callback được gọi với ba tham số: giá trị của phần tử, index của phần tử, và chính mảng đang được gọi.

- -

Nếu tham số thisArg được truyền cho map, nó sẽ được gán cho từ khóa this trong hàm callback. Nếu không, giá trị undefined sẽ được dùng cho this với strict mode. Tóm lại, giá trị của từ khóa this trong hàm callback được xác định tuân theo các quy tắc thông thường để xác định this trong một hàm.

- -

map không làm thay đổi mảng ban đầu mà nó được gọi (mặc dù mảng ban đầu vẫn có thể bị thay đổi trong hàm callback).

- -

Các phần tử được map() xử lý được xác định từ đầu trước khi callback được gọi lần đầu tiên. Những phần tử mới được thêm vào sau khi map đã bắt đầu chạy sẽ không được callback gọi đến. Trong lúc map đang chạy, nếu những phần tử hiện tại của mảng bị thay đổi, thì giá trị mới của chúng sẽ được truyền cho hàm callback ngay tại thời điểm callback chạy qua. Những phần tử bị xóa sau khi map đã bắt đầu và trước khi đến lượt nó cũng sẽ bị bỏ qua.

- -

Do thuật toán đã quy định trong đặc tả, nếu như mảng ban đầu đã có sẵn những lỗ trống (index rỗng) thì sau khi được gọi với map, mảng đầu ra cũng sẽ có những index rỗng như mảng ban đầu.

- -

Ví dụ

- -

Map (ánh xạ) một mảng các số thành một mảng các giá trị căn bậc hai

- -

Đoạn code sau sẽ map một mảng các số thành một mảng mới chứa giá trị là căn bậc hai của các số trong mảng ban đầu.

- -
var numbers = [1, 4, 9];
-var roots = numbers.map(Math.sqrt);
-// mảng roots: [1, 2, 3]
-// mảng numbers vẫn là: [1, 4, 9]
-
- -

Dùng map để format lại các object trong mảng

- -

Đoạn code sau sẽ xử lý một mảng các object và trả về một mảng mới chứa các object đã được format lại:

- -
var kvArray = [{key: 1, value: 10},
-               {key: 2, value: 20},
-               {key: 3, value: 30}];
-
-var reformattedArray = kvArray.map(obj =>{
-   var rObj = {};
-   rObj[obj.key] = obj.value;
-   return rObj;
-});
-// reformattedArray bây giờ là: [{1: 10}, {2: 20}, {3: 30}],
-
-// kvArray vẫn là:
-// [{key: 1, value: 10},
-//  {key: 2, value: 20},
-//  {key: 3, value: 30}]
-
- -

Map một mảng các số sử dụng hàm có tham số

- -

Đoạn code sau minh họa cách thức map hoạt động khi callback có sử dụng tham số. Tham số này sẽ có giá trị của từng phần tử của mảng ban đầu khi map duyệt qua mảng này.

- -
var numbers = [1, 4, 9];
-var doubles = numbers.map(function(num) {
-  return num * 2;
-});
-
-// doubles is now [2, 8, 18]
-// numbers is still [1, 4, 9]
-
- -

Sử dụng map một cách độc lập

- -

Ví dụ sau sẽ minh họa cách dùng map lên một {{jsxref("String")}} một cách độc lập để trả về một mảng các mã byte trong bảng ASCII đại diện cho từng ký tự của chuỗi.

- -
var map = Array.prototype.map;
-var a = map.call('Hello World', function(x) {
-  return x.charCodeAt(0);
-});
-// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
-
- -

Sử dụng map với kết quả của querySelectorAll

- -

Ví dụ sau minh họa cách duyệt qua một tập các object (không phải mảng) trả về từ querySelectorAll. Trong trường hợp này, chúng ta sẽ in ra giá trị của tất cả các option được chọn (của các thẻ select) lên console: 

- -
var elems = document.querySelectorAll('select option:checked');
-var values = Array.prototype.map.call(elems, function(obj) {
-  return obj.value;
-});
-
- -

Cách trên có thể được giải quyết đơn giản hơn bằng cách sử dụng {{jsxref("Array.from()")}}.

- -

Trường hợp đặc biệt

- -

(ý tưởng từ bài viết này)

- -

Chúng ta hay dùng map với hàm một tham số (tham số đó chính là phần tử được duyệt). Và có một số hàm đặc biệt cũng thường được gọi với một tham số, mặc dù chúng có thêm tham số phụ không bắt buộc. Những thói quen này có thể dẫn đến những kết quả ngoài dự đoán.

- -
// Lấy ví dụ:
-['1', '2', '3'].map(parseInt);
-// Bạn sẽ nghĩ rằng kết quả là [1, 2, 3]
-// Nhưng kết quả lại là [1, NaN, NaN]
-
-// parseInt thường được dùng với 1 tham số, nhưng nó có thể nhận đến 2 tham số.
-// Tham số thứ nhất là một biểu thức giá trị và tham số thứ hai là cơ số
-// Với hàm callback của Array.prototype.map, nó sẽ nhận vào 3 tham số:
-// phần tử, index, mảng ban đầu
-// Tham số thứ 3 sẽ được parseInt bỏ qua, nhưng tham số thứ 2 lại có vai trò
-// và sẽ dẫn đến kết quả không mong muốn.
-
-// Sau đây là kết quả thực thi tại từng phần tử:
-// parseInt(string, radix) -> map(parseInt(value, index))
-// lần chạy 1 (index là 0): parseInt('1', 0) // cho ta parseInt('1', 0) -> 1
-// lần chạy 2 (index là 1): parseInt('2', 1) // cho ta parseInt('2', 1) -> NaN
-// lần chạy 3 (index là 2): parseInt('3', 2) // cho ta parseInt('3', 2) -> NaN
-
-function returnInt(element) {
-  return parseInt(element, 10);
-}
-
-['1', '2', '3'].map(returnInt); // [1, 2, 3]
-// Thông qua hàm returnInt, kết quả trả về là mảng các số (như mong muốn)
-
-// Tương tự như trên, nhưng sử dụng một hàm arrow
-['1', '2', '3'].map( str => parseInt(str) );
-
-// Một cách nữa đơn giản hơn nhưng tránh được vấn đề hàm nhiều tham số:
-['1', '2', '3'].map(Number); // [1, 2, 3]
-// Tuy nhiên khác với `parseInt`, cách này sẽ giữ lại định dạng
-// số thập phân hoặc ký hiệu mũ từ chuỗi ban đầu
-['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]
-
- -

Một ví dụ khác khi gọi map với parseInt là tham số cho callback:

- -
var xs = ['10', '10', '10'];
-
-xs = xs.map(parseInt);
-
-console.log(xs);
-// Kết quả trả về là 10,NaN,2 như đã lý giải ở trên.
- -

Polyfill

- -

map() chỉ được thêm vào đặc tả ECMA-262 với phiên bản lần thứ 5; cho nên nó có thể không tồn tại trong một số hiện thực (implementation) của đặc tả. Bạn có thể work around bằng cách thêm vào đoạn code bên dưới vào đầu script của bạn, cho phép sử dụng hàm map tại những nơi mà nó không được hỗ trợ sẵn. Giải thuật trong polyfill này tương đương với hàm map được mô tả trong đặc tả ECMA-262, 5th edition với điều kiện {{jsxref("Object")}}, {{jsxref("TypeError")}}, và {{jsxref("Array")}} không bị thay đổi và callback.call chính là hàm được định nghĩa trong {{jsxref("Function.prototype.call")}}.

- -
-

Ghi chú bản dịch: những đoạn comment trong code bên dưới trích từ đặc tả ECMA nên sẽ giữ nguyên.

-
- -
// 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 = arguments[1];
-    }
-
-    // 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;
-  };
-}
-
- -

Đặc Tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}{{Spec2('ES5.1')}}Định nghĩa lần đầu. Hiện thực trong JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ESDraft')}} 
- -

Tương thích trình duyệt

- -
- - -

{{Compat("javascript.builtins.Array.map")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.forEach()")}}
  • -
  • {{jsxref("Map")}} object
  • -
  • {{jsxref("Array.from()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/of/index.html b/files/vi/web/javascript/reference/global_objects/array/of/index.html deleted file mode 100644 index fdd6d03d53..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/of/index.html +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Array.of() -slug: Web/JavaScript/Reference/Global_Objects/Array/of -translation_of: Web/JavaScript/Reference/Global_Objects/Array/of ---- -
{{JSRef}}
- -

Phương thức Array.of() được dùng để tạo ra một mảng mới với các phần tử được truyền vào thông qua tham số truyền vào.

- -

Cả Array.of()Array đều chấp nhận tham số đầu vào là các số nguyên để khởi tạo một mảng mới, tuy nhiên chúng ta cần lưu ý trong trường hợp chỉ truyền vào một giá trị nguyên,  Array.of() sẽ tạo ra một mảng số nguyên có một phần tử duy nhất, trong khi Array() ?sẽ tạo ra một mảng có số lượng phần tử rỗng (phần tử rỗng không mang giá trị undefined hoặc null)  tương ứng với giá trị số nguyên truyền vào.

- -
Array.of(7);       // [7]
-Array.of(1, 2, 3); // [1, 2, 3]
-
-Array(7);          // [ , , , , , , ]
-Array(1, 2, 3);    // [1, 2, 3]
-
- -

 Cú pháp

- -
Array.of(element0[, element1[, ...[, elementN]]])
- -

Tham số

- -
-
elementN
-
Các phần tử dùng để khởi tạo mảng
-
- -

Giá trị trả về

- -

Kết quả sau khi thực thi sẽ trả về một mảng mới

- -

Mô tả

- -

Đây là một phương thức chuẩncủa ECMAScript 2015. Có thể tham khảo thêm Array.of and Array.from proposal và Array.of polyfill.

- -

Ví dụ

- -
Array.of(1);         // [1]
-Array.of(1, 2, 3);   // [1, 2, 3]
-Array.of(undefined); // [undefined]
-
- -

Polyfill

- -

Nếu trình duyệt không hỗ trợ Array.of(), có thể gắn đoạn mã JS sau và thực thi nó trước tất cả các đoạn mã JS khác.

- -
if (!Array.of) {
-  Array.of = function() {
-    return Array.prototype.slice.call(arguments);
-  };
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích giữa các trình duyệt

- -
- - -

{{Compat("javascript.builtins.Array.of")}}

-
- -

Tham khảo thêm

- -
    -
  • {{jsxref("Array")}}
  • -
  • {{jsxref("Array.from()")}}
  • -
  • {{jsxref("TypedArray.of()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/pop/index.html b/files/vi/web/javascript/reference/global_objects/array/pop/index.html deleted file mode 100644 index b5740406a5..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/pop/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Array.prototype.pop() -slug: Web/JavaScript/Reference/Global_Objects/Array/pop -tags: - - JavaScript - - Mảng -translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop ---- -
{{JSRef}}
- -

Phương thức pop() xoá phần tử cuối cùng của một mảng và trả về phần tử đó. Phương thức này làm thay đổi độ dài của mảng.

- -
{{EmbedInteractiveExample("pages/js/array-pop.html")}}
- - - -

Cú pháp

- -
arr.pop()
- -

Giá trị trả về

- -

Phần tử bị xoá từ mảng; {{jsxref("undefined")}} nếu mảng rỗng.

- -

Mô tả

- -

The pop method removes the last element from an array and returns that value to the caller.
- Phương thức pop xoá phần tử cuối cùng của một mảng và trả về giá trị đó cho lời gọi.

- -

pop is intentionally generic; this method can be {{jsxref("Function.call", "called", "", 1)}} ?or {{jsxref("Function.apply", "applied", "", 1)}} to objects resembling arrays. 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.

- -

Nếu bạn gọi pop() trên một mảng rỗng, nó trả về {{jsxref("undefined")}}.

- -

Ví dụ

- -

Xoá phần tử cuối cùng của một mảng

- -

Đoạn mã sau tạo mảng myFish chứa 4 phần tử, sau đó xoá phần tử cuối cùng.

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-
-var popped = myFish.pop();
-
-console.log(myFish); // ['angel', 'clown', 'mandarin' ]
-
-console.log(popped); // 'sturgeon'
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tả?Trạng tháiGhi chú
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa lần đầu. Cài đặt trong 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')}} 
- -

Tương thích trình duyệt

- -
- - -

{{Compat("javascript.builtins.Array.pop")}}

-
- -

See also

- -
    -
  • {{jsxref("Array.prototype.push()")}}
  • -
  • {{jsxref("Array.prototype.shift()")}}
  • -
  • {{jsxref("Array.prototype.unshift()")}}
  • -
  • {{jsxref("Array.prototype.concat()")}}
  • -
  • {{jsxref("Array.prototype.splice()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/push/index.html b/files/vi/web/javascript/reference/global_objects/array/push/index.html deleted file mode 100644 index 2b3e6cca4d..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/push/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Array.prototype.push() -slug: Web/JavaScript/Reference/Global_Objects/Array/push -translation_of: Web/JavaScript/Reference/Global_Objects/Array/push ---- -
{{JSRef}}
- -

Phương thức push() giúp thêm 1 hay nhiều  phần tử vào cuối mảng và trả về chiều dài mới của mảng.

- -
{{EmbedInteractiveExample("pages/js/array-push.html")}}
- - - -

Cú pháp

- -
arr.push(element1[, ...[, elementN]])
- -

Tham số

- -
-
elementN
-
Các phần tử sẽ thêm vào cuối mảng.
-
- -

Giá trị trả về

- -

Giá trị mới của thuộc tính {{jsxref("Array.length", "length")}} của mảng mà phương thức được gọi thực thi.

- -

Mô tả

- -

Phương thức push giúp thêm các giá trị vào mảng.

- -

push là "intentionally generic". Phương thức này có thể được dùng với {{jsxref("Function.call", "call()")}} hoặc {{jsxref("Function.apply", "apply()")}} trên các đối tượng giống với mảng. Phương thức push phụ thuộc vào thuộc tính length để xác định vị trí bắt đầu thêm các giá trị mới. Nếu thuộc tính length không thể  convert thành số, vị trí bắt đầu sẽ là 0. Điều này cũng bao gồm cả trường hợp thuộc tính length không tồn tại, khi đó length sẽ được tạo.

- -

Các đối tượng tương tự mảng (array-like) như {{jsxref("Global_Objects/String", "strings", "", 1)}}, không thích hợp để áp dụng phương thức này, vì các chuỗi là bất biến.

- -

Ví dụ

- -

Thêm phần tử vào mảng

- -

Đoạn mã dưới đây tạo mảng sports gồm 2 phần tử, sau đó sẽ thêm 2 phần tử vào cuối mảng này. Biến total có giá trị là chiều dài mới của mảng.

- -
var sports = ['soccer', 'baseball'];
-var total = sports.push('football', 'swimming');
-
-console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
-console.log(total);  // 4
-
- -

Merge 2 mảng

- -

Ví dụ này sẽ sử dụng {{jsxref("Function.apply", "apply()")}} để thêm tất cả các phần tử từ mảng thứ 2 vào mảng đầu.

- -

Không sử dụng phương thức này nếu mảng thứ 2 (trong ví dụ này là moreVegs) quá lớn, vì số lượng tối đa các tham số mà 1  hàm có thể nhận là giới hạn. Xem thêm chi tiết {{jsxref("Function.apply", "apply()")}}.

- -
var vegetables = ['parsnip', 'potato'];
-var moreVegs = ['celery', 'beetroot'];
-
-// Merge the second array into the first one
-// Equivalent to vegetables.push('celery', 'beetroot');
-Array.prototype.push.apply(vegetables, moreVegs);
-
-console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
-
- -

Sử dụng một đối tượng theo kiểu tương tự mảng

- -

Như đã để cập ở trên, push là "intentionally generic", và chúng ta có thể lợi dụng điều đó. Array.prototype.push có thể được thực thi trên 1 đối tượng, như ví dụ dưới đây. Chú ý rằng chúng ta không tạo mảng để lưu trữ các đối tượng. Mà thay vào đó chúng ta lưu trữ trên chính bản thân đối tượng bằng cách sử dụng call trên Array.prototype.push để áp dụng phương thức như là đang thao tác với mảng, việc này có thể thực hiện được chính là nhờ cái cách mà JavaScript cho phép chúng ta thiết lập ngữ cảnh thực thi.

- -
var obj = {
-    length: 0,
-
-    addElem: function addElem(elem) {
-        // obj.length is automatically incremented
-        // every time an element is added.
-        [].push.call(this, elem);
-    }
-};
-
-// Let's add some empty objects just to illustrate.
-obj.addElem({});
-obj.addElem({});
-console.log(obj.length);
-// → 2
-
- -

Chú ý rằng obj không phải là mảng, phương thức push vẫn tăng giá trị thuộc tính length của obj như khi chúng ta thao tác với 1 mảng thực sự.

- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa lần đầu. Hiện thực trong 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')}} 
- -

Tương thích trình duyệt

- -
- - -

{{Compat("javascript.builtins.Array.push")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.pop()")}}
  • -
  • {{jsxref("Array.prototype.shift()")}}
  • -
  • {{jsxref("Array.prototype.unshift()")}}
  • -
  • {{jsxref("Array.prototype.concat()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/reduce/index.html b/files/vi/web/javascript/reference/global_objects/array/reduce/index.html deleted file mode 100644 index c665d37ad3..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/reduce/index.html +++ /dev/null @@ -1,553 +0,0 @@ ---- -title: Array.prototype.reduce() -slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce -translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce ---- -
{{JSRef}}
- -

Phương thức reduce() dùng để thực thi một hàm lên từng phần tử của mảng (từ trái sang phải) với một biến tích lũy để thu về một giá trị duy nhất.

- -
{{EmbedInteractiveExample("pages/js/array-reduce.html")}}
- - - -

Cú pháp

- -
arr.reduce(callback[, initialValue])
- -

Các tham số

- -
-
callback
-
Hàm dùng để thực thi với từng phần tử (element) của mảng, nhận vào 04 tham số: -
-
accumulator
-
Biến tích lũy, truyền giá trị trả về của mỗi lần gọi callback; nó là giá trị tích lũy được trả về trong lần gọi callback trước, hoặc giá trị của tham số initialValue, nếu được cung cấp (xem bên dưới).
-
currentValue
-
Phần tử trong mảng hiện tại đang được xử lý.
-
currentIndex{{optional_inline}}
-
Chỉ mục (index) của phần tử đang được xử lý. Bắt đầu tại 0, nếu giá trị initialValue được cung cấp, và tại 1 nếu không có initialValue.
-
array{{optional_inline}}
-
Mảng đang được gọi với reduce().
-
-
-
initialValue{{optional_inline}}
-
Giá trị cho tham số thứ nhất (accumulator) của hàm callback trong lần gọi đầu tiên. Nếu giá trị ban đầu này không được cung cấp, phần tử đầu tiên của mảng sẽ được dùng. Do đó, gọi reduce() trên một mảng rỗng và không có giá trị ban đầu sẽ gây ra lỗi.
-
- -

Giá trị trả về

- -

Giá trị sau khi rút gọn.

- -

Mô tả

- -

reduce() thực thi hàm callback lên từng phần tử đang tồn tại trong mảng, bỏ qua những lỗ trống không giá trị, và nhận vào 04 tham số:

- -
    -
  • accumulator
  • -
  • currentValue
  • -
  • currentIndex
  • -
  • array
  • -
- -

Trong lần đầu tiên callback được gọi, accumulator and currentValue có thể có một trong hai giá trị. Nếu tham số initialValue được cung cấp cho reduce(), thì accumulator sẽ bằng initialValue, và currentValue sẽ bằng phần tử đầu tiên của mảng. Nếu không có initialValueaccumulator sẽ bằng phần tử đầu tiên của mảng, và currentValue sẽ bằng phần tử thứ hai.

- -
-

Ghi chú: Nếu initialValue không được cung cấp, reduce() sẽ thực thi callback bắt đầu từ index 1, bỏ qua index đầu tiên. Nếu initialValue được cung cấp, index sẽ bắt đầu từ 0.

-
- -

Nếu mảng rỗng, và initialValue không được cung cấp, gọi reduce() sẽ gây ra lỗi {{jsxref("TypeError")}}. Nếu mảng chỉ có một phần tử có giá trị (bất kể vị trí index) đồng thời không có initialValue, hoặc có initialValue nhưng mảng lại rỗng, thì giá trị duy nhất đó sẽ được trả về và callback sẽ không được gọi.

- -

Sẽ an toàn hơn nếu giá trị ban đầu được cung cấp, bởi vì có đến ba khả năng xảy ra nếu không có initialValue như ở ví dụ sau:

- -
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
-var maxCallback2 = ( max, cur ) => Math.max( max, cur );
-
-// reduce() không có initialValue
-[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
-[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }
-[                      ].reduce( maxCallback ); // TypeError
-
-// map/reduce; giải pháp hay hơn, và nó có thể áp dụng được cho mảng rỗng hoặc lớn hơn
-[ { x: 22 }, { x: 42 } ].map( el => el.x )
-                        .reduce( maxCallback2, -Infinity );
-
- -

Cách reduce() làm việc

- -

Giả sử có một đoạn code với reduce() được hiện thực như sau:

- -
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
-  return accumulator + currentValue;
-});
-
- -

Callback sẽ được gọi bốn lần, với giá trị tham số và trả về trong mỗi lần gọi như sau:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackaccumulatorcurrentValuecurrentIndexarraygiá trị trả về
lần gọi thứ nhất011[0, 1, 2, 3, 4]1
lần gọi thứ hai122[0, 1, 2, 3, 4]3
lần gọi thứ ba333[0, 1, 2, 3, 4]6
lần gọi thứ tư644[0, 1, 2, 3, 4]10
- -

Giá trị trả về cho reduce() chính là giá trị trả về của lần gọi callback cuối cùng (10).

- -

Bạn cũng có thể cung cấp một hàm mũi tên {{jsxref("Functions/Arrow_functions", "Arrow Function","",1)}} thay vì một hàm đầy đủ. Đoạn code sau đây sẽ cho kết quả giống như đoạn code ở trên:

- -
[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue );
-
- -

Nếu bạn cung cấp giá trị initialValue cho tham số thứ hai của hàm reduce(), thì kết quả sẽ như bên dưới:

- -
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
-    return accumulator + currentValue;
-}, 10);
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackaccumulatorcurrentValuecurrentIndexarraygiá trị trả về
lần gọi thứ nhất1000[0, 1, 2, 3, 4]10
lần gọi thứ hai1011[0, 1, 2, 3, 4]11
lần gọi thứ ba1122[0, 1, 2, 3, 4]13
lần gọi thứ tư1333[0, 1, 2, 3, 4]16
lần gọi thứ năm1644[0, 1, 2, 3, 4]20
- -

Giá trị trả về cho reduce() lần này sẽ là 20.

- -

Ví dụ

- -

Tính tổng của tất cả các phần tử của mảng

- -
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
-  return accumulator + currentValue;
-}, 0);
-// sum is 6
-
-
- -

Tương tự, nhưng viết bằng hàm arrow function

- -
var total = [ 0, 1, 2, 3 ].reduce(
-  ( accumulator, currentValue ) => accumulator + currentValue,
-  0
-);
- -

Tính tổng các giá trị bên trong một mảng các object

- -

Để tính tổng các giá trị nằm bên trong các phần tử là object, bạn phải cung cấp một giá trị ban đầu để từng phần tử đều được callback chạy qua (và accumulator luôn luôn là giá trị kiểu số):

- -
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
-
- -

Tương tự, viết bằng 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
- -

Trải phẳng một mảng chứa nhiều mảng con

- -
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
-  function(accumulator, currentValue) {
-    return accumulator.concat(currentValue);
-  },
-  []
-);
-// flattened is [0, 1, 2, 3, 4, 5]
-
- -

Tương tự, viết bằng arrow function:

- -
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
-  ( accumulator, currentValue ) => accumulator.concat(currentValue),
-  []
-);
-
- -

Đếm số lần xuất hiện của phần tử trong mảng

- -
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 }
-
- -

Nhóm các đối tượng theo giá trị property nào đó

- -
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 }]
-// }
-
- -

Ghép các mảng con bên trong các object sử dụng toán tử spread và initialValue

- -
// 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'
-// ]
- -

Xóa các phần tử bị trùng trong mảng

- -
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]
-
- -

Chạy các Promise theo trình tự

- -
/**
- * 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
-
- -

Tổ hợp các hàm và gọi chuyền (piping)

- -
// 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
-
-
- -

Hiện thực lại map() sử dụng reduce()

- -
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]
-
-
- -

Polyfill

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.21
-// Reference: 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;
-    }
-  });
-}
-
- -

Nếu bạn thực sự cần chức năng này trên những engine JavaScript không hỗ trợ Object.defineProperty(), bạn không nên thêm polyfill này vào Array.prototype bởi vì không có cách nào làm cho nó không-duyệt-qua (non-enumerable) được (property mới sẽ xuất hiện trong các vòng lặp for).

- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}{{Spec2('ES5.1')}}Định nghĩa lần đầu. Hiện thực trong 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')}} 
- -

Tương thích trình duyệt

- -
- - -

{{Compat("javascript.builtins.Array.reduce")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.reduceRight()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/reduceright/index.html b/files/vi/web/javascript/reference/global_objects/array/reduceright/index.html deleted file mode 100644 index 7334a47f25..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/reduceright/index.html +++ /dev/null @@ -1,347 +0,0 @@ ---- -title: Array.prototype.reduceRight() -slug: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight -tags: - - JavaScr - - Mảng - - Phương thức - - Thuộc tính -translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight ---- -
{{JSRef}}
- -

Phương thức reduceRight() đảo ngược các giá trị trong mảng (từ phải sang trái), xử lý và trả về một giá trị duy nhất.

- -
var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
-    return a.concat(b);
-}, []);
-
-// flattened is [4, 5, 2, 3, 0, 1]
-
- -

Xem thêm {{jsxref("Array.prototype.reduce()")}} cho việc sắp xếp từ trái qua phải.

- -

Cú pháp

- -
arr.reduceRight(callback[, initialValue])
- -

Tham số truyền vào

- -
-
callback
-
Hàm gọi thực thi mỗi giá trị của mảng, truyền vào 4 tham số: -
-
previousValue
-
Giá trí trả về của hàm callback sau khi xử lý phần tử trước nó hoặc là initialValue, nếu như nó là phần tử đầu tiên (Xem bên dưới.)
-
currentValue
-
Giá trị hiện tại đang được duyệt.
-
index
-
Chỉ số vị trí của phần tử trong mảng.
-
array
-
Mảng phần tử ban đầu.
-
-
-
initialValue
-
Giá trị không bắt buộc. Đối tượng sử dụng cho phần tử đầu tiền của mảng, khi mà chưa có kết quả nào từ hàm callback trả về.
-
- -

Return value

- -

Giá trị trả về từ việc rút gọn.

- -

Mô tả

- -

reduceRight xử lý từng phần tử trong mảng, trừ các phần tử vô giá trị (rỗng), truyền vào 4 tham số: giá trị ban đâu (or hoặc giá trị trả về sau khi xử lý một phần tử trước đó), giá trị phần tử hiện tại, vị trí phần tử hiện tại, và giá trị mảng ban đầu.

- -

Việc xử lý phần tử hiện tại sẽ làm trong dấu (...) :

- -
array.reduceRight(function(previousValue, currentValue, index, array) {
-  // ... xử lý tại đây
-});
-
- -

Trong lần đầu xử lý, tham số previousValue và currentValue có thể là một trong hai.

- -
    -
  1. Nếu tham sô initialValue được truyền vào reduceRight, thì tham số previousValue sẽ bằng giá trị  tham số initialValue (nói cách khác nó chính là initialValue) and currentValue sẽ là giá trị cuối cùng của mảng.
  2. -
  3. Nếu tham số initialValue không được truyền vào, thì previousValue sẽ là giá trị cuối cùng của mảng và currentValue sẽ là giá trị cuối cùng thứ 2 của mảng ( giá trị thứ 2 tỉnh từ cuối mảng ).
  4. -
- -

Nếu mảng rỗng và không có tham số initialValue  nào được truyền vào thì {{jsxref("TypeError")}} xảy ra. Nếu mảng chỉ có một phần tử (bất kể vị trí) à không có tham số initialValue  nào được truyền vào, hoặc nếu initialValue được truyền vào nhưng mảng lại rỗng, giá trị duy nhất sẽ được trả lại mà không cần tới hàm callback.

- -

Một số ví dụ mô tả luồng hoạt động của reduceRight, bạn có thể xem :

- -
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
-  return previousValue + currentValue;
-});
-
- -

Bảng mô tả cách xử lý phần tử trong mảng ở ví dụ trên như sau:

- -

(*Tên gọi các tham số giữ nguyên để tiện theo dõi)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackpreviousValuecurrentValueindexarrayreturn value
lần 1433[0, 1, 2, 3, 4]7
lần 2722[0, 1, 2, 3, 4]9
lần 3911[0, 1, 2, 3, 4]10
lần 41000[0, 1, 2, 3, 4]10
- -

Giá trị trả về của hàm reduceRight sẽ là giá trị của lần thực thi cuối cùng (10).

- -

Và nếu bạn có đưa vào một giá trị initialValue, thì kết quả nó sẽ như thế này :

- -
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
-  return previousValue + currentValue;
-}, 10);
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackpreviousValuecurrentValueindexarrayreturn 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
- -

Và tất nhiên giá trị trả về của hàm reduceRight sẽ là 20.

- -

Ví dụ

- -

Tính tổng các giá trị trong một mảng

- -
var sum = [0, 1, 2, 3].reduceRight(function(a, b) {
-  return a + b;
-});
-// sum is 6
-
- -

Ghép nhiều mảng thành một mảng

- -
var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
-    return a.concat(b);
-}, []);
-// flattened is [4, 5, 2, 3, 0, 1]
-
- -

Sự khác nhau giữa reduce và 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"
- -

Polyfill 

- -

Đây là thuật ngữ dùng để chỉ các đoạn code được dùng để cung cấp một chức năng (hoặc công nghệ) của các trình duyệt hiện đại cho các trình duyệt cũ. Thông qua đó, các trang web sử dụng các công nghệ mới (như HTML5) có thể chạy ổn định trên các trình duyệt cũ chưa hỗ trợ.

- -

reduceRight đã được thêm vào chuẩn ECMA-262 trong lần sửa đổi thứ 5; do đó có thể nó không xuất hiện trong các trình duyệt chưa hỗ trợ nó . Bạn có thể dùng reduceRight bằng việc thêm đoạn mã sau vào code của bạn với khi làm việc với các trình duyệt không hỗ trợ nó.

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.22
-// Reference: 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;
-  };
-}
-
- -

Điều khoản

- - - - - - - - - - - - - - - - - - - - - - - - -
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')}} 
- -

Trình duyệt hỗ trợ

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.reduce()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/reverse/index.html b/files/vi/web/javascript/reference/global_objects/array/reverse/index.html deleted file mode 100644 index 19e4c5ce6d..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/reverse/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Array.prototype.reverse() -slug: Web/JavaScript/Reference/Global_Objects/Array/reverse -tags: - - Array - - JavaScript - - Mảng - - hàm -translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse ---- -
{{JSRef}}
- -

Hàm reverse() khi gọi bởi một mảng thì đảo ngược thứ tự của chính mảng đó. Phần tử đầu tiên của mảng trở thành phần tử cuối và ngược lại, phần tử cuối trở thành phần tử đầu tiên của mảng.

- -

Cú pháp

- -
arr.reverse()
- -

Tham số

- -

Không.

- -

Mô tả

- -

Hàm reverse đảo ngược thứ tự các phần tử của bản thân mảng, thay đổi mảng, và trả về tham chiếu của mảng đó.

- -

Ví dụ

- -

Đảo ngược thứ tự của một mảng

- -

Ví dụ dưới đây tạo một mảng myArray chứa 3 phần tử, sau đó đảo ngược thứ tự của các phần tử trong mảng.

- -
var myArray = ['one', 'two', 'three'];
-myArray.reverse();
-
-console.log(myArray) // ['three', 'two', 'one']
-
- -

Các đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu. Được cài đặt ở 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')}} 
- -

Tính tương thích đối với các trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.join()")}}
  • -
  • {{jsxref("Array.prototype.sort()")}}
  • -
  • {{jsxref("TypedArray.prototype.reverse()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/shift/index.html b/files/vi/web/javascript/reference/global_objects/array/shift/index.html deleted file mode 100644 index 19dd4b4aab..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/shift/index.html +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: Array.prototype.shift() -slug: Web/JavaScript/Reference/Global_Objects/Array/shift -tags: - - Array - - JavaScript - - Method - - Mảng - - Nguyên mẫu - - Prototype - - hàm -translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift ---- -
{{JSRef}}
- -

Hàm shift() sẽ xóa phần tử đầu tiên của một mảng và trả về phần tử đó. Hàm này sau khi thực thi sẽ làm thay đổi kích thước của mảng bị tác động.

- -

Cú pháp

- -
arr.shift()
- -

Giá trị trả về

- -

Phần tử đầu tiên của mảng.

- -

Mô tả

- -

Hàm shift sẽ xóa phần tử ở vị trí 0 trong mảng và dịch vị trí của các phần tử tiếp theo xuống, sau đó trả về giá trị của phần tử bị xóa. Nếu giá trị của thuộc tính {{jsxref("Array.length", "length")}} bằng 0, giá trị {{jsxref("undefined")}} được trả về.

- -

shift is intentionally generic; this method can be {{jsxref("Function.call", "called", "", 1)}} or {{jsxref("Function.apply", "applied", "", 1)}} to objects resembling arrays. 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.

- -

Ví dụ

- -

Xóa bỏ một phần tử khỏi một mảng

- -

Đoạn mã code dưới đây hiển thị mảng myFish trước và sau khi xóa bỏ phần tử đầu tiên của mảng đó. Nó cũng hiển thị phần tử bị xóa bỏ:

- -
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
-
-console.log('myFish before: ' + myFish);
-// "myFish before: angel,clown,mandarin,surgeon"
-
-var shifted = myFish.shift();
-
-console.log('myFish after: ' + myFish);
-// "myFish after: clown,mandarin,surgeon"
-
-console.log('Removed this element: ' + shifted);
-// "Removed this element: angel"
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiChú thích
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Đã cài đặt từ phiên bản 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')}}
{{SpecName('ESDraft', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ESDraft')}}
- -

Tương thích với trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
Tính năngChromeFirefox (Gecko)Internet ExplorerOperaSafari
Đã hỗ trợ{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
Tính năngAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Đã hỗ trợ{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Xem thêm các mục tương tự

- -
    -
  • {{jsxref("Array.prototype.push()")}}
  • -
  • {{jsxref("Array.prototype.pop()")}}
  • -
  • {{jsxref("Array.prototype.unshift()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/slice/index.html b/files/vi/web/javascript/reference/global_objects/array/slice/index.html deleted file mode 100644 index ee7fd81890..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/slice/index.html +++ /dev/null @@ -1,249 +0,0 @@ ---- -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}}
- -

Phương thức slice() trả về một bản sao tham chiếu (shallow copy) một phần của một mảng dưới dạng một mảng mới nhận các giá trị có chỉ số từ begin dến end (không bao gồm end). Mảng ban đầu không bị thay đổi.

- -
{{EmbedInteractiveExample("pages/js/array-slice.html")}}
- - - -

Cú pháp

- -
arr.slice()
-arr.slice(begin)
-arr.slice(begin, end)
-
- -

Tham số

- -
-
begin {{optional_inline}}
-
Chỉ số bắt đầu chọn phần tử từ phần tử 0.
-
Nếu chỉ số này là số âm, được xem như tính ngược từ cuối của mảng. slice(-2) chọn hai phần tử cuối cùng của mảng.
-
Nếu begin là không xác định (undefined), slice bắt đầu từ chỉ số 0.
-
- -

     Nếu begin lớn hơn độ dài của mảng, một mảng trống được trả về.

- -
-
end {{optional_inline}}
-
Chỉ số ngừng chọn phần tử. slice chọn ra các phần tử có chỉ số trước chỉ số end.
-
Ví dụ, slice(1,4) chọn phần thử thứ hai, thứ ba và thứ tư (ở các chỉ số 1, 2, và 3).
-
Chỉ số âm tính ngược từ cuối mảng về. slice(2,-1) chọn các phần tử thứ ba cho đến phần tử sát cuối của mảng, không bao gồm phần từ cuối cùng ở chỉ số -1.
-
Nếu tham số end không được truyền vào, slice chọn đến cuối mảng (arr.length).
-
Nếu end lớn hơn độ dài mảng, slice chỉ chọn đến cuối mảng (arr.length).
-
- -

Gia trị trả về

- -

Một mảng mới chứa các phần tử được chọn.

- -

Mô tả

- -

slice không chỉnh sửa mảng ban đầu mà trả về bản sao tham chiếu (shallow copy, chỉ copy một cấp) phần được chọn từ mảng ban đầu. Các phần tử của mảng gốc được copy vào mảng trả về như sau:

- -
    -
  • Đối với tham chiếu đối tượng, slice sao chép tham chiếu của đối tượng vào mảng mới. Cả mảng ban đầu và mảng mới trả về đều tham chiếu tới chung đối tượng. Nếu đối tượng được tham chiếu thay đổi, cả hai mảng đều nhận sự thay đổi này.
  • -
  • Đối với giá trị kiểu chuỗi, số và bool, (không phải các đối tượng kiểu {{jsxref("String")}}, {{jsxref("Number")}} và {{jsxref("Boolean")}} ), slice sao chép các giá trị vào mảng mới. Những thay đổi đối với các giá trị kiểu chuỗi, số và bool ở mảng này không còn ảnh hưởng tới mảng kia.
  • -
- -

Nếu một phần tử được thêm vào một trong hai mảng, mảng còn lại không bị thay đổi.

- -

Ví dụ

- -

Trả về mảng con của một mảng 

- -
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
-var citrus = fruits.slice(1, 3);
-
-// fruits có giá trị ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
-// citrus có giá trị ['Orange','Lemon']
-
- -

Sử dụng slice

- -

Trong ví dụ sau, slice tạo một mảng mới, newCar, từ myCar. Cả hai chứa tham chiếu tới đối tượng myHonda. Khi trường color của đối tượng myHonda đổi sang purple, cả hai mảng đều thấy sự thay đổi này.

- -
// Using slice, create newCar from myCar.
-var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } };
-var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997'];
-var 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);
-
- -

Đoạn mã trên in ra:

- -
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
-
- -

Các đối tượng giống kiểu mảng

- -

slice còn được dùng để thao tác với chuyển các đối tượng giống kiểu mảng (Array-like objects / collections) sang một mảng mới. Bạn chỉ cần gọi phương thức này trên đối tượng đó. Biến {{jsxref("Functions/arguments", "arguments")}} trong một hàm là ví dụ của một đối tượng kiểu mảng.

- -
function list() {
-  return Array.prototype.slice.call(arguments);
-}
-
-var list1 = list(1, 2, 3); // [1, 2, 3]
-
- -

Để sử dụng phương thức này, sử dụng phương thức.call  {{jsxref("Function.prototype")}} để gọi [].slice.call(arguments) thay vì Array.prototype.slice.call. Hoặc đơn giản hơn là {{jsxref("Function.prototype.bind", "bind")}}.

- -
var unboundSlice = Array.prototype.slice;
-var slice = Function.prototype.call.bind(unboundSlice);
-
-function list() {
-  return slice(arguments);
-}
-
-var list1 = list(1, 2, 3); // [1, 2, 3]
-
- -

Sử dụng trên nhiều trình duyệt

- -

Mặc dù các đối tượng trên trình duyệt (ví dụ các đối tượng DOM) không được yêu cầu theo chuẩn phải theo định nghĩa cả Mozilla khi chuyển  Array.prototype.slice và IE < 9 không làm thế, các phiên bản IE từ bản 9 hỗ trợ phương thức này. “Shimming” giúp đảm bảo phương thức này được hỗ trợ trên các trình duyệt khác nhau. Vì các trình duyệt ngày nay tiếp tục hỗ trợ tính năng này (IE, Mozilla, Chrome, Safari, and Opera), những nhà phát triển phần mềm đọc (DOM-supporting) mã slice dựa trên shim sẽ không bị nhầm lẫn về ngữ nghĩa; họ có thể tin tưởng dựa trên ngữ nghĩa này để mang lại hành vi được xem là tiêu chuẩn này. (Mã shim sửa IE cho tham số thứ hai của slice() để chuyển ra giá trị {{jsxref("null")}}/{{jsxref("undefined")}} không có trong các phiên bản trước của IE nhưng các trình duyệt ngày nay đều hỗ trợ, kể cả IE >= 9.)

- -
/**
- * Shim for "fixing" IE's lack of support (IE < 9) for applying slice
- * on host objects like NamedNodeMap, NodeList, and HTMLCollection
- * (technically, since host objects have been implementation-dependent,
- * at least before ES2015, IE hasn't needed to work this way).
- * Also works on strings, fixes IE < 9 to allow an explicit undefined
- * for the 2nd argument (as in Firefox), and prevents errors when
- * called on other DOM objects.
- */
-(function () {
-  'use strict';
-  var _slice = Array.prototype.slice;
-
-  try {
-    // Can't be used with DOM elements in IE < 9
-    _slice.call(document.documentElement);
-  } catch (e) { // Fails in IE < 9
-    // This will work for genuine arrays, array-like objects,
-    // NamedNodeMap (attributes, entities, notations),
-    // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
-    // and will not fail on other DOM objects (as do DOM elements in IE < 9)
-    Array.prototype.slice = function(begin, end) {
-      // IE < 9 gets unhappy with an undefined end argument
-      end = (typeof end !== 'undefined') ? end : this.length;
-
-      // For native Array objects, we use the native slice function
-      if (Object.prototype.toString.call(this) === '[object Array]'){
-        return _slice.call(this, begin, end);
-      }
-
-      // For array like object we handle it ourselves.
-      var i, cloned = [],
-        size, len = this.length;
-
-      // Handle negative value for "begin"
-      var start = begin || 0;
-      start = (start >= 0) ? start : Math.max(0, len + start);
-
-      // Handle negative value for "end"
-      var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
-      if (end < 0) {
-        upTo = len + end;
-      }
-
-      // Actual expected size of the slice
-      size = upTo - start;
-
-      if (size > 0) {
-        cloned = new Array(size);
-        if (this.charAt) {
-          for (i = 0; i < size; i++) {
-            cloned[i] = this.charAt(start + i);
-          }
-        } else {
-          for (i = 0; i < size; i++) {
-            cloned[i] = this[start + i];
-          }
-        }
-      }
-
-      return cloned;
-    };
-  }
-}());
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiBình luận
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa ban đầu. Xuất hiện ở Javascript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.10', 'Array.prototype.slice')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}{{Spec2('ESDraft')}}
- -

Độ tương thích với trình duyệt

- -
- - -

{{Compat("javascript.builtins.Array.slice")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.splice()")}}
  • -
  • {{jsxref("Function.prototype.call()")}}
  • -
  • {{jsxref("Function.prototype.bind()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/some/index.html b/files/vi/web/javascript/reference/global_objects/array/some/index.html deleted file mode 100644 index bbc279dc5c..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/some/index.html +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: Array.prototype.some() -slug: Web/JavaScript/Reference/Global_Objects/Array/some -tags: - - ECMAScript 5 - - JavaScript - - Mảng - - Phương Thức - - Prototype - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/some ---- -
{{JSRef}}
- -

Phương thức some() kiểm tra xem có ít nhất một phần tử của mảng thoả điều kiện ở hàm được truyền vào hay không. Kết quả trả về có kiểu Boolean

- -
-

Chú ý: Phương thức này sẽ trả về false nếu mảng rỗng.

-
- -
{{EmbedInteractiveExample("pages/js/array-some.html")}}
- - - -

Cú pháp

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

Các tham số

- -
-
callback
-
Hàm dùng để kiểm tra từng phần tử, nhận vào ba đối số: -
-
element
-
Phần tử đang được kiểm tra.
-
index {{Optional_inline}}
-
Chỉ mục của phần tử đang được kiểm tra.
-
array{{Optional_inline}}
-
Là bản thân mảng đã gọi phương thức some() ở trên.
-
-
-
thisArg{{Optional_inline}}
-
Được sử dụng làm giá trị this khi thực thi hàm callback.
-
- -

Giá trị trả về

- -

true khi hàm callback trả về một giá trị {{Glossary("truthy")}} nếu có ít nhất một phần tử của mảng thoả điều kiện. Ngược lại sẽ trả về false.

- -

Mô tả

- -

Phương thức some() thực thi hàm callback một lần và lặp qua từng phần tử của mảng cho đến khi hàm callback trả về một giá trị truthy (tức là true khi được chuyển sang kiểu Boolean). Nếu như có một phần tử thoả mãn, some() sẽ lập tức trả về true. Ngược lại sẽ trả về false. callback được gọi chỉ khi các phần tử của mảng có giá trị.

- -

callback được gọi với ba đối số: giá trị của phần tử, số chỉ mục của phần tử và mảng đang được lặp qua.

- -

Nếu như tham số thisArg được truyền vào some(), nó sẽ được sử dụng làm giá trị this của callback. Nếu bỏ qua, this sẽ có giá trị {{jsxref("undefined")}}. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

- -

some() không làm thay đổi mảng ban đầu.

- -

The range of elements processed by some() is set before the first invocation of callback. Elements appended to the array after the call to some() begins will not be visited by callback. If an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that some() visits that element's index. Elements that are deleted are not visited.

- -

Ví dụ

- -

Kiểm tra giá trị của các phần tử

- -

Ví dụ bên dưới đang kiểm tra xem có phần tử nào lớn hơn 10 hay không.

- -
function isBiggerThan10(element, index, array) {
-  return element > 10;
-}
-
-[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
-[12, 5, 8, 1, 4].some(isBiggerThan10); // true
-
- -

Kiểm tra giá trị của các phần tử sử dụng arrow function

- -

Arrow functions làm cho cú pháp trở nên gọn hơn.

- -
[2, 5, 8, 1, 4].some(x => x > 10);  // false
-[12, 5, 8, 1, 4].some(x => x > 10); // true
-
- -

Kiểm tra phần tử có tồn tại trong mảng hay không

- -

Hàm checkAvailability() bên dưới đang mô phỏng lại phương thức includes(), trả về true nếu phần tử có tồn tại trong mảng:

- -
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
- -

Kiểm tra phần tử có tồn tại trong mảng hay không sử dụng arrow function

- -
var fruits = ['apple', 'banana', 'mango', 'guava'];
-
-function checkAvailability(arr, val) {
-  return arr.some(arrVal => val === arrVal);
-}
-
-checkAvailability(fruits, 'kela');   // false
-checkAvailability(fruits, 'banana'); // true
- -

Chuyển giá trị bất kì sang kiểu Boolean

- -
var TRUTHY_VALUES = [true, 'true', 1];
-
-function getBoolean(value) {
-  'use strict';
-
-  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
- -

Polyfill

- -

some() was added to the ECMA-262 standard in the 5th edition, and it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of some() in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that fun.call evaluates to the original value of {{jsxref("Function.prototype.call()")}}.

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.17
-// Reference: 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;
-
-    for (var i = 0; i < len; i++) {
-      if (i in t && fun.call(thisArg, t[i], i, t)) {
-        return true;
-      }
-    }
-
-    return false;
-  };
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiChú thích
{{SpecName('ES5.1', '#sec-15.4.4.17', 'Array.prototype.some')}}{{Spec2('ES5.1')}}Được đưa vào lần đầu trong 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')}}
- -

Khả năng tương thích của trình duyệt

- -
- - -

{{Compat("javascript.builtins.Array.some")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.forEach()")}}
  • -
  • {{jsxref("Array.prototype.every()")}}
  • -
  • {{jsxref("Array.prototype.find()")}}
  • -
  • {{jsxref("TypedArray.prototype.some()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/sort/index.html b/files/vi/web/javascript/reference/global_objects/array/sort/index.html deleted file mode 100644 index 3b723bc8f9..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/sort/index.html +++ /dev/null @@ -1,248 +0,0 @@ ---- -title: Array.prototype.sort() -slug: Web/JavaScript/Reference/Global_Objects/Array/sort -translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort -original_slug: Web/JavaScript/Reference/Global_Objects/Array/Sắp_xếp ---- -
{{JSRef}}
- -

Phương thức sort() sẽ sắp xếp các phần tử của mảng ngay tại chỗ (in place) và trả về mảng đó. Kết quả sắp xếp có thể không ổn định (stable). Cách sắp xếp mặc định là theo Unicode code point của chuỗi.

- -

Độ phức tạp về thời gian và không gian của thuật toán sắp xếp sẽ tùy vào cách hiện thực.

- -
{{EmbedInteractiveExample("pages/js/array-sort.html")}}
- - - -

Cú Pháp

- -
arr.sort([compareFunction])
-
- -

 

- -

Tham số

- -
-
compareFunction {{optional_inline}}
-
Hàm dùng để xác định thứ tự sắp xếp. Nếu bỏ qua, mảng sẽ được sắp xếp dựa vào giá trị Unicode code point của từng ký tự của chuỗi được chuyển đổi từ giá trị của phần tử.
-
- -

Giá trị trả về

- -

Mảng đã sắp xếp. Chú ý mảng này được sắp xếp in place, và không có bản sao được tạo.

- -

Mô Tả

- -

Nếu không truyền compareFunction vào, các phần tử sẽ được sẽ được quy đổi về chuỗi kí tự và được so sánh dựa trên thứ tự của chuỗi kí tự đó trong bảng mã Unicode. Chẳng hạn, "Banana" đứng trước "Cherry". Còn nếu so sánh số học, 9 đứng trước 80, nhưng bởi vì các chữ số đã được quy đổi về chuỗi kí tự, nên "80" sẽ đứng trước "9" theo bảng mã Unicode.

- -

Nếu truyền compareFunction vào, phần tử của mảng sẽ được sắp xếp dựa theo giá trị trả về của hàm so sánh. Nếu a và b là hai phần tử được so sánh, thì:

- -
    -
  • Nếu compareFunction(a, b) trả về nhỏ hơn 0, đặt chỉ số cho a nhỏ hơn so với chỉ số của b, tức là để a lên trước.
  • -
  • Nếu compareFunction(a, b) trả về 0, giữ nguyên a và b, nhưng tiếp tục so sánh lần lượt các phần tử khác của mảng. Chú ý: quy định của ECMAscript không đảm bảo hành vi này, tương tự đối với tất cả các trình duyệt (ví dụ các phiên bản của Mozilla từ 2003).
  • -
  • Nếu compareFunction(a, b) trả về lớn hơn 0, đặt chỉ số của b nhỏ hơn chỉ số của a, tức là để b lên trước.
  • -
  • compareFunction(a, b) luôn phải trả về cùng một giá trị với mỗi cặp phần tử a và b. Nếu kết quả trả về không nhất quán thì thứ tự sắp xếp sẽ không xác định.
  • -
- -

Ví dụ đơn giản cho hàm so sánh:

- -
function compare(a, b) {
-  if (a nhỏ hơn b) {
-    return -1;
-  }
-  if (a lớn hơn b) {
-    return 1;
-  }
-  // a bằng b
-  return 0;
-}
-
- -

Để so sánh giữa các số, chỉ cần lấy a trừ cho b. Hàm dưới đây sẽ sắp xếp mảng theo chiều tăng dần (nếu mảng không chứa Infinity và NaN):

- -
function compareNumbers(a, b) {
-  return a - b;
-}
-
- -

Phương thức sort có thể dùng dễ dàng với {{jsxref("Operators/function", "function expressions", "", 1)}} (và closure):

- -
var numbers = [4, 2, 5, 1, 3];
-numbers.sort(function(a, b) {
-  return a - b;
-});
-console.log(numbers);
-
-// [1, 2, 3, 4, 5]
-
- -

Các Object cũng có thể được sắp xếp với một trong những thuộc tính của chúng.

- -
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 }
-];
-
-// ?sắp xếp theo value (giá trị)
-items.sort(function (a, b) {
-  return a.value - b.value;
-});
-
-// sắp xếp theo name (tên)
-items.sort(function(a, b) {
-  var nameA = a.name.toUpperCase(); // bỏ qua hoa thường
-  var nameB = b.name.toUpperCase(); // bỏ qua hoa thường
-  if (nameA < nameB) {
-    return -1;
-  }
-  if (nameA > nameB) {
-    return 1;
-  }
-
-  // name trùng nhau
-  return 0;
-});
- -

Ví dụ

- -

 

- -

Tạo, hiển thị và sắp xếp một mảng

- -

Ví dụ sau sẽ tạo bốn mảng và hiển thị chúng ở dạng nguyên bản và dạng đã được sắp xếp. Những mảng số sẽ được sắp xếp bằng cách sử dụng và không sử dụng hàm so sánh.

- -
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));
-
- -

Kết quả trả về như phía dưới. Như ta thấy, khi sử dụng hàm so sánh thì dù là ở dạng số hay dạng chuỗi kí tự, mảng luôn được sắp xếp đúng.

- -
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
-
- -

Sắp xếp kí tự ngoài mã ASCII

- -

Để sắp xếp kí tự ngoài ASCII, ví dụ chuỗi kí tự có dấu (e, é, è, a, ä, vân vân), chuỗi kí tự thuộc ngôn ngữ không phải tiếng Anh: hãy dùng {{jsxref("String.localeCompare")}}. Hàm này có thể so sánh các kí tự đó để chúng luôn trả về thứ tự đúng.

- -
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é']
-
- -

Sắp xếp cùng với map

- -

Hàm compareFunction có thể được gọi nhiều lần trên cùng một phần tử của mảng. Tuỳ thuộc vào bản chất của compareFunction, việc này có thể tốn nhiều chi phí ban đầu. Hàm compareFunction càng phức tạp và càng có nhiều phần tử phải sắp xếp, thì việc sắp xếp càng phải thông minh hơn, như là dùng thêm phương thức map chẳng hạn. Ý tưởng là truyền mảng vào một lần để sàng ra những phần tử cần sắp xếp và lưu chúng vào một mảng tạm, sắp xếp mảng tạm ấy rồi sàng lại mảng tạm sẽ ra được thứ tự mong muốn.

- -
// mảng cần sắp xếp
-var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
-
-// temporary array holds objects with position and sort-value
-var mapped = list.map(function(el, i) {
-  return { index: i, value: el.toLowerCase() };
-})
-
-// sorting the mapped array containing the reduced values
-mapped.sort(function(a, b) {
-  if (a.value > b.value) {
-    return 1;
-  }
-  if (a.value < b.value) {
-    return -1;
-  }
-  return 0;
-});
-
-// container for the resulting order
-var result = mapped.map(function(el){
-  return list[el.index];
-});
-
- -

Đặc điểm kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTình trạngGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa lần đầu.
{{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')}} 
- -

Trình duyệt tương thích

- -
- - -

{{Compat("javascript.builtins.Array.sort")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.reverse()")}}
  • -
  • {{jsxref("String.prototype.localeCompare()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/splice/index.html b/files/vi/web/javascript/reference/global_objects/array/splice/index.html deleted file mode 100644 index a942e28e67..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/splice/index.html +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Array.prototype.splice() -slug: Web/JavaScript/Reference/Global_Objects/Array/splice -translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice ---- -
{{JSRef}}
- -

Phương thức splice() thay đổi phần tử của mảng bằng cách xóa phần tử đang tồn tại và/hoặc thêm phần tử mới.

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-
-myFish.splice(2, 0, 'drum'); // chèn 'drum' vào vị trí 2
-// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
-
-myFish.splice(2, 1); // xóa 1 phần tử từ vị trí 2
-// myFish is ["angel", "clown","mandarin", "sturgeon"]
- -

Cú pháp

- -
array.splice(start[deleteCount[item1[item2[...]]]])
- -

Các tham số 

- -
-
start
-
Vị trí để bắt đầu thay đổi mảng (mặc định là 0). Nếu lớn hơn độ dài của mảng, thì chỉ số start được thiết lập bằng độ dài của mảng. Nếu giá trị là âm , thì bắt đầu từ các phần từ cuối mảng (gốc là -1, -n ứng với vị thứ thứ n cuối cùng và viết là array.length - n) và sẽ set giá trị 0 nếu trị tuyệt đối lớn hơn độ dài mảng.
-
deleteCount {{optional_inline}}
-
Con số chỉ định số lượng các phần tử sẽ bị xóa.
-
Nếu deleteCount bị bỏ qua hoặc có giá trị lớn hơn hoặc bằng array.length - start (nếu giá trị lớn hơn số phần tử còn lại của mảng, bắt đầu từ  start), thì tất cả các phần tử từ vị trí start đến cuối mảng sẽ bị xóa bỏ.
-
Nếu deleteCount bằng 0 hoặc là số âm, không phần tử nào được xóa. Trong trường hợp này bạn sẽ phải xác định ít nhất 1 phần tử mới (xem bên dưới).
-
item1, item2, ... {{optional_inline}}
-
Các phần tử thêm vào mảng, bắt đầu từ chỉ số  start . Nếu không có, splice() thì sẽ chỉ xóa các phần tử trong mảng.
-
- -

Giá trị trả về

- -

Trả về một mảng chứa các phần từ bị xóa. Nếu chỉ có 1 phần từ bị xóa, trả về mảng chứa 1 phần tử. Nếu không có phần tử nào bị xóa, trả về mảng rỗng.

- -

Mô tả

- -

Nếu số các phần tử chèn vào khác với số các phần tử bị xóa đi. Mảng mới sẽ có độ dài khác.

- -

Ví dụ

- -

Xóa 0 phần tử từ vị trí số 2, và thêm "drum"

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2, 0, 'drum');
-
-// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
-// removed is [], không có phần tử nào bị xóa
-
- -

Không xóa phần tử nào và thêm "drum" và "guitar" tại vị trí số 2

- - - -
 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
- - - -

Xóa 1 phần tử từ vị trí số 3

- -
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(3, 1);
-
-// removed is ["mandarin"]
-// myFish is ["angel", "clown", "drum", "sturgeon"]
-
- -

Xóa 1 phần tử mảng từ vị trí số 2 , và thêm phần tử "trumpet"

- -
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
-var removed = myFish.splice(2, 1, 'trumpet');
-
-// myFish is ["angel", "clown", "trumpet", "sturgeon"]
-// removed is ["drum"]
- -

Xóa 2 phần tử mảng từ vị trí số 0, và thêm "parrot", "anemone" và "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"]
- -

Xóa 2 phần tử mảng từ vị trí số 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"]
- -

Xóa 1 phần tử mảng từ vị trí số -2

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(-2, 1);
-
-// myFish is ["angel", "clown", "sturgeon"]
-// removed is ["mandarin"]
- -

Xóa mọi phần tử mảng phía sau vị trí số 2 (incl.)

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2);
-
-// myFish is ["angel", "clown"]
-// removed is ["mandarin", "sturgeon"]
- -

Đặc điểm kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tả kỹ thuậtTình trạngChú ý
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa sơ khai được ghi trong 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')}}
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ESDraft')}}
- -

Trình duyệt tương thích

- -
- - -

{{Compat("javascript.builtins.Array.splice")}}

-
- -

Liên quan

- -
    -
  • {{jsxref("Array.prototype.push()", "push()")}} / {{jsxref("Array.prototype.pop()", "pop()")}} — thêm/xóa phần tử từ vị trí cuối mảng
  • -
  • {{jsxref("Array.prototype.unshift()", "unshift()")}} / {{jsxref("Array.prototype.shift()", "shift()")}} — thêm/xóa phần tử từ vị trí đầu mảng
  • -
  • {{jsxref("Array.prototype.concat()", "concat()")}} — trả về mảng mới là mảng sau khi được nối với (các) mảng hoặc các giá trị khác.
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/tolocalestring/index.html b/files/vi/web/javascript/reference/global_objects/array/tolocalestring/index.html deleted file mode 100644 index 1c9072af63..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/tolocalestring/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Array.prototype.toLocaleString() -slug: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString -translation_of: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString ---- -
Hàm toLocaleString() trả về 1 chuỗi các phần tử trong mảng. Các phần tử này được chuyển đổi sang kiểu chuỗi nhờ hàm toLocalString và được ngăn cách với nhau bằng một xâu đặc biệt (ví dụ : dấu phẩy (,))
- -

Syntax

- -
arr.toLocaleString([locales[, options]]);
-
- -

Parameters

- -
-
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()")}}.
-
- -

Return value

- -

A string representing the elements of the array.

- -

Examples

- -

Using locales and options

- -

The elements of the array are converted to strings using their toLocaleString methods.

- -
    -
  • Object: {{jsxref("Object.prototype.toLocaleString()")}}
  • -
  • Number: {{jsxref("Number.prototype.toLocaleString()")}}
  • -
  • Date: {{jsxref("Date.prototype.toLocaleString()")}}
  • -
- -

Always display the currency for the strings and numbers in the prices array:

- -
var prices = ['¥7', 500, 8123, 12];
-prices.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' });
-
-// "¥7,¥500,¥8,123,¥12"
-
- -

For more examples, see also the {{jsxref("Intl")}}, {{jsxref("NumberFormat")}}, and {{jsxref("DateTimeFormat")}} pages.

- -

Polyfill

- -
// 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;
-    }
-  });
-}
-
- -

If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable.

- -

Specifications

- - - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}
{{SpecName('ES Int Draft', '#sup-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.toLocaleString")}}

-
- -

See also

- -
    -
  • {{jsxref("Array.prototype.toString()")}}
  • -
  • {{jsxref("Intl")}}
  • -
  • {{jsxref("Object.prototype.toLocaleString()")}}
  • -
  • {{jsxref("Number.prototype.toLocaleString()")}}
  • -
  • {{jsxref("Date.prototype.toLocaleString()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/tostring/index.html b/files/vi/web/javascript/reference/global_objects/array/tostring/index.html deleted file mode 100644 index c62919e81e..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/tostring/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: Array.prototype.toString() -slug: Web/JavaScript/Reference/Global_Objects/Array/toString -translation_of: Web/JavaScript/Reference/Global_Objects/Array/toString ---- -
{{JSRef}}
- -

Phương thức toString()trả về một chuỗi string đại diện cho mảng được chỉ định và các phần tử trong mảng đó.

- -
{{EmbedInteractiveExample("pages/js/array-tostring.html")}}
- -

Cú pháp

- -
arr.toString()
- -

Giá trị trả về

- -

Một chuỗi string đại diện cho mảng được chỉ định và các phần tử trong mảng đó.

- -

Mô tả

- -

Đối tượng {{jsxref("Array")}} ghi đè phương thức toString của {{jsxref("Object")}}. Đối với các array objects, phương thức toString nối mảng lại và trả về một chuỗi string chứa các phần tử trong mảng và được ngăn cách bởi dấu phẩy.

- -

Javascript tự động gọi phương thức toString khi một mảng được biểu diễn dưới dạng text hoặc khi một mảng được tham chiếu trong một string concate

- -

ECMAScript 5 semantics

- -

Bắt đầu từ JavaScript 1.8.5 (Firefox 4),  và phù hợp với ngữ nghĩa của ECMAScript 5th, phương thức toString() là phương thức chung và có thể sử dụng với bất cứ object nào. {{jsxref("Object.prototype.toString()")}} sẽ được gọi và  giá trị kết quả sẽ được trả về.

- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu. Được triển khai trong 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')}}
- -

Tương thích với trình duyệt web

- -
- - -

{{Compat("javascript.builtins.Array.toString")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.join()")}}
  • -
  • {{jsxref("Object.prototype.toSource()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/unshift/index.html b/files/vi/web/javascript/reference/global_objects/array/unshift/index.html deleted file mode 100644 index 580bd9bca3..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/unshift/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Array.prototype.unshift() -slug: Web/JavaScript/Reference/Global_Objects/Array/unshift -translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift ---- -
{{JSRef}}
- -

Phương thức unshift() thêm một hoặc nhiều phần tử vào vị trí đầu mảng sau đó trả về chiều dài của mảng mới.

- -
{{EmbedInteractiveExample("pages/js/array-unshift.html")}}
- -

Syntax

- -
arr.unshift(element1[, ...[, elementN]])
- -

Parameters

- -
-
elementN
-
Các phần tử được thêm vào đầu mảng.
-
- -

Return value

- -

Trả về độ dài mới của mảng {{jsxref("Array.length", "length")}}   sau khi thực hiện thêm phần tử.

- -

Description

- -

Phương thức unshift sẽ thêm vào đầu mảng các giá trị được truyền vào.

- -

unshift là "intentionally generic"; Phương thức này có thể được {{jsxref("Function.call", "gọi", "", 1)}} or {{jsxref("Function.apply", "áp dụng", "", 1)}} đối với các đối tượng giống như mảng. 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.

- -

Chú ý rằng, Nếu truyền nhiều phần tử vào cùng lức như một biến, chúng sẽ được thêm vào vị trí đầu tiên của mảng, theo đúng vị trí ban đầu mà chúng được truyền vào. Việc gọi phương thức unshift với n phần tử trong một lần sẽ không trả về cùng kết quả (vị trí các phần tử) so với việc gọi n lần với mỗi lần 1 phần tử.

- -

Xem ví dụ bên dưới

- -
let arr = [4,5,6];
-
-arr.unshift(1,2,3);
-console.log(arr);
-// [1, 2, 3, 4, 5, 6]
-
-arr = [4,5,6]; // resetting the array
-
-arr.unshift(1);
-arr.unshift(2);
-arr.unshift(3);
-
-console.log(arr);
-// [3, 2, 1, 4, 5, 6]
-
- -

Examples

- -

Using unshift

- -
let arr = [1, 2];
-
-arr.unshift(0); // result of the call is 3, which is the new array length
-// arr is [0, 1, 2]
-
-arr.unshift(-2, -1); // the new array length is 5
-// arr is [-2, -1, 0, 1, 2]
-
-arr.unshift([-4, -3]); // the new array length is 6
-// arr is [[-4, -3], -2, -1, 0, 1, 2]
-
-arr.unshift([-7, -6], [-5]); // the new array length is 8
-// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{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')}}
{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.unshift")}}

-
- -

See also

- -
    -
  • {{jsxref("Array.prototype.push()")}}
  • -
  • {{jsxref("Array.prototype.pop()")}}
  • -
  • {{jsxref("Array.prototype.shift()")}}
  • -
  • {{jsxref("Array.prototype.concat()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/array/values/index.html b/files/vi/web/javascript/reference/global_objects/array/values/index.html deleted file mode 100644 index 9460fdfbc3..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/values/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Array.prototype.values() -slug: Web/JavaScript/Reference/Global_Objects/Array/values -translation_of: Web/JavaScript/Reference/Global_Objects/Array/values ---- -
{{JSRef}}
- -

Method values()trả về một Array Iterator object chứa các giá trị của mỗi index trong mảng.

- -
{{EmbedInteractiveExample("pages/js/array-values.html")}}
- -

Cú Pháp

- -
arr.values()
- -

Giá trị trả về

- -

Một object {{jsxref("Array")}} lặp lại mới.

- -

Ví dụ

- -

Sử dụng vòng lặp for...of loop

- -
var arr = ['a', 'b', 'c', 'd', 'e'];
-var iterator = arr.values();
-
-for (let letter of iterator) {
-  console.log(letter);
-}  //"a" "b" "c" "d" "e"
-
- -

Array.prototype.values là triển khai mặc định của Array.prototype[Symbol.iterator].

- -
Array.prototype.values === Array.prototype[Symbol.iterator]      //true
- -

Sử dụng vòng lặp .next()

- -
var arr = ['a', 'b', 'c', 'd', 'e'];
-var iterator = arr.values();
-iterator.next();               // Object { value: "a", done: false }
-iterator.next().value;         // "b"
-iterator.next()["value"];      // "c"
-iterator.next();               // Object { value: "d", done: false }
-iterator.next();               // Object { value: "e", done: false }
-iterator.next();               // Object { value: undefined, done: true }
-iteraror.next().value;         // undefined 
- -
-

Sử dụng một lần: đối tượng trình lặp mảng là một đối tượng sử dụng một lần hoặc tạm thời

-
- -

Ví dụ:

- -
var arr = ['a', 'b', 'c', 'd', 'e'];
- var iterator = arr.values();
- for (let letter of iterator) {
- console.log(letter);
-} //"a" "b" "c" "d" "e"
-for (let letter of iterator) {
-console.log(letter);
-} // undefined
-
- -

Lý do: khi next().done=true  hoặc  currentIndex>length thì vòng lặp for..of kết thúc. Xem tại Iteration protocols.

- -

Giá trị: không có giá trị nào được lưu trữ trong object lặp mảng; thay vào đó, nó lưu trữ địa chỉ của mảng được sử dụng trong quá trình tạo của nó và do đó phụ thuộc vào các giá trị được lưu trữ trong mảng đó.

- -
var arr = ['a', 'b', 'c', 'd', 'e'];
-var iterator = arr.values();
-console.log(iterator);        // Array Iterator {  }
-iterator.next().value;        // "a"
-arr[1]='n';
-iterator.next().value;        //  "n"
-
- -
-

nếu các giá trị trong mảng thay đổi thì các giá trị trong mảng lặp cũng thay đổi.

-
- - - -

Thông số kỹ thuật

- - - - - - - - - - - - -
Thông số kỹ thuật
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}
- -

Tính tương thích của trình duyệt web

- -
- - -

{{Compat("javascript.builtins.Array.values")}}

-
- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.keys()")}}
  • -
  • {{jsxref("Array.prototype.entries()")}}
  • -
  • {{jsxref("Array.prototype.forEach()")}}
  • -
  • {{jsxref("Array.prototype.every()")}}
  • -
  • {{jsxref("Array.prototype.some()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/arraybuffer/index.html b/files/vi/web/javascript/reference/global_objects/arraybuffer/index.html deleted file mode 100644 index 1cf512233b..0000000000 --- a/files/vi/web/javascript/reference/global_objects/arraybuffer/index.html +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: ArrayBuffer -slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer -translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer ---- -
{{JSRef}}
- -
Đối tượng ArrayBuffer được sử dụng để biểu diễn một bộ đệm dữ liệu nhị phân nguyên gốc có độ dài cố định. Ta không thể trực tiếp thay đổi nội dung của một ArrayBuffer; mà thay vào đó là tạo ra một typed array objects hoặc một đối tượng {{jsxref("DataView")}} đại diện cho bộ đệm với một định dạng cụ thể, và sử dụng nó để đọc và ghi nội dung của bộ đệm.
- -
 
- -
{{EmbedInteractiveExample("pages/js/arraybuffer-constructor.html")}}
- - - -

Cú pháp

- -
new ArrayBuffer(length)
-
- -

Tham số

- -
-
length
-
Kích thước tính theo bytes của bộ đệm mảng cần tạo
-
- -

Giá trị trả về

- -

Là một ArrayBuffer mới có kích thước được chỉ định. Nội dung khởi tạo là 0.

- -

Ngoại lệ

- -

Lỗi {{jsxref("RangeError")}} sẽ được đưa ra nếu length lớn hơn  {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) hoặc mang giá trị âm.

- -

Mô tả

- -

Hàm dựng ArrayBuffer tạo ra một  ArrayBuffer  dựa trên chiều dài đã cho tính theo byte

- -

Lấy một mảng đệm từ dữ liệu hiện có

- - - -

Thuộc tính

- -
-
ArrayBuffer.length
-
Thuộc tính chiều dài của hàm dựng của ArrayBuffer có giá trị là 1.
-
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
-
Hàm dựng để tạo ra các đối tượng kế thừa
-
{{jsxref("ArrayBuffer.prototype")}}
-
Cho phép bổ sung các thuộc tính cho tất cả các đối tượng ArrayBuffer .
-
- -

Phương thức

- -
-
{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}
-
Trả về true nếu tham số arg là một trong các views của ArrayBuffer, ví dụ như typed array objects hoặc {{jsxref("DataView")}}. Trả về false trong trường hợp ngược lại.
-
{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}
-
-
Trả về một ArrayBuffer nội dung lấy từ dữ liệu của oldBuffer và sau đó được cắt bớt hoặc không mở rộng thông qua newByteLength.
-
-
- -

Thực thể

- -

Tất cả các thực thể của  ArrayBuffer đều kế thừa từ {{jsxref("ArrayBuffer.prototype")}}.

- -

Thuộc tính

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Properties')}}

- -

Phương thức

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Methods')}}

- -
-
{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}
-
Cùng chức năng như {{jsxref("ArrayBuffer.prototype.slice()")}}.
-
- -

Ví dụ

- -

Ví dụu sau tạo ra một vùng đệm 8 byte với view của {{jsxref("Global_Objects/Int32Array", "Int32Array")}} ?trỏ đến bộ đệm

- -
var buffer = new ArrayBuffer(8);
-var view   = new Int32Array(buffer);
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}?Thay thế bởi ECMAScript 6.
{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ES6')}}Initial definition in an ECMA standard. Specified that new is required.
{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt tương thích

- - - -

{{Compat("javascript.builtins.ArrayBuffer")}}

- -

Ghi chú thêm về tính tương thích

- -

Với ECMAScript 2015, hàm dựng ArrayBuffer cần được khởi tạo với {{jsxref("Operators/new", "new")}}. Việc gọi một hàm dựng ArrayBuffer nhưng một hàm thông thường không có toán tử new sẽ gây ra lỗi {{jsxref("TypeError")}}.

- -
var dv = ArrayBuffer(10);
-// TypeError: calling a builtin ArrayBuffer constructor
-// without new is forbidden
- -
var dv = new ArrayBuffer(10);
- -

Tham khảo thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/date/index.html b/files/vi/web/javascript/reference/global_objects/date/index.html deleted file mode 100644 index 7e485400e4..0000000000 --- a/files/vi/web/javascript/reference/global_objects/date/index.html +++ /dev/null @@ -1,260 +0,0 @@ ---- -title: Date -slug: Web/JavaScript/Reference/Global_Objects/Date -tags: - - Date - - JavaScript - - Vietnamese -translation_of: Web/JavaScript/Reference/Global_Objects/Date ---- -
{{JSRef}}
- -

Tạo ra một thể hiện JavaScript Date đại diện cho một khoảnh khắc trong thời gian. Đối tượng ngày được dựa trên giá trị thời gian là số mili giây kể từ ngày 1 tháng 1 năm 1970 UTC.

- -

Cú pháp

- -
new Date();
-new Date(value);
-new Date(dateString);
-new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);
-
- -
-

Lưu ý: Đối tượng JavaScript Date chỉ có thể được khởi tạo bằng cách gọi JavaScript Date như một constructor: gọi nó như là một hàm thông thường (tức là không có toán tử {{jsxref ("Operators / new", "new")}}) sẽ trả về một chuỗi thay vì một tượng Date; không giống như các kiểu đối tượng JavaScript khác, đối tượng JavaScript Date không có cú pháp rút gọn.

-
- -

Các tham số

- -
-

Chú ý: Trường hợp Date được gọi như một hàm khởi tạo với nhiều hơn một đối số, nếu các giá trị lớn hơn phạm vi hợp lý của chúng (ví dụ: 13 được cung cấp như là giá trị tháng hoặc 70 cho giá trị phút) thì giá trị liền kề sẽ được điều chỉnh. Ví dụ, new Date(2013, 13, 1) tương đương với new Date(2014, 1, 1), cả hai đều tạo ra một ngày cho 2014-02-01 (lưu ý rằng tháng này là 0). Tương tự cho các giá trị khác: new Date(2013, 2, 1, 0, 70) tương đương với new Date(2013, 2, 1, 1, 10) mà cả hai đều tạo ra một ngày cho 2013-03-01T01:10:00.

-
- -
-

Chú ý: Trường hợp Date được gọi như một hàm khởi tạo với nhiều hơn một đối số, các đối số xác định đại diện cho thời gian địa phương. Nếu UTC là mong muốn, sử dụng Date mới ({{jsxref ("Date.UTC ()", "Date.UTC (...)")}}) với cùng một đối số.

-
- -
-
value
-
Giá trị số nguyên đại diện cho số mili giây kể từ 01/01/1970-00:00:00 UTC.
-
dateString
-
Giá trị chuỗi đại diện cho một ngày. Chuỗi phải ở định dạng được công nhận bới phương thức {{jsxref("Date.parse()")}}. -
-

Lưu ý: Việc phân tách chuỗi ngày với constructor Date (và Date.parse, chúng là tương đương) đôi khi không như mong muốn do sự khác biệt và sự không nhất quán của trình duyệt. Hỗ trợ cho các chuỗi định dạng RFC 2822 chỉ là theo quy ước. Hỗ trợ các định dạng ISO 8601 khác với chuỗi "chỉ có ngày" (ví dụ: "1970-01-01") được coi như là UTC chứ không phải địa phương.

-
-
-
year
-
Giá trị số nguyên đại diện cho năm. Các giá trị từ 0 đến 99 ứng với các năm từ 1900 đến 1999.
-
month
-
Giá trị số nguyên đại diện cho tháng, bắt đầu với 0 cho Tháng Một đến 11 cho Tháng Mười Hai.
-
date
-
Tùy chọn. Giá trị số nguyên đại diện cho ngày trong tháng.
-
hours
-
Tùy chọn. Giá trị số nguyên đại diện cho giờ trong ngày.
-
minutes
-
Tùy chọn. Giá trị số nguyên đại diện cho phần phút của một thời gian.
-
seconds
-
Tùy chọn. Giá trị số nguyên đại diện cho phần giây của một thời gian.
-
milliseconds
-
Tùy chọn. Giá trị số nguyên đại diện cho phần mili giây của một thời gian.
-
- -

Mô tả

- -
    -
  • Nếu không có các đối số được cung cấp, các hàm khởi tạo tạo đối tượng JavaScript Date với ngày và giờ hiện tại theo các cài đặt hệ thống.
  • -
  • Nếu có ít nhất hai đối số được cung cấp, thiếu các đối số được đặt thành 1 (nếu thiếu ngày) hoặc 0 cho tất cả các đối số khác.
  • -
  • Ngày JavaScript được dựa trên giá trị thời gian là mili giây kể từ nửa đêm 01 tháng 1 năm 1970 UTC. Một ngày giữ 86.400.000 mili giây. Phạm vi đối tượng JavaScript Date là -100.000.000 ngày đến 100.000.000 ngày liên quan đến ngày 01 tháng 1 năm 1970 UTC.
  • -
  • Đối tượng JavaScript Date cung cấp hành vi thống nhất giữa các nền tảng. Giá trị thời gian có thể được truyền giữa các hệ thống để tạo ra một ngày đại diện cho cùng một thời điểm trong thời gian.
  • -
  • Đối tượng JavaScript Date hỗ trợ một số phương pháp UTC (phổ quát), cũng như các phương pháp thời gian địa phương. UTC, còn được gọi là Greenwich Mean Time (GMT), nghĩa là thời gian theo World Time Standard (Tiêu chuẩn Thời gian Thế giới). Thời gian địa phương là thời gian được biết đến với máy tính nơi thực hiện lệnh JavaScript.
  • -
  • Gọi JavaScript Date như một hàm (nghĩa là không có toán tử {{jsxref("Operators/new", "new")}}) sẽ trả về một chuỗi đại diện cho ngày và giờ hiện tại.
  • -
- -

Các thuộc tính

- -
-
{{jsxref("Date.prototype")}}
-
Cho phép thêm thuộc tính vào một đối tượng JavaScript Date.
-
Date.length
-
Giá trị của Date.length là 7. Đây là số lượng các đối số được xử lý bởi hàm khởi tạo.
-
- -

Các phương thức

- -
-
{{jsxref("Date.now()")}}
-
Trả về giá trị số tương ứng với thời gian hiện tại - số mili giây trôi qua kể từ ngày 1 tháng 1 năm 1970, 00:00:00, giờ UTC, với giây phút nhuận được bỏ qua.
-
{{jsxref("Date.parse()")}}
-
Phân tích cú pháp của một chuỗi đại diện ngày tháng và trả về số mili giây kể từ ngày 1 tháng 1 năm 1970, 00:00:00, giờ UTC, với giây phút nhuận được bỏ qua. -
-

Note: Việc phân tách cú pháp với Date.parse rất không chính xác do sự khác biệt giữa trình duyệt và sự không nhất quán..

-
-
-
{{jsxref("Date.UTC()")}}
-
Chấp nhận các tham số giống với dạng dài nhất của hàm khởi tạo (tức là 2 đến 7) và trả về số mili giây kể từ ngày 1 tháng 1 năm 1970, 00:00:00 giờ UTC, với giây phút nhuận được bỏ qua.
-
- -

Thể hiện của JavaScript Date

- -

Tất cả thể hiện của Date kế thừa từ {{jsxref("Date.prototype")}}. Đối tượng nguyên mẫu của hàm khởi tạo Date có thể được sửa đổi để ảnh hưởng đến tất cả thể hiện của Date.

- -

Date.prototype Methods

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}
- -

Các ví dụ

- -

Một số cách để tạo một đối tượng Date

- -

Các ví dụ sau đây cho thấy một số cách để tạo các ngày JavaScript:

- -
-

Chú ý: Việc phân tích các chuỗi ngày với constructor Date (và Date.parse, chúng là tương đương) rất không chính xác do sự khác biệt và sự không nhất quán của trình duyệt.

-
- -
var today = new Date();
-var birthday = new Date('October 30, 1996 15:27:08');
-var birthday = new Date('1996-10-30T15:27:08');
-var birthday = new Date(1996, 10, 30);
-var birthday = new Date(1996, 10, 30, 15, 27, 8);
-
- -

Các năm hai số ứng với 1900 - 1999

- -

Để tạo và lấy các ngày giữa các năm 0 đến 99 các phương thức {{jsxref("Date.prototype.setFullYear()")}} và {{jsxref("Date.prototype.getFullYear()")}} nên được sử dụng.

- -
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT).
-
-// Phương thức bị phản đối, 98 ứng với 1998 ở đây cũng vậy.
-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).
-
- -

Tính thời gian trôi qua

- -

Các ví dụ sau chỉ ra cách xác định thời gian trôi qua giữa hai ngày JavaScript trong mili giây.

- -

Do những ngày dài khác nhau (do thay đổi ánh sáng ban ngày), tháng và năm, thể hiện thời gian trôi qua theo đơn vị lớn hơn giờ, phút và giây đòi hỏi phải giải quyết một số vấn đề và cần được nghiên cứu kỹ trước khi cố gắng thử.

- -
// using Date objects
-var start = Date.now();
-
-// the event to time goes here:
-doSomethingForALongTime();
-var end = Date.now();
-var elapsed = end - start; // elapsed time in milliseconds
-
- -
// using built-in methods
-var start = new Date();
-
-// the event to time goes here:
-doSomethingForALongTime();
-var end = new Date();
-var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
-
- -
// 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;
-}
-
-yourFunctionReturn = printElapsedTime(yourFunction);
-
- -
-

Chú ý: Trong các trình duyệt hỗ trợ {{domxref("window.performance", "API Hiệu suất Web", "", 1)}} tính năng thời gian có độ phân giải cao, {{domxref("Performance.now()")}} có thể cung cấp các phép đo đáng tin cậy và chính xác về thời gian trôi qua hơn {{jsxref("Date.now()")}}.

-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc điểm kỹ thuậtTrạng tháiChú thích
{{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')}}Định nghĩa ban đầu. Được thực hiện trong JavaScript 1.1.
- -

Khả năng tương thích trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
Đặc tínhChromeFirefox (Gecko)Internet ExplorerOperaSafari
Hỗ trợ cơ bản{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]
-
- -
- - - - - - - - - - - - - - - - - - - - - -
Đặc tínhAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Hỗ trợ cơ bản{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] Một số trình duyệt có thể gặp sự cố khi phân tích ngày tháng: 3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings.

- -

[2] ISO8601 Date Format is not supported Trong Internet Explorer 8, và các phiên bản khác có thể có vấn đề chuyển đổi ngày tháng.

diff --git a/files/vi/web/javascript/reference/global_objects/date/parse/index.html b/files/vi/web/javascript/reference/global_objects/date/parse/index.html deleted file mode 100644 index 34b139a8f0..0000000000 --- a/files/vi/web/javascript/reference/global_objects/date/parse/index.html +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Date.parse() -slug: Web/JavaScript/Reference/Global_Objects/Date/parse -translation_of: Web/JavaScript/Reference/Global_Objects/Date/parse ---- -
{{JSRef}}
- -

Phương thức Date.parse() phân tích cú pháp của một chuỗi đại diện của một ngày và trả về số mili giây kể từ 01 tháng 01 năm 1970, 00:00:00 UTC hoặc NaN nếu chuỗi không nhận dạng được hoặc trong một số trường hợp, chứa các giá trị ngày không hợp lệ (ví dụ 2015-02-31).

- -

It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated).

- -
{{EmbedInteractiveExample("pages/js/date-parse.html")}}
- - - -

Syntax

- -

Direct call:

- -
Date.parse(dateString)
-
- -

Implicit call:

- -
new Date(dateString)
-
- -

Parameters

- -
-
dateString
-
A string representing a simplification of the ISO 8601 calendar date extended format (other formats may be used, but results are implementation-dependent).
-
- -

Return value

- -

A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, {{jsxref("NaN")}} is returned.

- -

Description

- -

The parse() method takes a date string (such as "2011-10-10T14:48:00") and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the {{jsxref("Date.prototype.setTime()", "setTime()")}} method and the {{jsxref("Global_Objects/Date", "Date")}} object.

- -

Date Time String Format

- -

The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format (see Date Time String Format section in the ECMAScript specification for more details). For example, "2011-10-10" (date-only form), "2011-10-10T14:48:00" (date-time form), or "2011-10-10T14:48:00.000+09:00" (date-time form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.

- -

While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or NaN.

- -

Because parse() is a static method of {{jsxref("Date")}}, it is called as Date.parse() rather than as a method of a {{jsxref("Date")}} instance.

- -

Fall-back to implementation-specific date formats

- -
-

This section contains implementation-specific behavior that can be inconsistent across implementations.

-
- -

The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause Date.parse() to return {{jsxref("NaN")}}.

- -

However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in {{jsxref("NaN")}}, depending on the browser and values provided, e.g.:

- -
// Non-ISO string with invalid date values
-new Date('23/25/2014');
-
- -

will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return {{jsxref("NaN")}} in all browsers compliant with ES5 and later:

- -
// ISO string with invalid values
-new Date('2014-25-23').toISOString();
-// returns "RangeError: invalid date" in all es5 compliant browsers
-
- -

SpiderMonkey's implementation-specific heuristic can be found in jsdate.cpp. The string "10 06 2014" is an example of a non–conforming ISO format and thus falls back to a custom routine. See also this rough outline on how the parsing works.

- -
new Date('10 06 2014');
-
- -

will be treated as a local date of 6 October, 2014 and not 10 June, 2014. Other examples:

- -
new Date('foo-bar 2014').toString();
-// returns: "Invalid Date"
-
-Date.parse('foo-bar 2014');
-// returns: NaN
-
- -

Differences in assumed time zone

- -
-

This section contains implementation-specific behavior that can be inconsistent across implementations.

-
- -

Given a non-standard date string of "March 7, 2014", parse() assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as "2014-03-07", it will assume a time zone of UTC (ES5 and ECMAScript 2015). Therefore {{jsxref("Date")}} objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted.

- -

Examples

- -

Using Date.parse()

- -

The following calls all return 1546300800000.  The first according to ES5 will imply UTC time, and the others are specifying UTC timezone via the ISO date specification (Z and +00:00)

- -
Date.parse("2019-01-01")
-Date.parse("2019-01-01T00:00:00.000Z")
-Date.parse("2019-01-01T00:00:00.000+00:00")
-
- -

The following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system.

- -
Date.parse("2019-01-01T00:00:00")
-
- -

Non-standard date strings

- -
-

This section contains implementation-specific behavior that can be inconsistent across implementations.

-
- -

If IPOdate is an existing {{jsxref("Date")}} object, it can be set to August 9, 1995 (local time) as follows:

- -
IPOdate.setTime(Date.parse('Aug 9, 1995'));
-
- -

Some other examples of parsing non–standard date strings:

- -
Date.parse('Aug 9, 1995');
-
- -

Returns 807937200000 in time zone GMT-0300, and other values in other time zones, since the string does not specify a time zone and is not ISO format, therefore the time zone defaults to local.

- -
Date.parse('Wed, 09 Aug 1995 00:00:00 GMT');
-
- -

Returns 807926400000 no matter the local time zone as GMT (UTC) is provided.

- -
Date.parse('Wed, 09 Aug 1995 00:00:00');
-
- -

Returns 807937200000 in time zone GMT-0300, and other values in other time zones, since there is no time zone specifier in the argument and it is not ISO format, so is treated as local.

- -
Date.parse('Thu, 01 Jan 1970 00:00:00 GMT');
-
- -

Returns 0 no matter the local time zone as a time zone GMT (UTC) is provided.

- -
Date.parse('Thu, 01 Jan 1970 00:00:00');
-
- -

Returns 14400000 in time zone GMT-0400, and other values in other time zones, since no time zone is provided and the string is not in ISO format, therefore the local time zone is used.

- -
Date.parse('Thu, 01 Jan 1970 00:00:00 GMT-0400');
-
- -

Returns 14400000 no matter the local time zone as a time zone GMT (UTC) is provided.

- -

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')}}Simplified ISO 8601 format added.
{{SpecName('ES6', '#sec-date.parse', 'Date.parse')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-date.parse', 'Date.parse')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Date.parse")}}

- -

Compatibility notes

- -
    -
  • Firefox 49 {{geckoRelease(49)}} changed the parsing of 2-digit years to be aligned with the Google Chrome browser instead of Internet Explorer. Now, 2-digit years that are less than 50 are parsed as 21st century years. For example, 04/16/17, previously parsed as April 16, 1917, will be April 16, 2017 now. To avoid any interoperability issues or ambiguous years, it is recommended to use the ISO 8601 format like "2017-04-16" ({{bug(1265136)}}).
  • -
  • Google Chrome will accept a numerical string as a valid dateString parameter. This means that, for instance, while !!Date.parse("42") evaluates to false in Firefox, it evaluates to true in Google Chrome because "42" is interpreted as January 1st, 2042.
  • -
- -

See also

- -
    -
  • {{jsxref("Date.UTC()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/error/index.html b/files/vi/web/javascript/reference/global_objects/error/index.html deleted file mode 100644 index c1e957c6f0..0000000000 --- a/files/vi/web/javascript/reference/global_objects/error/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: Lỗi -slug: Web/JavaScript/Reference/Global_Objects/Error -tags: - - JavaScript - - Lỗi - - Tham chiếu -translation_of: Web/JavaScript/Reference/Global_Objects/Error -original_slug: Web/JavaScript/Reference/Global_Objects/loi ---- -
{{JSRef}}
- -
Hàm Error tạo ra một đối tượng kiểu lỗi. Các thể hiện của đối tượng Error được ném ra khi xảy ra lỗi thực thi. Một đối tượng Error ngoài ra có thể được dùng như là một đối tượng căn bản cho các ngoại lệ do người dùng tự định nghĩa. Xem bên dưới các loại lỗi chuẩn được xây dựng sẵn.
- -

Cú pháp

- -
new Error([message[, fileName[, lineNumber]]])
- -

Tham số

- -
-
message
-
Tùy chọn. Một mô tả của lỗi rằng người dùng có thể đọc được.
-
fileName {{non-standard_inline}}
-
Tùy chọn. Giá trị của thuộc tính fileName trong quá trình tạo ra đối tượng Error. Các mặc định là tên của tập tin chứa đoạn mã gọi tới hàm Error().  
-
lineNumber {{non-standard_inline}}
-
Tuỳ chọn. Giá trị của thuộc tính lineNumber trong quá trình tạo ra đối tượng Error. Các mặc định là số dòng hiện tại đang gọi tới hàm Error().
-
- -

Mô tả

- -

Các lỗi thực thi dẫn đến các đối tượng Error được tạo ra và ném đi.

- -

Trang này ghi lại việc sử dụng đối tượng Error và cách sử dụng nó như là một hàm. Để biết danh sách các thuộc tính và phương thức được kế thừa bởi các thể hiện của Error, xem {{jsxref("Error.prototype")}}.

- -

Được sử dụng như là một hàm

- -

Khi Error được sử dụng như là một hàm -- không có từ khoá new, nó sẽ trả về một đối tượng Error. Do đó, gọi hàm Error cũng sẽ tạo ra cùng một đối tượng Error thông qua từ khóa new.

- -
// this:
-const x = Error('Tôi được tạo ra bằng cách sử dụng gọi hàm!');
-​​​​// tương tự như this
-const y = new Error('Tôi được xây dựng thông qua từ khoá "new"!');
- -

Các loại lỗi

- -

Bên cạnh hàm Error, còn có 7 hàm khác làm việc với lỗi trong JavaScript. Đối với ngoại lệ phía client, xem thêm tại Các câu lệnh xử lý ngoại lệ.

- -
-
{{jsxref("EvalError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra liên quan đến hàm toàn cục {{jsxref("Global_Objects/eval", "eval()")}}.
-
{{jsxref("InternalError")}} {{non-standard_inline}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra khi một lỗi bên trong bộ máy JavaScript được ném. Ví dụ: "quá nhiều đệ quy".
-
{{jsxref("RangeError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra khi một biến số hoặc tham số nằm ngoài phạm vi hợp lệ của nó.
-
{{jsxref("ReferenceError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra khi hủy tham chiếu của một tham chiếu không hợp lệ.
-
{{jsxref("SyntaxError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra trong khi phân tích cú pháp mã trong {{jsxref("Global_Objects/eval", "eval()")}}.
-
{{jsxref("TypeError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra khi một biến hoặc một tham số có kiểu không hợp lệ.
-
{{jsxref("URIError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra khi {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} hoặc {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} truyền các tham số không hợp lệ.
-
- -

Thuộc tính

- -
-
{{jsxref("Error.prototype")}}
-
Cho phép thêm các thuộc tính mới vào các thể hiện của Error.
-
- -

Phương thức

- -

Một đối tượng Error toàn cục không chứa phương thức riêng của nó, tuy nhiên, nó thừa hưởng các phương thức từ prototype.

- -

Các thể hiện của Error

- -
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Description')}}
- -

Các thuộc tính

- -
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Properties')}}
- -

Các phương thức

- -
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Methods')}}
- -

Các ví dụ

- -

Ném một lỗi thông thường

- -

Thông thường bạn tạo ra một đối tượng Error và muốn sử dụng nó cùng tới từ khoá {{jsxref("Statements/throw", "throw")}}. Bạn có thể bẫy lỗi bằng cách sử dụng cú pháp {{jsxref("Statements/try...catch", "try...catch")}}:

- -
try {
-  throw new Error('Whoops!');
-} catch (e) {
-  console.log(e.name + ': ' + e.message);
-}
-
- -

Xử lý một lỗi cụ thể

- -

Bạn có thể chọn cách chỉ xử lý các loại lỗi cụ thể bằng cách kiểm tra loại lỗi với thuộc tính {{jsxref("Object.prototype.constructor", "constructor")}} của lỗi hoặc, nếu bạn đang viết cho các công cụ JavaScript hiện đại, hãy dùng từ khoá {{jsxref("Operators/instanceof", "instanceof")}}:

- -
try {
-  foo.bar();
-} catch (e) {
-  if (e instanceof EvalError) {
-    console.log(e.name + ': ' + e.message);
-  } else if (e instanceof RangeError) {
-    console.log(e.name + ': ' + e.message);
-  }
-  // ... etc
-}
-
- -

Tùy biến các loại lỗi

- -

Bạn có thể muốn định nghĩa các loại lỗi của riêng mình được dẫn xuất từ Error để có thể throw new MyError() và sử dụng instanceof MyError để kiểm tra loại lỗi trong trình xử lý ngoại lệ. Điều này làm cho mã xử lý lỗi sạch hơn và nhất quán hơn. Xem "Cách tốt để thừa kế hàm Error trong JavaScript là gì?" trên StackOverflow để thảo luận chuyên sâu.

- -

Tuỳ biến lớp Error trong ES6

- -
-

Babel và các trình biên dịch khác sẽ không xử lý chính xác đoạn mã sau mà không cần cấu hình bổ sung.

-
- -
-

Một số trình duyệt đã thêm hàm CustomError trong ngăn xếp qua cách dùng class trong ES6.

-
- -
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
-}
- -

Tuỳ biến đối tượng trong ES5

- -
-

Tất cả trình duyệt đã thêm hàm CustomError trong ngăn xếp qua cách khai báo chuẩn.

-
- -
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
-}
- -

Các đặc điểm kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc điểm kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu. Được triển khai trong JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.11', 'Error')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error-objects', 'Error')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích của trình duyệt

- -
- - -

{{Compat("javascript.builtins.Error")}}

-
- -

Tham khảo

- -
    -
  • {{jsxref("Error.prototype")}}
  • -
  • {{jsxref("Statements/throw", "throw")}}
  • -
  • {{jsxref("Statements/try...catch", "try...catch")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/function/call/index.html b/files/vi/web/javascript/reference/global_objects/function/call/index.html deleted file mode 100644 index 681b98474b..0000000000 --- a/files/vi/web/javascript/reference/global_objects/function/call/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Function.prototype.call() -slug: Web/JavaScript/Reference/Global_Objects/Function/call -tags: - - JavaScript - - Phương Thức - - hàm -translation_of: Web/JavaScript/Reference/Global_Objects/Function/call ---- -
{{JSRef}}
- -

Phương thức call() gọi một hàm với giá trị của this và các đối số riêng lẻ.

- -
-

Chú ý: Mặc dù hàm này có cú pháp gần giống với hàm {{jsxref("Function.prototype.apply", "apply()")}} nhưng có sự khác biệt cơ bản. Hàm call() nhận nhiều đối số riêng lẻ, còn hàm apply() nhận một mảng tập hợp của nhiều đối  số.

-
- -

Cú Pháp

- -
function.call(thisArg, arg1, arg2, ...)
- -

Tham số

- -
-
thisArg
-
Giá trị của this được đưa ra để gọi hàm. Lưu ý rằng this có thể không phải ?là giá trị thực tế được thấy bởi phương thức: Nếu phương thức là một hàm trong {{jsxref("Functions_and_function_scope/Strict_mode", "non-strict mode", "", 1)}} , giá trị {{jsxref("Global_Objects/null", "null")}} và {{jsxref("Global_Objects/undefined", "undefined")}} sẽ được thay thế với global object và các giá trị sơ khai (primitive) sẽ được chuyển thành các đối tượng (objects).
-
arg1, arg2, ...
-
Các đối số cho hàm.
-
- -

Giá trị trả về

- -

Kết quả của của việc gọi hàm với giá trị xác định của this và các đối số.

- -

Miêu tả

- -

Một đối tượng this có thể được chỉ định khi gọi một hàm có sẵn. this đề cập đến đối tượng hiện tại (current object), là đối tượng đang gọi (calling object). Với hàm call, bạn có thể viết một phương thức một lần duy nhất và sau đó thừa kế nó trong một đối tương khác mà không phải viết lại phương thức đó cho đối tượng mới.

- -

Ví du

- -

Sử dung call để chain constructors cho một đối tượng

- -

Bạn có thể sử dụng hàm call để chain constructors cho một đối tượng giống như trong Java. Trong ví dụ dưới đây, hàm khởi tại của đối tượng Product được định nghĩa với 2 tham số, name và price. Hai hàm Food và Toy gọi Product với tham số this , name và price. Product khởi tạo thuộc tính name và price, cả 2 hàm này định nghĩa category.

- -
function Product(name, price) {
-  this.name = name;
-  this.price = 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);
-
- -

 Sử dung hàm call để gọi một hàm ẩn danh (anonymous function)

- -

Trong ví dụ dưới đây, chúng ta tạo một hàm ẩn danh và sử dụng hàm call để gọi hàm đó nhận mọi đối tượng trong một mảng. Mục đích chính của hàm ẩn danh này là thêm tính năng hàm print cho mọi đối tượng, từ đó các đối tượng này có thể in ra vị trí của chúng trong mảng. Việc này có thể không cần thiết nhưng được đưa ra với mục đích ví dụ.

- -
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);
-}
-
- -

 Sử dung hàm call để gọi hàm và đưa ra một giá trị cho đối tượng 'this'

- -

Trong ví dụ dưới đây khi chúng ta gọi hàm greet , giá trị của this trong hàm greet chính là đối tượng i.

- -
function greet() {
-  var reply = [this.person, 'Is An Awesome', this.role].join(' ');
-  console.log(reply);
-}
-
-var i = {
-  person: 'Douglas Crockford', role: 'Javascript Developer'
-};
-
-greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer
-
- -

 Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in 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')}}
- -

Tính tương thích với trình duyệt web

- -
- - -

{{Compat("javascript.builtins.Function.call")}}

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/function/index.html b/files/vi/web/javascript/reference/global_objects/function/index.html deleted file mode 100644 index c94856a200..0000000000 --- a/files/vi/web/javascript/reference/global_objects/function/index.html +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Function -slug: Web/JavaScript/Reference/Global_Objects/Function -tags: - - Constructor - - Function - - JavaScript - - TopicStub - - hàm -translation_of: Web/JavaScript/Reference/Global_Objects/Function ---- -
{{JSRef}}
- -

Hàm Function tạo mới một đối tượng Function. Gọi hàm tạo trực tiếp có thể tạo các hàm một cách linh hoạt, nhưng gặp phải các vấn đề về bảo mật và hiệu suất tương tự như {{jsxref("eval")}}.

- -

Mỗi một JavaScript function thực sự là một đối tượng Function.

- -

Cú pháp

- -
new Function ([arg1[, arg2[, ...argN]],] functionBody)
- -

Tham số

- -
-
arg1, arg2, ... argN
-
Đây là các tên được sử dụng bởi hàm làm tên các tham số chính thức. Mỗi tên của tham số phải là một chuỗi tương ứng với một mã định danh JavaScript hợp lệ hoặc một danh sách các chuỗi tương tự được phân tách bằng dấu phẩy; ví dụ "x", "theValue" hoặc "a,b".
-
functionBody
-
Một chuỗi chứa các câu lệnh JavaScript bao gồm định nghĩa hàm.
-
- -

Mô tả

- -

Đối tượng Function được tạo ra thông qua hàm Function được chuyển đổi khi hàm được tạo ra. Điều này kém hiệu quả hơn so với việc khai báo một hàm với biểu thức hàm hoặc câu lệnh hàm và gọi nó trong mã của bạn, bởi vì các hàm đó được phân tích cú pháp với phần còn lại của mã. 

- -

Tất cả các tham số truyền cho hàm được coi là tên định danh của các tham số trong hàm, thứ mà sẽ được tạo, theo thứ tự chúng được truyền.

- -

Gọi Function như là một hàm (không sử dụng toán tử new) có tác dụng tương tự như gọi nó là một hàm thông thường.

- -

Các thuộc tính và phương thức của Function

- -

Một đối tượng Function toàn cục không có phương thức hoặc thuộc tính của riêng nó. Tuy nhiên, vì bản thân nó là một hàm, nó thừa hưởng một số phương thức và thuộc tính thông qua {{jsxref("Function.prototype")}}.

- -

Function prototype

- -

Các thuộc tính

- -
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
- -

Các phương thức

- -
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
- -

Các thể hiện của Function

- -

Các thể hiện của Function kế thừa các phương thức và thuộc tính từ {{jsxref("Function.prototype")}}. Cũng như tất cả các hàm khác, bạn có thể thay đổi prototype của hàm tạo để thực hiện thay đổi cho tất cả các thể hiện của Function.

- -

Các ví dụ

- -

Các tham số xác định cùng với hàm Function

- -

Đoạn mã sau tạo ra một đối tượng Function có hai tham số.

- -
// Ví dụ này có thể chạy trực tiếp trên JavaScript Console
-
-// Tạo một hàm gồm hai tham số và trả về tổng của những tham số đó
-var adder = new Function('a', 'b', 'return a + b');
-
-// Gọi hàm
-adder(2, 6);
-// > 8
-
- -

Những tham số "a" và "b"  là các tên tham số chính thức được sử dụng trong thân hàm, "return a + b".

- -

Sự khác biệt giữa hàm Function constructor và định nghĩa hàm

- -

Các hàm được tạo ra cùng với Function constructor không tạo ra sự khép kín với bối cảnh sáng tạo của chúng; chúng luôn luôn được tạo ra trong phạm vi toàn cục. Khi gọi, chúng sẽ chỉ có thể truy cập đên các biến cục bộ và biến toàn cục của chúng, chứ không phải các biến từ phạm vi mà Function constructor được tạo. Điều này khác với việc sử dụng {{jsxref("eval")}} với mã cho biểu thức hàm.

- -
var x = 10;
-
-function createFunction1() {
-    var x = 20;
-    return new Function('return x;'); // |x| trỏ tới |x| toàn cục
-}
-
-function createFunction2() {
-    var x = 20;
-    function f() {
-        return x; // |x| trỏ tới |x| cục bộ ngay bên trên
-    }
-    return f;
-}
-
-var f1 = createFunction1();
-console.log(f1());          // 10
-var f2 = createFunction2();
-console.log(f2());          // 20
-
- -

Các thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu. Được triển khai trong JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích của trình duyệt

- -
- - -

{{Compat("javascript.builtins.Function")}}

-
- -

Tham khảo

- -
    -
  • {{jsxref("Functions", "Functions and function scope")}}
  • -
  • {{jsxref("Function")}}
  • -
  • {{jsxref("Statements/function", "function statement")}}
  • -
  • {{jsxref("Operators/function", "function expression")}}
  • -
  • {{jsxref("Statements/function*", "function* statement")}}
  • -
  • {{jsxref("Operators/function*", "function* expression")}}
  • -
  • {{jsxref("GeneratorFunction")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/function/tosource/index.html b/files/vi/web/javascript/reference/global_objects/function/tosource/index.html deleted file mode 100644 index 32a43d0da2..0000000000 --- a/files/vi/web/javascript/reference/global_objects/function/tosource/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Function.prototype.toSource() -slug: Web/JavaScript/Reference/Global_Objects/Function/toSource -translation_of: Web/JavaScript/Reference/Global_Objects/Function/toSource ---- -
{{JSRef}} {{non-standard_header}}
- -

Phương pháp toSource() trả về một chuỗi đại diện cho mã nguồn của đối tượng.

- -

Cú pháp

- -
function.toSource();
-
- -

Giá trị trả về

- -

Một chuỗi đại diện cho mã nguồn của đối tượng.

- -

Mô tả

- -

Phương pháp toSource trả về các giá trị theo

- -
    -
  • Đối với đối tượng tích hợp {{jsxref("Function")}}, toSource() trả về chuỗi mã nguồn không khả dụng: - -
    function Function() {
    -  [native code]
    -}
    -
    -
  • -
  • Đối với các hàm tùy chỉnh, toSource() trả về nguồn Javascript định nghĩa đối tượng dưới dạng chuỗi. -
    // For example:
    -function hello() {
    -  console.log("Hello, World!");
    -}
    -
    -hello.toSource();
    -
    - -
    // Results in:
    -"function hello() {
    -    console.log(\"Hello, World!\");
    -}"
    -
  • -
- -

Phương pháp này thường được gọi cục bộ trong Javascript và không rõ ràng bằng mã. Bạn có thể gọi toSource() trong khi gỡ lỗi để kiểm tra nội dung của một đối tượng.

- -

Đặc điểm chi tiết

- -

Không phải là một đặc tính chuẩn nào. Ghi rõ trong JavaScript 1.3.

- -

Trình duyệt tương thích

- -
- - -

{{Compat("javascript.builtins.Function.toSource")}}

-
- -

Liên quan

- -
    -
  • {{jsxref("Object.prototype.toSource()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/generator/index.html b/files/vi/web/javascript/reference/global_objects/generator/index.html deleted file mode 100644 index a1ed3ecf07..0000000000 --- a/files/vi/web/javascript/reference/global_objects/generator/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: Generator -slug: Web/JavaScript/Reference/Global_Objects/Generator -translation_of: Web/JavaScript/Reference/Global_Objects/Generator ---- -
{{JSRef}}
- -

Generator là một object return bởi một {{jsxref("Statements/function*", "generator function", "", 1)}}, nó phù hợp với cả iterable protocol và iterator protocol.

- -

Cú pháp

- -
function* gen() {
-  yield 1;
-  yield 2;
-  yield 3;
-}
-
-var g = gen(); // "Generator { }"
- -

Phương thức

- -
-
{{jsxref("Generator.prototype.next()")}}
-
Trả về giá trị yielded, được khai báo qua câu lệnh {{jsxref("Operators/yield", "yield")}}.
-
{{jsxref("Generator.prototype.return()")}}
-
Trả về giá trị và kết thúc generator.
-
{{jsxref("Generator.prototype.throw()")}}
-
Quăng lỗi vào generator (đồng thời kết thúc generator, trừ khi được bắt lại trong generator đó).
-
- -

Ví dụ

- -

Một vòng lặp vô hạn

- -
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 object cũ

- -

Firefox (SpiderMonkey) đã hiện thực phiên bản generators đầu tiên trong JavaScript 1.7, lúc đó dấu sao (*) trong khai báo không bắt buộc (bạn chỉ cần dùng từ khóa yield bên trong hàm). Tuy nhiên, kiểu viết này đã không còn được hổ trợ từ Firefox 58 (released ngày 23, tháng 1, 2018) ({{bug(1083482)}}).

- -

Các phương thức generator cũ

- -
-
Generator.prototype.next() {{non-standard_inline}}
-
Returns a value yielded by the {{jsxref("Operators/yield", "yield")}} expression. This corresponds to next() in the ES2015 generator object.
-
Generator.prototype.close() {{non-standard_inline}}
-
Closes the generator, so that when calling next() an {{jsxref("StopIteration")}} error will be thrown. This corresponds to the return() method in the ES2015 generator object.
-
Generator.prototype.send() {{non-standard_inline}}
-
Used to send a value to a generator. The value is returned from the {{jsxref("Operators/yield", "yield")}} expression, and returns a value yielded by the next {{jsxref("Operators/yield", "yield")}} expression. send(x) corresponds to next(x) in the ES2015 generator object.
-
Generator.prototype.throw() {{non-standard_inline}}
-
Throws an error to a generator. This corresponds to the throw() method in the ES2015 generator object.
-
- -

Legacy generator example

- -
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)
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator-objects', 'Generator objects')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hổ trợ

- - - -

{{Compat("javascript.builtins.Generator")}}

- -

Xem thêm

- -

Legacy generators

- -
    -
  • {{jsxref("Statements/Legacy_generator_function", "The legacy generator function", "", 1)}}
  • -
  • {{jsxref("Operators/Legacy_generator_function", "The legacy generator function expression", "", 1)}}
  • -
  • {{jsxref("StopIteration")}}
  • -
  • The legacy Iterator protocol
  • -
- -

ES2015 generators

- -
    -
  • {{jsxref("Functions", "Functions", "", 1)}}
  • -
  • {{jsxref("Statements/function", "function")}}
  • -
  • {{jsxref("Operators/function", "function expression")}}
  • -
  • {{jsxref("Function")}}
  • -
  • {{jsxref("Statements/function*", "function*")}}
  • -
  • {{jsxref("Operators/function*", "function* expression")}}
  • -
  • {{jsxref("GeneratorFunction")}}
  • -
  • The Iterator protocol
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/index.html b/files/vi/web/javascript/reference/global_objects/index.html deleted file mode 100644 index 58625d24b9..0000000000 --- a/files/vi/web/javascript/reference/global_objects/index.html +++ /dev/null @@ -1,203 +0,0 @@ ---- -title: Standard built-in objects -slug: Web/JavaScript/Reference/Global_Objects -tags: - - JavaScript - - NeedsTranslation - - Objects - - Reference - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects ---- -
{{jsSidebar("Objects")}}
- -

Chương này bao gồm các chuẩn của JavaScript, đối tượng tích hợp, gồm phương thức và thuộc tính của chúng.

- -

Thuật ngữ "đối tượng toàn cục" (hay đối tượng tích hợp chuẩn) ở đây không bị nhầm lẫn với đối tượng toàn cục. Ở đây, các đối tượng toàn cục đề cập đến các đối tượng trong phạm vi toàn cục. Bản thân đối tượng toàn cục cũng có thể được truy cập bằng toán tử: {{JSxRef("Toán tử/this", "this")}} trong toàn cục (nhưng chỉ khi ECMAScript 5 không được sử dụng; trong trường hợp đó, nó trả về: {{JSxRef("undefined")}}). Trong thực tế, phạm vi toàn cục bao gồm các thuộc tính của đối tượng toàn cục, các thuộc tính được kế thừa (nếu có).

- -
-

Các đối tượng khác trong phạm vi toàn cục cũng được tạo bởi tập lệnh từ người dùng (created by the user script) hoặc được cung cấp bởi các ứng dụng máy chủ. Các đối tượng mà máy chủ có sẵn trong trình duyệt được ghi lại trong tài liệu tham khảo API (API reference). Để biết thêm thông tin về sự khác biệt giữa DOM và JavaScript Core, hãy xem JavaScript technologies overview.

- -

Đối tượng chuẩn theo thể loại

- -

Các thuộc tính của giá trị

- -

Những đặc tính toàn cục này trả về một giá trị đơn giản; chúng không có thuộc tính hay phương thức nào.

- -
    -
  • {{jsxref("Infinity")}}
  • -
  • {{jsxref("NaN")}}
  • -
  • {{jsxref("undefined")}}
  • -
  • {{jsxref("null")}} literal
  • -
- -

Các thuộc tính chức năng

- -

Các hàm toàn cục (gọi trên toàn cục chứ không phải trên một đối tượng) trực tiếp trả về kết quả cho người gọi.

- -
    -
  • {{jsxref("Global_Objects/eval", "eval()")}}
  • -
  • {{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}
  • -
  • {{jsxref("Global_Objects/isFinite", "isFinite()")}}
  • -
  • {{jsxref("Global_Objects/isNaN", "isNaN()")}}
  • -
  • {{jsxref("Global_Objects/parseFloat", "parseFloat()")}}
  • -
  • {{jsxref("Global_Objects/parseInt", "parseInt()")}}
  • -
  • {{jsxref("Global_Objects/decodeURI", "decodeURI()")}}
  • -
  • {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}
  • -
  • {{jsxref("Global_Objects/encodeURI", "encodeURI()")}}
  • -
  • {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}
  • -
  • {{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}
  • -
  • {{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}
  • -
- -

Các đối tượng cơ bản

- -

Đây là những đối tượng cơ bản mà tất cả các đối tượng các đều dựa vào. Nó bao gồm đối tượng đại diện cho các đối tượng, hàm, và lỗi chung.

- -
    -
  • {{jsxref("Object")}}
  • -
  • {{jsxref("Function")}}
  • -
  • {{jsxref("Boolean")}}
  • -
  • {{jsxref("Symbol")}} {{experimental_inline}}
  • -
  • {{jsxref("Error")}}
  • -
  • {{jsxref("EvalError")}}
  • -
  • {{jsxref("InternalError")}}
  • -
  • {{jsxref("RangeError")}}
  • -
  • {{jsxref("ReferenceError")}}
  • -
  • {{jsxref("SyntaxError")}}
  • -
  • {{jsxref("TypeError")}}
  • -
  • {{jsxref("URIError")}}
  • -
- -

Số và ngày 

- -

Đây là các đối tượng cơ sở đại diện cho số, ngày, và các phép toán học.

- -
    -
  • {{jsxref("Number")}}
  • -
  • {{jsxref("Math")}}
  • -
  • {{jsxref("Date")}}
  • -
- -

Xử lí văn bản

- -

Những đối tượng này đại diện cho chuỗi và hỗ trợ thao tác chúng.

- -

{{jsxref("String")}}

- -
    -
  • {{jsxref("RegExp")}}
  • -
- -

Mục lục các bộ sưu tập

- -

Các đối tượng này đại diện cho các bộ sưu tập dữ liệu sắp xếp theo giá trị. Chúng bao gồm các mảng và cấu trúc mảng.

- -
    -
  • {{jsxref("Array")}}
  • -
  • {{jsxref("Int8Array")}}
  • -
  • {{jsxref("Uint8Array")}}
  • -
  • {{jsxref("Uint8ClampedArray")}}
  • -
  • {{jsxref("Int16Array")}}
  • -
  • {{jsxref("Uint16Array")}}
  • -
  • {{jsxref("Int32Array")}}
  • -
  • {{jsxref("Uint32Array")}}
  • -
  • {{jsxref("Float32Array")}}
  • -
  • {{jsxref("Float64Array")}}
  • -
  • {{JSxRef("BigInt64Array")}}
  • -
  • {{JSxRef("BigUint64Array")}}
  • -
- -

Bộ sưu tập khóa

- -

Các đối tượng này đại diện cho các bộ sưu tập sử dụng với khóa; chúng chứa các phần tử lặp đi lặp lại theo thứ tự chèn.

- -
    -
  • {{jsxref("Map")}} 
  • -
  • {{jsxref("Set")}} 
  • -
  • {{jsxref("WeakMap")}}
  • -
  • {{jsxref("WeakSet")}} 
  • -
- -

Cấu trúc dữ liệu

- -

Các đối tượng này đại diện và tương tác với các bộ đệm cấu trúc dữ liệu và dữ liệu được mã hóa bởi JavaScript Object Notation (JSON).

- - - -
    -
  • {{JSxRef("ArrayBuffer")}}
  • -
  • {{JSxRef("SharedArrayBuffer")}} {{Experimental_Inline}}
  • -
  • {{JSxRef("Atomics")}} {{Experimental_Inline}}
  • -
  • {{JSxRef("DataView")}}
  • -
  • {{JSxRef("JSON")}}
  • -
- - - -

Kiểm soát các đối tượng trừu tượng

- - - -
    -
  • {{JSxRef("Promise")}}
  • -
  • {{JSxRef("Generator")}}
  • -
  • {{JSxRef("GeneratorFunction")}}
  • -
  • {{JSxRef("AsyncFunction")}} {{Experimental_Inline}}
  • -
- - - -

Sự phản 

- -
    -
  • {{JSxRef("Reflect")}}
  • -
  • {{JSxRef("Proxy")}}
  • -
- -

Quốc tế hóa

- -

Bổ sung vào ECMAScript Core các chức năng phát hiện ngôn ng

- - - -
    -
  • {{JSxRef("Intl")}}
  • -
  • {{JSxRef("Global_Objects/Collator", "Intl.Collator")}}
  • -
  • {{JSxRef("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}
  • -
  • {{JSxRef("Global_Objects/ListFormat", "Intl.ListFormat")}}
  • -
  • {{JSxRef("Global_Objects/NumberFormat", "Intl.NumberFormat")}}
  • -
  • {{JSxRef("Global_Objects/PluralRules", "Intl.PluralRules")}}
  • -
  • {{JSxRef("Global_Objects/RelativeTimeFormat", "Intl.RelativeTimeFormat")}}
  • -
  • {{JSxRef("Global_Objects/Locale", "Intl.Locale")}}
  • -
- - - -

WebAssembly

- - - -
    -
  • {{JSxRef("WebAssembly")}}
  • -
  • {{JSxRef("WebAssembly.Module")}}
  • -
  • {{JSxRef("WebAssembly.Instance")}}
  • -
  • {{JSxRef("WebAssembly.Memory")}}
  • -
  • {{JSxRef("WebAssembly.Table")}}
  • -
  • {{JSxRef("WebAssembly.CompileError")}}
  • -
  • {{JSxRef("WebAssembly.LinkError")}}
  • -
  • {{JSxRef("WebAssembly.RuntimeError")}}
  • -
- - - -

Khác

- - - -
    -
  • {{JSxRef("Functions/arguments", "arguments")}}
  • -
- - -
diff --git a/files/vi/web/javascript/reference/global_objects/infinity/index.html b/files/vi/web/javascript/reference/global_objects/infinity/index.html deleted file mode 100644 index 73e388b0d1..0000000000 --- a/files/vi/web/javascript/reference/global_objects/infinity/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Infinity -slug: Web/JavaScript/Reference/Global_Objects/Infinity -translation_of: Web/JavaScript/Reference/Global_Objects/Infinity ---- -
{{jsSidebar("Objects")}}
- -

Thuộc tính global Infinity là giá trị kiểu số biểu diễn vô cùng.

- -

{{js_property_attributes(0,0,0)}}

- -
{{EmbedInteractiveExample("pages/js/globalprops-infinity.html")}}
- - - -

Cú pháp

- -
Infinity 
- -

Mô tả

- -

Infinity là một thuộc tính của global object, hay nói các khác, là một biến trong global scope.

- -

Giá trị khởi đầu của Infinity là {{jsxref("Number.POSITIVE_INFINITY")}}. Giá trị Infinity (dương vô cùng) lớn hơn mọi số. Về mặt toán học, giá trị này có biểu hiện giống hệt với vô cùng; chẳng hạn, mọi số dương nhân với Infinity đều bằng Infinity, và mọi số chia cho Infinity đều bằng 0.

- -

Như đã định nghĩa trong bản đặc tả ECMAScript 5, Infinity là chỉ-đọc (cài đặt trong JavaScript 1.8.5 / Firefox 4).

- -

Ví dụ

- -
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 */
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa lần đầu. Cài đặt trong JavaScript 1.3
{{SpecName('ES5.1', '#sec-15.1.1.2', 'Infinity')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Infinity")}}

- -

Xem thêm

- -
    -
  • {{jsxref("Number.NEGATIVE_INFINITY")}}
  • -
  • {{jsxref("Number.POSITIVE_INFINITY")}}
  • -
  • {{jsxref("Number.isFinite")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/isfinite/index.html b/files/vi/web/javascript/reference/global_objects/isfinite/index.html deleted file mode 100644 index a846d37172..0000000000 --- a/files/vi/web/javascript/reference/global_objects/isfinite/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: isFinite() -slug: Web/JavaScript/Reference/Global_Objects/isFinite -translation_of: Web/JavaScript/Reference/Global_Objects/isFinite ---- -
{{jsSidebar("Objects")}}
- -

Hàm global isFinite() xác định liệu giá trị truyền vào có phải một giá trị hữu hạn hay không. Nếu cần thiết, tham số sẽ được ép kiểu sang số trước.

- -
{{EmbedInteractiveExample("pages/js/globalprops-isfinite.html")}}
- - - -

Cú pháp

- -
isFinite(testValue)
- -

Tham số

- -
-
testValue
-
Giá trị để kiểm tra tính hữu hạn.
-
- -

Giá trị trả về

- -

false nếu đối số là dương hoặc âm {{jsxref("Infinity")}} hay là {{jsxref("NaN")}}; ngoài ra thì trả về true.

- -

Mô tả

- -

isFinite là hàm top-level và không liên kết với bất cứ object nào.

- -

Bạn có thể dùng hàm này để xác định liệu một số có phải là hữu hạn hay không. Hàm isFinite kiểm tra giá trị kiểu số truyền trong đối số của nó. Nếu đối số của nó là NaN, dương vô cùng, hoặc âm vô cùng, phương thức này trả về false; ngoài ra, nó trả về true.

- -

Ví dụ

- -
isFinite(Infinity);  // false
-isFinite(NaN);       // false
-isFinite(-Infinity); // false
-
-isFinite(0);         // true
-isFinite(2e64);      // true
-isFinite(910);       // true
-
-isFinite(null);      // true, sẽ trả về false với phương thức
-                     // chuyên biệt hơn Number.isFinite(null)
-
-isFinite('0');       // true, sẽ trả về false với phương thức
-                     // chuyên biệt hơn Number.isFinite("0")
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa lần đầu.
{{SpecName('ES5.1', '#sec-15.1.2.5', 'isFinite')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.isFinite")}}

- -

Xem thêm

- -
    -
  • {{jsxref("Number.isFinite()")}}
  • -
  • {{jsxref("Number.NaN")}}
  • -
  • {{jsxref("Number.POSITIVE_INFINITY")}}
  • -
  • {{jsxref("Number.NEGATIVE_INFINITY")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/json/index.html b/files/vi/web/javascript/reference/global_objects/json/index.html deleted file mode 100644 index 513e41e3ae..0000000000 --- a/files/vi/web/javascript/reference/global_objects/json/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: JSON -slug: Web/JavaScript/Reference/Global_Objects/JSON -translation_of: Web/JavaScript/Reference/Global_Objects/JSON ---- -
{{JSRef}}
- -

JSON object chứa các phương thức để phân giải JavaScript Object Notation ({{glossary("JSON")}}) và chuyển hóa các giá trị sang JSON. Nó có thể được called, hoặc constructed, và aside từ 2 phương thức thuộc tính của nó, nó tự bản thân lại không có chức năng thú vị nào.

- -

Khác nhau giữa JavaScript and JSON

- -

JSON là một cú pháp để serializing các object, array, number, string, boolean và {{jsxref("null")}}. Nó dựa trên cú pháp JavaScript nhưng lại khác biệt với JavaScript: một số JavaScript không phải là JSON.

- -
-
Objects và Arrays
-
Các tên thuộc tính phải được đặt trong nháy kép; dấu phẩy kéo đuôi trailing commas sẽ không được chấp nhận.
-
Numbers
-
Các số 0 nằm ở đầu sẽ bị cấm. Một dấu chấm thập phân phải được theo sau bởi ít nhất một chữ số. NaN và Infinity cũng không được hỗ trợ.
-
Bất kỳ JSON text nào cũng là một biểu thức JavaScript hợp lệ...
-
...Nhưng chỉ có các JavaScript engines mà đã từng triển khai proposal để làm làm tất cả JSON text hợp lệ ECMA-262. Trong các engines mà không triển khai proposal, U+2028 LINE SEPARATOR và U+2029 PARAGRAPH SEPARATOR được cho phép trong các string literals và các property keys trong JSON; nhưng việc sử dụng chúng trong các tính năng này trong các JavaScript string literal sẽ gây ra {{jsxref("SyntaxError")}}.
-
- -

Consider this example where {{jsxref("JSON.parse()")}} parses the string as JSON and eval executes the string as JavaScript:

- -
let code = '"\u2028\u2029"'
-JSON.parse(code)  // evaluates to "\u2028\u2029" in all engines
-eval(code)        // throws a SyntaxError in old engines
-
- -

Other differences include allowing only double-quoted strings and having no provisions for {{jsxref("undefined")}} or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is JSON5, used by the Babel compiler, and the more commonly used YAML.

- -

Cú pháp JSON đầy đủ

- -

Cú pháp JSON đầy đủ như sau:

- -
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
-
- -

Các khoảng trắng lớn có thể hiện diện ở bất cứ đâu ngoại trừ bên trong một JSONnumber (các số không được chứa khoảng trắng nào) hoặc JSONString (nơi mà nó được interpreted như là một ký tự tương ứng trong một chuỗi, hoặc sẽ gây ra lỗi). Ký tự tab (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) là những ký tự khoảng trắng duy nhất hợp lệ.

- -

Methods

- -
-
{{jsxref("JSON.parse()", "JSON.parse(text[, reviver])")}}
-
Phân giải chuỗi text dưới dạng JSON, tùy chọn thêm việc chuyển hóa giá trị được tạo ra và các thuộc tính của nó, sau đó return giá trị. Bất kì sự vi phạm nào về cú pháp JSON, kể cả những trường hợp liên quan đến sự khác nhau giữa JavaScript và JSON, sẽ dấn đến một {{jsxref("SyntaxError")}} được thrown. Lựa chọn reviver cho phép interpreting những gì mà replacer sử dụng để đại diện cho các kiểu dữ liệu khác.
-
{{jsxref("JSON.stringify()", "JSON.stringify(value[, replacer[, space]])")}}
-
Return một chuỗi JSON tương ứng với giá trị được chỉ định, tùy chọn thêm việc bao gồm chỉ các thuộc tính nhất định hoặc thay thế giá trị thuộc tính theo cách user định nghĩa. Mặc định, tất cả các instances của {{jsxref("undefined")}} sẽ được thay thế bằng {{jsxref("null")}}, và các kiểu dữ liệu native không được hỗ trợ khác sẽ bị kiểm duyệt. Tùy chọn replacer cho phép chỉ định các cách thực thi khác.
-
- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}
- -

Browser compatibility

- -
-
- - -

{{Compat("javascript.builtins.JSON")}}

-
-
- -

See also

- -
    -
  • {{jsxref("Date.prototype.toJSON()")}}
  • -
- -

Tools

- - diff --git a/files/vi/web/javascript/reference/global_objects/map/index.html b/files/vi/web/javascript/reference/global_objects/map/index.html deleted file mode 100644 index 45be246c96..0000000000 --- a/files/vi/web/javascript/reference/global_objects/map/index.html +++ /dev/null @@ -1,263 +0,0 @@ ---- -title: Map -slug: Web/JavaScript/Reference/Global_Objects/Map -tags: - - ES6 - - JavaScript - - Map - - cách dùng - - hàm -translation_of: Web/JavaScript/Reference/Global_Objects/Map ---- -
{{JSRef}}
- -

Đối tượng Map lưu cặp key-value (khoá - giá trị) theo thứ tự chèn vào của khoá. Bất kỳ giá trị nào (cả đối tượng (objects) và {{Glossary("Primitive", "primitive values")}}) đều có thể sử dụng làm key hoặc value.

- -

Cú pháp

- -
new Map([iterable])
- -

Tham số

- -
-
iterable
-
Một {{jsxref("Array")}} hoặc iterable object có các phần tử là cặp key-value (các mảng có 2 phần tử, vd. [[ 1, 'one' ],[ 2, 'two' ]]). Mỗi cặp key-value sẽ được thêm vào Map mới; những giá trị null chuyển thành undefined.
-
- -

Mô tả

- -

Một Map object duyệt qua các phần tử của nó theo thứ tự chèn vào –– một vòng lặp {{jsxref("Statements/for...of", "for...of")}} trả về một mảng [key, value] cho mỗi lần lặp.

- -

Key equality (so sánh key)

- -

Key được xác định bằng nhau dựa vào giải thuật "SameValueZero": NaN được xem là giống NaN (mặc dù NaN !== NaN) và tất cả các giá trị khác được xem xét bằng nhau theo toán tử ===. Trong đặc tả ECMAScript hiện tại, -0+0 là bằng nhau, cho dù điều này không đúng ở các bản dự thảo trước đó. Xem "Value equality for -0 and 0" trong bảng tương thích trình duyệt để biết thêm chi tiết.

- -

Objects and maps compared

- -

{{jsxref("Object", "Objects")}} tương tự với Maps ở chỗ cả hai đều cho phép bạn đặt keys cho values, lấy các values, xoá các keys và xem có gì được chứa trong một key không. Bởi vì điều này (và bởi vì trước đây không tích hợp các lựa chọn khác), trong lịch sử, Objects đã được dùng như Maps; Tuy vậy, có những điểm khác biệt khiến sử dụng một Map thích hợp hơn trong các trường hợp nhất định: 

- -
    -
  • Keys của một Object là {{jsxref("String", "Strings")}} và {{jsxref("Symbol", "Symbols")}}, trong khi chúng có thể là bất kỳ giá trị nào với Map, bao gồm hàm, objects và primitive.
  • -
  • Các keys trong Map có thứ tự trong khi các keys trong object thì không. Vì thế, khi duyệt qua, Map object trả về keys theo thứ tự chèn vào.
  • -
  • Bạn có thể lấy kích cỡ của một Map dễ dàng qua thuộc tính size, trong khi số thuộc tính trong một Object phải xác định thủ công.
  • -
  • Một Map là một iterable và do đó có thể được duyệt trực tiếp, trong khi để duyệt qua một Object cần lấy các keys của nó rồi mới duyệt.
  • -
  • Một Object có một prototype, vậy nên có các keys mặc định có thể xung đột với các keys của bạn nếu không cẩn thận. Ở ES5, điều này có thể tránh bằng cách sử dụng map = Object.create(null), nhưng hiếm khi thực hiện.
  • -
  • Một Map có thể thực thi tốt hơn ở các hoàn cảnh thường xuyên thêm và xoá các cặp keys.
  • -
- -

Các thuộc tính

- -
-
Map.length
-
Giá trị của thuộc tính length là 0.
-
Để lấy số phần tử đang có trong mảng, sử dụng {{jsxref("Map.prototype.size")}}.
-
{{jsxref("Map.@@species", "get Map[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("Map.prototype")}}
-
Represents the prototype for the Map constructor. Allows the addition of properties to all Map objects.
-
- -

Map instances

- -

?Tất cả Map instances kế thừa từ {{jsxref("Map.prototype")}}.

- -

Các thuộc tính

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}

- -

Các phương thức

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}

- -

?Ví dụ

- -

Sử dụng Map object

- -
var myMap = new Map();
-
-var keyString = 'a string',
-    keyObj = {},
-    keyFunc = function() {};
-
-// đặt các values
-myMap.set(keyString, "value associated with 'a string'");
-myMap.set(keyObj, 'value associated with keyObj');
-myMap.set(keyFunc, 'value associated with keyFunc');
-
-myMap.size; // 3
-
-// lấy các values
-myMap.get(keyString);    // "value associated with 'a string'"
-myMap.get(keyObj);       // "value associated with keyObj"
-myMap.get(keyFunc);      // "value associated with keyFunc"
-
-myMap.get('a string');   // "value associated with 'a string'"
-                         // ?vì keyString === 'a string'
-myMap.get({});           // undefined, vì keyObj !== {}
-myMap.get(function() {}) // undefined, vì  keyFunc !== function () {}
-
- -

Sử dụng NaN làm Map keys

- -

NaN có thể sử dụng làm một key. Kể cả khi mỗi NaN không bằng chính nó (NaN !== NaN trả về true), ví dụ sau chạy tốt bởi vì các NaNs không phân biệt lẫn nhau:

- -
var myMap = new Map();
-myMap.set(NaN, 'not a number');
-
-myMap.get(NaN); // "not a number"
-
-var otherNaN = Number('foo');
-myMap.get(otherNaN); // "not a number"
-
- -

Duyệt Maps với for..of

- -

Maps có thể được duyệt với vòng lặp for..of:

- -
var myMap = new Map();
-myMap.set(0, 'zero');
-myMap.set(1, 'one');
-for (var [key, value] of myMap) {
-  console.log(key + ' = ' + value);
-}
-// 0 = zero
-// 1 = one
-
-for (var key of myMap.keys()) {
-  console.log(key);
-}
-// 0
-// 1
-
-for (var value of myMap.values()) {
-  console.log(value);
-}
-// zero
-// one
-
-for (var [key, value] of myMap.entries()) {
-  console.log(key + ' = ' + value);
-}
-// 0 = zero
-// 1 = one
-
- -

Duyệt Maps với forEach()

- -

Maps có thể được duyệt bằng phương thức forEach():

- -
myMap.forEach(function(value, key) {
-  console.log(key + ' = ' + value);
-});
-// Will show 2 logs; first with "0 = zero" and second with "1 = one"
-
- -

Quan hệ với Array objects

- -
var kvArray = [['key1', 'value1'], ['key2', 'value2']];
-
-// Sử dụng hàm khởi tạo Map để chuyển một 2D key-value Array vào một map
-var myMap = new Map(kvArray);
-
-myMap.get('key1'); // returns "value1"
-
-// Sử dụng hàm Array.from để chuyển một map vào một 2D key-value Array
-console.log(Array.from(myMap)); // Sẽ hiện ra Array giống hệt kvArray
-
-// Hoặc sử dụng duyệt keys hoặc values và chuyển chúng thành một mảng
-console.log(Array.from(myMap.keys())); // Sẽ hiện ["key1", "key2"]
-
- -

Nhân bản (cloning) và gộp (merging) Maps

- -

Giống như Arrays, Maps có thể được nhân bản:

- -
var original = new Map([
-  [1, 'one']
-]);
-
-var clone = new Map(original);
-
-console.log(clone.get(1)); // one
-console.log(original === clone); // false. Useful for shallow comparison
- -

Keep in mind that the data itself is not cloned

- -

Maps có thể được gộp lại, vẫn đảm bảo các key là duy nhất: 

- -
var first = new Map([
-  [1, 'one'],
-  [2, 'two'],
-  [3, 'three'],
-]);
-
-var second = new Map([
-  [1, 'uno'],
-  [2, 'dos']
-]);
-
-// Merge two maps. The last repeated key wins.
-// Spread operator essentially converts a Map to an Array
-var merged = new Map([...first, ...second]);
-
-console.log(merged.get(1)); // uno
-console.log(merged.get(2)); // dos
-console.log(merged.get(3)); // three
- -

Maps cũng có thể được gộp với Arrays:

- -
var first = new Map([
-  [1, 'one'],
-  [2, 'two'],
-  [3, 'three'],
-]);
-
-var second = new Map([
-  [1, 'uno'],
-  [2, 'dos']
-]);
-
-// Merge maps with an array. The last repeated key wins.
-var merged = new Map([...first, ...second, [1, 'eins']]);
-
-console.log(merged.get(1)); // eins
-console.log(merged.get(2)); // dos
-console.log(merged.get(3)); // three
- -

Các đặc tả

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map-objects', 'Map')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}{{Spec2('ESDraft')}} 
- -

Tương thích trình duyệt

- - - -

{{Compat("javascript.builtins.Map")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/math/abs/index.html b/files/vi/web/javascript/reference/global_objects/math/abs/index.html deleted file mode 100644 index 94c4b859e8..0000000000 --- a/files/vi/web/javascript/reference/global_objects/math/abs/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Math.abs() -slug: Web/JavaScript/Reference/Global_Objects/Math/abs -tags: - - JavaScript - - Math - - Phương Thức - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs ---- -
{{JSRef}}
- -

Hàm Math.abs() trả về giá trị tuyệt đối của một số như sau

- -

Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(z)}} = {|z|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ x & \text{if} \quad x < 0 \end{cases}

- -
{{EmbedInteractiveExample("pages/js/math-abs.html")}}
- - - -

Cú pháp

- -
Math.abs(x)
- -

Tham số

- -
-
x
-
Loại số liệu.
-
- -

Giá trị trả về

- -

Giá trị tuyệt đối của số đã cho.

- -

Mô tả

- -

 

- -

Do abs() là phương thức tĩnh của Math, nên ta phải khai báo là Math.abs(), thay vì dùng nó như 1 phương thức của đối tượng được tạo ra từ Math (Math không phải hàm tạo).

- -

 

- -

Ví dụ

- -

Hành vi của Math.abs()

- -

Truyền một đối tượng rỗng, một mảng có hơn một giá trị, một chuỗi ký tự không-có-số hay một {{jsxref("undefined")}}/biến rỗng sẽ trả về {{jsxref("NaN")}}. Truyền {{jsxref("null")}}, một chuỗi rỗng hay một mảng rỗng sẽ trả về số 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
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa đầu tiên. Được đưa vào 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')}} 
- -

Tính tương thích trên trình duyệt

- - - -

{{Compat("javascript.builtins.Math.abs")}}

- -

Xem thêm

- -
    -
  • {{jsxref("Math.ceil()")}}
  • -
  • {{jsxref("Math.floor()")}}
  • -
  • {{jsxref("Math.round()")}}
  • -
  • {{jsxref("Math.sign()")}}
  • -
  • {{jsxref("Math.trunc()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/math/ceil/index.html b/files/vi/web/javascript/reference/global_objects/math/ceil/index.html deleted file mode 100644 index 09b056af36..0000000000 --- a/files/vi/web/javascript/reference/global_objects/math/ceil/index.html +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Math.ceil() -slug: Web/JavaScript/Reference/Global_Objects/Math/ceil -tags: - - JavaScript - - Math - - Phương Thức - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil ---- -
{{JSRef}}
- -

Hàm Math.ceil() trả về số nguyên nhỏ nhất có giá trị lớn hơn hoặc bằng số đã cho.

- -

Lưu ý: Math.ceil({{jsxref("null")}}) trả về số nguyên 0 và không đưa ra lỗi {{jsxref("NaN")}}.

- -
{{EmbedInteractiveExample("pages/js/math-ceil.html")}}
- - - -

Cú pháp

- -
Math.ceil(x)
- -

Tham số

- -
-
x
-
Loại số liệu.
-
- -

Giá trị trả về

- -

Số nguyên nhỏ nhất có giá trị lớn hơn hoặc bằng số đã cho (bằng tham số).

- -

Mô tả

- -

Do ceil() là phương thức tĩnh của Math, nên ta phải khai báo là Math.ceil(), thay vì dùng nó như 1 phương thức của đối tượng được tạo ra từ Math (Math không phải hàm tạo).

- -

Ví dụ

- -

Cách dùng Math.ceil()

- -

Ví dụ sau minh họa cách dùng Math.ceil() điển hình.

- -
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
-
- -

Tinh chỉ số thập phân

- -
// Đóng kín
-(function() {
-  /**
-   * Tinh chỉ số thập phân của một con số.
-   *
-   * @param {String}  type  Loại điều chỉnh.
-   * @param {Number}  value Số liệu.
-   * @param {Integer} exp   Số mũ (the 10 logarithm of the adjustment base).
-   * @returns {Number} Giá trị đã chỉnh sửa.
-   */
-  function decimalAdjust(type, value, exp) {
-    // Nếu exp có giá trị undefined hoặc bằng không thì...
-    if (typeof exp === 'undefined' || +exp === 0) {
-      return Math[type](value);
-    }
-    value = +value;
-    exp = +exp;
-    // Nếu value không phải là ố hoặc exp không phải là số nguyên thì...
-    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));
-  }
-
-  // Làm tròn số thập phân (theo mốc số 5)
-  if (!Math.round10) {
-    Math.round10 = function(value, exp) {
-      return decimalAdjust('round', value, exp);
-    };
-  }
-  // Làm tròn số thập phân (về gần giá trị 0)
-  if (!Math.floor10) {
-    Math.floor10 = function(value, exp) {
-      return decimalAdjust('floor', value, exp);
-    };
-  }
-  // Làm tròn số thập phân (ra xa giá trị 0)
-  if (!Math.ceil10) {
-    Math.ceil10 = function(value, exp) {
-      return decimalAdjust('ceil', value, exp);
-    };
-  }
-})();
-
-// Chạy hàm 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
-// Chạy hàm 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
-// Chạy hàm 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
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa đầu tiên được đưa vào 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')}} 
- -

Tính tương thích trên trình duyệt

- - - -

{{Compat("javascript.builtins.Math.ceil")}}

- -

Xem thêm

- -
    -
  • {{jsxref("Math.abs()")}}
  • -
  • {{jsxref("Math.floor()")}}
  • -
  • {{jsxref("Math.round()")}}
  • -
  • {{jsxref("Math.sign()")}}
  • -
  • {{jsxref("Math.trunc()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/math/floor/index.html b/files/vi/web/javascript/reference/global_objects/math/floor/index.html deleted file mode 100644 index 2f660fcf00..0000000000 --- a/files/vi/web/javascript/reference/global_objects/math/floor/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Math.floor() -slug: Web/JavaScript/Reference/Global_Objects/Math/floor -translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor ---- -
{{JSRef}}
- -

Hàm Math.floor() trả về số nguyên bé hơn hoặc bằng số ban đầu.

- -
{{EmbedInteractiveExample("pages/js/math-floor.html")}}
- - - -

Cú pháp

- -
Math.floor(x)
- -

Tham số

- -
-
x
-
Một số.
-
- -

Giá trị trả về

- -

Số nguyên lớn nhất nhỏ hơn hoặc bằng số đã cho.

- -

Mô tả

- -

Bởi vì floor() là một phương thức tĩnh của Math, bạn luôn sử dụng Math.floor(), thay vì sử dụng như là một phương thức của đối tượng được tạo ra từ Math (Math không phải là một constructor).

- -
-

Lưu ý: Math.floor(null) trả về 0, không phải {{jsxref("NaN")}}.

-
- -

Ví dụ

- -

Sử dụng 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
-
- -

Điều chỉnh thập phân

- -
/**
- * 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
-const round10 = (value, exp) => decimalAdjust('round', value, exp);
-// Decimal floor
-const floor10 = (value, exp) => decimalAdjust('floor', value, exp);
-// Decimal ceil
-const ceil10 = (value, exp) => decimalAdjust('ceil', value, exp);
-
-// Round
-round10(55.55, -1);   // 55.6
-round10(55.549, -1);  // 55.5
-round10(55, 1);       // 60
-round10(54.9, 1);     // 50
-round10(-55.55, -1);  // -55.5
-round10(-55.551, -1); // -55.6
-round10(-55, 1);      // -50
-round10(-55.1, 1);    // -60
-// Floor
-floor10(55.59, -1);   // 55.5
-floor10(59, 1);       // 50
-floor10(-55.51, -1);  // -55.6
-floor10(-51, 1);      // -60
-// Ceil
-ceil10(55.51, -1);    // 55.6
-ceil10(51, 1);        // 60
-ceil10(-55.59, -1);   // -55.5
-ceil10(-59, 1);       // -50
-
- -

Quy cách kỹ thuật

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}
- -

Trình duyệt tương thích

- - - -

{{Compat("javascript.builtins.Math.floor")}}

- -

Xem thêm:

- -
    -
  • {{jsxref("Math.abs()")}}
  • -
  • {{jsxref("Math.ceil()")}}
  • -
  • {{jsxref("Math.round()")}}
  • -
  • {{jsxref("Math.sign()")}}
  • -
  • {{jsxref("Math.trunc()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/math/index.html b/files/vi/web/javascript/reference/global_objects/math/index.html deleted file mode 100644 index bfaa405142..0000000000 --- a/files/vi/web/javascript/reference/global_objects/math/index.html +++ /dev/null @@ -1,196 +0,0 @@ ---- -title: Math -slug: Web/JavaScript/Reference/Global_Objects/Math -tags: - - JavaScript - - Math - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Math ---- -
{{JSRef}}
- -

Math is a built-in object that has properties and methods for mathematical constants and functions. Not a function object.

- -

Description

- -

Unlike the other global objects, Math is not a constructor. All properties and methods of Math are static. You refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument. Constants are defined with the full precision of real numbers in JavaScript.

- -

Properties

- -
-
{{jsxref("Math.E")}}
-
Euler's constant and the base of natural logarithms, approximately 2.718.
-
{{jsxref("Math.LN2")}}
-
Natural logarithm of 2, approximately 0.693.
-
{{jsxref("Math.LN10")}}
-
Natural logarithm of 10, approximately 2.303.
-
{{jsxref("Math.LOG2E")}}
-
Base 2 logarithm of E, approximately 1.443.
-
{{jsxref("Math.LOG10E")}}
-
Base 10 logarithm of E, approximately 0.434.
-
{{jsxref("Math.PI")}}
-
Ratio of the circumference of a circle to its diameter, approximately 3.14159.
-
{{jsxref("Math.SQRT1_2")}}
-
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
-
{{jsxref("Math.SQRT2")}}
-
Square root of 2, approximately 1.414.
-
- -

Methods

- -
-

Note that the trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) expect or return angles in radians. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

-
- -
-

Note that many math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.

-
- -
-
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
-
Returns the absolute value of a number.
-
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
-
Returns the arccosine of a number.
-
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
-
Returns the hyperbolic arccosine of a number.
-
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
-
Returns the arcsine of a number.
-
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
-
Returns the hyperbolic arcsine of a number.
-
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
-
Returns the arctangent of a number.
-
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
-
Returns the hyperbolic arctangent of a number.
-
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
-
Returns the arctangent of the quotient of its arguments.
-
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
-
Returns the cube root of a number.
-
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
-
Returns the smallest integer greater than or equal to a number.
-
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
-
Returns the number of leading zeroes of a 32-bit integer.
-
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
-
Returns the cosine of a number.
-
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
-
Returns the hyperbolic cosine of a number.
-
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
-
Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
-
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
-
Returns subtracting 1 from exp(x).
-
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
-
Returns the largest integer less than or equal to a number.
-
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
-
Returns the nearest single precision float representation of a number.
-
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
-
Returns the square root of the sum of squares of its arguments.
-
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
-
Returns the result of a 32-bit integer multiplication.
-
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
-
Returns the natural logarithm (loge, also ln) of a number.
-
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
-
Returns the natural logarithm (loge, also ln) of 1 + x for a number x.
-
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
-
Returns the base 10 logarithm of a number.
-
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
-
Returns the base 2 logarithm of a number.
-
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
-
Returns the largest of zero or more numbers.
-
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
-
Returns the smallest of zero or more numbers.
-
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
-
Returns base to the exponent power, that is, baseexponent.
-
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
-
Returns a pseudo-random number between 0 and 1.
-
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
-
Returns the value of a number rounded to the nearest integer.
-
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
-
Returns the sign of the x, indicating whether x is positive, negative or zero.
-
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
-
Returns the sine of a number.
-
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
-
Returns the hyperbolic sine of a number.
-
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
-
Returns the positive square root of a number.
-
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
-
Returns the tangent of a number.
-
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
-
Returns the hyperbolic tangent of a number.
-
Math.toSource() {{non-standard_inline}}
-
Returns the string "Math".
-
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
-
Returns the integer part of the number x, removing any fractional digits.
-
- -

Extending the Math object

- -

As with most of the built-in objects in JavaScript, the Math object can be extended with custom properties and methods. To extend the Math object, you do not use prototype. Instead, you directly extend Math:

- -
Math.propName = propValue;
-Math.methodName = methodRef;
- -

For instance, the following example adds a method to the Math object for calculating the greatest common divisor of a list of arguments.

- -
/* Variadic function -- Returns the greatest common divisor of a list of arguments */
-Math.gcd = function() {
-    if (arguments.length == 2) {
-        if (arguments[1] == 0)
-            return arguments[0];
-        else
-            return Math.gcd(arguments[1], arguments[0] % arguments[1]);
-    } else if (arguments.length > 2) {
-        var result = Math.gcd(arguments[0], arguments[1]);
-        for (var i = 2; i < arguments.length; i++)
-            result = Math.gcd(result, arguments[i]);
-        return result;
-    }
-};
- -

Try it:

- -
console.log(Math.gcd(20, 30, 15, 70, 40)); // `5`
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Math")}}

- -

See also

- -
    -
  • {{jsxref("Number")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/math/sqrt/index.html b/files/vi/web/javascript/reference/global_objects/math/sqrt/index.html deleted file mode 100644 index cefbcccb04..0000000000 --- a/files/vi/web/javascript/reference/global_objects/math/sqrt/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Math.sqrt() -slug: Web/JavaScript/Reference/Global_Objects/Math/sqrt -tags: - - JavaScript - - Math - - Phương Thức - - Tham khảo - - Toán -translation_of: Web/JavaScript/Reference/Global_Objects/Math/sqrt ---- -
{{JSRef}}
- -

Hàm Math.sqrt() trả về giá trị căn bậc hai, that is

- -

x0,Math.sqrt(x)=x=trị tuyệt đối củay0tương ứngy2=x\forall x \geq 0, \mathtt{Math.sqrt(x)} = \sqrt{x} = \text{the unique} \; y \geq 0 \; \text{such that} \; y^2 = x

- -
{{EmbedInteractiveExample("pages/js/math-sqrt.html")}}
- - - -

Cú pháp

- -
Math.sqrt(x)
- -

Tham số

- -
-
x
-
Một con số
-
- -

Giá trị trả về

- -

Căn bậc hai của số cung cấp. Nếu hàm nhận giá trị, {{jsxref("NaN")}} sẽ bị trả về.

- -

Mô tả

- -

Nếu x là con số âm, Math.sqrt() sẽ trả về {{jsxref("NaN")}}.

- -

Do sqrt() là phương thức tĩnh của Math, ta phải dùng theo cách này Math.sqrt(), thay vì dùng dưới dạng phương thức của đối tượng Math mà bạn tạo ra (Math không phải là một hàm khởi tạo, constructor).

- -

Ví dụ

- -

Dùng Math.sqrt()

- -
Math.sqrt(9); // 3
-Math.sqrt(2); // 1.414213562373095
-
-Math.sqrt(1);  // 1
-Math.sqrt(0);  // 0
-Math.sqrt(-1); // NaN
-Math.sqrt(-0); // -0
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa lần đầu. Tích hợp trong 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')}}
- -

Tính tương thích trên trình duyệt

- - - -

{{Compat("javascript.builtins.Math.sqrt")}}

- -

Xem thêm

- -
    -
  • {{jsxref("Math.cbrt()")}}
  • -
  • {{jsxref("Math.exp()")}}
  • -
  • {{jsxref("Math.log()")}}
  • -
  • {{jsxref("Math.pow()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/nan/index.html b/files/vi/web/javascript/reference/global_objects/nan/index.html deleted file mode 100644 index cf7be92a59..0000000000 --- a/files/vi/web/javascript/reference/global_objects/nan/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: NaN -slug: Web/JavaScript/Reference/Global_Objects/NaN -tags: - - JavaScript - - Tham khảo - - Thuộc tính -translation_of: Web/JavaScript/Reference/Global_Objects/NaN ---- -
{{jsSidebar("Objects")}}
- -

Thuộc tính global NaN có giá trị đại diện cho khái niệm Not-A-Number (Không-phải-Số).

- -

{{js_property_attributes(0,0,0)}}

- -
{{EmbedInteractiveExample("pages/js/globalprops-nan.html")}}
- - - -

Cú pháp

- -
NaN
- -

Mô tả

- -

NaN là thuộc tính của đối tượng global.

- -

Giá trị khởi tạo của NaN là Not-A-Number — giống như giá trị của {{jsxref("Number.NaN")}}. Với các trình duyệt hiện đại, NaN không thể cấu hình được, không có thuộc tính được-viết. Kể cả khi được phép thì vẫn phải tránh việc ghi đè lên nó.

- -

Người ta hiếm khi dùng NaN trong viết chương trình. Nó được dùng làm giá trị trả về khi việc tính toán của các hàm {{jsxref("Math")}} thất bại (Math.sqrt(-1)) hoặc khi hàm phân tích phải dữ liệu số sai (parseInt("là lá la")).

- -

Kiểm thử phép so sánh NaN

- -

Không thể thực hiện phép so sánh bằng (thông qua ==, !=, ===, và !==NaN với bất kỳ giá trị nào khác, bao gồm cả một giá trị NaN khác. Hãy dùng {{jsxref("Number.isNaN()")}} hoặc {{jsxref("Global_Objects/isNaN", "isNaN()")}} để xác định rõ ràng đó có phải là NaN hay không. Hoặc làm thử một phép so sánh bản thân: NaN, và chỉ NaN, sẽ so sánh không cân bằng với chính nó.

- -
NaN === NaN;        // false (sai)
-Number.NaN === NaN; // false
-isNaN(NaN);         // true (đúng)
-isNaN(Number.NaN);  // true
-
-function valueIsNaN(v) { return v !== v; }
-valueIsNaN(1);          // false
-valueIsNaN(NaN);        // true
-valueIsNaN(Number.NaN); // true
-
- -

Tuy nhiên, lưu ý rằng có khác biệt giữa isNaN() và Number.isNaN(): isNaN() sẽ trả về giá trị true (đúng) nếu như giá trị hiện tại là NaN hoặc nó sẽ thành NaN sau khi bị ép số hóa dữ liệu, còn với Number.isNaN() thì dữ liệu trả về là true chỉ khi giá trị hiện tại là NaN.

- -
isNaN('hello world'); // trả về giá trị 'true'.
-Number.isNaN('hello world'); // trả về giá trị 'false'.
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa đầu tiên. Được đưa vào JavaScript 1.3
{{SpecName('ES5.1', '#sec-15.1.1.1', 'NaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích trên trình duyệt

- - - -

{{Compat("javascript.builtins.NaN")}}

- -

Xem thêm

- -
    -
  • {{jsxref("Number.NaN")}}
  • -
  • {{jsxref("Number.isNaN()")}}
  • -
  • {{jsxref("isNaN", "isNaN()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/number/index.html b/files/vi/web/javascript/reference/global_objects/number/index.html deleted file mode 100644 index 24b3e1b756..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/index.html +++ /dev/null @@ -1,216 +0,0 @@ ---- -title: Number -slug: Web/JavaScript/Reference/Global_Objects/Number -tags: - - JavaScript - - Number - - Reference - - Vietnamese -translation_of: Web/JavaScript/Reference/Global_Objects/Number ---- -
{{JSRef}}
- -

Đối tượng JavaScript Number là một đối tượng bao bọc cho phép bạn làm việc với các giá trị số. Một đối tượng Number có thể được tạo ra sử dụng hàm khởi tạo Number().

- -

Cú pháp

- -
new Number(value);
- -

Các tham số

- -
-
value
-
Giá trị số của đối tượng được tạo ra.
-
- -

Mô tả

- -

Các sử dụng chính cho đối tượng Number là:

- -
    -
  • Nếu đối số không thể chuyển đổi được sang một số, nó trả về {{jsxref("NaN")}}.
  • -
  • Trong một ngữ cảnh không phải constructor (vd, không dùng toán tử {{jsxref("Operators/new", "new")}}), Number có thể được sử dụng để thực hiện chuyển đổi kiểu.
  • -
- -

Các thuộc tính

- -
-
{{jsxref("Number.EPSILON")}}
-
Khoảng cách nhỏ nhất giữa hai số có thể biểu thị được.
-
{{jsxref("Number.MAX_SAFE_INTEGER")}}
-
Các số an toàn tối đa trong JavaScript (253 - 1)
-
{{jsxref("Number.MAX_VALUE")}}
-
Đại diện cho giá trị số lớn nhất.
-
{{jsxref("Number.MIN_SAFE_INTEGER")}}
-
Các số an toàn tối thiểu trong JavaScript (-(253 - 1)).
-
{{jsxref("Number.MIN_VALUE")}}
-
Đại diện cho giá trị số nhỏ nhất - nghĩa là số dương gần với không nhất (không thực sự bằng không).
-
{{jsxref("Number.NaN")}}
-
Giá trị đặc biệt "không phải là một số".
-
{{jsxref("Number.NEGATIVE_INFINITY")}}
-
Giá trị đặc biệt đại diện cho âm vô cùng; được trả về khi tràn.
-
{{jsxref("Number.POSITIVE_INFINITY")}}
-
Giá trị đặc biệt đại diện cho dương vô cùng; được trả về khi tràn.
-
{{jsxref("Number.prototype")}}
-
-

Cho phép thêm các thuộc tính cho đối tượng Number

-
-
- -

Các phương thức

- -
-
{{jsxref("Number.isNaN()")}}
-
Xác định giá trị được truyền là NaN.
-
{{jsxref("Number.isFinite()")}}
-
Xác định giá trị được truyền là một số hữu hạn.
-
{{jsxref("Number.isInteger()")}}
-
Xác định giá trị được truyền là một số nguyên.
-
{{jsxref("Number.isSafeInteger()")}}
-
Xác định giá trị được truyền là một số an toàn (số giữa -(253 - 1) và 253 - 1).
-
{{jsxref("Number.toInteger()")}} {{obsolete_inline}}
-
Được sử dụng để đánh giá giá trị được truyền và chuyển đổi nó sang một số nguyên (or {{jsxref("Global_Objects/Infinity", "Infinity")}}), nhưng đã được loại bỏ.
-
{{jsxref("Number.parseFloat()")}}
-
Giá trị cũng giống như {{jsxref("parseFloat", "parseFloat()")}} của đối tượng toàn cầu.
-
{{jsxref("Number.parseInt()")}}
-
Giá trị cũng giống như {{jsxref("parseInt", "parseInt()")}} của đối tượng toàn cầu.
-
- -

Các thể hiện của Number

- -

Tất cả các thể hiện của Number được kế thừa từ {{jsxref("Number.prototype")}}. Các đối tượng nguyên mẫu (prototype) của hàm khởi tạo Number có thể được sửa đổi để ảnh hưởng đến tất cả các thể hiện của Number.

- -

Các ví dụ

- -

Sử dụng đối tượng Number để gán các giá trị cho các biến số.

- -

Ví dụ sau sử dụng các thuộc tính của đối tượng Number để gán các giá trị cho các biến số khác nhau:

- -
var biggestNum = Number.MAX_VALUE;
-var smallestNum = Number.MIN_VALUE;
-var infiniteNum = Number.POSITIVE_INFINITY;
-var negInfiniteNum = Number.NEGATIVE_INFINITY;
-var notANum = Number.NaN;
- -

Phạm vi số nguyên của Number

- -

Ví dụ sau cho thấy các giá trị số nguyên tối thiểu và tối đa có thể được biểu diễn dưới dạng đối tượng Number:

- -
var biggestInt = 9007199254740992;
-var smallestInt = -9007199254740992;
-
- -

Khi phân tích cú pháp dữ liệu đã được tuần tự hóa thành JSON, các giá trị số nguyên vượt ra khỏi phạm vi này có thể được dự kiến sẽ bị hỏng khi trình phân tích cú pháp JSON ép buộc chúng với kiểu Số. Sử dụng {{jsxref ("String")}} thay vào đó là một giải pháp khả thi.

- -

Sử dụng Number để chuyển đổi một đối tượng Date

- -

Ví dụ sau chuyển đổi một đối tượng {{jsxref("Date")}} sang một giá trị số sử dụng Number như là một hàm:

- -
var d = new Date('October 30, 1996 13:46:36');
-console.log(Number(d));
-
- -

Kết quả: 846657996000.

- -

Chuyển đổi chuỗi dạng số sang số

- -
Number("123")     // 123
-Number("")        // 0
-Number("   ")     // 0
-Number("0x11")    // 17
-Number("0b11")    // 3
-Number("0o11")    // 9
-Number("foo")     // NaN
-Number("100a")    // NaN
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc điểm kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu. Được thực hiện trong JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number-objects', 'Number')}}{{Spec2('ES6')}}Đã thêm các phương pháp và thuộc tính mới: {{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')}} 
- -

Khả năng tương thích trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
Đặc tínhChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
Đặc tínhAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Xem thêm

- -
    -
  • {{jsxref("NaN")}}
  • -
  • The {{jsxref("Math")}} đối tượng toàn cầu
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/number/isfinite/index.html b/files/vi/web/javascript/reference/global_objects/number/isfinite/index.html deleted file mode 100644 index 907227aa76..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/isfinite/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Number.isFinite() -slug: Web/JavaScript/Reference/Global_Objects/Number/isFinite -translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite ---- -
{{JSRef}}
- -

Phương thức Number.isFinite() xác định liệu giá trị truyền vào có phải một giá trị hữu hạn hay không.

- -
{{EmbedInteractiveExample("pages/js/number-isfinite.html")}}
- - - -

Cú pháp

- -
Number.isFinite(value)
- -

Tham số

- -
-
value
-
Giá trị để kiểm tra tính hữu hạn.
-
- -

Giá trị trả về

- -

Giá trị {{jsxref("Boolean")}} cho biết liệu giá trị truyền vào có phải hữu hạn hay không.

- -

Mô tả

- -

So sánh với hàm global {{jsxref("isFinite", "isFinite()")}}, phương thức này không ép kiểu tham số truyền vào thành kiểu số. Nghĩa là chỉ những giá trị có kiểu số, đồng thời có giá trị hữu hạn, mới trả về true.

- -

Ví dụ

- -
Number.isFinite(Infinity);  // false
-Number.isFinite(NaN);       // false
-Number.isFinite(-Infinity); // false
-
-Number.isFinite(0);         // true
-Number.isFinite(2e64);      // true
-
-Number.isFinite('0');       // false, sẽ thành true nếu dùng
-                            // global isFinite('0')
-Number.isFinite(null);      // false, sẽ thành true nếu dùng
-                            // global isFinite(null)
-
- -

Polyfill

- -
if (Number.isFinite === undefined) Number.isFinite = function(value) {
-    return typeof value === 'number' && isFinite(value);
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ES6')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.isFinite")}}

- -

Xem thêm

- -
    -
  • Đối tượng {{jsxref("Number")}} mà phương thức thuộc về.
  • -
  • The global function {{jsxref("isFinite")}}.
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/number/isinteger/index.html b/files/vi/web/javascript/reference/global_objects/number/isinteger/index.html deleted file mode 100644 index 522ff1945a..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/isinteger/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -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}}
- -

Phương thức Number.isInteger() xác định xem giá trị truyền vô có phải là một integer hay không.

- -

Cú pháp

- -
Number.isInteger(value)
- -

Parameters

- -
-
value
-
Giá trị cần kiểm tra xem nó có phải là một integer hay không.
-
- -

Mô tả

- -

Nếu giá trị mà bạn truyền vô trong phương thức này là một integer, kết quả trả về sẽ là true, ngược lại thì trả về false. Nếu giá trị đó là {{jsxref("NaN")}} hoặc các giá trị Infinity thì đương nhiên vẫn trả về false.

- -

Các ví dụ

- -
Number.isInteger(0);         // true
-Number.isInteger(1);         // true
-Number.isInteger(-100000);   // true
-
-Number.isInteger(0.1);       // false
-Number.isInteger(Math.PI);   // 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
-
- -

Polyfill

- -
Number.isInteger = Number.isInteger || function(value) {
-  return typeof value === "number" &&
-    isFinite(value) &&
-    Math.floor(value) === value;
-};
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-number.isinteger', 'Number.isInteger')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.isinteger', 'Number.isInteger')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- -

{{Compat("javascript.builtins.Number.isInteger")}}

- -
 
- -

Xem thêm

- -
    -
  • Các đối tượng thuộc {{jsxref("Number")}}.
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/number/isnan/index.html b/files/vi/web/javascript/reference/global_objects/number/isnan/index.html deleted file mode 100644 index a4497d6dae..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/isnan/index.html +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Number.isNaN() -slug: Web/JavaScript/Reference/Global_Objects/Number/isNaN -tags: - - ECMAScript 2015 - - JavaScript - - Method - - Number -translation_of: Web/JavaScript/Reference/Global_Objects/Number/isNaN ---- -
{{JSRef}}
- -

Phương thức Number.isNaN() (NaN viết tắt cho Not a Number) xác định xem giá trị đó có chính xác là {{jsxref("NaN")}} hay không. Một phiên bản khác của phương thức này, nhưng nằm trong phạm vi global đó là: {{jsxref("isNaN", "isNaN()")}}.

- -

Cú pháp

- -
Number.isNaN(value)
- -

Parameters

- -
-
value
-
Giá trị truyền vô để kiểm tra xem nó có phải chính xác là {{jsxref("NaN")}} hay không.
-
- -

Mô tả

- -

Cả hai phương pháp operator so sánh bằng, đó là {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} và {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}} đề trả ra false khi chúng ta kiểm tra giá trị {{jsxref("NaN")}} {{jsxref("NaN")}} ví dụ: NaN === NaN, (đáng lẽ ra là true đúng không ?, nhưng thực tế giá trị NaN này không thể được xác định bằng cách này.), phương thức Number.isNaN() được tạo ra để làm việc này. Phương pháp này đưa ra 1 giải pháp để xác định NaN, NaN là một giá trị mà không thể so sánh với chính nó để kiểm tra như các giá trị khác trong JavaScript.

- -

{{jsxref("isNaN", "isNaN()")}} là phương thức kiểm tra NaN trong phạm vi global, lưu ý là Number.isNaN() không giống như isNaN() trong global, Number.isNaN() xác định chính xác {{jsxref("NaN")}} đó có phải là giá trị {{jsxref("NaN")}} của Number hay không. Vì, chỉ có NaN thật sự mới đưa ra được giá trị true khi mang vô phương thức này. Khác với global, miễn cái gì không phải là số thì cũng trả ra giá trị là true.

- -

Các ví dụ

- -
Number.isNaN(NaN);        // true
-Number.isNaN(Number.NaN); // true
-Number.isNaN(0 / 0)       // true
-
-// e.g. these would have been true with global isNaN()
-Number.isNaN("NaN");      // false
-Number.isNaN(undefined);  // false
-Number.isNaN({});         // false
-Number.isNaN("blabla");   // false
-
-// These all return false
-Number.isNaN(true);
-Number.isNaN(null);
-Number.isNaN(37);
-Number.isNaN("37");
-Number.isNaN("37.37");
-Number.isNaN("");
-Number.isNaN(" ");
-
- -

Polyfill

- -
Number.isNaN = Number.isNaN || function(value) {
-    return typeof value === "number" && isNaN(value);
-}
-
-// Or
-Number.isNaN = Number.isNaN || function(value) {
-    return value !== value;
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-number.isnan', 'Number.isnan')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.isnan', 'Number.isnan')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{Compat("javascript.builtins.Number.isNaN")}}
- -
 
- -

See also

- -
    -
  • {{jsxref("Number")}}
  • -
  • {{jsxref("isNaN", "isNaN()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/number/issafeinteger/index.html b/files/vi/web/javascript/reference/global_objects/number/issafeinteger/index.html deleted file mode 100644 index f49bf8d30e..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/issafeinteger/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Number.isSafeInteger() -slug: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger -translation_of: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger ---- -
{{JSRef}}
- -

Phương thức Number.isSafeInteger() xác định xem giá trị truyền vào có phải một số nằm trong khoảng của số nguyên an toàn hay không.

- -
{{EmbedInteractiveExample("pages/js/number-issafeinteger.html")}}
- - - -

Số nguyên an toàn là số nguyên mà

- -
    -
  • có thể được biểu diễn chính xác theo chuẩn số nguyên độ chính xác kép IEEE-754, và
  • -
  • cách biểu diễn theo chuẩn IEEE-754 đó không thể bằng kết quả của một phép làm tròn số nguyên khác theo chuẩn biểu diễn IEEE-754.
  • -
- -

Chẳng hạn, 253 - 1 là một số nguyên an toàn: nó có thể hiển thị chính xác, và không có số nguyên nào có thể làm tròn đến nó với bất cứ chế độ làm tròn theo chuẩn IEEE-754. Ngoài ra, 253 không phải là một số nguyên an toàn: nó có thể được biểu diễn chính xác theo chuẩn IEEE-754, nhưng số nguyên 253 + 1 không thể hiển thị chính xác theo chuẩn IEEE-754 mà thay vào đó được làm tròn về 253 theo kiểu làm tròn về số gần nhất và làm tròn về không. Số nguyên an toàn nằm trong đoạn từ -(253 - 1) đến 253 - 19007199254740991hoặc ±9,007,199,254,740,991).

- -

Xử lý giá trị lớn hơn hoặc nhỏ hơn ~9 triệu tỉ với độ chính xác toàn vẹn yêu cầu sử dụng thư viện số học độ chính xác bất kì. Xem What Every Programmer Needs to Know about Floating Point Arithmetic để biết thêm thông tin về cách biểu diễn số thực dấu phẩy động.

- -

Cú pháp

- -
Number.isSafeInteger(testValue)
-
- -

Tham số

- -
-
testValue
-
Giá trị để kiểm tra có phải số nguyên an toàn hay không.
-
- -

Giá trị trả về

- -

{{jsxref("Boolean")}} cho biết liệu giá trị truyền vào có phải là số nguyên an toàn hay không.

- -

Ví dụ

- -
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
-
- -

Polyfill

- -
Number.isSafeInteger = Number.isSafeInteger || function (value) {
-   return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
-};
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}{{Spec2('ES2015')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.isSafeInteger")}}

- -

Xem thêm

- -
    -
  • Đối tượng {{jsxref("Number")}}.
  • -
  • {{jsxref("Number.MIN_SAFE_INTEGER")}}
  • -
  • {{jsxref("Number.MAX_SAFE_INTEGER")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/number/max_safe_integer/index.html b/files/vi/web/javascript/reference/global_objects/number/max_safe_integer/index.html deleted file mode 100644 index 7ae2ab0657..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/max_safe_integer/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Number.MAX_SAFE_INTEGER -slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER -translation_of: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER ---- -
{{JSRef}}
- -

Hằng Number.MAX_SAFE_INTEGER biểu diễn giá trị số nguyên an toàn lớn nhất trong JavaScript (253 - 1).

- -
{{EmbedInteractiveExample("pages/js/number-maxsafeinteger.html")}}
- - - -
{{js_property_attributes(0, 0, 0)}}
- -

Mô tả

- -

Hằng MAX_SAFE_INTEGER có giá trị là 9007199254740991(9,007,199,254,740,991 hay là ~9 triệu tỉ). Nguyên do đằng sau con số đó là do JavaScript sử dụng số thực dấu phẩy động độ chính xác kép được đặc tả trong chuẩn IEEE 754 và chỉ có thể biểu diễn an toàn các số trong khoảng -(253 - 1)253 - 1.

- -

An toàn trong ngữ cảnh này ám chỉ khả năng biểu diễn cũng như so sánh số nguyên một cách chính xác. Chẳng hạn,Number.MAX_SAFE_INTEGER+1 === Number.MAX_SAFE_INTEGER+2 sẽ trả về true, theo toán học thì là sai. Xem {{jsxref("Number.isSafeInteger()")}} để biết thêm chi tiết.

- -

Bởi vì MAX_SAFE_INTEGER là một thuộc tính tĩnh của {{jsxref("Number")}}, bạn thường dùng nó bằng Number.MAX_SAFE_INTEGER, thay vì tự tạo ra thuộc tính cho object {{jsxref("Number")}}.

- -

Ví dụ

- -
Number.MAX_SAFE_INTEGER // 9007199254740991
-Number.MAX_SAFE_INTEGER * Number.EPSILON // 2 bởi vì đối với số thực dấu phẩy động, giá trị thực tế chính là the decimal trailing "1"
-                                        // ngoại trừ trường hợp có độ chính xác subnormal như là zero (0)
-
- -

Polyfill

- -
if (!Number.MAX_SAFE_INTEGER) {
-    Number.MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; // 9007199254740991
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-number.max_safe_integer', 'Number.MAX_SAFE_INTEGER')}}{{Spec2('ES2015')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-number.max_safe_integer', 'Number.MAX_SAFE_INTEGER')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.MAX_SAFE_INTEGER")}}

- -

Xem thêm

- -
    -
  • {{jsxref("Number.MIN_SAFE_INTEGER")}}
  • -
  • {{jsxref("Number.isSafeInteger()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/number/min_safe_integer/index.html b/files/vi/web/javascript/reference/global_objects/number/min_safe_integer/index.html deleted file mode 100644 index 4a3ecf1a76..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/min_safe_integer/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Number.MIN_SAFE_INTEGER -slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER -translation_of: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER ---- -
{{JSRef}}
- -

The Number.MIN_SAFE_INTEGER biểu diễn giá trị số nguyên an toàn lớn nhất trong JavaScript (-(253 - 1)).

- -
{{EmbedInteractiveExample("pages/js/number-min-safe-integer.html")}}
- - - -
{{js_property_attributes(0, 0, 0)}}
- -

Mô tả

- -

Hằng MAX_SAFE_INTEGER có giá trị là -9007199254740991(-9,007,199,254,740,991 hay là khoảng âm 9 triệu tỉ). Nguyên do đằng sau con số đó là do JavaScript sử dụng số thực dấu phẩy động độ chính xác kép được đặc tả trong chuẩn IEEE 754 và chỉ có thể biểu diễn an toàn các số trong khoảng -(253 - 1)253 - 1. Xem {{jsxref("Number.isSafeInteger()")}} để biết thêm chi tiết.

- -

Bởi vì MIN_SAFE_INTEGER là một thuộc tính tĩnh của {{jsxref("Number")}}, bạn thường dùng nó bằng Number.MIN_SAFE_INTEGER, thay vì tự tạo ra thuộc tính cho object {{jsxref("Number")}}.

- -

Ví dụ

- -
Number.MIN_SAFE_INTEGER // -9007199254740991
--(Math.pow(2, 53) - 1)  // -9007199254740991
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-number.min_safe_integer', 'Number.MIN_SAFE_INTEGER')}}{{Spec2('ES2015')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-number.min_safe_integer', 'Number.MIN_SAFE_INTEGER')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.MIN_SAFE_INTEGER")}}

- -

Xem thêm

- -
    -
  • {{jsxref("Number.MAX_SAFE_INTEGER")}}
  • -
  • {{jsxref("Number.isSafeInteger()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/number/nan/index.html b/files/vi/web/javascript/reference/global_objects/number/nan/index.html deleted file mode 100644 index daf2661d0a..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/nan/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Number.NaN -slug: Web/JavaScript/Reference/Global_Objects/Number/NaN -tags: - - JavaScript - - Number - - Thuộc tính -translation_of: Web/JavaScript/Reference/Global_Objects/Number/NaN ---- -
{{JSRef}}
- -

Thuộc tính Number.NaN đại diện cho khái niệm Not-A-Number (Không-phải-Số). Tương đương với {{jsxref("NaN")}}.

- -
{{EmbedInteractiveExample("pages/js/number-nan.html")}}
- -

Ta không phải tạo đối tượng {{jsxref("Number")}} để truy cập vào thuộc tính tĩnh này (dùng cú pháp Number.NaN).

- -
{{js_property_attributes(0, 0, 0)}}
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa đầu tiên. Được đưa vào JavaScript 1.0.
{{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')}} 
- -

Tính tương thích trên trình duyệt

- - - -

{{Compat("javascript.builtins.Number.NaN")}}

- -

Xem thêm

- -
    -
  • Đối tượng global {{jsxref("NaN")}}.
  • -
  • Đối tượng {{jsxref("Number")}} sở hữu thuộc tính này.
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/number/negative_infinity/index.html b/files/vi/web/javascript/reference/global_objects/number/negative_infinity/index.html deleted file mode 100644 index 75e87a4657..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/negative_infinity/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Number.NEGATIVE_INFINITY -slug: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY -translation_of: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY ---- -
{{JSRef}}
- -

Thuộc tính Number.NEGATIVE_INFINITY biểu diễn giá trị âm của Infinity (âm vô cực).

- -
{{EmbedInteractiveExample("pages/js/number-negative-infinity.html")}}
- - - -

Bạn không cần tạo đối tượng {{jsxref("Number")}} để truy cập vào đối tượng này (hãy dùng Number.NEGATIVE_INFINITY).

- -
{{js_property_attributes(0, 0, 0)}}
- -

Mô tả

- -

Giá trị của Number.NEGATIVE_INFINITY cũng giống như giá trị âm của thuộc tính {{jsxref("Infinity")}} của global object.

- -

Giá trị này hành xử hơi khác so với âm vô cực trong toán học:

- -
    -
  • Bất cứ giá trị dương nào, bao gồm cả {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, nhân với NEGATIVE_INFINITY trả ra NEGATIVE_INFINITY.
  • -
  • Bất cứ giá trị âm nào, bao gồm cả NEGATIVE_INFINITY, nhân với NEGATIVE_INFINITY trả ra {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}.
  • -
  • Bất cứ giá trị dương nào chia cho NEGATIVE_INFINITY trả ra âm 0.
  • -
  • Bất cứ giá trị âm nào chia cho NEGATIVE_INFINITY trả ra dương 0.
  • -
  • 0 nhân với NEGATIVE_INFINITY trả ra {{jsxref("NaN")}}.
  • -
  • {{jsxref("NaN")}} nhân với NEGATIVE_INFINITY is {{jsxref("NaN")}}.
  • -
  • NEGATIVE_INFINITY chia cho bất cứ giá trị âm nào ngoại trừ NEGATIVE_INFINITY, trả ra ra {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}.
  • -
  • NEGATIVE_INFINITY chia cho bất cứ giá trị dương nào ngoại trừ {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}} trả ra NEGATIVE_INFINITY.
  • -
  • NEGATIVE_INFINITY chia cho cả NEGATIVE_INFINITY hay {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, đều trả về {{jsxref("NaN")}}.
  • -
- -

Bạn có thể dùng thuộc tính Number.NEGATIVE_INFINITY để xác định điều kiện xem có trả về số hữu hạn hay không. Chú ý, ngoài ra, {{jsxref("isFinite")}} sẽ hợp với trường hợp này hơn.

- -

Ví dụ

- -

Sử dụng NEGATIVE_INFINITY

- -

Trong ví dụ sau đây, biến smallNumber được gán giá trị nhỏ hơn giá trị nhỏ nhất. Khi lệnh {{jsxref("Statements/if...else", "if")}} được thực thi, smallNumber có giá trị -Infinity, nên smallNumber được gán lại giá trị dễ kiểm soát hơn trước khi tiếp tục.

- -
var smallNumber = (-Number.MAX_VALUE) * 2;
-
-if (smallNumber === Number.NEGATIVE_INFINITY) {
-  smallNumber = returnFinite();
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa lần đầu. Cài đặt trong JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.5', 'Number.NEGATIVE_INFINITY')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.NEGATIVE_INFINITY")}}

- -

Xem thêm

- -
    -
  • {{jsxref("Number.POSITIVE_INFINITY")}}
  • -
  • {{jsxref("Number.isFinite()")}}
  • -
  • {{jsxref("Global_Objects/Infinity", "Infinity")}}
  • -
  • {{jsxref("Global_Objects/isFinite", "isFinite()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/number/positive_infinity/index.html b/files/vi/web/javascript/reference/global_objects/number/positive_infinity/index.html deleted file mode 100644 index 54b2db905e..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/positive_infinity/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Number.POSITIVE_INFINITY -slug: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY -translation_of: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY ---- -
{{JSRef}}
- -

Thuộc tính Number.POSITIVE_INFINITY biểu diễn giá trị dương Infinity (dương vô cùng).

- -
{{EmbedInteractiveExample("pages/js/number-positive-infinity.html")}}
- - - -

Bạn không cần tạo đối tượng{{jsxref("Number")}} để truy cập vào đối tượng này (hãy dùng Number.POSITIVE_INFINITY).

- -
{{js_property_attributes(0, 0, 0)}}
- -

Mô tả

- -

Giá trị của Number.POSITIVE_INFINITY cũng giống như giá trị dương của thuộc tính {{jsxref("Infinity")}} của global object.

- -

Giá trị này hành xử hơi khác so với vô cùng trong toán học:

- -
    -
  • Bất cứ giá trị dương nào, bao gồm cả POSITIVE_INFINITY, nhân với POSITIVE_INFINITY trả ra POSITIVE_INFINITY.
  • -
  • Bất cứ giá trị âm nào, bao gồm cả {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}, nhân với POSITIVE_INFINITY trả ra {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}.
  • -
  • Bất cứ giá trị dương nào chia cho POSITIVE_INFINITY trả ra dương 0.
  • -
  • Bất cứ giá trị âm nào chia cho POSITIVE_INFINITY trả ra âm 0.
  • -
  • 0 nhân với POSITIVE_INFINITY trả ra {{jsxref("NaN")}}.
  • -
  • {{jsxref("Global_Objects/NaN", "NaN")}} nhân với POSITIVE_INFINITY trả ra {{jsxref("NaN")}}.
  • -
  • POSITIVE_INFINITY, chia cho bất cứ giá trị âm nào ngoại trừ {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}, trả ra {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}.
  • -
  • POSITIVE_INFINITY, chia cho bất cứ giá trị dương nào ngoại trừ POSITIVE_INFINITY, trả ra POSITIVE_INFINITY.
  • -
  • POSITIVE_INFINITY, chia cho cả {{jsxref("Number.NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}} hay POSITIVE_INFINITY, đều ra {{jsxref("NaN")}}.
  • -
- -

Bạn có thể dùng thuộc tính Number.POSITIVE_INFINITY để xác định điều kiện xem có trả về số hữu hạn hay không. Chú ý, ngoài ra, {{jsxref("isFinite")}} sẽ hợp với trường hợp này hơn.

- -

Ví dụ

- -

Sử dụng POSITIVE_INFINITY

- -

Trong ví dụ sau đây, biến bigNumber được gán giá trị lớn hơn giá trị lớn nhất. Khi lệnh {{jsxref("Statements/if...else", "if")}} được thực thi, bigNumber có giá trị Infinity, nên bigNumber được gán lại giá trị dễ kiểm soát hơn trước khi tiếp tục.

- -
var bigNumber = Number.MAX_VALUE * 2;
-
-if (bigNumber == Number.POSITIVE_INFINITY) {
-  bigNumber = returnFinite();
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa lần đầu. Cài đặt trong JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.6', 'Number.POSITIVE_INFINITY')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.positive_infinity', 'Number.POSITIVE_INFINITY')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.positive_infinity', 'Number.POSITIVE_INFINITY')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.POSITIVE_INFINITY")}}

- -

Xem thêm

- -
    -
  • {{jsxref("Number.NEGATIVE_INFINITY")}}
  • -
  • {{jsxref("Number.isFinite()")}}
  • -
  • {{jsxref("Infinity")}}
  • -
  • {{jsxref("isFinite", "isFinite()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/object/assign/index.html b/files/vi/web/javascript/reference/global_objects/object/assign/index.html deleted file mode 100644 index 2f5b00f1ec..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/assign/index.html +++ /dev/null @@ -1,259 +0,0 @@ ---- -title: Object.assign() -slug: Web/JavaScript/Reference/Global_Objects/Object/assign -tags: - - JavaScript - - Method - - Object -translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign ---- -
{{JSRef}}
- -

Object.assign() được sử dụng để sao chép các giá trị của tất cả thuộc tính có thể liệt kê từ một hoặc nhiều đối tượng nguồn đến một đối tượng đích. Nó sẽ  trả về đối tượng đích đó.

- -

{{EmbedInteractiveExample("pages/js/object-assign.html")}}

- -

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

- -

Cú pháp

- -
Object.assign(target, ...sources)
- -

Các tham số

- -
-
target
-
Đối tượng đích
-
sources
-
Các đối tượng nguồn
-
- -

Giá trị trả về

- -

(Các) Đối tượng đích

- -

Mô tả

- -

Các thuộc tính trong đối tượng đích sẽ bị ghi lại bởi các thuộc tính trong đối tượng nguồn nếu chúng có cùng key. Tương tự, các thuộc tính nguồn sau sẽ ghi đè lên những thuộc tính nguồn trước. 

- -

Phương thức Object.assign() chỉ sao chép những giá trị liệt kê được và và các thuộc tính của bản thân nó đến đối tượng đích. Nó sử dụng  [[Get]] trên nguồn và [[Set]] trên đích, vì vậy nó sẽ gọi các hàm getter và setter.  Vì lý do đó nó chỉ định thuộc tính so với việc chỉ sao chép hoặc xác đinh các thuộc tính mới. Điều này có thể khiến nó không phù hợp khi gộp các thuộc tính mới vào một nguyên mẫu (prototype) nếu các nguồn gộp chứa các getter. Để sao chép các thuộc tính xác định, bao gồm cả khả năng đếm được vào trong các nguyên mẫu thì nên sử dụng {{jsxref("Object.getOwnPropertyDescriptor()")}} và {{jsxref("Object.defineProperty()")}} để thay thế.

- -

Các thuộc tính {{jsxref("String")}} và {{jsxref("Symbol")}} đều được sao chép.

- -

Trong trường hợp có một lỗi, như việc một thuộc tính không được phép ghi đè, một  {{jsxref("TypeError")}}  sẽ sinh ra, và đối tượng đích có thể được thay đổi nếu có bất kỳ thuộc tính nào đã được thêm vào trước khi lỗi được sinh ra.

- -

Chú ý rằng Object.assign() không ném ra một {{jsxref("null")}} hoặc {{jsxref("undefined")}}.

- -

Ví dụ

- -

Sao chép một object

- -
var obj = { a: 1 };
-var copy = Object.assign({}, obj);
-console.log(copy); // { a: 1 }
-
- -

Cảnh báo về Deep Clone

- -

Với deep cloning, chúng ta cần sử dụng những lựa chọn khác khác bởi vì Object.assign() sao chép các giá trị thuộc tính. Nếu giá trị nguồn là tham chiếu đến một object,  nó chỉ sao chép gía trị tham chiếu đó. 

- -
function test() {
-  'use strict';
-
-  let a = { b: {c: 4} , d: { e: {f: 1} } };
-  let g = Object.assign({}, a);
-  let h = JSON.parse(JSON.stringify(a));
-  console.log(JSON.stringify(g.d)); // { e: { f: 1 } }
-  g.d.e = 32;
-  console.log('g.d.e set to 32.'); // g.d.e set to 32.
-  console.log(JSON.stringify(g)); // { b: { c: 4 }, d: { e: 32 } }
-  console.log(JSON.stringify(a)); // { b: { c: 4 }, d: { e: 32 } }
-  console.log(JSON.stringify(h)); // { b: { c: 4 }, d: { e: { f: 1 } } }
-  h.d.e = 54;
-  console.log('h.d.e set to 54.'); // h.d.e set to 54.
-  console.log(JSON.stringify(g)); // { b: { c: 4 }, d: { e: 32 } }
-  console.log(JSON.stringify(a)); // { b: { c: 4 }, d: { e: 32 } }
-  console.log(JSON.stringify(h)); // { b: { c: 4 }, d: { e: 54 } }
-}
-
-test();
- -

Gộp các object

- -
var o1 = { a: 1 };
-var o2 = { b: 2 };
-var o3 = { c: 3 };
-
-var obj = Object.assign(o1, o2, o3);
-console.log(obj); // { a: 1, b: 2, c: 3 }
-console.log(o1);  // { a: 1, b: 2, c: 3 }, object đích tự nó bị thay đổi.
- -

Gộp các đối tượng với cùng giá trị

- -
var o1 = { a: 1, b: 1, c: 1 };
-var o2 = { b: 2, c: 2 };
-var o3 = { c: 3 };
-
-var obj = Object.assign({}, o1, o2, o3);
-console.log(obj); // { a: 1, b: 2, c: 3 }
- -

Các giá trị được ghi đè bởi các đối tượng khác mà chúng có chung các thuộc tính sau đó theo thứ tự các tham số.

- -

Sao chép thuộc tính symbol-typed

- -
var o1 = { a: 1 };
-var o2 = { [Symbol('foo')]: 2 };
-
-var obj = Object.assign({}, o1, o2);
-console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 trên Firefox)
-Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
-
- -

Các thuộc tính trên chuỗi nguyên mẫu và các thuộc tính không có khả năng đếm được thì không thể sao chép. 

- -
var obj = Object.create({ foo: 1 }, { // foo ở trên mắt xích prototype của obj.
-  bar: {
-    value: 2  // bar chứa thuộc tính không liệt kê được.
-  },
-  baz: {
-    value: 3,
-    enumerable: true  // baz chứa thuộc tính liệt kê được.
-  }
-});
-
-var copy = Object.assign({}, obj);
-console.log(copy); // { baz: 3 }
-
- -

Các giá trị nguyên thủy sẽ được gói thành các đối tượng.

- -
var v1 = 'abc';
-var v2 = true;
-var v3 = 10;
-var v4 = Symbol('foo');
-
-var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
-// Sự nguyên bản sẽ bị gói lại, null và undefined sẽ bị bỏ qua.
-// Ghi chú,chỉ có string wrapper mới có thuộc tính liệt kê được.
-console.log(obj); // { "0": "a", "1": "b", "2": "c" }
-
- -

Các ngoại lệ sẽ làm gián đoạn quá trình sao chép.

- -
var target = Object.defineProperty({}, 'foo', {
-  value: 1,
-  writable: false
-}); // target.foo chỉ read-only
-
-Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
-// TypeError: "foo" là read-only
-// Trường hợp ngoại lệ được tạo ra khi gán target.foo
-
-console.log(target.bar);  // 2, nguồn thứ nhất được sao chép thành công
-console.log(target.foo2); // 3, đặc tính thứ nhất của nguồn thứ 2 được chép thành công.
-console.log(target.foo);  // 1, ngoại lệ được ném ra
-console.log(target.foo3); // undefined, phương thức gán đã hoàn tất, foo3 sẽ không bị sao chép
-console.log(target.baz);  // undefined, nguồn thứ ba cũng không bị sao chép
-
- -

Sao chép các trình truy cập (accessor)

- -
var obj = {
-  foo: 1,
-  get bar() {
-    return 2;
-  }
-};
-
-var copy = Object.assign({}, obj);
-console.log(copy);
-// { foo: 1, bar: 2 }, giá trị của copy.bar là giá trị return của getter của obj.bar.
-
-// Đây là function gán sao chép toàn bộ các mô tả.
-function completeAssign(target, ...sources) {
-  sources.forEach(source => {
-    let descriptors = Object.keys(source).reduce((descriptors, key) => {
-      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
-      return descriptors;
-    }, {});
-    // Mặc định thì Object.assign sao chép cả Symbol thống kê được luôn
-    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 } }
-
- -

Polyfill

- -

 {{Glossary("Polyfill","polyfill")}}  không hỗ trợ các thuộc tính symbol, kể từ ES5 thì cũng không còn symbol nữa:

- -
if (typeof Object.assign != 'function') {
-  Object.assign = function(target, varArgs) { // .length của function là 2
-    'use strict';
-    if (target == null) { // TypeError nếu undefined hoặc 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) { // Bỏ qua nếu undefined hoặc 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;
-  };
-}
-
- -

Đặc tính kỹ thuật

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}{{Spec2('ES2015')}}Initial definition.
- -

Tương thích trình duyệt

- -
{{Compat("javascript.builtins.Object.assign")}}
- -
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html deleted file mode 100644 index c96b3f7527..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: Object.defineProperties() -slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties -translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties ---- -
{{JSRef}}
- -

Phương thức Object.defineProperties() định nghĩa hoặc thay đổi tức thì các thuộc tính của một đối tượng, sau đó trả lại đối tượng đó.

- -

Cú pháp

- -
Object.defineProperties(obj, props)
- -

Các tham số

- -
-
obj
-
Đối tượng được định nghĩa hoặc thay đổi các thuộc tính.
-
props
-
Đối tượng mà các thuộc tính có thể liệt kê (enumerable) của riêng nó sẽ cấu thành các bộ mô tả (descriptor) cho các thuộc tính được định nghĩa hoặc sửa đổi. Các bộ mô tả thuộc tính (property descriptors) có trong các đối tượng bao gồm hai loại chính: các bộ mô tả dữ liệu (data descriptors) và các bộ mô tả truy cập (accessor descriptors) (xem {{jsxref("Object.defineProperty()")}} để biết thêm chi tiết). Các bộ mô tả bao gồm các khóa sau:
-
-
-
configurable
-
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
- Defaults to false.
-
enumerable
-
true if and only if this property shows up during enumeration of the properties on the corresponding object.
- Defaults to false.
-
- -
-
value
-
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
- Defaults to {{jsxref("undefined")}}.
-
writable
-
true if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.
- Defaults to false.
-
- -
-
get
-
A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. The function return will be used as the value of property.
- Defaults to {{jsxref("undefined")}}.
-
set
-
A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. The function will receive as only argument the new value being assigned to the property.
- Defaults to {{jsxref("undefined")}}.
-
-
-
- -

Giá trị trả về

- -

Đối tượng được truyền khi gọi phương thức.

- -

Mô tả

- -

Object.defineProperties, in essence, defines all properties corresponding to the enumerable own properties of props on the object obj object.

- -

Ví dụ

- -
var obj = {};
-Object.defineProperties(obj, {
-  'property1': {
-    value: true,
-    writable: true
-  },
-  'property2': {
-    value: 'Hello',
-    writable: false
-  }
-  // etc. etc.
-});
-
- -

Polyfill

- -

Assuming a pristine execution environment with all names and properties referring to their initial values, Object.defineProperties is almost completely equivalent (note the comment in isCallable) to the following reimplementation in JavaScript:

- -
function defineProperties(obj, properties) {
-  function convertToDescriptor(desc) {
-    function hasProperty(obj, prop) {
-      return Object.prototype.hasOwnProperty.call(obj, prop);
-    }
-
-    function isCallable(v) {
-      // NB: modify as necessary if other values than functions are callable.
-      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;
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5
{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ESDraft')}} 
- -

Tương thích trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2")}}{{CompatChrome("5")}}{{CompatVersionUnknown}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
-
- -

Tham khảo

- - diff --git a/files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html deleted file mode 100644 index 87c16604ea..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html +++ /dev/null @@ -1,483 +0,0 @@ ---- -title: Object.defineProperty() -slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty -translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty ---- -
{{JSRef}}
- -

Phương thức Object.defineProperty() định nghĩa ngay một thuộc tính mới trên một đối tượng, hoặc thay đổi một thuộc tính đã có trên một đối tượng, và trả về đối tượng đó.

- -
-

Lưu ý: Bạn có thể gọi phương thức ngay trên  {{jsxref("Object")}} hơn là trên một thể hiện của kiểu Object.

-
- -
{{EmbedInteractiveExample("pages/js/object-defineproperty.html")}}
- - - -

Cú pháp

- -
Object.defineProperty(obj, prop, descriptor)
- -

Các tham số

- -
-
obj
-
Object cần định nghĩa thuộc tính.
-
prop
-
Tên của thuộc tính sẽ định nghĩa hoặc sửa đổi.
-
descriptor
-
Mô tả cho thuộc tính được định nghĩa hoặc sửa đổi.
-
- -

Giá trị trả về

- -

Object đã được truyền vào hàm.

- -

Mô tả

- -

This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration ({{jsxref("Statements/for...in", "for...in")}} loop or {{jsxref("Object.keys")}} method), whose values may be changed, and which may be {{jsxref("Operators/delete", "deleted", "", 1)}}. This method allows these extra details to be changed from their defaults. By default, values added using Object.defineProperty() are immutable.

- -

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

- -

Both data and accessor descriptors are objects. They share the following optional keys:

- -
-
configurable
-
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
- Defaults to false.
-
enumerable
-
true if and only if this property shows up during enumeration of the properties on the corresponding object.
- Defaults to false.
-
- -

A data descriptor also has the following optional keys:

- -
-
value
-
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
- Defaults to {{jsxref("undefined")}}.
-
writable
-
true if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.
- Defaults to false.
-
- -

An accessor descriptor also has the following optional keys:

- -
-
get
-
A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. When the property is accessed, this function is called without arguments and with this set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property.
- Defaults to {{jsxref("undefined")}}.
-
set
-
A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. When the property is assigned to, this function is called with one argument (the value being assigned to the property) and with this set to the object through which the property is assigned.
- Defaults to {{jsxref("undefined")}}.
-
- -

If a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. If a descriptor has both value or writable and get or set keys, an exception is thrown.

- -

Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze the {{jsxref("Object.prototype")}} upfront, specify all options explicitly, or point to {{jsxref("null")}} with {{jsxref("Object.create", "Object.create(null)")}}.

- -
// using __proto__
-var obj = {};
-var descriptor = Object.create(null); // no inherited properties
-// not enumerable, not configurable, not writable as defaults
-descriptor.value = 'static';
-Object.defineProperty(obj, 'key', descriptor);
-
-// being explicit
-Object.defineProperty(obj, 'key', {
-  enumerable: false,
-  configurable: false,
-  writable: false,
-  value: 'static'
-});
-
-// recycling same object
-function withValue(value) {
-  var d = withValue.d || (
-    withValue.d = {
-      enumerable: false,
-      writable: false,
-      configurable: false,
-      value: null
-    }
-  );
-  d.value = value;
-  return d;
-}
-// ... and ...
-Object.defineProperty(obj, 'key', withValue('static'));
-
-// if freeze is available, prevents adding or
-// removing the object prototype properties
-// (value, get, set, enumerable, writable, configurable)
-(Object.freeze || Object)(Object.prototype);
-
- -

Ví dụ

- -

If you want to see how to use the Object.defineProperty method with a binary-flags-like syntax, see additional examples.

- -

Creating a property

- -

When the property specified doesn't exist in the object, Object.defineProperty() creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are inputted.

- -
var o = {}; // Creates a new object
-
-// Example of an object property added
-// with defineProperty with a data property descriptor
-Object.defineProperty(o, 'a', {
-  value: 37,
-  writable: true,
-  enumerable: true,
-  configurable: true
-});
-// 'a' property exists in the o object and its value is 37
-
-// Example of an object property added
-// with defineProperty with an accessor property descriptor
-var bValue = 38;
-Object.defineProperty(o, 'b', {
-  // Using shorthand method names (ES2015 feature).
-  // This is equivalent to:
-  // get: function() { return bValue; },
-  // set: function(newValue) { bValue = newValue; },
-  get() { return bValue; },
-  set(newValue) { bValue = newValue; },
-  enumerable: true,
-  configurable: true
-});
-o.b; // 38
-// 'b' property exists in the o object and its value is 38
-// The value of o.b is now always identical to bValue,
-// unless o.b is redefined
-
-// You cannot try to mix both:
-Object.defineProperty(o, 'conflict', {
-  value: 0x9f91102,
-  get() { return 0xdeadbeef; }
-});
-// throws a TypeError: value appears
-// only in data descriptors,
-// get appears only in accessor descriptors
-
- -

Modifying a property

- -

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false the property is said to be “non-configurable”. It is not possible to change any attribute of a non-configurable accessor property. For data properties, it is possible to modify the value if the property is writable, and it is possible to change writable attribute from true to false. It is not possible to switch between data and accessor property types when the property is non-configurable.

- -

A {{jsxref("TypeError")}} is thrown when attempts are made to change non-configurable property attributes (except value and writable, if permitted) unless the current and new values are the same.

- -

Writable attribute

- -

When the writable property attribute is set to false, the property is said to be “non-writable”. It cannot be reassigned.

- -
var o = {}; // Creates a new object
-
-Object.defineProperty(o, 'a', {
-  value: 37,
-  writable: false
-});
-
-console.log(o.a); // logs 37
-o.a = 25; // No error thrown
-// (it would throw in strict mode,
-// even if the value had been the same)
-console.log(o.a); // logs 37. The assignment didn't work.
-
-// strict mode
-(function() {
-  'use strict';
-  var o = {};
-  Object.defineProperty(o, 'b', {
-    value: 2,
-    writable: false
-  });
-  o.b = 3; // throws TypeError: "b" is read-only
-  return o.b; // returns 2 without the line above
-}());
-
- -

As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.

- -

Enumerable attribute

- -

The enumerable property attribute defines whether the property shows up in a {{jsxref("Statements/for...in", "for...in")}} loop and {{jsxref("Object.keys()")}} or not.

- -
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
-
-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
-
- -

Configurable attribute

- -

The configurable attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than value and writable) can be changed.

- -
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
-
- -

If the configurable attribute of o.a had been true, none of the errors would be thrown and the property would be deleted at the end.

- -

Adding properties and default values

- -

It is important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using Object.defineProperty(), as shown in the example below.

- -
var o = {};
-
-o.a = 1;
-// is equivalent to:
-Object.defineProperty(o, 'a', {
-  value: 1,
-  writable: true,
-  configurable: true,
-  enumerable: true
-});
-
-// On the other hand,
-Object.defineProperty(o, 'a', { value: 1 });
-// is equivalent to:
-Object.defineProperty(o, 'a', {
-  value: 1,
-  writable: false,
-  configurable: false,
-  enumerable: false
-});
-
- -

Custom Setters and Getters

- -

The example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.

- -
function Archiver() {
-  var temperature = null;
-  var archive = [];
-
-  Object.defineProperty(this, 'temperature', {
-    get() {
-      console.log('get!');
-      return temperature;
-    },
-    set(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 }]
-
- -

In this example, a getter always returns the same value.

- -
var pattern = {
-    get() {
-        return 'I always return this string, ' +
-               'whatever you have assigned';
-    },
-    set() {
-        this.myname = 'this is my name string';
-    }
-};
-
-function TestDefineSetAndGet() {
-    Object.defineProperty(this, 'myproperty', pattern);
-}
-
-var instance = new TestDefineSetAndGet();
-instance.myproperty = 'test';
-console.log(instance.myproperty);
-// I always return this string, whatever you have assigned
-
-console.log(instance.myname); // this is my name string
-
- -

Inheritance of properties

- -

If an accessor property is inherited, its get and set methods will be called when the property is accessed and modified on descendant objects. If these methods use a variable to store the value, this value will be shared by all objects.

- -
function myclass() {
-}
-
-var value;
-Object.defineProperty(myclass.prototype, "x", {
-  get() {
-    return value;
-  },
-  set(x) {
-    value = x;
-  }
-});
-
-var a = new myclass();
-var b = new myclass();
-a.x = 1;
-console.log(b.x); // 1
-
- -

This can be fixed by storing the value in another property. In get and set methods, this points to the object which is used to access or modify the property.

- -
function myclass() {
-}
-
-Object.defineProperty(myclass.prototype, "x", {
-  get() {
-    return this.stored_x;
-  },
-  set(x) {
-    this.stored_x = x;
-  }
-});
-
-var a = new myclass();
-var b = new myclass();
-a.x = 1;
-console.log(b.x); // undefined
-
- -

Unlike accessor properties, value properties are always set on the object itself, not on a prototype. However, if a non-writable value property is inherited, it still prevents from modifying the property on the object.

- -
function myclass() {
-}
-
-myclass.prototype.x = 1;
-Object.defineProperty(myclass.prototype, "y", {
-  writable: false,
-  value: 1
-});
-
-var a = new myclass();
-a.x = 2;
-console.log(a.x); // 2
-console.log(myclass.prototype.x); // 1
-a.y = 2; // Ignored, throws in strict mode
-console.log(a.y); // 1
-console.log(myclass.prototype.y); // 1
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
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')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Object.defineProperty")}}

-
- -

Compatibility notes

- -

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's 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("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:

- -
    -
  • Trying to use Object.defineProperty() on native objects throws an error.
  • -
  • Property attributes must be set to some values. The configurable, enumerable and writable attributes should all be set to true for data descriptor and true for configurable, false for enumerable for accessor descriptor.(?) Any attempt to provide other value(?) will result in an error being thrown.
  • -
  • Reconfiguring a property requires first deleting the property. If the property isn't deleted, it stays as it was before the reconfiguration attempt.
  • -
- -

See also

- -
    -
  • Enumerability and ownership of properties
  • -
  • {{jsxref("Object.defineProperties()")}}
  • -
  • {{jsxref("Object.propertyIsEnumerable()")}}
  • -
  • {{jsxref("Object.getOwnPropertyDescriptor()")}}
  • -
  • {{jsxref("Object.prototype.watch()")}}
  • -
  • {{jsxref("Object.prototype.unwatch()")}}
  • -
  • {{jsxref("Operators/get", "get")}}
  • -
  • {{jsxref("Operators/set", "set")}}
  • -
  • {{jsxref("Object.create()")}}
  • -
  • Additional Object.defineProperty examples
  • -
  • {{jsxref("Reflect.defineProperty()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html b/files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html deleted file mode 100644 index d1e533fceb..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: Object.getOwnPropertyNames() -slug: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames -translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames ---- -
{{JSRef}}
- -

The Object.getOwnPropertyNames() phuong thuc nay tra ve mang (including non-enumerable properties except for those which use Symbol) found directly in a given object.

- -
{{EmbedInteractiveExample("pages/js/object-getownpropertynames.html")}}
- -

Syntax

- -
Object.getOwnPropertyNames(obj)
- -

Parameters

- -
-
obj
-
The object whose enumerable and non-enumerable properties are to be returned.
-
- -

Return value

- -

An array of strings that corresponds to the properties found directly in the given object.

- -

Description

- -

Object.getOwnPropertyNames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object obj. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a {{jsxref("Statements/for...in", "for...in")}} loop (or by {{jsxref("Object.keys()")}}) over the properties of the object. The ordering of the non-enumerable properties in the array and the ordering among the enumerable properties is not defined.

- -

Examples

- -

Using Object.getOwnPropertyNames()

- -
var arr = ['a', 'b', 'c'];
-console.log(Object.getOwnPropertyNames(arr).sort());
-// logs ["0", "1", "2", "length"]
-
-// Array-like object
-var obj = { 0: 'a', 1: 'b', 2: 'c' };
-console.log(Object.getOwnPropertyNames(obj).sort());
-// logs ["0", "1", "2"]
-
-// Logging property names and values using Array.forEach
-Object.getOwnPropertyNames(obj).forEach(
-  function (val, idx, array) {
-    console.log(val + ' -> ' + obj[val]);
-  }
-);
-// logs
-// 0 -> a
-// 1 -> b
-// 2 -> c
-
-// non-enumerable property
-var my_obj = Object.create({}, {
-  getFoo: {
-    value: function() { return this.foo; },
-    enumerable: false
-  }
-});
-my_obj.foo = 1;
-
-console.log(Object.getOwnPropertyNames(my_obj).sort());
-// logs ["foo", "getFoo"]
-
- -

If you want only the enumerable properties, see {{jsxref("Object.keys()")}} or use a {{jsxref("Statements/for...in", "for...in")}} loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with {{jsxref("Object.prototype.hasOwnProperty()", "hasOwnProperty()")}}).

- -

Items on the prototype chain are not listed:

- -
function ParentClass() {}
-ParentClass.prototype.inheritedMethod = function() {};
-
-function ChildClass() {
-  this.prop = 5;
-  this.method = function() {};
-}
-ChildClass.prototype = new ParentClass;
-ChildClass.prototype.prototypeMethod = function() {};
-
-console.log(
-  Object.getOwnPropertyNames(
-    new ChildClass() // ["prop", "method"]
-  )
-);
-
- -

Get non-enumerable properties only

- -

This uses the {{jsxref("Array.prototype.filter()")}} function to remove the enumerable keys (obtained with {{jsxref("Object.keys()")}}) from a list of all keys (obtained with Object.getOwnPropertyNames()) thus giving only the non-enumerable keys as output.

- -
var target = myObject;
-var enum_and_nonenum = Object.getOwnPropertyNames(target);
-var enum_only = Object.keys(target);
-var nonenum_only = enum_and_nonenum.filter(function(key) {
-  var indexInEnum = enum_only.indexOf(key);
-  if (indexInEnum == -1) {
-    // Not found in enum_only keys,
-    // meaning that the key is non-enumerable,
-    // so return true so we keep this in the filter
-    return true;
-  } else {
-    return false;
-  }
-});
-
-console.log(nonenum_only);
-
- -

Notes

- -

In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, a non-object argument will be coerced to an object.

- -
Object.getOwnPropertyNames('foo');
-// TypeError: "foo" is not an object (ES5 code)
-
-Object.getOwnPropertyNames('foo');
-// ["0", "1", "2", "length"]  (ES2015 code)
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-object.getownpropertynames', 'Object.getOwnPropertyNames')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Object.getOwnPropertyNames")}}

- -

Firefox-specific notes

- -

Prior to Firefox 28, Object.getOwnPropertyNames did not see unresolved properties of {{jsxref("Error")}} objects. This has been fixed in later versions (bug 724768).

- -

See also

- -
    -
  • Enumerability and ownership of properties
  • -
  • {{jsxref("Object.prototype.hasOwnProperty()")}}
  • -
  • {{jsxref("Object.prototype.propertyIsEnumerable()")}}
  • -
  • {{jsxref("Object.create()")}}
  • -
  • {{jsxref("Object.keys()")}}
  • -
  • {{jsxref("Array.forEach()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/object/index.html b/files/vi/web/javascript/reference/global_objects/object/index.html deleted file mode 100644 index 06fd8ef967..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/index.html +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: Object -slug: Web/JavaScript/Reference/Global_Objects/Object -tags: - - Constructor - - JavaScript - - NeedsTranslation - - Object - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Object ---- -
{{JSRef}}
- -

The Object constructor creates an object wrapper.

- -

Syntax

- -
// Object initialiser or literal
-{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
-
-// Called as a constructor
-new Object([value])
- -

Parameters

- -
-
nameValuePair1, nameValuePair2, ... nameValuePairN
-
Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.
-
value
-
Any value.
-
- -

Description

- -

The Object constructor creates an object wrapper for the given value. If the value is {{jsxref("null")}} or {{jsxref("undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

- -

When called in a non-constructor context, Object behaves identically to new Object().

- -

See also the object initializer / literal syntax.

- -

Properties of the Object constructor

- -
-
Object.length
-
Has a value of 1.
-
{{jsxref("Object.prototype")}}
-
Allows the addition of properties to all objects of type Object.
-
- -

Methods of the Object constructor

- -
-
{{jsxref("Object.assign()")}} {{experimental_inline}}
-
Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object.
-
{{jsxref("Object.create()")}}
-
Creates a new object with the specified prototype object and properties.
-
{{jsxref("Object.defineProperty()")}}
-
Adds the named property described by a given descriptor to an object.
-
{{jsxref("Object.defineProperties()")}}
-
Adds the named properties described by the given descriptors to an object.
-
{{jsxref("Object.freeze()")}}
-
Freezes an object: other code can't delete or change any properties.
-
{{jsxref("Object.getOwnPropertyDescriptor()")}}
-
Returns a property descriptor for a named property on an object.
-
{{jsxref("Object.getOwnPropertyNames()")}}
-
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
-
{{jsxref("Object.getOwnPropertySymbols()")}} {{experimental_inline}}
-
Returns an array of all symbol properties found directly upon a given object.
-
{{jsxref("Object.getPrototypeOf()")}}
-
Returns the prototype of the specified object.
-
{{jsxref("Object.is()")}} {{experimental_inline}}
-
Compares if two values are distinguishable (ie. the same)
-
{{jsxref("Object.isExtensible()")}}
-
Determines if extending of an object is allowed.
-
{{jsxref("Object.isFrozen()")}}
-
Determines if an object was frozen.
-
{{jsxref("Object.isSealed()")}}
-
Determines if an object is sealed.
-
{{jsxref("Object.keys()")}}
-
Returns an array containing the names of all of the given object's own enumerable properties.
-
{{jsxref("Object.observe()")}} {{experimental_inline}}
-
Asynchronously observes changes to an object.
-
{{jsxref("Object.preventExtensions()")}}
-
Prevents any extensions of an object.
-
{{jsxref("Object.seal()")}}
-
Prevents other code from deleting properties of an object.
-
{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}
-
Sets the prototype (i.e., the internal [[Prototype]] property)
-
- -

Object instances and Object prototype object

- -

All objects in JavaScript are descended from Object; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString() methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

- -

Properties

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}
- -

Methods

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}
- -

Examples

- -

Using Object given undefined and null types

- -

The following examples store an empty Object object in o:

- -
var o = new Object();
-
- -
var o = new Object(undefined);
-
- -
var o = new Object(null);
-
- -

Using Object to create Boolean objects

- -

The following examples store {{jsxref("Boolean")}} objects in o:

- -
// equivalent to o = new Boolean(true);
-var o = new Object(true);
-
- -
// equivalent to o = new Boolean(false);
-var o = new Object(Boolean());
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{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/vi/web/javascript/reference/global_objects/object/tostring/index.html b/files/vi/web/javascript/reference/global_objects/object/tostring/index.html deleted file mode 100644 index 78a46f1272..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/tostring/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: Object.prototype.toString() -slug: Web/JavaScript/Reference/Global_Objects/Object/toString -translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString ---- -
{{JSRef}}
- -

Phương thức toString() trả về một chuỗi đại diện cho object.

- -

Cú pháp

- -
obj.toString()
- -

Giá trị trả về

- -

Một chuỗi đại diện cho object.

- -

Miêu tả

- -

Mỗi object có 1 phương thức toString(). Phương thức này được tự động gọi khi object được biểu diễn dưới dạng text hoặc trong bối cảnh mà một chuỗi được mong đợi để trả về. Mặc định, phương thức toString() được kế thừa cho tất cả object khi tất cả object được kế thừa từ Object. Nếu phương thức này không bị ghi đè bởi một object đã được tuỳ chỉnh, phương thức này trả về "[object type]", trong đó type là kiểu của object. Phần code theo sau mô tả điều này:

- -
var o = new Object();
-o.toString(); // returns [object Object]
-
- -
-

Note: Kể từ JavaScript 1.8.5, toString() khi được gọi trong {{jsxref("null")}} sẽ trả về [object Null], và {{jsxref("undefined")}} sẽ trả về [object Undefined], như đã được định nghĩa trong 5th Edition of ECMAScript and a subsequent Errata. Tham khảo {{anch("Using_toString()_to_detect_object_class", "Using_toString()_to_detect_object_class")}}.

-
- -

Ví dụ

- -

Ghi đè phương thức mặc định toString

- -

Bạn có thể tạo một hàm để thay thể phương thức mặc định toString(). Phương thức mặc định toString() không có tham số truyền vào và sẽ trả về một chuỗi. Phương thức toString() bạn tự tạo có thể trả về bất kì giá trị gì bạn muốn, nhưng sẽ tốt hơn nếu nó mang thông tin về object.

- -

Phần code sau đây định nghĩa kiểu Dog object và tạo ra theDog, một object của kiểu Dog:

- -
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');
-
- -

Nếu bạn gọi phương thức toString() trên object tuỳ chỉnh này, nó sẽ trả về giá trị mặc định được kế thừa từ {{jsxref("Object")}}:

- -
theDog.toString(); // returns [object Object]
-
- -

Phần code sau đây tạo ra và gán dogToString() để ghi đè lên phương thức mặc định toString(). Hàm này sẽ tạo một chuỗi chứa tên, giống, màu và giới tính của object, theo dạng "property = value;".

- -
Dog.prototype.toString = function dogToString() {
-  var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed;
-  return ret;
-}
-
- -

Với phần code ở phía trên, mỗi khi theDog được sử dụng để trả về một chuỗi, JavaScript sẽ tự động gọi hàm dogToString(), trả về kết quả sau:

- -
"Dog Gabby is a female chocolate Lab"
-
- -

Sử dụng toString() để xác định lớp đối tượng

- -

toString() có thể được sử dụng với tất cả object và cho phép bạn xác định lớp của object đó. Để sử dụng Object.prototype.toString() với mọi đối tượng, bạn cần gọi {{jsxref("Function.prototype.call()")}} or {{jsxref("Function.prototype.apply()")}} trên object đó, truyền vào object mà bạn muốn vào tham số đầu tiên hay còn được gọi là 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]
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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')}}
- -

Tính tương thích với trình duyệt

- -
- - -

{{Compat("javascript.builtins.Object.toString")}}

-
- -

Tham khảo thêm

- -
    -
  • {{jsxref("Object.prototype.toSource()")}}
  • -
  • {{jsxref("Object.prototype.valueOf()")}}
  • -
  • {{jsxref("Number.prototype.toString()")}}
  • -
  • {{jsxref("Symbol.toPrimitive")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/object/valueof/index.html b/files/vi/web/javascript/reference/global_objects/object/valueof/index.html deleted file mode 100644 index 44a440e1f6..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/valueof/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Object.prototype.valueOf() -slug: Web/JavaScript/Reference/Global_Objects/Object/valueOf -translation_of: Web/JavaScript/Reference/Global_Objects/Object/valueOf ---- -
{{JSRef}}
- -

Phương thức valueOf() trả về giá trị nguyên thuỷ(primitive value) của object đang được nói tới.

- -

Cú pháp

- -
object.valueOf()
- -

Giá trị trả về

- -

Giá trị nguyên thuỷ(primitive value) của object đang được nói tới.

- -

Miêu tả

- -

JavaScript gọi phương thức valueOf để chuyển đổi một object sang một giá trị nguyên thuỷ. Bạn hiếp khi cần gọi phương thức valueOf bởi chính bạn; JavaScript tự động gọi nó khi gặp phải một object ở chỗ mà một giá trị nguyên thuỷ cần được trả về.

- -

Mặc định, phương thức valueOf được kế thừa cho mọi object khi mà mọi object đó được kế thừa từ {{jsxref("Object")}}. Mọi core-object được tạo sẵn để ghi đè phương thức này để trả về giá trị phù hợp. Nếu một object ko có giá trị nguyên thuỷ, valueOf sẽ trả về chính object đó.

- -

Bạn có thể sử dụng valueOf trong code của bạn để chuyển đổi một object được tạo sẵn thành một giá trị nguyên thuỷ. Khi bạn tạo một object tuỳ chỉnh, bạn có thể ghi đè Object.prototype.valueOf() để gọi phương thức tuỳ chỉnh thay vì phương thức mặc định {{jsxref("Object")}}.

- -

Ghi đè valueOf cho object tuỳ chỉnh

- -

Bạn có thể tạo một hàm để được gọi thay thể cho phương thức valueOf. Hàm của bạn phải không nhận tham số nào cả.

- -

Giả sử bạn có một object loại MyNumberType và bạn muốn tạo một phương thức valueOf cho nó. Phần code sau đây gán một hàm định nghĩa bới người dùng cho phương thức valueOf của object:

- -
MyNumberType.prototype.valueOf = function() { return customPrimitiveValue; };
- -

 

- -

Với phần code phía trên, mỗi khi một object loại MyNumberType được sử dụng trong bối cảnh mà nó cần được biểu diễn bởi một giá trị nguyên thuỷ, JavaScript sẽ tự động gọi hàm đã được viết trên đây.

- -

Một phương thức valueOf của object thường được gọi bởi JavaScript, nhưng bạn có thể tự gọi nó bằng cách sau:

- -
myNumberType.valueOf()
- -
-

Note: Objects in string contexts convert via the {{jsxref("Object.toString", "toString()")}} method, which is different from {{jsxref("String")}} objects converting to string primitives using valueOf. All objects have a string conversion, if only "[object type]". But many objects do not convert to number, boolean, or function.

-
- -

Ví dụ

- -

Sử dụng valueOf

- -
function MyNumberType(n) {
-    this.number = n;
-}
-
-MyNumberType.prototype.valueOf = function() {
-    return this.number;
-};
-
-var myObj = new MyNumberType(4);
-myObj + 3; // 7
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.2.4.4', 'Object.prototype.valueOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích trình duyệt

- -
- - -

{{Compat("javascript.builtins.Object.valueOf")}}

-
- -

See also

- -
    -
  • {{jsxref("Object.prototype.toString()")}}
  • -
  • {{jsxref("parseInt", "parseInt()")}}
  • -
  • {{jsxref("Symbol.toPrimitive")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/promise/all/index.html b/files/vi/web/javascript/reference/global_objects/promise/all/index.html deleted file mode 100644 index 403b8b5161..0000000000 --- a/files/vi/web/javascript/reference/global_objects/promise/all/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Promise.all() -slug: Web/JavaScript/Reference/Global_Objects/Promise/all -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all ---- -
{{JSRef}}
- -

Phương thức Promise.all(iterable) trả ra một Promise mới và promise mới này chỉ được kết thúc khi tất cả các promise trong iterable kết thúc hoặc có một promise nào đó xử lý thất bại. Kết quả của promise mới này là một mảng chứa kết quả của tất cả các promise theo đúng thứ tự hoặc kết quả lỗi của promise gây lỗi.

- -

Cú pháp

- -
Promise.all(iterable);
- -

Tham số

- -
-
iterable
-
Một đối tượng có thể duyệt lặp. Ví dụ như một mảng {{jsxref("Array")}}. Để hiểu thêm về đối tượng có thể duyệt lặp, bạn có thể xem tại đây iterable.
-
- -

Đầu ra

- -

Kết quả trả ra là một {{jsxref("Promise")}}. Promise này chỉ được kết thúc khi mà tất cả các promise trong interable truyền vào được kết thúc hoặc một promise nào đó thất bại.

- -

Mô tả

- -

Promise.all sẽ lưu kết quả trả ra của tất cả các promise bằng một mảng theo đúng thứ tự của các promise đầu vào. Bạn lưu ý là thứ tự của các promise đầu vào chứ không phải là thứ tự kết thúc cả các promise. Ngoài ra, với các phần tử đầu vào không phải là một Promise, thì nó sẽ được coi là một giá trị trả ra và được trả với phương thức {{jsxref("Promise.resolve")}}. Tức là nó được đóng gói với 1 promise mới chứa kết quả là chính nó. 

- -

Nếu một promise nào đó bị lỗi, thì Promise.all sẽ bị kết thúc với mã lỗi của promise lỗi đó ngay lập tức. Trong trường hợp này, tất cả các promise khác dù đã kết thúc hay chưa thì đều không được quan tâm nữa.

- -

Ví dụ

- -

Sử dụng Promise.all

- -

Promise.all đợi tất cả các promise kết thúc, hoặc một promise nào đó thât bại.

- -
var p1 = Promise.resolve(3);
-var p2 = 1337;
-var p3 = new Promise((resolve, reject) => {
-  setTimeout(resolve, 100, "foo");
-});
-
-Promise.all([p1, p2, p3]).then(values => {
-  console.log(values); // [3, 1337, "foo"]
-});
- -

Promise.all kết thúc ngay khi có lỗi

- -

Promise.all sẽ bị kết thúc lỗi ngay khi có một promise nào đó bị lỗi.

- -
var p1 = new Promise((resolve, reject) => {
-  setTimeout(resolve, 1000, "one");
-});
-var p2 = new Promise((resolve, reject) => {
-  setTimeout(resolve, 2000, "two");
-});
-var p3 = new Promise((resolve, reject) => {
-  setTimeout(resolve, 3000, "three");
-});
-var p4 = new Promise((resolve, reject) => {
-  setTimeout(resolve, 4000, "four");
-});
-var p5 = new Promise((resolve, reject) => {
-  reject("reject");
-});
-
-Promise.all([p1, p2, p3, p4, p5]).then(values => {
-  console.log(values);
-}, reason => {
-  console.log(reason)
-});
-
-//From console:
-//"reject"
-
-// Evenly, it's possible to use .catch
-Promise.all([p1, p2, p3, p4, p5]).then(values => {
-  console.log(values);
-}).catch(reason => {
-  console.log(reason)
-});
-
-//From console:
-//"reject"
-
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES6', '#sec-promise.all', 'Promise.all')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt tương thích

- - - -

{{Compat}}

- -

Xem thêm

- -
    -
  • {{jsxref("Promise")}}
  • -
  • {{jsxref("Promise.race()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/promise/catch/index.html b/files/vi/web/javascript/reference/global_objects/promise/catch/index.html deleted file mode 100644 index 0564b81afd..0000000000 --- a/files/vi/web/javascript/reference/global_objects/promise/catch/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Promise.prototype.catch() -slug: Web/JavaScript/Reference/Global_Objects/Promise/catch -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch ---- -
{{JSRef}}
- -

Phương thức catch() trả ra một Promise để xử lý trường hợp xử lý của ta thất bại. Nó cũng giống như {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}} nhưng chỉ được gọi khi thao tác của ta thất bại.

- -

Cú pháp

- -
p.catch(onRejected);
-
-p.catch(function(reason) {
-   // rejection
-});
-
- -

Tham số

- -
-
onRejected
-
Một hàm {{jsxref("Function")}} được gọi khi mà Promise của ta thất bại. Hàm này có một tham số đầu vào là: -
-
reason
-
Lý do lỗi.
-
-
-
- -

Trả ra

- -

Một {{jsxref("Promise")}} mới.

- -

Mô tả

- -

Phương thước catch rất hữu ích cho việc xử lý các lỗi xảy ra trong 1 Promise hoặc một chuỗi Promise có quan hệ thứ tự với nhau (đợi nhau).

- -

Ví dụ

- -

Sử dụng phương thức catch

- -
var p1 = new Promise(function(resolve, reject) {
-  resolve('Success');
-});
-
-p1.then(function(value) {
-  console.log(value); // "Success!"
-  throw 'oh, no!';
-}).catch(function(e) {
-  console.log(e); // "oh, no!"
-}).then(function(){
-  console.log('after a catch the chain is restored');
-}, function () {
-  console.log('Not fired due to the catch');
-});
-
-// The following behaves the same as above
-p1.then(function(value) {
-  console.log(value); // "Success!"
-  return Promise.reject('oh, no!');
-}).catch(function(e) {
-  console.log(e); // "oh, no!"
-}).then(function(){
-  console.log('after a catch the chain is restored');
-}, function () {
-  console.log('Not fired due to the catch');
-});
-
- -

Lấy mã lỗi khi ném lỗi

- -
// Throwing an error will call the catch method most of the time
-var p1 = new Promise(function(resolve, reject) {
-  throw 'Uh-oh!';
-});
-
-p1.catch(function(e) {
-  console.log(e); // "Uh-oh!"
-});
-
-// Errors thrown inside asynchronous functions will act like uncaught errors
-var p2 = new Promise(function(resolve, reject) {
-  setTimeout(function() {
-    throw 'Uncaught Exception!';
-  }, 1000);
-});
-
-p2.catch(function(e) {
-  console.log(e); // This is never called
-});
-
-// Errors thrown after resolve is called will be silenced
-var p3 = new Promise(function(resolve, reject) {
-  resolve();
-  throw 'Silenced Exception!';
-});
-
-p3.catch(function(e) {
-   console.log(e); // This is never called
-});
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat}}

- -

Xem thêm

- -
    -
  • {{jsxref("Promise")}}
  • -
  • {{jsxref("Promise.prototype.then()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/promise/finally/index.html b/files/vi/web/javascript/reference/global_objects/promise/finally/index.html deleted file mode 100644 index a8796382a2..0000000000 --- a/files/vi/web/javascript/reference/global_objects/promise/finally/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Promise.prototype.finally() -slug: Web/JavaScript/Reference/Global_Objects/Promise/finally -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/finally ---- -
{{JSRef}}
- -

Phương thức finally() trả về một {{jsxref("Promise")}}. Một khi promise được thực hiện (settle), dù kết quả là fulfilled hay rejected, thì hàm callback đã chỉ định sẽ được thực thi. Đây là cách để làm cho một đoạn code phải được thực thi sau khi Promise hoàn thành, dù kết quả là fulfilled hay rejected.

- -

Cách này giúp bạn tránh phải viết những dòng code trùng lặp giữa hai phương thức xử lý {{jsxref("Promise.then", "then()")}} và {{jsxref("Promise.catch", "catch()")}}.

- -

Syntax

- -
p.finally(onFinally);
-
-p.finally(function() {
-   // settled (fulfilled or rejected)
-});
-
- -

Parameters

- -
-
onFinally
-
Một {{jsxref("Function")}} được gọi khi Promise được thực hiện
-
- -

Return value

- -

Return a {{jsxref("Promise")}} whose finally handler is set to the specified function, onFinally.

- -

Description

- -

Phương thức finally() hữu ích khi bạn muốn xử lý công việc sau khi promise được thực hiện.

- -

Phương thức finally() cũng tương tự như việc gọi .then(onFinally, onFinally) , tuy nhiên có một số sự khác biệt:

- -
    -
  • Khi tạo một hàm inline, bạn có thể gán nó một lần, thay vì phải định nghĩa tới hai lần, hoặc phải tạo thêm biến cho nó.
  • -
  • Một callback finally sẽ không nhận tham số nào, vì không có cách xác đáng nào để biết liệu promise đã fulfilled hay bị rejected. Bạn dùng tới hàm này trong trường hợp bạn không quan tâm đến kết quả khi fulfilled, hay lý do khi reject. Vậy nên, không dùng tới thì bạn không cần phải truyền vào.
  • -
  • Không như Promise.resolve(2).then(() => {}, () => {}) (sẽ được resolve với undefined), Promise.resolve(2).finally(() => {}) sẽ được resolve với 2.
  • -
  • Tương tự, không như Promise.reject(3).then(() => {}, () => {}) (sẽ được fulfill với undefined), Promise.reject(3).finally(() => {}) sẽ bị reject với 3.
  • -
- -
-

Note: Một throw (hoặc trả về một promise bị reject) trong callback finally sẽ reject cái promise mới với lý do reject được chỉ định khi gọi throw().

-
- -

Examples

- -
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; });
-
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
TC39 proposalStage 4 
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Promise.finally")}}

- -

See also

- -
    -
  • {{jsxref("Promise")}}
  • -
  • {{jsxref("Promise.prototype.then()")}}
  • -
  • {{jsxref("Promise.prototype.catch()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/promise/index.html b/files/vi/web/javascript/reference/global_objects/promise/index.html deleted file mode 100644 index 9b069daf74..0000000000 --- a/files/vi/web/javascript/reference/global_objects/promise/index.html +++ /dev/null @@ -1,317 +0,0 @@ ---- -title: Promise -slug: Web/JavaScript/Reference/Global_Objects/Promise -translation_of: Web/JavaScript/Reference/Global_Objects/Promise ---- -
{{JSRef}}
- -

Promise là một đối tượng đặc biệt dùng cho các xử lý bất đồng bộ. Nó đại diện cho một xử lý bất đồng bộ và chứa kết quả cũng như các lỗi xảy ra từ xử lý bất đồng bộ đó.

- -

Cú pháp

- -
new Promise(executor);
-new Promise(function(resolve, reject) { ... } );
- -

Tham số đầu vào

- -
-
executor
-
Một hàm có 2 tham số đầu vào là 2 hàm phản hồi resolve và reject. Hàm resolve sẽ được gọi khi xử lý thành công, còn reject sẽ được gọi khi xử lý thất bại. 
-
* Chú ý: 2 hàm phản hồi này rất dễ bị nhầm lẫn với phong cách của hàm phản hồi của Node.js. Với Node.js hàm phản hồi lỗi thường là tham số đầu tiên, còn Promise thì ngược lại.
-
Hàm executor sẽ được gọi ngay khi Promise được gọi tới, tức là nó còn được chạy trước cả hàm khởi tạo trả ra kết quả của Promise. Sau khi xử lý kết thúc tùy theo tình huống mà hàm phản hồi resolve hoặc reject sẽ được gọi tới. Trường hợp xử lý thành công thì hàm resolve sẽ được gọi tới để trả ra kết quả. Còn trường hợp thất bại thì hàm reject sẽ được gọi tới để trả ra mã lỗi thực thi.
-
- -

Mô tả

- -

Một Promise có thể như một proxy đại diện cho một giá trị mà ta không cần phải biết ngay khi khởi tạo. Bằng các sử dụng Promise  ta có thể kết hợp với các hàm xử lý khác để sử dụng kết quả sau khi thực thi xử lý bất đồng bộ mà nó đang đại diện. Vì vậy mà ta có thể lập trình bất đồng bộ gần giống với kiểu lập trình đồng bộ - tức là đợi xử lý bất đồng bộ xong mới thực thi các thao tác mà cần sử dụng tới kết quả của xử lý đó. Để có thể làm được việc đó thay vì trả ra kết quả của việc xử lý đồng bộ, Promise  sẽ trả ra một promise khác. Bằng promise mới này ta lại có thể lặp lại việc sử dụng kết quả của thao tác xử lý lúc trước để làm đầu vào cho các thao tác xử lý lúc sau.

- -

Tại mỗi thời điểm Promise sẽ có thể ở một trong các trạng thái sau:

- -
    -
  • pending: Trạng thái chờ xử lý kết thúc. Trạng thái này chính là trạng thái ban đầu của Promise, nó thể hiện rằng thao tác xử lý của ta chưa kết thúc.
  • -
  • fulfilled: Trạng thái xử lý thành công. Trạng thái này thể hiện rằng thao tác xử lý của ta đã kết thúc và thành công.
  • -
  • rejected: Trạng thái xử lý thất bại. Trạng thái này thể hiện thao tác xử lý đã kết thúc và thất bại.
  • -
- -

Như vậy một Promise khi ở trạng thái pending sẽ được chuyển thành trạng thái fulfilled với kết quả thành công hoặc trạng thái rejected kèm với mã lỗi xảy ra khi xử lý kết thúc. Sau khi xử lý kết thúc, bất kể trạng thái được chuyển thành là thành công hay thất bại thì các hàm xử lý được đính kèm sẽ được gọi thực thi. Để đính kèm một hàm cho Promise, ta có thể sử dụng {{jsxref("Promise.then", "Promise.prototype.then()")}} cho trường hợp thành công và {{jsxref("Promise.catch", "Promise.prototype.catch()")}} cho trường hợp xử lý thất bại.

- -

Hàm đính kèm xử lý {{jsxref("Promise.then", "Promise.prototype.then()")}} và {{jsxref("Promise.catch", "Promise.prototype.catch()")}} sẽ trả ra một promise khác nên thao tác hậu xử lý bằng hàm đính kèm có thể được chuyển tiếp kiểu xử lý chuỗi (chained). Cụ thể hơn ta có thể xem hình dưới đây.

- -

- -

Như hình minh họa hoạt động của Promise trên, ta có thể thấy khi khởi tạo Promise sẽ có trạng thái là pending. Sau khi xử lý kết thúc, tùy theo kết quả xử lý mà trạng thái sẽ là fullfil hoặc reject. Lúc đó các hàm đính kèm sẽ được thực thi thông qua hàm {{jsxref("Promise.then", "Promise.prototype.then()")}} hoặc {{jsxref("Promise.catch", "Promise.prototype.catch()")}}. Chính các hàm này lại trả ra một Promise khác nên ta có thể xử lý một loạt các thao tác phía sau một cách chuyển tiếp.

- -

 

- -
-

Đừng nhầm lẫn với: một số ngôn ngữ khác như Scheme cũng có khái niệm “promises” - nhưng khái niệm này để chỉ thị một thao tác được gọi thực thi sau. Còn, Promises trong JavaScript biểu diễn các thao tác bất đồng bộ mà đã được thực thi (thao tác bất đồng bộ này được gọi ngay khi ta gọi Promise - ngay cả trước khi hàm khởi tạo của Promise được gọi tới) và có thể đính kèm các hàm hậu xử lý sau khi xử lý bất đồng bộ mà nó biểu diễn kết thúc. Nếu bạn muốn dùng các thao tác kiểu thi sau như vậy thì có thể sử dụng hàm mũi tên (arrow function) không có tham số đầu vào, như: f = () => expression để tạo một hàm được gọi sau, và sử dụng f() để thực thi nó.

-
- -
-

Lưu ý: Promise được gọi kết thúc (settled) khi và chỉ khi nó ở trạng thái fulfilled (thành công) hoặc rejected (thất bại). Đôi lúc có thể bạn thấy đâu đó nói rằng Promise được giải quyết xong (resolved) để ám chỉ rằng Promise được kết thúc, lúc đó đừng nhầm lẫn là nó được kết thúc thành công vì nó chỉ đơn giản là nói tới Promise đã được kết thúc mà thôi. Để biết rõ hơn về các thuật ngữ liên quan tới Promise, bạn có thể tham khảo bài viết này: States and fates.

-
- -

Thuộc tính

- -
-
Promise.length
-
Thuộc tính length này luôn có giá trị là 1 (số lượng của tham số khởi tạo).
-
{{jsxref("Promise.prototype")}}
-
Biểu diễn prototype cho hàm khởi tạo Promise.
-
- -

Phương thức

- -
-
{{jsxref("Promise.all", "Promise.all(iterable)")}}
-
Phương thức này được sử dụng khi ta cần đợi một tập các Promise kết thúc. Trả ra một promise đại diện cho tất cả các kết quả thu được từ các promise nằm trong iterable sau khi tất cả các promise này kết thúc xử lý thành công. Hoặc, trả ra một promise đại diện cho lỗi thực thi ngay khi một promise nào đó kết thúc lỗi, khi đó promise được trả ra cũng sẽ ở trạng thái lỗi. Khi tất cả các promise trong iterable kết thúc thành công thì promise trả ra cũng ở trạng thái thành công với kết quả là một mảng chứa tất cả các kết quả của các promise đã thực thi theo đúng thứ tự trong iterable. Còn khi một promise nào đó xảy ra lỗi thì promise được trả ra cũng sẽ ở trạng thái lỗi và chứa mã lỗi của promise đầu tiên gây lỗi đó.
-
{{jsxref("Promise.race", "Promise.race(iterable)")}}
-
Trả ra một promise ngay sau khi một trong các promise trong iterable kết thúc xử lý. Tức là dù kết quả thu được là lỗi hay thành công thì ta cũng sẽ trả ngay ra một promise mới và promise mới này sẽ chứa kết quả của promise được kết thúc đầu tiên.
-
- -
-
{{jsxref("Promise.reject", "Promise.reject(reason)")}}
-
Trả ra một promise trạng thái lỗi với mã lỗi mà hàm xử lý trả ra. Hàm này sẽ được gọi tới khi hàm xử lý của ta bị lỗi (thất bại).
-
- -
-
{{jsxref("Promise.resolve", "Promise.resolve(value)")}}
-
Trả ra một promise thành công với kết quả mà hàm xử lý trả ra. 
-
- -

Nguyên mẫu Promise

- -

Thuộc tính

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}

- -

Phương thức

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}

- -

Ví dụ

- -

Tạo một Promise

- - - -

Ví dụ nhỏ này sẽ mô tả cơ chế của một Promise. Hàm testPromise() sẽ được gọi tới mỗi khi ta click vào {{HTMLElement("button")}}. Ta sẽ sử dụng {{domxref("window.setTimeout()")}} để thiết lập giá trị kết thúc cho nó. Hàm xử lý này sẽ đếm (bắt đầu từ 1) sau mỗi khoảng thời gian ngẫu nhiên từ 1 tới 3 giây.

- -

Hàm hậu xử lý đính kèm ở đây chỉ đơn giản là một hàm log lại các giá trị được trả ra và được gán bằng cách sử dụng hàm {{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 +
-        ') Started (<small>Sync code started</small>)<br/>');
-
-    // Tạo một Promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s)
-    var p1 = new Promise(
-        // The resolver function is called with the ability to resolve or
-        // reject the promise
-        function(resolve, reject) {
-            log.insertAdjacentHTML('beforeend', thisPromiseCount +
-                ') Promise started (<small>Async code started</small>)<br/>');
-            // This is only an example to create asynchronism
-            window.setTimeout(
-                function() {
-                    // We fulfill the promise !
-                    resolve(thisPromiseCount);
-                }, Math.random() * 2000 + 1000);
-        }
-    );
-
-    // We define what to do when the promise is resolved/fulfilled with the then() call,
-    // and the catch() method defines what to do if the promise is rejected.
-    p1.then(
-        // Log the fulfillment value
-        function(val) {
-            log.insertAdjacentHTML('beforeend', val +
-                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
-        })
-    .catch(
-        // Log the rejection reason
-        function(reason) {
-            console.log('Handle rejected promise ('+reason+') here.');
-        });
-
-    log.insertAdjacentHTML('beforeend', thisPromiseCount +
-        ') Promise made (<small>Sync code terminated</small>)<br/>');
-}
- - - -

Ví dụ này được thực thi mỗi khi ta click vào button và để chạy được ví dụ này, bạn cần một trình duyệt có hỗ trợ Promise. Bạn hãy thử click vào button một vài lần liên tiếp trong một khoảng thời gian ngắn để thấy được các promise được xử lý thành chuỗi và sau khi kết thúc xử lý sẽ ở trạng thái thế nào nhé.

- -

{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}

- -

Ví dụ với XMLHttpRequest

- -

Tạo một Promise

- -

Ví dụ này sẽ trình bày một cách sử dụng Promise để lấy kết quả (thành công hoặc lỗi) trả về từ {{domxref("XMLHttpRequest")}}.

- -
'use strict';
-
-// A-> $http function is implemented in order to follow the standard Adapter pattern
-function $http(url){
-
-  // A small example of object
-  var core = {
-
-    // Method that performs the ajax request
-    ajax: function (method, url, args) {
-
-      // Creating a promise
-      var promise = new Promise( function (resolve, reject) {
-
-        // Instantiates the XMLHttpRequest
-        var client = new XMLHttpRequest();
-        var uri = url;
-
-        if (args && (method === 'POST' || method === 'PUT')) {
-          uri += '?';
-          var argcount = 0;
-          for (var key in args) {
-            if (args.hasOwnProperty(key)) {
-              if (argcount++) {
-                uri += '&';
-              }
-              uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
-            }
-          }
-        }
-
-        client.open(method, uri);
-        client.send();
-
-        client.onload = function () {
-          if (this.status >= 200 && this.status < 300) {
-            // Performs the function "resolve" when this.status is equal to 2xx
-            resolve(this.response);
-          } else {
-            // Performs the function "reject" when this.status is different than 2xx
-            reject(this.statusText);
-          }
-        };
-        client.onerror = function () {
-          reject(this.statusText);
-        };
-      });
-
-      // Return the promise
-      return promise;
-    }
-  };
-
-  // Adapter pattern
-  return {
-    'get': function(args) {
-      return core.ajax('GET', url, args);
-    },
-    'post': function(args) {
-      return core.ajax('POST', url, args);
-    },
-    'put': function(args) {
-      return core.ajax('PUT', url, args);
-    },
-    'delete': function(args) {
-      return core.ajax('DELETE', url, args);
-    }
-  };
-};
-// End A
-
-// B-> Here you define its functions and its payload
-var mdnAPI = 'https://developer.mozilla.org/en-US/search.json';
-var payload = {
-  'topic' : 'js',
-  'q'     : 'Promise'
-};
-
-var callback = {
-  success: function(data) {
-    console.log(1, 'success', JSON.parse(data));
-  },
-  error: function(data) {
-    console.log(2, 'error', JSON.parse(data));
-  }
-};
-// End B
-
-// Executes the method call
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success)
-  .catch(callback.error);
-
-// Executes the method call but an alternative way (1) to handle Promise Reject case
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success, callback.error);
-
-// Executes the method call but an alternative way (2) to handle Promise Reject case
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success)
-  .then(undefined, callback.error);
-
- -

Tải một ảnh với XHR

- -

Một ví dụ đơn giản khác được sử dụng Promise và XMLHttpRequest để tải về một ảnh là MDN  GitHub - promise-test. Ngoài ra, bạn có thể xem nó hoạt động ra sao tại đây. Mỗi bước đều được chú thích đầy đủ để giúp bạn hình dung được việc sử dụng Promise với XHR dễ dàng hơn.

- -

Mô tả

- - - - - - - - - - - - - - - - - - - -
Mô tảTrạng tháiChú thích
{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat}}

- -

Tham khảo thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/regexp/exec/index.html b/files/vi/web/javascript/reference/global_objects/regexp/exec/index.html deleted file mode 100644 index 9fdf5c193e..0000000000 --- a/files/vi/web/javascript/reference/global_objects/regexp/exec/index.html +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: RegExp.prototype.exec() -slug: Web/JavaScript/Reference/Global_Objects/RegExp/exec -tags: - - Biểu thức chính quy - - Phương Thức - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/exec ---- -
{{JSRef}}
- -

Phương thức exec() tiến hành tìm kiếm một so khớp trong một chuỗi xác định. Trả về một mảng kết quả hoặc {{jsxref("null")}}.

- -

Nếu bạn đơn giản chỉ muốn xác định có khớp hay không, tức kết quả trả về là true hoặc false, bạn nên sử dụng phương thức {{jsxref("RegExp.prototype.test()")}} hoặc phương thức {{jsxref("String.prototype.search()")}}.

- -
{{EmbedInteractiveExample("pages/js/regexp-prototype-exec.html")}}
- - - -

Cú pháp

- -
regexObj.exec(str)
- -

Tham số

- -
-
str
-
Chuỗi dùng để so khớp với biểu thức chính quy.
-
- -

Giá trị trả về

- -

Nếu so khớp thành công, phương thức exec() trả về một mảng và cập nhật các thuộc tính của đối tượng biểu thức chính quy. Mảng trả về item đầu tiên là đoạn text khớp, và các item tiếp theo là giá trị trong các dấu ngoặc tròn có nhớ đã khớp.

- -

Nếu việc so khớp thất bại, exec() trả về  {{jsxref("null")}}.

- -

Mô tả

- -

Hãy xem xét ví dụ sau:

- -
// So khớp "quick brown" theo sau bởi "jumps", bỏ qua các kí tự ở giữa
-// Nhớ "brown" và "jumps"
-// Không phân biệt chữ hoa/thường
-var re = /quick\s(brown).+?(jumps)/ig;
-var result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');
-
- -

Bảng dưới đây là kết quả trả về của so khớp trên.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đối tượngThuộc tính/Chỉ mụcMô tảVí dụ
result[0]Chuỗi đầy đủ của các kí tự đã khớp.Quick Brown Fox Jumps
[1], ...[n ] -

Các chuỗi con khớp được đặt trong ngoặc, nếu có. Số lượng ngoặc không giới hạn.

-
[1] = Brown
- [2] = Jumps
index -

Chỉ mục (tính từ 0) của bản khớp trong chuỗi.

-
4
inputChuỗi ban đầu.The Quick Brown Fox Jumps Over The Lazy Dog
relastIndex -

Chỉ mục bắt đầu tìm so khớp tiếp theo. Khi không có cờ "g" thì chỉ mục sẽ trở về 0.

-
25
ignoreCaseXác định xem liệu cờ "i" (không phân biệt chữ hoa/thường) được sử dụng hay không.true
globalXác định liệu cờ "g" (so khớp toàn cục) có được sử dụng hay không.true
multilineXác định xem cờ "m" (tìm kiếm chuỗi đa dòng) có được sử dụng hay không.false
sourcemẫu dùng để so khớp.quick\s(brown).+?(jumps)
- -

Ví dụ

- -

Tìm các so khớp tiếp theo

- -

Nếu biểu thức chính quy của bạn sử dụng cờ g, bạn có thể dùng phương thức exec() nhiều lần để tìm các so khớp tiếp theo trong chuỗi giống vậy. Lúc đó, việc tìm kếu bắt đầu từ chuỗi con của str đã được chỉ định bởi thuộc tính {{jsxref("RegExp.lastIndex", "lastIndex")}} của biểu thức chính quy. ({{jsxref("RegExp.prototype.test()", "test()")}} cũng sẽ tăng tới thuộc tính {{jsxref("RegExp.lastIndex", "lastIndex")}} property. Ví dụ, giả sử bạn có kịch bản:

- -
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);
-}
-
- -

Kịch bản này hiển thị văn bản sau:

- -
Found abb. Next match starts at 3
-Found ab. Next match starts at 9
-
- -

Chú ý: Đừng đặt biểu thức chính quy thuần (hoặc cấu trúc {{jsxref("RegExp")}}) bên trong điều kiện while hoặc nó sẽ tạo ra một vòng lặp vĩnh cửu nếu có một so khớp vì thuộc tính {{jsxref("RegExp.lastIndex", "lastIndex")}} sẽ reset lại sau mỗi vòng lặp. Và hãy chắc rằng cờ toàn cùng được xét nếu không một vòng lặp sẽ xảy ra.

- -

Sử dụng exec() với RegExp thuần

- -

Bạn có thể sử dụng exec() mà không cần tạo đối tượng {{jsxref("RegExp")}}:

- -
var matches = /(hello \S+)/.exec('This is a hello world!');
-console.log(matches[1]);
-
- -

Kịch bản này sẽ ghi ra lời nhắn chứa 'hello world!'.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.10.6.21', 'RegExp.exec')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp.prototype.exec', 'RegExp.exec')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-regexp.prototype.exec', 'RegExp.exec')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.RegExp.exec")}}

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/regexp/index.html b/files/vi/web/javascript/reference/global_objects/regexp/index.html deleted file mode 100644 index 01f9b60832..0000000000 --- a/files/vi/web/javascript/reference/global_objects/regexp/index.html +++ /dev/null @@ -1,618 +0,0 @@ ---- -title: RegExp -slug: Web/JavaScript/Reference/Global_Objects/RegExp -tags: - - Constructor - - JavaScript - - NeedsTranslation - - Reference - - RegExp - - Regular Expressions - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/RegExp ---- -
{{JSRef}}
- -

The RegExp constructor creates a regular expression object for matching text with a pattern.

- -

For an introduction to regular expressions, read the Regular Expressions chapter in the JavaScript Guide.

- -
{{EmbedInteractiveExample("pages/js/regexp-constructor.html")}}
- - - -

Syntax

- -

Literal, constructor, and factory notations are possible:

- -
/pattern/flags
-new RegExp(pattern[, flags])
-RegExp(pattern[, flags])
-
- -

Parameters

- -
-
pattern
-
The text of the regular expression.
-
flags
-
-

If specified, flags can have any combination of the following values:

- -
-
g
-
global match; find all matches rather than stopping after the first match
-
i
-
ignore case; if u flag is also enabled, use Unicode case folding
-
m
-
multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
-
u
-
Unicode; treat pattern as a sequence of Unicode code points
-
y
-
sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).
-
-
-
- -

Description

- -

There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:

- -
/ab+c/i;
-new RegExp('ab+c', 'i');
-new RegExp(/ab+c/, 'i');
-
- -

The literal notation provides a compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

- -

The constructor of the regular expression object, for example, new RegExp('ab+c'), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

- -

Starting with ECMAScript 6, new RegExp(/ab+c/, 'i') no longer throws a {{jsxref("TypeError")}} ("can't supply flags when constructing one RegExp from another") when the first argument is a RegExp and the second flags argument is present. A new RegExp from the arguments is created instead.

- -

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:

- -
var re = /\w+/;
-var re = new RegExp('\\w+');
-
- -

Special characters meaning in regular expressions

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Character Classes
CharacterMeaning
. -

(The dot, the decimal point) matches any single character except line terminators: \n, \r, \u2028 or \u2029.

- -

Inside a character set, the dot loses its special meaning and matches a literal dot.

- -

Note that the m multiline flag doesn't change the dot behavior. So to match a pattern across multiple lines, the character set [^] can be used (if you don't mean an old version of IE, of course), it will match any character including newlines.

- -

For example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day".

-
\d -

Matches any digit (Arabic numeral). Equivalent to [0-9].

- -

For example, /\d/ or /[0-9]/ matches "2" in "B2 is the suite number".

-
\D -

Matches any character that is not a digit (Arabic numeral). Equivalent to [^0-9].

- -

For example, /\D/ or /[^0-9]/ matches "B" in "B2 is the suite number".

-
\w -

Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_].

- -

For example, /\w/ matches "a" in "apple", "5" in "$5.28", and "3" in "3D".

-
\W -

Matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_].

- -

For example, /\W/ or /[^A-Za-z0-9_]/ matches "%" in "50%".

-
\s -

Matches a single white space character, including space, tab, form feed, line feed and other Unicode spaces. Equivalent to [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

- -

For example, /\s\w*/ matches " bar" in "foo bar".

-
\S -

Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

- -

For example, /\S\w*/ matches "foo" in "foo bar".

-
\tMatches a horizontal tab.
\rMatches a carriage return.
\nMatches a linefeed.
\vMatches a vertical tab.
\fMatches a form-feed.
[\b]Matches a backspace. (Not to be confused with \b)
\0Matches a NUL character. Do not follow this with another digit.
\cX -

Where X is a letter from A - Z. Matches a control character in a string.

- -

For example, /\cM/ matches control-M in a string.

-
\xhhMatches the character with the code hh (two hexadecimal digits).
\uhhhhMatches a UTF-16 code-unit with the value hhhh (four hexadecimal digits).
\u{hhhh} or \u{hhhhh}(only when u flag is set) Matches the character with the Unicode value U+hhhh or U+hhhhh (hexadecimal digits).
\ -

For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.

- -

For example, /b/ matches the character "b". By placing a backslash in front of "b", that is by using /\b/, the character becomes special to mean match a word boundary.

- -

or

- -

For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally.

- -

For example, "*" is a special character that means 0 or more occurrences of the preceding character should be matched; for example, /a*/ means match 0 or more "a"s. To match * literally, precede it with a backslash; for example, /a\*/ matches "a*".

-
Character Sets
CharacterMeaning
[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".

-
Alternation
CharacterMeaning
x|y -

Matches either x or y.

- -

For example, /green|red/ matches "green" in "green apple" and "red" in "red apple".

-
Boundaries
CharacterMeaning
^ -

Matches 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".

-
$ -

Matches 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.

-
\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. Such as 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 bondary is also not included in the match.

- -

For example, /\Bon/ matches "on" in "at noon", and /ye\B/ matches "ye" in "possibly yesterday".

-
Grouping and back references
CharacterMeaning
(x) -

Matches x and remembers the match. These are called capturing groups.

- -

For example, /(foo)/ matches and remembers "foo" in "foo bar". 

- -

The capturing groups are numbered according to the order of left parentheses of capturing groups, starting from 1. The matched substring can be recalled from the resulting array'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).

-
\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.

-
(?:x)Matches x but does not remember the match. These are called non-capturing groups. The matched substring cannot be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.
Quantifiers
CharacterMeaning
x* -

Matches the preceding item x 0 or more times.

- -

For example, /bo*/ matches "boooo" in "A ghost booooed" and "b" in "A bird warbled", but nothing in "A goat grunted".

-
x+ -

Matches the preceding item x 1 or more times. Equivalent to {1,}.

- -

For example, /a+/ matches the "a" in "candy" and all the "a"'s in "caaaaaaandy".

-
x? -

Matches the preceding item x 0 or 1 time.

- -

For example, /e?le?/ matches the "el" in "angel" and the "le" in "angle."

- -

If used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times).

-
x{n} -

Where n is a positive integer. Matches exactly n occurrences of the preceding item x.

- -

For example, /a{2}/ doesn't match the "a" in "candy", but it matches all of the "a"'s in "caandy", and the first two "a"'s in "caaandy".

-
x{n,} -

Where n is a positive integer. Matches at least n occurrences of the preceding item x.

- -

For example, /a{2,}/ doesn't match the "a" in "candy", but matches all of the a's in "caandy" and in "caaaaaaandy".

-
x{n,m} -

Where n is 0 or a positive integer, and m is a positive integer. Matches at least n and at most m occurrences of the preceding item x.

- -

For example, /a{1,3}/ matches nothing in "cndy", the "a" in "candy", the two "a"'s in "caandy", and the first three "a"'s in "caaaaaaandy". Notice that when matching "caaaaaaandy", the match is "aaa", even though the original string had more "a"'s in it.

-
-

x*?
- x+?
- x??
- x{n}?
- x{n,}?
- x{n,m}?

-
-

Matches the preceding item x like *, +, ?, and {...} from above, however the match is the smallest possible match.

- -

For example, /<.*?>/ matches "<foo>" in "<foo> <bar>", whereas /<.*>/ matches "<foo> <bar>".

- -

Quantifiers without ? are said to be greedy. Those with ? are called "non-greedy".

-
Assertions
CharacterMeaning
x(?=y) -

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) -

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.141".

-
- -

Properties

- -
-
{{jsxref("RegExp.prototype")}}
-
Allows the addition of properties to all objects.
-
RegExp.length
-
The value of RegExp.length is 2.
-
{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("RegExp.lastIndex")}}
-
The index at which to start the next match.
-
- -

Methods

- -

The global RegExp object has no methods of its own, however, it does inherit some methods through the prototype chain.

- -

RegExp prototype objects and instances

- -

Properties

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype', 'Properties')}}
- -

Methods

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype', 'Methods')}}
- -

Examples

- -

Using a regular expression to change data format

- -

The following script uses the {{jsxref("String.prototype.replace()", "replace()")}} method of the {{jsxref("Global_Objects/String", "String")}} instance to match a name in the format first last and output it in the format last, first. In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

- -
var re = /(\w+)\s(\w+)/;
-var str = 'John Smith';
-var newstr = str.replace(re, '$2, $1');
-console.log(newstr);
-
- -

This displays "Smith, John".

- -

Using regular expression to split lines with different line endings/ends of line/line breaks

- -

The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.

- -
var text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end';
-var lines = text.split(/\r\n|\r|\n/);
-console.log(lines); // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
-
- -

Note that the order of the patterns in the regular expression matters.

- -

Using regular expression on multiple lines

- -
var s = 'Please yes\nmake my day!';
-s.match(/yes.*day/);
-// Returns null
-s.match(/yes[^]*day/);
-// Returns ["yes\nmake my day"]
-
- -

Using a regular expression with the sticky flag

- -

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at {{jsxref("RegExp.prototype.lastIndex")}}.

- -
var str = '#foo#';
-var 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)
- -

Regular expression and Unicode characters

- -

As mentioned above, \w or \W only matches ASCII based characters; for example, "a" to "z", "A" to "Z", "0" to "9" and "_". To match characters from other languages such as Cyrillic or Hebrew, use \uhhhh, where "hhhh" is the character's Unicode value in hexadecimal. This example demonstrates how one can separate out Unicode characters from a word.

- -
var text = 'Образец text на русском языке';
-var regex = /[\u0400-\u04FF]+/g;
-
-var match = regex.exec(text);
-console.log(match[0]);        // logs 'Образец'
-console.log(regex.lastIndex); // logs '7'
-
-var match2 = regex.exec(text);
-console.log(match2[0]);       // logs 'на' [did not log 'text']
-console.log(regex.lastIndex); // logs '15'
-
-// and so on
-
- -

Here's an external resource for getting the complete Unicode block range for different scripts: Regexp-Unicode-block.

- -

Extracting sub-domain name from URL

- -
var url = 'http://xxx.domain.com';
-console.log(/[^.]+/.exec(url)[0].substr(7)); // logs 'xxx'
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.10', 'RegExp')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp-regular-expression-objects', 'RegExp')}}{{Spec2('ES6')}}The RegExp constructor no longer throws when the first argument is a RegExp and the second argument is present. Introduces Unicode and sticky flags.
{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.RegExp")}}

-
- -

Firefox-specific notes

- -

Starting with Firefox 34, in the case of a capturing group with quantifiers preventing its exercise, the matched text for a capturing group is now undefined instead of an empty string:

- -
// Firefox 33 or older
-'x'.replace(/x(.)?/g, function(m, group) {
-  console.log("'group:" + group + "'");
-}); // 'group:'
-
-// Firefox 34 or newer
-'x'.replace(/x(.)?/g, function(m, group) {
-  console.log("'group:" + group + "'");
-}); // 'group:undefined'
-
- -

Note that due to web compatibility, RegExp.$N will still return an empty string instead of undefined ({{bug(1053944)}}).

- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/index.html b/files/vi/web/javascript/reference/global_objects/string/index.html deleted file mode 100644 index c9f5680a0c..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/index.html +++ /dev/null @@ -1,405 +0,0 @@ ---- -title: String -slug: Web/JavaScript/Reference/Global_Objects/String -tags: - - ECMAScript6 - - JavaScript - - NeedsTranslation - - Reference - - String - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/String ---- -
{{JSRef}}
-

lnyannini

- -

HTML

- -
Nội dung HTML mẫu
- -

CSS

- -
Nội dung CSS mẫu
- -

JavaScript

- -
Nội dung JavaScript mẫu
- -

Kết quả

- -

{{EmbedLiveSample('lnyannini')}}

-f}} - -

Copy dtoc: june-12-2017
- The String global object is a constructor for strings, or a sequence of characters.
- Đối tượng Chuỗi toàn cục là một constructor cho chuỗi, hoặc chuỗi ký tự.

- -

Syntax

- -

String literals take the forms:

- -
'string text'
-"string text"
-"中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"
- -

Strings can also be created using the String global object directly:

- -
String(thing)
- -

Parameters

- -
-
thing
-
Anything to be converted to a string.
-
- -

Template literals

- -

Starting with ECMAScript 2015, string literals can also be so-called Template literals:
- Trong ES6 Chuỗi cũng được gọi là Template Strings.

- -
`hello world`
-`hello!
- world!`
-`hello ${who}`
-escape `<a>${who}</a>`
- -
-
- -

Escape notation

- -

Beside regular, printable characters, special characters can be encoded using escape notation:
- Ngoài ký tự thường, các ký tự đặc biệt có thể được code ra bằng cách dùng các ký hiệu loại trừ:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CodeOutput
\0the NULL character
\'single quote
\"double quote
\\backslash
\nnew line
\rcarriage return
\vvertical tab
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXthe Latin-1 character
- -
-

Unlike some other languages, JavaScript makes no distinction between single-quoted strings and double-quoted strings; therefore, the escape sequences above work in strings created with either single or double quotes.

-
- -
-
- -

Long literal strings

- -

Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.

- -

You can use the + operator to append multiple strings together, like this:

- -
let longString = "This is a very long string which needs " +
-                 "to wrap across multiple lines because " +
-                 "otherwise my code is unreadable.";
-
- -

Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:

- -
let longString = "This is a very long string which needs \
-to wrap across multiple lines because \
-otherwise my code is unreadable.";
-
- -

Both of these result in identical strings being created.

- -

Description

- -

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.

- -

Character access

- -

There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:

- -
return 'cat'.charAt(1); // returns "a"
-
- -

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:

- -
return 'cat'[1]; // returns "a"
-
- -

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)

- -

Comparing strings

- -

C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:

- -
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.');
-}
-
- -

A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by String instances.

- -

Distinction between string primitives and String objects

- -

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)

- -

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

- -
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 primitives and String objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

- -
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"
-
- -

For these reasons, code may break when it encounters String objects when it expects a primitive string instead, although generally authors need not worry about the distinction.

- -

A String object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.

- -
console.log(eval(s2.valueOf())); // returns the number 4
-
- -
Note: For another possible approach to strings in JavaScript, please read the article about StringView — a C-like representation of strings based on typed arrays.
- -

Properties

- -
-
{{jsxref("String.prototype")}}
-
Allows the addition of properties to a String object.
-
- -

Methods

- -
-
{{jsxref("String.fromCharCode()")}}
-
Returns a string created by using the specified sequence of Unicode values.
-
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
-
Returns a string created by using the specified sequence of code points.
-
{{jsxref("String.raw()")}} {{experimental_inline}}
-
Returns a string created from a raw template string.
-
- -

String generic methods

- -
-

String generics are non-standard, deprecated and will get removed near future.

-
- -

The String instance methods are also available in Firefox as of JavaScript 1.6 (not part of the ECMAScript standard) on the String object for applying String methods to any object:

- -
var num = 15;
-console.log(String.replace(num, /5/, '2'));
-
- -

For migrating away from String generics, see also Warning: String.x is deprecated; use String.prototype.x instead.

- -

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.

- -

String instances

- -

Properties

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}
- -

Methods

- -

Methods unrelated to 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')}}
- -

Examples

- -

String conversion

- -

It's possible to use String as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, although it still normally calls the underlying toString(). It also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:

- -
var outputStrings = [];
-for (var i = 0, n = inputValues.length; i < n; ++i) {
-  outputStrings.push(String(inputValues[i]));
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}}
{{SpecName('ES2015', '#sec-string-objects', 'String')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/match/index.html b/files/vi/web/javascript/reference/global_objects/string/match/index.html deleted file mode 100644 index d40ffc4482..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/match/index.html +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: String.prototype.match() -slug: Web/JavaScript/Reference/Global_Objects/String/match -tags: - - Biểu thức chính quy - - Chuỗi - - Phương Thức -translation_of: Web/JavaScript/Reference/Global_Objects/String/match ---- -
{{JSRef}}
- -
 
- -

Phương thức match() đưa ra những so khớp khi so khớp một chuỗi (string) với biểu thức chính quy.

- -

Cú pháp

- -
str.match(regexp)
- -

Tham số

- -
-
regexp
-
Đối tượng biểu thức chính quy.  Nếu một đối tượng obj không phải biểu thức chính quy được truyền vào, nó sẽ ngầm chuyển đổi thành một {{jsxref("RegExp")}} bằng cách sử dụng new RegExp(obj). Nếu bạn không truyền tham số và sử dụng trực tiếp phương thức match(), bạn sẽ nhận lại một {{jsxref("Array")}} với một chuỗi rỗng: [""].
-
- -

Giá trị trả về

- -

Nếu một chuỗi khớp với biểu thức, nó sẽ trả lại một {{jsxref("Array")}} chứa chuỗi khớp hoàn toàn là phần tử đầu tiên, tiếp đó là các kết quả nằm trong dấu ngoặc đơn (ngoặc có nhớ). Nếu không có so khớp, nó sẽ trả về {{jsxref("null")}}.

- -

Mô tả

- -

Nếu một biểu thức chính quy không có cờ gstr.match() trả về kết quả giống như  {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}. {{jsxref("Array")}} trả về có thêm thuộc tính input chứa chuỗi ban đầu được phân tích ngữ pháp. Thêm nữa, nó có một thuộc tính index đại diện cho chỉ mục (tính từ 0) của so khớp trong chuỗi.

- -

Nếu biểu thức chính quy có cờ g, phương thức trả về một {{jsxref("Array")}} chứa tất cả chuỗi con khớp mà không phải các đối tượng khớp. Nó không trả về chuỗi trong dấu ngoặc tròn có nhớ. Nếu không có so khớp, phương thức trả về {{jsxref("null")}}.

- -

Xem thêm: Các phương thức RegEx

- -
    -
  • Trường hợp bạn cần biết liệu một chuỗi có khớp với biểu thức chính quy {{jsxref("RegExp")}} hay không, sử dụng {{jsxref("RegExp.prototype.test()", "RegExp.test()")}}.
  • -
  • Nếu chỉ muốn xem so khớp đầu tiên được tìm thấy, bạn sử dụng {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}.
  • -
  • Nếu bạn muốn lấy nhóm trong ngoặc có nhớ và xét cờ, bạn cần sử dụng {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}.
  • -
- -

Ví dụ

- -

Sử dụng match()

- -

Trong ví dụ dưới đây, match() được dùng để tìm chuỗi 'Chapter ' theo sau là một hoặc nhiều kí tự số, tiếp đó là một dấu chấm . thập phân và một số lặp lại 0 hoặc nhiều lần. Biểu thức chính quy có cờ i nên không phân biệt chữ hoa và thường.

- -
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' là so khớp toàn bộ.
-// 'Chapter 3.4.5.1' được bắt bởi '(chapter \d+(\.\d)*)'.
-// '.1' là giá trị cuối cùng được bắt bởi '(\.\d)'.
-// Thuộc tính 'index' (22) là chỉ mục tính từ 0 của so khớp toàn bộ.
-// Thuộc tính 'input' là chuỗi gốc đã được phân tích ngữ pháp.
- -

Sử dụng cờ toàn cục và cờ không phân biệt chữ hoa/thường với match()

- -

Ví dụ dưới đây mô tả cách sử dụng cờ g và cờ i với match(). Tất cả chữ A tớ E và a tới e sẽ được trả lại và mỗi phần từ khớp nằm trong mảng.

- -
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']
-
- -

Sử dụng match() không truyền tham số

- -
var str = "Nothing will come of nothing.";
-
-str.match();   //trả về [""]
- -

Một đối tượng không phải biểu thức chính quy được coi như một tham số

- -

Khi tham số là một chuỗi hoặc một số, ngầm định, nó được chuyển đổi thành một {{jsxref("RegExp")}} sử dụng new RegExp(obj). Nếu nó là một số dương với một dấu dương, phương thức Regexp() sẽ bỏ qua dấu dương.

- -
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" là một chuỗi. Trả về ["number"]
-str1.match(NaN);        // kiểu của NaN là kiểu number. Trả về ["NaN"]
-str1.match(Infinity);   // kiểu của Infinity là number. Trả về ["Infinity"]
-str1.match(+Infinity);  // Trả về ["Infinity"]
-str1.match(-Infinity);  // Trả về ["-Infinity"]
-str2.match(65);         // Trả về ["65"]
-str2.match(+65);        // Một số với dấu dương. Trả về ["65"]
-str3.match(null);       // Trả về ["null"]
- -

Thông số

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông sốTrạng tháiBình luận
{{SpecName('ES3')}}{{Spec2('ES3')}} -

Định nghĩa ban đầu. Được bổ sung trong 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')}} 
- -

Tương thích trình duyệt

- - - -

{{Compat("javascript.builtins.String.match")}}

- -

Lưu ý cho Firefox

- -
    -
  • các cờ flags từng không phải đối số thứ hai tiêu chuẩn, nó chỉ có hiệu lực trong Gecko: str.match(regexp, flags)
  • -
  • Bắt đầu từ Gecko 27 {{geckoRelease(27)}}, phương thức này đã được điều chỉnh để phù hợp với ECMAScript. Khi match() được gọi với một biểu thức chính quy toàn cục, thuộc tính {{jsxref("RegExp.lastIndex")}} (nếu nó được chỉ định) sẽ được đưa về 0 ({{bug(501739)}}).
  • -
  • Từ Gecko 39 {{geckoRelease(39)}}, đối số flags không chuẩn  không được chấp nhận và sẽ có cảnh báo ({{bug(1142351)}}) trên giao diện điều khiển.
  • -
  •  Từ Gecko 47 {{geckoRelease(47)}}, đối số flags không chuẩn không còn được hỗ trợ trong các phiên bản chưa phát hành và sẽ sớm bị gỡ bỏ {{bug(1245801)}}) hoàn toàn.
  • -
  • Từ Gecko 49 {{geckoRelease(49)}}, đối số flags không chuẩn còn còn được hỗ trợ ({{bug(1108382)}}).
  • -
  • Starting with Gecko 49 {{geckoRelease(49)}}, the non-standard flags argument is no longer supported ({{bug(1108382)}}).
  • -
- -

Xem thêm

- -
    -
  • {{jsxref("RegExp")}}
  • -
  • {{jsxref("RegExp.prototype.exec()")}}
  • -
  • {{jsxref("RegExp.prototype.test()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/string/normalize/index.html b/files/vi/web/javascript/reference/global_objects/string/normalize/index.html deleted file mode 100644 index faf26687eb..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/normalize/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: String.prototype.normalize() -slug: Web/JavaScript/Reference/Global_Objects/String/normalize -tags: - - Chuỗi - - ECMAScript 2015 - - JavaScript - - Phương Thức - - Prototype - - String - - Tham khảo - - Unicode -translation_of: Web/JavaScript/Reference/Global_Objects/String/normalize ---- -
{{JSRef}}
- -

Phương thức normalize() trả về chuỗi với các ký tự Unicode đã được bình thường hóa (nếu giá trị truyền vào không phải chuỗi, nó sẽ được chuyển thành chuỗi trước).

- -
{{EmbedInteractiveExample("pages/js/string-normalize.html")}}
- - - -

Cú pháp

- -
str.normalize([form])
- -

Tham số

- -
-
form
-
Là một trong các giá trị "NFC", "NFD", "NFKC", hoặc "NFKD", để chỉ định định dạng Unicode của chuỗi ký tự. Nếu bỏ qua hoặc mang giá trị {{jsxref("undefined")}}, "NFC" sẽ được sử dụng. -
    -
  • NFC — Normalization Form Canonical Composition. (Unicode Dựng Sẵn)
  • -
  • NFD — Normalization Form Canonical Decomposition. (Unicode Tổ Hợp)
  • -
  • NFKC — Normalization Form Compatibility Composition. (Unicode Dựng Sẵn Tương Thích)
  • -
  • NFKD — Normalization Form Compatibility Decomposition. (Unicode Tổ Hợp Tương Thích)
  • -
-
-
- -

Giá trị trả về

- -

Một chuỗi mới với các ký tự Unicode đã được bình thường hóa.

- -

Lỗi có thể gây ra

- -
-
{{jsxref("RangeError")}}
-
Phương thức sẽ gây ra lỗi {{jsxref("RangeError")}} nếu như giá trị tham số form không phải là một trong các giá trị liệt kê ở trên.
-
- -

Mô tả

- -

Phương thức normalize() sẽ trả về một chuỗi mới với các ký tự Unicode đã được bình thường hóa theo một trong các định dạng Unicode Normalization Form. Nó không làm thay đổi chuỗi ban đầu.

- -
-

Đối với tiếng Việt, việc bình thường hóa giữa hai định dạng Canonical hoặc Compatibility (cùng Tổ Hợp hoặc Dựng Sẵn) là như nhau.

-
- -

Ví dụ

- -

Sử dụng normalize()

- -
// Chuỗi ban đầu
-
-// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
-// U+0323: COMBINING DOT BELOW
-var str = '\u1E9B\u0323';
-
-
-// Canonically-composed form (NFC)
-
-// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
-// U+0323: COMBINING DOT BELOW
-str.normalize('NFC'); // '\u1E9B\u0323'
-str.normalize();      // như trên
-
-
-// Canonically-decomposed form (NFD)
-
-// U+017F: LATIN SMALL LETTER LONG S
-// U+0323: COMBINING DOT BELOW
-// U+0307: COMBINING DOT ABOVE
-str.normalize('NFD'); // '\u017F\u0323\u0307'
-
-
-// Compatibly-composed (NFKC)
-
-// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE
-str.normalize('NFKC'); // '\u1E69'
-
-
-// Compatibly-decomposed (NFKD)
-
-// U+0073: LATIN SMALL LETTER S
-// U+0323: COMBINING DOT BELOW
-// U+0307: COMBINING DOT ABOVE
-str.normalize('NFKD'); // '\u0073\u0323\u0307'
-
-// So sánh chuỗi tiếng Việt:
-
-// Unicode Dựng Sẵn
-var tvds = 'Tiếng Việt';
-// Unicode Tổ Hợp
-var tvth = 'Tiếng Việt';
-
-console.log(tvds.length); // 10
-console.log(tvth.length); // 14
-console.log(tvds == tvth); // false
-console.log(tvds.normalize('NFC') == tvth.normalize('NFC')); // true
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ES2015')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.String.normalize")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/repeat/index.html b/files/vi/web/javascript/reference/global_objects/string/repeat/index.html deleted file mode 100644 index 72e2179cf1..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/repeat/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: String.prototype.repeat() -slug: Web/JavaScript/Reference/Global_Objects/String/repeat -tags: - - Chuỗi - - ES6 - - Phương Thức - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat ---- -
{{JSRef}}
- -

Phương thức repeat() xây dựng và trả về một chuỗi mới chứa số lượng nhất định bản sao chép của chuỗi được gọi tới và nối chung với nhau.

- -

Cú pháp

- -
str.repeat(count);
-
- -

Tham số

- -
-
count
-
Là 0 hoặc số nguyên dương, tức là giá trị nằm trong khoảng: [0, +∞), xác định số lần lặp để tạo chuỗi mới.
-
- -

Giá trị trả về

- -

Một chuỗi mới chứa số lần sao chép (count) chuỗi đầu vào.

- -

Ngoại lệ

- -
    -
  • {{jsxref("Errors/Negative_repetition_count", "RangeError")}}: số lần lặp phải không âm.
  • -
  • {{jsxref("Errors/Resulting_string_too_large", "RangeError")}}: số lần lặp phải nhỏ hơn vô cực và không vượt kích cỡ chuỗi tối đa.
  • -
- -

Ví dụ

- -
'abc'.repeat(-1);   // RangeError
-'abc'.repeat(0);    // ''
-'abc'.repeat(1);    // 'abc'
-'abc'.repeat(2);    // 'abcabc'
-'abc'.repeat(3.5);  // 'abcabcabc' (tham số đếm sẽ được chuyển thành số nguyên)
-'abc'.repeat(1/0);  // RangeError
-
-({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2);
-// 'abcabc' (repeat() is a generic method)
-
- -

Polyfill

- -

Phương thức này đã được thêm vào kỹ thuật ES6 và có thể chưa có sẵn trong tất cả các bản bổ sung JS. Tuy nhiên bạn có thể sử dụng polyfill String.prototype.repeat() với snippet dưới đây:

- -
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 '';
-    }
-
-    // Đảm bảo tham số đếm là số nguyên 31 bít cho phép ta tối ưu hóa nhiều
-    // phần chính. Nhưng dù sao thì, hầu hết các trình duyệt hiện tại (tháng Tám năm 2014) không thể xử lý
-    // các chuỗi 1 << 28 chars hoặc lớn hơn, vậy nên:
-    if (str.length * count >= 1 << 28) {
-      throw new RangeError('repeat count must not overflow maximum string size');
-    }
-    var rpt = '';
-    for (var i = 0; i < count; i++) {
-      rpt += str;
-    }
-    return rpt;
-  }
-}
-
- -

Thông số

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ES2015')}}Định nghĩa bổ sung.
{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ESDraft')}} 
- -

Tương thích trình duyệt

- - - -

{{Compat("javascript.builtins.String.repeat")}}

diff --git a/files/vi/web/javascript/reference/global_objects/string/replace/index.html b/files/vi/web/javascript/reference/global_objects/string/replace/index.html deleted file mode 100644 index b9d5330c6c..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/replace/index.html +++ /dev/null @@ -1,233 +0,0 @@ ---- -title: String.prototype.replace() -slug: Web/JavaScript/Reference/Global_Objects/String/replace -translation_of: Web/JavaScript/Reference/Global_Objects/String/replace ---- -
{{JSRef}}
- -

Phương thức replace() sẽ trả về một chuỗi mới với một vài (hoặc tất cả) phần tử trùng khớp với pattern được thay thế bằng replacement. Pattern có thể là một chuỗi, hoặc một {{jsxref("RegExp")}}, và replacement có thể là một chuỗi, hoặc một function được gọi áp dụng cho mỗi kết quả trùng khớp. Nếu pattern là một chuỗi, thì phương thức replace() chỉ trả về kết quả đầu tiên trùng khớp.

- -

Replace() không làm thay đổi chuỗi gốc.

- -
{{EmbedInteractiveExample("pages/js/string-replace.html")}}
- - - -

Cú pháp

- -
const newStr = str.replace(regexp|substr, newSubstr|function)
- -

Parameters

- -
-
regexp (pattern)
-
Một {{jsxref("RegExp")}} object hoặc biểu thức RegEx. Phần tử được match sẽ được thay thế bởi newSubstr hoặc giá trị trả về bởi function.
-
substr
-
Một {{jsxref("String")}} cái mà sẽ bị thay thế bởi newSubstr. String này sẽ được xem như là một literal string và không phải là một regular expression. Nên chỉ có phần tử trùng khớp đầu tiên sẽ bị thay thế.
-
newSubstr (replacement)
-
Một {{jsxref("String")}} có nhiệm vụ thay thế substr được chỉ định trong regexp hoặc substr. Có nhiều kiểu thay thế khác nhau, xem chi tiết tại phần "Specifying a string as a parameter" bên dưới.
-
function (replacement)
-
Function được định nghĩa và gọi để sử dụng cho việc thay thế các phần tử trùng khớp với regexp hoặc substr. Đối số của function này có thể là các loại sau, xem chi tiết tại phần: "Specifying a function as a parameter" bên dưới.
-
- -

Return value

- -

Một string mới, với một số phần tử trùng khớp (hoặc tất cả phần tử trùng khớp) đã bị thay thế bởi các replacement.

- -

Mô tả

- -

Phương thức này không làm thay đổi {{jsxref("String")}} gốc. Nó chỉ đơn giản tạo ra một string mới.

- -

Để thực hiện tìm kiếm global search và replace, hãy thêm từ khóa g và biểu thức regular expression.

- -

Specifying a string as a parameter

- -

The replacement string can include the following special replacement patterns:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PatternInserts
$$Inserts a "$".
$&Inserts the matched substring.
$`Inserts the portion of the string that precedes the matched substring.
$'Inserts the portion of the string that follows the matched substring.
$nWhere n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a {{jsxref("RegExp")}} object. Note that this is 1-indexed.
- -

Specifying a function as a parameter

- -

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: The above-mentioned special replacement patterns do not apply in this case.)

- -

Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

- -

The arguments to the function are as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Possible nameSupplied value
matchThe matched substring. (Corresponds to $& above.)
p1, p2, ...The nth string found by a parenthesized capture group, provided the first argument to replace() was a {{jsxref("RegExp")}} object. (Corresponds to $1, $2, etc. above.) For example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+.
offsetThe offset of the matched substring within the whole string being examined. (For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.)
stringThe whole string being examined.
- -

(The exact number of arguments depends on whether the first argument is a {{jsxref("RegExp")}} object—and, if so, how many parenthesized submatches it specifies.)

- -

The following example will set newString to 'abc - 12345 - #$*%':

- -
function replacer(match, p1, p2, p3, offset, string) {
-  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
-  return [p1, p2, p3].join(' - ');
-}
-let newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
-console.log(newString);  // abc - 12345 - #$*%
-
- -

Ví dụ

- -

Định nghĩa một biểu thức regular expression trong phương thức replace()

- -

Ví dụ bên dưới, regular expression được định nghĩa trong replace() và nó có thêm flat "i" (giúp kết quả matching không phân biệt chữ hoa và chữ thường).

- -
let str = 'Twas the night before Xmas...';
-let newstr = str.replace(/xmas/i, 'Christmas');
-console.log(newstr);  // Twas the night before Christmas...
-
- -

This logs 'Twas the night before Christmas...'.

- -
-

Note: See this guide for more explanations about regular expressions.

-
- -

Sử dụng flag global và flag ignore trong replace()

- -

Global replace (thay thế tất cả kết quả trùng khớp) có thể được thực hiện trong regex. Ví dụ sau, biểu thức regex có chứa các flag  global and ignore case flags cho phép replace() sẽ thay thế mỗi string 'apples' trong chuỗi gốc với string 'oranges'

- -
let re = /apples/gi;
-let str = 'Apples are round, and apples are juicy.';
-let newstr = str.replace(re, 'oranges');
-console.log(newstr);  // oranges are round, and oranges are juicy.
-
- -

This logs 'oranges are round, and oranges are juicy'.

- -

Đảo ngược vị trí của 2 từ trong một string

- -

Đoạn code bên dưới sẽ đảo qua lại vị trí của các từ trong một string. Ở phần replacement, đoạn code sử dụng capturing groups và ký tự $1,$2 để làm pattern cho phần replacement.

- -
let re = /(\w+)\s(\w+)/;
-let str = 'John Smith';
-let newstr = str.replace(re, '$2, $1');
-console.log(newstr);  // Smith, John
-
- -

This logs 'Smith, John'.

- -

Sử dụng một inline function để thay đổi các giá trị matched

- -

Trong ví dụ này, tất cả trường hợp chữ cái viết hoa trong một string sẽ được convert sang dạng viết thường, và dấu gạch ngang sẽ được thêm vào trước vị trí matching đó. Điều quan trọng ở đây, là cần thêm vào các dấu gạch ngang này trước khi trả về một replacement hoàn chỉnh để sử dụng.

- -

Replacement function này sẽ nhận vào các đoạn trích mà đã match với pattern làm tham số, và sử dụng các đoạn trích đó để biến đổi chữ hoa chữ thường, và ghép nối một dấu gạch ngang vào trước mỗi đoạn trích.

- -
function styleHyphenFormat(propertyName) {
-  function upperToHyphenLower(match, offset, string) {
-    return (offset > 0 ? '-' : '') + 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.

- -
let newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase());  // won't work
-
- -

This is because '$&'.toLowerCase() would first be evaluated 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';
-  }
-  let s = String(x);
-  let test = /(-?\d+(?:\.\d*)?)F\b/g;
-  return s.replace(test, convert);
-}
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.String.replace")}}

- -

See also

- -
    -
  • {{jsxref("String.prototype.replaceAll", "String.prototype.replaceAll()")}}
  • -
  • {{jsxref("String.prototype.match", "String.prototype.match()")}}
  • -
  • {{jsxref("RegExp.prototype.exec", "RegExp.prototype.exec()")}}
  • -
  • {{jsxref("RegExp.prototype.test", "RegExp.prototype.test()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/string/slice/index.html b/files/vi/web/javascript/reference/global_objects/string/slice/index.html deleted file mode 100644 index 002f1be65f..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/slice/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: String.prototype.slice() -slug: Web/JavaScript/Reference/Global_Objects/String/slice -translation_of: Web/JavaScript/Reference/Global_Objects/String/slice ---- -
{{JSRef}}
- -

Phương thức slice() tạo ra một Chuỗi mới từ một phần của Chuỗi hiện tại.

- -

Cú pháp

- -
str.slice(beginSlice[, endSlice])
- -

Các tham số

- -
-
beginSlice
-
Chỉ số điểm bắt đầu của chuỗi con muốn lấy - bắt đầu từ 0. Nếu tham số này là số âm, thì nó tương đương với việc bạn gán nó bằng "độ dài chuỗi" + beginSlice. Ví dụ nếu beginSlice bằng -3 thì tương đương với beginSlice bằng "đội dài chuỗi" - 3.
-
endSlice
-
Tham số này không bắt buộc. Nếu có nó sẽ chỉ điểm cuối của chuỗi con muốn lấy. Nếu tham số này âm, nó sẽ được hiểu bằng "đội dài chuỗi" + endSlice. Ví dụ endSlice bằng -3 nó sẽ tương đương với "độ dài chuỗi" - 3
-
- -

Mô tả

- -

slice() thực hiện lấy một phần chuỗi từ chuỗi ban đầu và trả về một chuỗi mới. Chuỗi ban đầu sẽ không bị thay đổi giá trị.

- -

slice() sẽ lấy một phần chuỗi nhưng sẽ không chứa ký tự có chỉ số bằng với tham số endSlice. str.slice(1, 4) sẽ chỉ lấy ba ký tự 1,2 và 3.

- -

Ví dụ khác, str.slice(2, -1) sẽ lấy từ ký tự thứ 3 đến ký tự gần cuối, ký tự cuối không được đưa vào chuỗi mới

- -

Ví dụ

- -

Dùng slice() để tạo chuỗi mới

- -

Ví dụ sau sử dụng slice() để tạo chuỗi mới.

- -
var str1 = 'The morning is upon us.';
-var str2 = str1.slice(4, -2);
-
-console.log(str2); // OUTPUT: morning is upon u
-
- -

Dùng slice() với chỉ số âm

- -

Ví dụ sau sử dụng slice() với chỉ số âm.

- -
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'
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tạTrạng tháiGhi chú
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.13', 'String.prototype.slice')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.slice', 'String.prototype.slice')}}{{Spec2('ES6')}} 
- -

Khả năng hỗ trợ của các trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
Tính năngChromeFirefox (Gecko)Internet ExplorerOperaSafari
Hỗ trợ cơ bản{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
Tính năngAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Hỗ trợ cơ bản{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Xem thêm

- -
    -
  • {{jsxref("String.prototype.substr()")}}
  • -
  • {{jsxref("String.prototype.substring()")}}
  • -
  • {{jsxref("Array.prototype.slice()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/string/startswith/index.html b/files/vi/web/javascript/reference/global_objects/string/startswith/index.html deleted file mode 100644 index 7d3f6bfaa6..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/startswith/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: String.prototype.startsWith() -slug: Web/JavaScript/Reference/Global_Objects/String/startsWith -translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith ---- -
{{JSRef}}
- -

startsWith() method xác định liệu một chuỗi bắt đầu với các chữ cái của chuỗi khác hay không, trả về giá trị true hoặc false tương ứng.

- -

Cú pháp

- -
str.startsWith(searchString[, position])
- -

Tham số

- -
-
searchString
-
Các ký tự cần tìm kiếm tại vị trí bắt đầu của chuỗi này.
-
position
-
Tùy chọn. Vị trí trong chuỗi bắt đầu tìm kiếm cho searchString; mặc định là 0.
-
- -

Miêu tả

- -

Method này cho phép bạn xác định liệu một chuỗi có bắt đầu với chuỗi khác không.

- -

Ví dụ

- -

Cách sử dụng 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
-
- -

Polyfill

- -

Method này đã được thêm vào chỉ dẫn kỹ thuật ECMAScript 6 và có thể chưa có sẵn trong tất cả JavaScript implementations. Tuy nhiên, bạn có thể polyfill String.prototype.startWith() với snippet sau:

- -
if (!String.prototype.startsWith) {
-  String.prototype.startsWith = function(searchString, position) {
-    position = position || 0;
-    return this.indexOf(searchString, position) === position;
-  };
-}
-
- -

Polyfill mạnh và được tối ưu hơn có sẵn trên GitHub bởi Mathias Bynens.

- -

Hướng dẫn kỹ thuật

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ES6')}}Initial definition.
- -

Khả năng tương thích với Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("41")}}{{CompatGeckoDesktop("17")}}{{CompatNo}}{{CompatChrome("41")}}{{CompatSafari("9")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("36")}}{{CompatGeckoMobile("17")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Xem thêm

- -
    -
  • {{jsxref("String.prototype.endsWith()")}} {{experimental_inline}}
  • -
  • {{jsxref("String.prototype.includes()")}} {{experimental_inline}}
  • -
  • {{jsxref("String.prototype.indexOf()")}}
  • -
  • {{jsxref("String.prototype.lastIndexOf()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/string/substr/index.html b/files/vi/web/javascript/reference/global_objects/string/substr/index.html deleted file mode 100644 index c7d477fede..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/substr/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: String.prototype.substr() -slug: Web/JavaScript/Reference/Global_Objects/String/substr -translation_of: Web/JavaScript/Reference/Global_Objects/String/substr ---- -
{{JSRef}}
- -
Phương thức substr()trả  về những ký tự trong một chuỗi được xác định bởi vị trí ký tự bắt đầu và số lượng ký tự theo sau đó.
- -

Cú pháp

- -
str.substr(start, [length])
- -

Các tham số

- -
-
start (bắt đầu)
-
Vị trí chính xác của ký tự bắt đầu. Nếu là một số âm, nó sẽ được xử lý như sau strLength - start trong đó strLengthlà chiều dài của chuỗi. Ví dụ, str.substr(-3) sẽ được coi như là str.substr(str.length -3)
-
length (độ dài)
-
Số lượng ký tự muốn lấy ra. Nếu tham số này là {{jsxref("undefined")}}, tất cả các ký tự từ vị trí bắt đầu tới kết thúc của chuỗi sẽ được lấy.
-
- -

Giá trị trả về

- -

Một chuỗi mới là phần đã lấy ra từ chuỗi ban đầu. Nếu  length là 0 hoặc là một số âm thì trả về một chuỗi rỗng.

- -

Mô tả

- -

start là chỉ số của ký tự. Chỉ số của ký tự đầu tiên là 0, và chỉ số của ký tự cuối cùng thì nhỏ hơn độ dài của chuỗi là 1. substr() bắt đầu lấy các ký tự tại start  và thu thập length các ký tự( trừ khi nó chấm tới cuối chuỗi trước, trong trường hợp này nó sẽ trả về ít hơn).

- -

Nếu start là số dương và lớn hơn hoặc bằng chiều dài của chuỗi, substr() trả về một chuỗi rỗng.

- -

Nếu start là số âm, substr() coi nó như chỉ là chỉ số của ký tự tính từ cuối chuỗi; chỉ số của ký tự cuối cùng là -1. Nếu  start là số âm và abs(start) lớn hơn chiều dài của chuỗi,substr() coi 0 như là chỉ số bắt đầu.

- -

Chú ý: Việc xử lý giá trị âm của tham số start như ở trên không được Microsoft JScript hỗ trợ.

- -

Nếu length là 0 hoặc âm, substr() trả về một mảng rỗng. Nếu length bị bỏ sót, substr() lấy các ký tự cho tới cuối chuỗi.

- -

Ví dụ

- -

Sử dụng 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): '
-
- -

Polyfill

- -

Microsoft's JScript không hỗ trợ các giá trị âm cho chi số bắt đầu. Nếu bạn mong muốn sử dụng tính năng này, bạn có thể sử dụng đoạn code dưới đây để xử lý bug này:

- -
// 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);
-}
-
- -

Các quy cách

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Quy cáchTình trạngÝ kiến
{{SpecName('ES3')}}{{Spec2('ES3')}}Da dinh nghia trong phu luc B bang Tuong thich (bo sung thong tin). Ap dung trong JavaScript 1.0
{{SpecName('ES5.1', '#sec-B.2.3', 'String.prototype.substr')}}{{Spec2('ES5.1')}}Da dinh nghia trong phu luc B bang Tuong thich (bo sung thong tin). 
{{SpecName('ES6', '#sec-string.prototype.substr', 'String.prototype.substr')}}{{Spec2('ES6')}}Da dinh nghia trong phu luc B (quy chuan) cho cac tinh nang bo sung cua ECMAScript doi voi cac trinh duyet Web
{{SpecName('ESDraft', '#sec-string.prototype.substr', 'String.prototype.substr')}}{{Spec2('ESDraft')}}Da dinh nghia trong phu luc B (quy chuan) cho cac tinh nang bo sung cua ECMAScript doi voi cac trinh duyet Web
- -

Tương thích với trình duyệt

- - - -

{{Compat("javascript.builtins.String.substr")}}

- -

Tương tự

- -
    -
  • {{jsxref("String.prototype.slice()")}}
  • -
  • {{jsxref("String.prototype.substring()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/string/substring/index.html b/files/vi/web/javascript/reference/global_objects/string/substring/index.html deleted file mode 100644 index e53b920581..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/substring/index.html +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: String.prototype.substring() -slug: Web/JavaScript/Reference/Global_Objects/String/substring -translation_of: Web/JavaScript/Reference/Global_Objects/String/substring ---- -
{{JSRef}}
- -

substring() phương thức trả về chuỗi con của 1 chuỗi bắt đầu từ vị trí bắt đầu đến vị trí kết thúc, hoặc đến cuối chuỗi nếu không có vị trí kết thúc

- -

Cú pháp

- -
str.substring(indexStart[, indexEnd])
- -

Parameters

- -
-
indexStart
-
Một số integer giữa 0 và một số nhỏ hơn độ dài chuỗi, xác định vị trí kí tự đầu tiên trong chuỗi gốc để đưa vào chuỗi con.
-
indexEnd
-
Không bắt buộc. Một số integer giữa 0 và độ dài chuỗi. Chuỗi con không bao gồm ký tự ở vị trí indexEnd.
-
- -

Return value

- -

Chuỗi con trả về là chuỗi nằm ở vị trí từ indexStart đến vị trí ( indexEnd - 1 )

- -

Description

- -

substring() lấy ký tự từ vị trí indexStart tới vị trí (nhưng không bao gồm) indexEnd. Đặc biệt:

- -
    -
  • Nếu indexStart bằng indexEnd, substring() trả về 1 chuỗi rỗng.
  • -
  • Nếu không có indexEnd, substring() sẽ lấy từ vị trí bắt đầu đến cuối chuỗi. (điều này giống với hàm substr()).
  • -
  • Nếu 1 trong 2 giá trị nhỏ hơn 0 hoặc là {{jsxref("NaN")}}, nó sẽ được xử lý như là 0.
  • -
  • Nếu 1 trong 2 giá trị lớn hơn  stringName.length, nó sẽ được xử lý như là stringName.length.
  • -
- -

Nếu indexStart lớn hơn indexEnd, chúng se được đổi chỗ; ví dụ, str.substring(1, 0) == str.substring(0, 1).

- -

Examples

- -

Using substring()

- -

The following example uses substring() to display characters from the string 'Mozilla':

- -
var anyString = 'Mozilla';
-
-// Displays 'Moz'
-console.log(anyString.substring(0, 3));
-console.log(anyString.substring(3, 0));
-
-// Displays 'lla'
-console.log(anyString.substring(4, 7));
-console.log(anyString.substring(4));
-console.log(anyString.substring(7, 4));
-
-// Displays 'Mozill'
-console.log(anyString.substring(0, 6));
-
-// 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);
-
- -

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' into '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('ES1')}}{{Spec2('ES1')}}Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{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

- -
    -
  • {{jsxref("String.prototype.substr()")}}
  • -
  • {{jsxref("String.prototype.slice()")}}
  • -
diff --git a/files/vi/web/javascript/reference/global_objects/weakmap/index.html b/files/vi/web/javascript/reference/global_objects/weakmap/index.html deleted file mode 100644 index bdc4c9d40a..0000000000 --- a/files/vi/web/javascript/reference/global_objects/weakmap/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: WeakMap -slug: Web/JavaScript/Reference/Global_Objects/WeakMap -translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap ---- -
{{JSRef}}
- -

Đối tượng WeakMap là bộ sưu tập của các cặp key/value với các key được tham chiếu yếu ớt. Các key phải là đối tượng và các value có thể là bất kỳ giá trị nào. 

- -

Bạn có thể tham khảo thêm về WeakMaps trong hướng dẫn WeakMap object (trong Keyed collections).

- -

Description

- -

Các key của WeakMap phải là kiểu Object. Primitive data types không được phép là key(ví dụ một {{jsxref("Symbol")}} không thể là key của WeakMap).

- -

Why WeakMap?

- -

Một map APIcó thể được triển khai trong JavaScript với 2 mảng (một cho các key, một cho các value) được chia sẽ bởi 4 API method. Thiết lập các phần tử trong map sẽ đẩy đồng thời một key và value vào cuối mỗi mảng. Kết quả là chỉ số của key và value sẽ tương ứng ở cả 2 mảng. Lấy value từ một map sẽ liên quan tới vòng lặp qua tất cả các key để tìm kiếm kết quả phù hợp, sau đó sử dụng chỉ số của kết quả đó để nhận được giá trị tương ứng từ mảng các value.

- -

Việc thực hiện như vậy sẽ có 2 sự bất tiện chính:

- -
    -
  1. Điều đầu tiên là thiết lập và tìm kiếm trong mảng có n phần tử, vì cả 2 hành động này đều phải lặp lại qua danh sách các key để tìm giá trị thích hợp.
  2. -
  3. Điều bất tiện thứ 2 là rò rỉ bộ nhớ bởi vì các mảng sẽ phải đảm bảo các tham chiếu tới mỗi key và mỗi value được duy trì vô thời hạn. Các tham chiếu này sẽ ngăn các key khỏi garbage collected, ngay cả khi không có một tham chiếu nào khác tới đối tượng. Điều này cũng ngăn các value tương ứng khỏi garbage collected.
  4. -
- -

Ngược lại, các WeakMap giữ các tham chiếu "yếu" tới key, điều này có nghĩa chúng không được bảo vệ khỏi garbage collection trong trường hợp không có tham chiếu nào tới key. Điều này cũng tương tự với value. WeakMaps có thể đặc biệt là cấu trúc hiệu quả khi cần ánh xạ các key tới các thông tin về key có giá trị chỉ khi key chưa được thu gom rác.

- -

Bởi vì các tham chiếu là yếu, các key của WeakMap key không thể đếm được. Không có phương thức nào để lấy được danh sách các key. Nếu có, danh sách key sẽ phụ thuộc vào trạng thái của garbage collection, đưa ra tính không xác định. Nếu bạn muốn lấy được danh sách của key, bạn phải sử dụng {{jsxref("Map")}}.

- -

Constructor

- -
-
WeakMap()
-
Creates new WeakMap objects.
-
- -

Instance methods

- -
-
{{jsxref("WeakMap.delete", "WeakMap.prototype.delete(key)")}}
-
Removes any value associated to the key. WeakMap.prototype.has(key) will return false afterwards.
-
{{jsxref("WeakMap.get", "WeakMap.prototype.get(key)")}}
-
Returns the value associated to the key, or undefined if there is none.
-
{{jsxref("WeakMap.has", "WeakMap.prototype.has(key)")}}
-
Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.
-
{{jsxref("WeakMap.set", "WeakMap.prototype.set(key, value)")}}
-
Sets the value for the key in the WeakMap object. Returns the WeakMap object.
-
- -

Examples

- -

Using WeakMap

- -
const wm1 = new WeakMap(),
-      wm2 = new WeakMap(),
-      wm3 = new WeakMap();
-const o1 = {},
-      o2 = function() {},
-      o3 = window;
-
-wm1.set(o1, 37);
-wm1.set(o2, 'azerty');
-wm2.set(o1, o2); // a value can be anything, including an object or a function
-wm2.set(o3, undefined);
-wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!
-
-wm1.get(o2); // "azerty"
-wm2.get(o2); // undefined, because there is no key for o2 on wm2
-wm2.get(o3); // undefined, because that is the set value
-
-wm1.has(o2); // true
-wm2.has(o2); // false
-wm2.has(o3); // true (even if the value itself is 'undefined')
-
-wm3.set(o1, 37);
-wm3.get(o1); // 37
-
-wm1.has(o1); // true
-wm1.delete(o1);
-wm1.has(o1); // false
-
- -

Implementing a WeakMap-like class with a .clear() method

- -
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;
-  }
-}
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-weakmap-objects', 'WeakMap')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.WeakMap")}}

- -

See also

- - diff --git a/files/vi/web/javascript/reference/index.html b/files/vi/web/javascript/reference/index.html deleted file mode 100644 index be6e0ebe3d..0000000000 --- a/files/vi/web/javascript/reference/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: JavaScript reference -slug: Web/JavaScript/Reference -tags: - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference ---- -
{{JsSidebar}}
- -

This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.

- -

Global Objects

- -

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}
- -

Statements

- -

This chapter documents all the JavaScript statements and declarations.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
- -

Expressions and operators

- -

This chapter documents all the JavaScript expressions and operators.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
- -

Functions

- -

This chapter documents how to work with JavaScript functions to develop your applications.

- - - -

Additional reference pages

- - diff --git a/files/vi/web/javascript/reference/iteration_protocols/index.html b/files/vi/web/javascript/reference/iteration_protocols/index.html deleted file mode 100644 index 2485382349..0000000000 --- a/files/vi/web/javascript/reference/iteration_protocols/index.html +++ /dev/null @@ -1,383 +0,0 @@ ---- -title: Iteration protocols -slug: Web/JavaScript/Reference/Iteration_protocols -translation_of: Web/JavaScript/Reference/Iteration_protocols ---- -
{{jsSidebar("More")}}
- -

Là một vài bổ sung cho ECMAScript 2015, Iteration protocols không phải là một tích hợp sẵn hay cú pháp mới mà là protocols. Các giao thức này có thể triển khai bởi bất kỳ đối tượng nào đơn giản bằng cách thực hiện theo một số quy ước.

- -

Có 2 giao thức: iterable protocol và iterator protocol.

- -

The iterable protocol

- -

Iterable protocol cho phép các đối tượng của JavaScript xác định hoặc tuỳ chỉnh hành vi lặp của chúng, chẳng hạn như giá trị nào sẽ được lặp trong vòng lặp {{jsxref("Statements/for...of", "for...of")}}. Một số kiểu tích hợp sẵn built-in iterables là hành vi lặp mặc định, chẳng hạn như {{jsxref("Array")}} hoặc {{jsxref("Map")}}, trong khi các kiểu khác (chẳng hạn {{jsxref("Object")}}) không có.

- -

Để có thể triển khai giao thức iterable, một đối tượng phải có phương thức @@iterator, điều này có nghĩa là một đối tượng (hoặc một trong các đối tượng trên prototype chain của đối tượng đó) phải có một thuộc tính @@iterator và thao tác với thuộc tính đó thông qua hằng số {{jsxref("Symbol.iterator")}}:

- - - - - - - - - - - - - - -
PropertyValue
[Symbol.iterator]Một hàm không có tham số đầu vào trả ra một đối tượng phù hợp với iterator protocol.
- -

Bất cứ khi nào một đối tượng thực hiện vòng lặp (chẳng hạn như sử dụng vòng lặp {{jsxref("Statements/for...of", "for...of")}}), phương thức @@iterator sẽ được gọi mà không có tham số đầu vào, và trả ra iterator được sử dụng để thu được giá trị được lặp.

- -

Lưu ý khi hàm không tham số đầu vào được gọi, nó sẽ được gọi như là một phương thức của iterable object. Do đó bên trong hàm, từ khoá this có thể được sử dụng để truy cập vào các thuộc tính của iterable object, để quyết định những gì được cung cấp trong quá trình lặp.

- -

Hàm này có thể là một hàm bình thường hoặc nó có thể là một generator function, do đó khi được gọi, một iterator object sẽ được trả về. Bên trong của generator function, mỗi giá trị trả về có thể cung cấp bằng cách sử dụng yield.

- -

The iterator protocol

- -

Ierator protocol định nghĩa một cách tiêu chuẩn để tạo ra một chuỗi các giá trị (hưu hạn hoặc vô hạn), và  có thể trả về 1 giá trị khi tất cả các giá trị đã được tạo.

- -

Một đối tượng là một iterator khi nó triển khai phương thức next() với ý nghĩa như sau:

- - - - - - - - - - - - - - -
PropertyValue
next() -

Một hàm không tham số đầu vào trả ra một đối tượng có ít nhất 2 thuộc tính sau: 

- -
-
done (boolean)
-
-

Có giá trị false nếu iterator có thể tạo ra giá trị tiếp theo trong chuỗi. (This is equivalent to not specifying the done property altogether.)

- -

Có giá trị true nếu iterator kết thúc chuỗi. Trong trường hợp này, value có thể tuỳ chọn giá trị trả về cho iterator.

-
-
value
-
Bất kỳ giá trị JavaScript nào được trả về bởi iterator. ?Có thể bỏ qua khi done là true.
-
- -

Phương thức next() phải luôn luôn trả về một đối tượng với các thuộc tính thích hợp bao gồm done và value. Nếu một giá trị không phải đối tượng được trả về (chẳng hạn như false hoặc undefined), một {{jsxref("TypeError")}} ("iterator.next() returned a non-object value") sẽ được đẩy ra.

-
- -
-

Lưu ý: Không thể biết liệu một đối tượng cụ thể có triển khai giao thức iterator hay không. Tuy nhiên, dễ dàng để tạo ra một đối tượng mà có cả 2 giao thức iterator và iterable (như ví dụ dưới đây).

- -

Làm như vậy cho phép một iterator có thể sử dụng các cú pháp đa dạng của iterables. Vì vậy, rất hiếm khi triển khai giao thức Iterator Protocol mà không triển khai Iterable.

- -
// Satisfies both the Iterator Protocol and Iterable
-let myIterator = {
-    next: function() {
-        // ...
-    },
-    [Symbol.iterator]: function() { return this; }
-};
-
-
- -

Examples using the iteration protocols

- -

{{jsxref("String")}} là một ví dụ tích hợp sẵn iterable object:

- -
let someString = 'hi';
-console.log(typeof someString[Symbol.iterator]); // "function"
-
- -

{{jsxref("String/@@iterator", "iterator mặc định", "", 1)}} của String  trả ra lần lượt từng mã của các ký tự:

- -
let iterator = someString[Symbol.iterator]();
-console.log(iterator + ''); // "[object String Iterator]"
-
-console.log(iterator.next()); // { value: "h", done: false }
-console.log(iterator.next()); // { value: "i", done: false }
-console.log(iterator.next()); // { value: undefined, done: true }
- -

Some built-in constructs—such as the {{jsxref("Operators/Spread_operator", "spread syntax", "", 1)}}—use the same iteration protocol under the hood:

- -
console.log([...someString]); // ["h", "i"]
- -

You can redefine the iteration behavior by supplying our own @@iterator:

- -
// need to construct a String object explicitly to avoid auto-boxing
-let someString = new String('hi');
-
-someString[Symbol.iterator] = function () {
-  return {
-    // this is the iterator object, returning a single element (the string "bye")
-    next: function () {
-      return this._first ? {
-        value: 'bye',
-        done: (this._first = false)
-      } : {
-        done: true
-      }
-    },
-    _first: true
-  };
-};
-
- -

Notice how redefining @@iterator affects the behavior of built-in constructs that use the iteration protocol:

- -
console.log([...someString]); // ["bye"]
-console.log(someString + ''); // "hi"
-
- -

Iterable examples

- -

Built-in iterables

- -

{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}}, and {{jsxref("Set")}} are all built-in iterables, because each of their prototype objects implements an @@iterator method.

- -

User-defined iterables

- -

You can make your own iterables like this:

- -
let myIterable = {};
-myIterable[Symbol.iterator] = function* () {
-    yield 1;
-    yield 2;
-    yield 3;
-};
-console.log([...myIterable]); // [1, 2, 3]
-
- -

Built-in APIs accepting iterables

- -

There are many APIs that accept iterables. Some examples include:

- -
    -
  • {{jsxref("Map", "new Map([iterable])")}}
  • -
  • {{jsxref("WeakMap", "new WeakMap([iterable])")}}
  • -
  • {{jsxref("Set", "new Set([iterable])")}}
  • -
  • {{jsxref("WeakSet", "new WeakSet([iterable])")}}
  • -
- -
new Map([[1, 'a'], [2, 'b'], [3, 'c']]).get(2); // "b"
-
-let myObj = {};
-
-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
-
- -

See Also

- -
    -
  • {{jsxref("Promise.all()", "Promise.all(iterable)")}}
  • -
  • {{jsxref("Promise.race()", "Promise.race(iterable)")}}
  • -
  • {{jsxref("Array.from()", "Array.from(iterable)")}}
  • -
- -

Syntaxes expecting iterables

- -

Some statements and expressions expect iterables, for example the {{jsxref("Statements/for...of", "for...of")}} loops, the {{jsxref("Operators/Spread_syntax", "spread operator", "", 1)}})}}, {{jsxref("Operators/yield*", "yield*")}}, and {{jsxref("Operators/Destructuring_assignment", "destructuring assignment")}}:

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

Non-well-formed iterables

- -

If an iterable's @@iterator method doesn't return an iterator object, then it's considered a non-well-formed iterable.

- -

Using one is likely to result in runtime errors or buggy behavior:

- -
let nonWellFormedIterable = {};
-nonWellFormedIterable[Symbol.iterator] = () => 1;
-[...nonWellFormedIterable]; // TypeError: [] is not a function
-
- -

Iterator examples

- -

Simple iterator

- -
function makeIterator(array) {
-  let nextIndex = 0
-  return {
-    next: function() {
-      return nextIndex < array.length ? {
-        value: array[nextIndex++],
-        done: false
-      } : {
-        done: true
-      };
-    }
-  };
-}
-
-let it = makeIterator(['yo', 'ya']);
-
-console.log(it.next().value); // 'yo'
-console.log(it.next().value); // 'ya'
-console.log(it.next().done);  // true
-
- -

Infinite iterator

- -
function idMaker() {
-  let index = 0;
-  return {
-    next: function() {
-      return {
-        value: index++,
-        done: false
-      };
-    }
-  };
-}
-
-let it = idMaker();
-
-console.log(it.next().value); // '0'
-console.log(it.next().value); // '1'
-console.log(it.next().value); // '2'
-// ...
-
- -

With a generator

- -
function* makeSimpleGenerator(array) {
-  let nextIndex = 0;
-  while (nextIndex < array.length) {
-    yield array[nextIndex++];
-  }
-}
-
-let gen = makeSimpleGenerator(['yo', 'ya']);
-
-console.log(gen.next().value); // 'yo'
-console.log(gen.next().value); // 'ya'
-console.log(gen.next().done);  // true
-
-function* idMaker() {
-  let index = 0;
-  while (true) {
-    yield index++;
-  }
-}
-
-let gen = idMaker()
-
-console.log(gen.next().value); // '0'
-console.log(gen.next().value); // '1'
-console.log(gen.next().value); // '2'
-// ...
-
- -

With ES2015 class

- -
class SimpleClass {
-  constructor(data) {
-    this.data = data;
-  }
-
-  [Symbol.iterator]() {
-    // Use a new index for each iterator. This makes multiple
-    // iterations over the iterable safe for non-trivial cases,
-    // such as use of break or nested looping over the same iterable.
-    let index = 0;
-
-    return {
-      next: () => {
-        if (index < this.data.length) {
-          return {value: this.data[index++], done: false}
-        } else {
-          return {done: true}
-        }
-      }
-    }
-  }
-}
-
-const simple = new SimpleClass([1,2,3,4,5]);
-
-for (const val of simple) {
-  console.log(val); // '1' '2' '3' '4' '5'
-}
-
- -

Is a generator object an iterator or an iterable?

- -

A {{jsxref("Generator", "generator object", "", 1)}} is both iterator and iterable:

- -
let aGeneratorObject = function* () {
-  yield 1;
-  yield 2;
-  yield 3;
-}();
-
-console.log(typeof aGeneratorObject.next);
-// "function", because it has a next method, so it's an iterator
-
-console.log(typeof aGeneratorObject[Symbol.iterator]);
-// "function", because it has an @@iterator method, so it's an iterable
-
-console.log(aGeneratorObject[Symbol.iterator]() === aGeneratorObject);
-// true, because its @@iterator method returns itself (an iterator), so it's an well-formed iterable
-
-console.log([...aGeneratorObject]);
-// [1, 2, 3]
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-iteration', 'Iteration')}}
- -

See also

- -
    -
  • To learn more about ES2015 generators, see:
    - {{jsxref("Statements/function*", "the function* documentation", "", 1)}}
  • -
diff --git a/files/vi/web/javascript/reference/operators/conditional_operator/index.html b/files/vi/web/javascript/reference/operators/conditional_operator/index.html deleted file mode 100644 index 62cc4cadb5..0000000000 --- a/files/vi/web/javascript/reference/operators/conditional_operator/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Conditional (ternary) operator -slug: Web/JavaScript/Reference/Operators/Conditional_Operator -translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator ---- -
{{jsSidebar("Operators")}}
- -

Toán tử điều kiện (ba ngôi) là toán tử duy nhất của JavaScript cần tới ba toán hạng. Toán tử này thường dùng tắt cho câu lệnh if.

- -
{{EmbedInteractiveExample("pages/js/expressions-conditionaloperators.html")}}
- - - -

Cú pháp

- -
condition ? exprT : exprF 
- -

Tham số

- -
-
condition
-
Biểu thức mà giá trị của nó được dùng như điều kiện.
-
- -
-
exprT, exprF
-
Biểu thức với giá trị có kiểu bất kỳ.
-
- -

Mô tả

- -

Nếu condition có thể chuyển đổi thànhtrue (hay là {{Glossary("truthy")}}), toán tử trả về giá trị của exprT; ngược lại (khi condition là {{Glossary("falsy")}}), nó trả về giá trị của exprF.

- -

(Trong cả hai trường hợp, biểu thức còn lại đều không được duyệt tới.)

- -

Ngoài false ra, các biểu thức falsy có thể xảy ra bao gồm: nullNaN0, xâu ký tự rỗng (""), và undefined. Nếu condition là một trong những gì vừa liệt kê phía trên, kết quả của biểu thức điều kiện sẽ là exprF.

- -

Ví dụ đơn giản:

- -
var age = 26;
-var beverage = (age >= 21) ? "Beer" : "Juice";
-console.log(beverage); // "Beer"
-
- -

Thường dùng để xử lý giá trị null:

- -
function greeting(person) {
-    var name = person ? person.name : "stranger";
-    return "Howdy, " + name;
-}
-
-console.log(greeting({name: 'Alice'}));  // "Howdy, Alice"
-console.log(greeting(null));             // "Howdy, stranger"​​​​​
-
- -

Điều kiện nối tiếp

- -

Toán tử điều kiện tuân theo suy dẫn phải, tức là nó có thể được gọi "nối tiếp" theo cách sau đây, tương tự như với if … else if … else if … else nối tiếp nhau:

- -
function example(…) {
-    return condition1 ? value1
-         : condition2 ? value2
-         : condition3 ? value3
-         : value4;
-}
-
-// Equivalent to:
-
-function example(…) {
-    if (condition1) { return value1; }
-    else if (condition2) { return value2; }
-    else if (condition3) { return value3; }
-    else { return value4; }
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiBình luận
{{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')}}Định nghĩa lần đầu. Cài đặt trong JavaScript 1.0.
- -

Tương thích trình duyệt

- - - -

{{Compat("javascript.operators.conditional")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/operators/delete/index.html b/files/vi/web/javascript/reference/operators/delete/index.html deleted file mode 100644 index 46a837d094..0000000000 --- a/files/vi/web/javascript/reference/operators/delete/index.html +++ /dev/null @@ -1,292 +0,0 @@ ---- -title: delete operator -slug: Web/JavaScript/Reference/Operators/delete -translation_of: Web/JavaScript/Reference/Operators/delete ---- -
{{jsSidebar("Operators")}}
- -

Toán tử delete của JavaScript loại bỏ một thuộc tính khỏi object; nếu không tồn tại tham chiếu tới thuộc tính, nó sẽ tự động giải phóng.

- -
{{EmbedInteractiveExample("pages/js/expressions-deleteoperator.html")}}
- - - -

Cú pháp

- -
delete expression 
- -

với expression thực thi thành tham chiếu đến thuộc tính nào đó, tức là:

- -
delete object.property
-delete object['property']
-
- -

Tham số

- -
-
object
-
Tên object, hoặc biểu thức thực thi tới object.
-
property
-
Thuộc tính muốn xoá.
-
- -

Giá trị trả về

- -

true cho mọi trường hợp trừ khi thuộc tính là own non-configurable, trong trường hợp đó, trả về false trong chế độ non-strict.

- -

Ngoại lệ

- -

Quăng {{jsxref("TypeError")}} trong chế độ strict nếu thuộc tính là own non-configurable.

- -

Mô tả

- -

Khác với suy nghĩ của nhiều người, toán tử delete không trực tiếp giải phóng bộ nhớ. Quản lý bộ nhớ được thực hiện trung gian qua việc bẻ tham chiếu. Xem trang quản lý bộ nhớ để biết thêm chi tiết.

- -

Toán tử delete loại bỏ thuộc tính xác định trong object. Nếu xoá thành công, nó sẽ trả về true, ngoài ra thì false. Tuy nhiên, hãy lưu ý những kịch bản có thể xảy đến sau đây:

- -
    -
  • Nếu thuộc tính muốn xoá không tồn tại, delete sẽ không có tác dụng và sẽ trả về true
  • -
  • Nếu tồn tại thuộc tính có cùng tên trong prototype nối với object, thì sau khi xoá xong, object sẽ dùng thuộc tính từ prototype đó (nói cách khác, delete chỉ có tác dụng với những thuộc tính của riêng object).
  • -
  • Bất cứ thuộc tính nào được khởi tạo bằng {{jsxref("Statements/var","var")}} không thể bị xoá khỏi phạm vi toàn cục hoặc phạm vi hàm. -
      -
    • Vì thế, delete không thể xoá bất cứ hàm nào trong phạm vi toàn cục (cho dù là một phần của định nghĩa hàm hay biểu thức hàm).
    • -
    • Các hàm là một phần của object (tách biệt với phạm vi toàn cục) có thể bị xoá với delete.
    • -
    -
  • -
  • Bất cứ thuộc tính nào được khởi tạo bởi {{jsxref("Statements/let","let")}} hoặc {{jsxref("Statements/const","const")}} không thể bị xoá khỏi phạm vi mà chúng được khai báo.
  • -
  • Thuộc tính không-thể-cấu-hình không thể bị loại bỏ. Các thuộc tính này bao gồm các object dựng sẵn như {{jsxref("Math")}}, {{jsxref("Array")}}, {{jsxref("Object")}} và thuộc tính được tạo ra như thuộc tính không-thể-cấu-hình bằng phương thức như là {{jsxref("Object.defineProperty()")}}.
  • -
- -

Snippet sau đưa ra ví dụ đơn giản:

- -
var Employee = {
-  age: 28,
-  name: 'abc',
-  designation: 'developer'
-}
-
-console.log(delete Employee.name);   // trả về true
-console.log(delete Employee.age);    // trả về true
-
-// Khi cố xoá một thuộc tính không tồn tại
-// sẽ trả về giá trị true
-console.log(delete Employee.salary); // trả về true
-
- -

Thuộc tính không-thể-cấu-hình

- -

Khi một thuộc tính được đánh dấu không-thể-cấu-hình, delete không có tác dụng nào, và sẽ trả về false. Trong chế độ strict, lỗi TypeError sẽ nhảy ra.

- -
var Employee = {};
-Object.defineProperty(Employee, 'name', {configurable: false});
-
-console.log(delete Employee.name);  // trả về false
-
- -

{{jsxref("Statements/var","var")}}, {{jsxref("Statements/let","let")}} và {{jsxref("Statements/const","const")}} tạo ra thuộc tính không-thể-cấu-hình mà không thể xoá bằng toán tử delete:

- -
var nameOther = 'XYZ';
-
-// Ta có thể truy cập vào thuộc tính toàn cục này thông qua:
-Object.getOwnPropertyDescriptor(window, 'nameOther');
-
-// output: Object {value: "XYZ",
-//                  writable: true,
-//                  enumerable: true,
-//                  configurable: false}
-
-// Bởi vì "nameOther" được thêm vào nhờ dùng
-// từ khoá var, nên nó được đánh dấu là "không-thể-cấu-hình"
-
-delete nameOther;   // trả về false
- -

Trong chế độ strict, ngoại lệ sẽ quăng ra.

- -

Chế độ strict và non-strict

- -

Khi ở trong chế độ strict, nếu delete được dùng để tham chiếu trực tiếp tới một biến, một đối số của hàm hoặc tên hàm, nó sẽ quăng ra {{jsxref("SyntaxError")}}.

- -

Bất cứ biến nào được định nghĩa với var đều được đánh dấu là không-thể-cấu-hình. Trong ví dụ sau đây, salary là không-thể-cấu-hình và không thể xoá. Trong chế độ non-strict, phép toán delete sẽ trả về false.

- -
function Employee() {
-  delete salary;
-  var salary;
-}
-
-Employee();
-
- -

Cùng xem mã nguồn tương tự hoạt động ra sao trong chế độ strict nhé. Thay vì trả về false, SyntaxError được quăng ra.

- -
"use strict";
-
-function Employee() {
-  delete salary;  // SyntaxError
-  var salary;
-}
-
-// Tương tự, bất cứ truy nhập trực tiếp nào vào hàm
-// dùng delete đều quăng ra SyntaxError
-
-function DemoFunction() {
-  //vài đoạn code
-}
-
-delete DemoFunction; // SyntaxError
-
- -

Ví dụ

- -
// Tạo thuộc tính adminName trên phạm vi toàn cục.
-adminName = 'xyz';
-
-// Tạo thuộc tính empCount trên phạm vi toàn cục =.
-// Vì dùng var, thuộc tính này được đánh dấu là không-thể-cấu-hình.
-// Điều tương tự xảy đến với let và const.
-var empCount = 43;
-
-EmployeeDetails = {
-  name: 'xyz',
-  age: 5,
-  designation: 'Developer'
-};
-
-// adminName là thuộc tính trên phạm vi toàn cục.
-// Nó có thể bị xoá bởi được khởi tạo mà không dùng var,
-// và vì thế khả cấu.
-delete adminName;       // trả về true
-
-// Ngược lại, empCount không khả cấu
-// bởi dùng var.
-delete empCount;       // trả về false
-
-// Có thể dùng delete để loại bỏ thuộc tính khỏi object.
-delete EmployeeDetails.name; // trả về true
-
-// Thậm chí thuộc tính không tồn tại, delete vẫn trả về "true".
-delete EmployeeDetails.salary; // trả về true
-
-// delete không có tác dụng với thuộc tính dựng sẵn.
-delete Math.PI; // trả về false
-
-// EmployeeDetails là thuộc tính trong phạm vi toàn cục.
-// Vì được khởi tạo mà không dùng "var", nó được đánh dấu là khả cấu.
-delete EmployeeDetails;   // trả về true
-
-function f() {
-  var z = 44;
-
-  // delete không có tác dụng với tên biến cục bộ
-  delete z;     // trả về false
-}
-
- -

delete và prototype chain

- -

Trong ví dụ sau, ta sẽ xoá một thuộc tính riêng của object mà vẫn tồn tại thuộc tính cùng tên trong prototype chain:

- -
function Foo() {
-  this.bar = 10;
-}
-
-Foo.prototype.bar = 42;
-
-var foo = new Foo();
-
-// foo.bar liên kết với
-// thuộc tính riêng.
-console.log(foo.bar); // 10
-
-// Xoá thuộc tính riêng trên
-// foo object.
-delete foo.bar; // trả về true
-
-// foo.bar vẫn sẵn sàng trên
-// prototype chain.
-console.log(foo.bar); // 42
-
-// Xoá thuộc tính trên prototype.
-delete Foo.prototype.bar; // trả về true
-
-// Thuộc tính "bar" không còn có thể
-// kể thừa từ Foo bởi nó đã bị xoá
-console.log(foo.bar); // undefined
- -

Xoá phần tử mảng

- -

Khi bạn xoá phần tử mảng, độ dài mảng không bị ảnh hưởng. Thậm chí khi bạn xoá phần tử cuối của mảng cũng không thay đổi được điều này.

- -

Khi toán tử delete loại bỏ một phần tử mảng, phần tử đó không còn trong mảng. Trong ví dụ sau, trees[3] bị xoá bởi delete.

- -
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
-delete trees[3];
-if (3 in trees) {
-    // không thực thi đoạn code này
-}
- -

Nếu bạn muốn giữ lại phần tử mảng và gán giá trị undefined cho nó, hãy dùng undefined thay vì toán tử delete. Trong ví dụ sau, trees[3] được gán giá trị undefined, nhưng phần tử mảng vẫn tồn tại:

- -
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
-trees[3] = undefined;
-if (3 in trees) {
-    // đoạn code trong này sẽ chạy
-}
- -

Thay vì thế, nếu muốn loại bỏ phần tử mảng bằng cách thay đổi nội dung của mảng, hãy dùng phương thức {{jsxref("Array.splice", "splice")}}. Trong ví dụ sau, trees[3] bị xoá bỏ hoàn toàn khỏi mảng thông qua {{jsxref("Array.splice", "splice")}}:

- -
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
-trees.splice(3,1);
-console.log(trees); // ["redwood", "bay", "cedar", "maple"]
-
- -

Đặc Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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')}}Định nghĩa lần đầu. Cài đặt trong JavaScript 1.2.
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.operators.delete")}}

- -

Ghi chú Cross-browser

- -

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.

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/operators/function/index.html b/files/vi/web/javascript/reference/operators/function/index.html deleted file mode 100644 index 1e302774be..0000000000 --- a/files/vi/web/javascript/reference/operators/function/index.html +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: function expression -slug: Web/JavaScript/Reference/Operators/function -translation_of: Web/JavaScript/Reference/Operators/function ---- -
{{jsSidebar("Operators")}}
- -

Từ khóa function (hàm) có thể dùng để định nghĩa chức năng bên trong một biểu thức.

- -

Cú pháp

- -
var myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
-   statements
-};
- -

Tham số

- -
-
name
-
Tên hàm. Có thể bỏ qua, trong trường hợp chức năng đó là vô danh. Nó mô tả chính xác nhiệm vụ mà hàm sẽ làm.
-
paramN
-
Tên các đối số truyền vào.
-
statements
-
Các câu lệnh xử lý các đối số paramN truyền vào.
-
- -

Mô tả

- -

Một biểu thức chức năng (function) is very similar to and has almost the same syntax as a function statement (see function statement for details). The main difference between a function expression and a function statement is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as a IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about functions for more information.

- -

Function expression hoisting

- -

Function expressions in JavaScript are not hoisted, unlike {{jsxref("Statements/function", "function declarations", "#Function_declaration_hoisting")}}. You can't use function expressions before you define them:

- -
notHoisted(); // TypeError: notHoisted is not a function
-
-var notHoisted = function() {
-   console.log('bar');
-};
-
- -

Examples

- -

The following example defines an unnamed function and assigns it to x. The function returns the square of its argument:

- -
var x = function(y) {
-   return y * y;
-};
-
- -

Named function expression

- -

If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This also avoids using the non-standard arguments.callee property.

- -
var math = {
-  'factorial': function factorial(n) {
-    if (n <= 1)
-      return 1;
-    return n * factorial(n - 1);
-  }
-};
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{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')}}Initial definition. Implemented in JavaScript 1.5.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Trailing comma in parameters{{CompatUnknown}}{{CompatGeckoDesktop("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Trailing comma in parameters{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- -
    -
  • {{jsxref("Functions_and_function_scope", "Functions and function scope")}}
  • -
  • {{jsxref("Function")}}
  • -
  • {{jsxref("Statements/function", "function statement")}}
  • -
  • {{jsxref("Statements/function*", "function* statement")}}
  • -
  • {{jsxref("Operators/function*", "function* expression")}}
  • -
  • {{jsxref("GeneratorFunction")}}
  • -
diff --git a/files/vi/web/javascript/reference/operators/index.html b/files/vi/web/javascript/reference/operators/index.html deleted file mode 100644 index 139208dbca..0000000000 --- a/files/vi/web/javascript/reference/operators/index.html +++ /dev/null @@ -1,298 +0,0 @@ ---- -title: Expressions and operators -slug: Web/JavaScript/Reference/Operators -tags: - - JavaScript - - NeedsTranslation - - Operators - - TopicStub -translation_of: Web/JavaScript/Reference/Operators ---- -
{{jsSidebar("Operators")}}
- -

This chapter documents all the JavaScript language operators, expressions and keywords.

- -

Expressions and operators by category

- -

For an alphabetical listing see the sidebar on the left.

- -

Primary expressions

- -

Basic keywords and general expressions in JavaScript.

- -
-
{{jsxref("Operators/this", "this")}}
-
The this keyword refers to the function's execution context.
-
{{jsxref("Operators/function", "function")}}
-
The function keyword defines a function expression.
-
{{jsxref("Operators/class", "class")}}
-
The class keyword defines a class expression.
-
{{jsxref("Operators/function*", "function*")}}
-
The function* keyword defines a generator function expression.
-
{{jsxref("Operators/yield", "yield")}}
-
Pause and resume a generator function.
-
{{jsxref("Operators/yield*", "yield*")}}
-
Delegate to another generator function or iterable object.
-
{{jsxref("Global_Objects/Array", "[]")}}
-
Array initializer/literal syntax.
-
{{jsxref("Operators/Object_initializer", "{}")}}
-
Object initializer/literal syntax.
-
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
-
Regular expression literal syntax.
-
{{jsxref("Operators/Grouping", "( )")}}
-
Grouping operator.
-
- -

Left-hand-side expressions

- -

Left values are the destination of an assignment.

- -
-
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
-
Member operators provide access to a property or method of an object
- (object.property and object["property"]).
-
{{jsxref("Operators/new", "new")}}
-
The new operator creates an instance of a constructor.
-
new.target
-
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
-
{{jsxref("Operators/super", "super")}}
-
The super keyword calls the parent constructor.
-
{{jsxref("Operators/Spread_operator", "...obj")}}
-
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
-
- -

Increment and decrement

- -

Postfix/prefix increment and postfix/prefix decrement operators.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
-
Postfix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
-
Postfix decrement operator.
-
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
-
Prefix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
-
Prefix decrement operator.
-
- -

Unary operators

- -

A unary operation is operation with only one operand.

- -
-
{{jsxref("Operators/delete", "delete")}}
-
The delete operator deletes a property from an object.
-
{{jsxref("Operators/void", "void")}}
-
The void operator discards an expression's return value.
-
{{jsxref("Operators/typeof", "typeof")}}
-
The typeof operator determines the type of a given object.
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
-
The unary plus operator converts its operand to Number type.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
-
The unary negation operator converts its operand to Number type and then negates it.
-
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
-
Bitwise NOT operator.
-
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
-
Logical NOT operator.
-
- -

Arithmetic operators

- -

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
-
Addition operator.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
-
Subtraction operator.
-
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
-
Division operator.
-
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
-
Multiplication operator.
-
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
-
Remainder operator.
-
- -
-
{{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
-
Exponentiation operator.
-
- -

Relational operators

- -

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

- -
-
{{jsxref("Operators/in", "in")}}
-
The in operator determines whether an object has a given property.
-
{{jsxref("Operators/instanceof", "instanceof")}}
-
The instanceof operator determines whether an object is an instance of another object.
-
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
-
Less than operator.
-
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
-
Greater than operator.
-
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
-
Less than or equal operator.
-
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
-
Greater than or equal operator.
-
- -
-

Note: => is not an operator, but the notation for Arrow functions.

-
- -

Equality operators

- -

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

- -
-
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
-
Equality operator.
-
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
-
Inequality operator.
-
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
-
Identity operator.
-
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
-
Nonidentity operator.
-
- -

Bitwise shift operators

- -

Operations to shift all bits of the operand.

- -
-
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
-
Bitwise left shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
-
Bitwise right shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
-
Bitwise unsigned right shift operator.
-
- -

Binary bitwise operators

- -

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

- -
-
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
-
Bitwise AND.
-
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
-
Bitwise OR.
-
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
-
Bitwise XOR.
-
- -

Binary logical operators

- -

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

- -
-
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
-
Logical AND.
-
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
-
Logical OR.
-
- -

Conditional (ternary) operator

- -
-
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
-
-

The conditional operator returns one of two values based on the logical value of the condition.

-
-
- -

Assignment operators

- -

An assignment operator assigns a value to its left operand based on the value of its right operand.

- -
-
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
-
Assignment operator.
-
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
-
Multiplication assignment.
-
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
-
Division assignment.
-
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
-
Remainder assignment.
-
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
-
Addition assignment.
-
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
-
Subtraction assignment
-
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
-
Left shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
-
Right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
-
Unsigned right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
-
Bitwise AND assignment.
-
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
-
Bitwise XOR assignment.
-
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
-
Bitwise OR assignment.
-
{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
- {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
-
-

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

-
-
- -

Comma operator

- -
-
{{jsxref("Operators/Comma_Operator", ",")}}
-
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
-
- -

Non-standard features

- -
-
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
-
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
-
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
-
The expression closure syntax is a shorthand for writing simple function.
-
{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
-
Array comprehensions.
-
{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
-
Generator comprehensions.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1', '#sec-11', 'Expressions')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword.
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ESDraft')}} 
- -

See also

- - diff --git a/files/vi/web/javascript/reference/operators/operator_precedence/index.html b/files/vi/web/javascript/reference/operators/operator_precedence/index.html deleted file mode 100644 index efa25029b2..0000000000 --- a/files/vi/web/javascript/reference/operators/operator_precedence/index.html +++ /dev/null @@ -1,477 +0,0 @@ ---- -title: Operator precedence -slug: Web/JavaScript/Reference/Operators/Operator_Precedence -translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence ---- -
{{jsSidebar ("Toán tử")}}
- -

Mức độ ưu tiên của toán tử xác định cách các toán tử được phân tích cú pháp liên quan đến nhau. Các toán tử có mức độ ưu tiên cao hơn trở thành toán hạng của các toán tử có mức độ ưu tiên thấp hơn.

- -
{{EmbedInteractiveExample ("pages / js / expression-operatorprecedence.html")}}
- - - -

Precedence And Associativity

- -

Consider an expression describable by the representation below. Note that both OP1 and OP2 are fill-in-the-blanks for OPerators.

- -
a OP1 b OP2 c
- -

If OP1 and OP2 have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. Observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code.

- -
console.log(3 + 10 * 2);   // logs 23
-console.log(3 + (10 * 2)); // logs 23 because parentheses here are superfluous
-console.log((3 + 10) * 2); // logs 26 because the parentheses change the order
-
- -

Left-associativity (left-to-right) means that it is processed as (a OP1 b) OP2 c, while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c). Assignment operators are right-associative, so you can write:

- -
a = b = 5; // same as writing a = (b = 5);
-
- -

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.

- -

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. It is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity.

- - - - - - - - - - - - - - - - -
CodeOutput
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the division operator (/)
-console.log(echo("left", 6) / echo("right", 2));
-
-
-
-Evaluating the left side
-Evaluating the right side
-3
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the exponentiation operator (**)
-console.log(echo("left", 2) ** echo("right", 3));
-
-
-Evaluating the left side
-Evaluating the right side
-8
-
- -

The difference in associativity comes into play when there are multiple operators of the same precedence. With only one operator or operators of different precedences, associativity doesn't affect the output, as seen in the example above. In the example below, observe how associativity affects the output when multiple of the same operator are used.

- - - - - - - - - - - - - - - - - - - - -
CodeOutput
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the division operator (/)
-console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3));
-
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-1
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the exponentiation operator (**)
-console.log(echo("left", 2) ** echo("middle", 3) ** echo("right", 2));
-
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-512
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the parentheses around the left and middle exponentiation
-console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2));
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-64
-
- -

Looking at the code snippets above, 6 / 3 / 2 is the same as (6 / 3) / 2 because division is left-associative. Exponentiation, on the other hand, is right-associative, so 2 ** 3 ** 2 is the same as 2 ** (3 ** 2). Thus, doing (2 ** 3) ** 2 changes the order and results in the 64 seen in the table above.

- -

Remember that precedence comes before associativity. So, mixing division and exponentiation, the exponentiation comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2).

- -

Note on grouping and short-circuiting

- -

In the table below, Grouping is listed as having the highest precedence. However, that does not always mean the expression within the grouping symbols ( … ) is evaluated first, especially when it comes to short-circuiting.

- -

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c), if a is {{Glossary("falsy")}}, then the sub-expression (b + c) will not even get evaluated, even if it is in parentheses. We could say that the logical disjunction operator ("OR") is "short-circuited". Along with logical disjunction, other short-circuited operators include logical conjunction ("AND"), nullish-coalescing, optional chaining, and the conditional operator. Some more examples follow.

- -
a || (b * c);  // evaluate `a` first, then produce `a` if `a` is "truthy"
-a && (b < c);  // evaluate `a` first, then produce `a` if `a` is "falsy"
-a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`
-a?.b.c;        // evaluate `a` first, then produce `undefined` if `a` is `null` or `undefined`
-
- -

Examples

- -
3 > 2 && 2 > 1
-// returns true
-
-3 > 2 > 1
-// Returns false because 3 > 2 is true, then true is converted to 1
-// in inequality operators, therefore true > 1 becomes 1 > 1, which
-//  is false. Adding parentheses makes things clear: (3 > 2) > 1.
-
- -

Table

- -

The following table is ordered from highest (21) to lowest (1) precedence.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PrecedenceOperator typeAssociativityIndividual operators
21{{jsxref("Operators/Grouping", "Grouping", "", 1)}}n/a( … )
20{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation", 1)}}left-to-right… . …
{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation", 1)}}left-to-right… [ … ]
{{jsxref("Operators/new","new")}} (with argument list)n/anew … ( … )
Function Callleft-to-right… ( )
Optional chainingleft-to-right?.
19{{jsxref("Operators/new","new")}} (without argument list)right-to-leftnew …
18{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment", 1)}}n/a… ++
{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement", 1)}}… --
17Logical NOTright-to-left! …
Bitwise NOT~ …
Unary Plus+ …
Unary Negation- …
Prefix Increment++ …
Prefix Decrement-- …
{{jsxref("Operators/typeof", "typeof")}}typeof …
{{jsxref("Operators/void", "void")}}void …
{{jsxref ("Toán tử / xóa", "xóa")}}delete …
{{jsxref ("Toán tử / await", "await")}}await …
16Luỹ thừaphải sang trái… ** …
15Phép nhântrái sang phải… * …
Sư đoàn… / …
Phần còn lại… % …
14Thêm vàotrái sang phải… + …
Phép trừ… - …
13Dịch chuyển sang trái theo chiều bittrái sang phải… << …
Chuyển sang phải theo chiều bit… >> …
Chuyển sang phải không dấu bit… >>> …
12Ít hơntrái sang phải… < …
Nhỏ hơn hoặc bằng… <= …
Lớn hơn… > …
Lớn hơn hoặc bằng… >= …
{{jsxref ("Toán tử / trong", "trong")}}… in …
{{jsxref ("Toán tử / instanceof", "instanceof")}}… instanceof …
11Bình đẳngtrái sang phải… == …
Bất bình đẳng… != …
Bình đẳng nghiêm ngặt… === …
Bất bình đẳng nghiêm ngặt… !== …
10Bitwise VÀtrái sang phải… & …
9Bitwise XORtrái sang phải… ^ …
số 8Bitwise HOẶCtrái sang phải… | …
7Logic ANDtrái sang phải… && …
6Logic HOẶCtrái sang phải… || …
5Nhà điều hành liên kết Nullishtrái sang phải… ?? …
4Có điều kiệnphải sang trái… ? … : …
3Chuyển nhượngphải sang trái… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
… &&= …
… ||= …
… ??= …
2{{jsxref ("Toán tử / lợi nhuận", "lợi nhuận")}}phải sang tráiyield …
{{jsxref ("Toán tử / lợi nhuận *", "lợi nhuận *")}}yield* …
1Dấu phẩy / Chuỗitrái sang phải… , …
diff --git a/files/vi/web/javascript/reference/operators/super/index.html b/files/vi/web/javascript/reference/operators/super/index.html deleted file mode 100644 index 4e5a092475..0000000000 --- a/files/vi/web/javascript/reference/operators/super/index.html +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: super -slug: Web/JavaScript/Reference/Operators/super -translation_of: Web/JavaScript/Reference/Operators/super ---- -
{{jsSidebar("Operators")}}
- -

Từ khóa super được sử dụng để gọi các hàm trên đối tượng cha.

- -

Các biểu thức super.prop và super[expr] là hợp lệ trong mọi định nghĩa phương thức ở cả classesobject literals.

- -

Cú pháp

- -
super([arguments]); // gọi hàm khởi tạo cha.
-super.functionOnParent([arguments]);
-
- -

Mô tả

- -

Khi được sử dụng trong một hàm khởi tạo, từ khóa super xuất hiện một mình và phải được sử dụng trước khi từ khóa this có thể sử dụng. Từ khóa này cũng có thể được sử dụng để gọi các hàm trên đối tượng cha.

- -

Ví dụ

- -

Sử dụng super trong classes

- -

Đoạn code này lấy từ ví dụ về class (live demo).  super()  ở đây được gọi để tránh việc lặp lại các phần giống nhau của Rectangle và Square.

- -
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; // ReferenceError, super needs to be called first!
-
-    // Here, it calls the parent class' constructor with lengths
-    // provided for the Polygon's width and height
-    super(length, length);
-
-    // Note: In derived classes, super() must be called before you
-    // can use 'this'. Leaving this out will cause a reference error.
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-
-  set area(value) {
-    this.area = value;
-  }
-}
- -

Gọi super trên các phương thức tĩnh

- -

Bạn cũng có thể gọi super() trên các phương thức tĩnh.

- -
class Human {
-  constructor() {}
-  static ping() {
-    return 'ping';
-  }
-}
-
-class Computer extends Human {
-  constructor() {}
-  static pingpong() {
-    return super.ping() + ' pong';
-  }
-}
-Computer.pingpong(); // 'ping pong'
-
- -

Xóa các thuộc tính của super sẽ gây ra lỗi

- -

Bạn không thể sử dụng thao tác deletesuper.prop hoặc super[expr] để xóa một thuộc tính của lớp cha, nó sẽ ném lỗi {{jsxref("ReferenceError")}}.

- -
class Base {
-  constructor() {}
-  foo() {}
-}
-class Derived extends Base {
-  constructor() {}
-  delete() {
-    delete super.foo;
-  }
-}
-
-new Derived().delete(); // ReferenceError: invalid delete involving 'super'. 
- -

Super.prop không thể ghi đè các thuộc tính non-writable

- -

Khi định nghĩa các thuộc tính non-writable ví dụ {{jsxref("Object.defineProperty")}},  super không thể ghi đè giá trị của thuộc tính này.

- -
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
-
- -

Sử dụng super.prop trong object literals

- -

Super cũng có thể được sử dụng trong khởi tạo đối tượng hoặc literal. Trong ví dụ này, 2 đối tượng định nghĩa một phương thức. Trong đối tượng thứ hai,  super gọi phương thức của đối tượng thứ nhất. Điều này làm được với sự trợ giúp của {{jsxref("Object.setPrototypeOf()")}} cái giúp chúng ta có thể thiết lập prototype của obj2 thành obj1, vì thế super có thể tìm method1 trên obj1.

- -
var obj1 = {
-  method1() {
-    console.log("method 1");
-  }
-}
-
-var obj2 = {
-  method2() {
-   super.method1();
-  }
-}
-
-Object.setPrototypeOf(obj2, obj1);
-obj2.method2(); // logs "method 1"
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-super-keyword', 'super')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}{{Spec2('ESDraft')}} 
- -

Khả năng tương thích của các trình duyệt

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
Tính năngChromeFirefox (Gecko)Internet ExplorerOperaSafari
Hỗ trợ cơ bản{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
Tính năngAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Hỗ trợ cơ bản{{CompatUnknown}}{{CompatChrome(42.0)}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
-
- -

Lưu ý cho Gecko

- -
    -
  • super() chưa làm việc như mong đợi cho việc xây dựng trong các nguyên mẫu
  • -
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/operators/this/index.html b/files/vi/web/javascript/reference/operators/this/index.html deleted file mode 100644 index d3112507cb..0000000000 --- a/files/vi/web/javascript/reference/operators/this/index.html +++ /dev/null @@ -1,382 +0,0 @@ ---- -title: this -slug: Web/JavaScript/Reference/Operators/this -translation_of: Web/JavaScript/Reference/Operators/this ---- -
{{jsSidebar("Operators")}}
- -

Từ khoá this của hàm  trong JavaScript hơi khác so với các ngôn ngữ khác. Nó cũng có  một vài điểm khác nhau giữa 2 chế độ strict mode và non-strict mode.

- -

Trong hầu hết các trường hợp, giá trị của this được xác định bởi cách gọi hàm (runtime binding). Nó không thể được thiết lập bằng cách gán trong khi thực thi, và nó có thể khác nhau mỗi lần hàm được gọi. ES5 giới thiệu phương thức {{jsxref("Function.prototype.bind()", "bind()")}} để thiết lập giá trị của this bất kể hàm được gọi thế nào, và ES2015 giới thiệu arrow functions mà không cung cấp ràng buộc với this của chúng (Nó sẽ giữ giá trị this của lexical context kèm theo).

- -
{{EmbedInteractiveExample("pages/js/expressions-this.html")}}
- - - -

Cú pháp

- -
this
- -

Giá trị

- -

Một thuộc tính của bối cảnh thực thi (global, function or eval), trong non–strict mode, luôn luôn tham chiếu tới một đối tượng và trong strict mode có thể là bất kỳ giá trị nào.

- -

Global context

- -

Trong global context (bên ngoài các hàm), this tham chiếu tới global object cho dù trong strict mode hoặc không.

- -
// Trong trình duyệt, đối tượng window ?là global object:
-console.log(this === window); // true
-
-a = 37;
-console.log(window.a); // 37
-
-this.b = "MDN";
-console.log(window.b)  // "MDN"
-console.log(b)         // "MDN"
-
- -
-

Note: Bạn có thể dễ dàng lấy được  global object bằng cách sử dụng thuộc tính toàn cầu {{jsxref("globalThis")}}, bất kể bối cảnh hiện tại mà mã của bạn đang chạy.

-
- -

Function context

- -

Bên trong một hàm, giá trị của this phụ thuộc vào cách gọi hàm.

- -

Simple call

- -

Vì đoạn mã sau không ở chế độ strict mode, và vì  giá trị của this không được thiết lập khi gọi, this mặc định là global objecct, đó là window trong trình duyệt. 

- -
function f1() {
-  return this;
-}
-
-// In a browser:
-f1() === window; // true
-
-// In Node:
-f1() === global; // true
- -

Tuy nhiên, trong chế độ strict mode, nếu giá trị của this không được thiết lập khi vào bối cảnh thực thi, nó sẽ giữ giá trị undefined, như ví dụ sau:

- -
function f2() {
-  'use strict'; // see strict mode
-  return this;
-}
-
-f2() === undefined; // true
-
- -
 Trong ví dụ thứ 2, this nên là {{jsxref("undefined")}}, bởi vì f2 được gọi 1 cách trực tiếp và không phải là một phương thức hoặc thuộc tính của một đối tượng(ví dụ window.f2()). ?Tính năng này sẽ không được triển khai trong một số trình duyệt khi chúng lần đầu hỗ trợ chế độ strict mode. Như kết quả trên, chúng không trả về đối tượng window.
- -

Để thiết lập giá trị cụ thể của this khi gọi hàm, sử dụng {{jsxref("Function.prototype.call()", "call()")}}, hoặc {{jsxref("Function.prototype.apply()", "apply()")}} như các ví dụ dưới đây.

- -

Example 1

- -
// Một đối tượng có thể truyền vào như là tham số đầu tiên của call hoặc apply và this sẽ được ràng buộc với nó..
-var obj = {a: 'Custom'};
-
-// Thuộc tính này được thiết lập trên global object
-var a = 'Global';
-
-function whatsThis() {
-  return this.a;  // Giá trị của this phụ thuộc vào cách hàm được gọi.
-}
-
-whatsThis();          // 'Global'
-whatsThis.call(obj);  // 'Custom'
-whatsThis.apply(obj); // 'Custom'
-
- -

Example 2

- -
function add(c, d) {
-  return this.a + this.b + c + d;
-}
-
-var o = {a: 1, b: 3};
-
-// Tham số đầu tiên là đối tượng sử dụng như là
-// 'this', tham số tiếp theo được truyền vào là
-// đối số trong hàm gọi
-add.call(o, 5, 7); // 16
-
-// Tham số đầu tiên là đối tượng sử dụng như là
-// 'this', tham số thứ 2 là 1 mảng
-// các phần tử được sử dụng làm đối số trong lệnh gọi hàm
-add.apply(o, [10, 20]); // 34
-
- -

 Chú ý trong chế độ  non–strict mode, với call và apply, nếu giá trị được truyền vào this không phải là đối tượng, một nỗ lực sẽ được thực hiện để chuyển đổi nó thành đối tượng bằng cách sử dụng ToObject. Vì thế nếu bạn truyền vào giá trị primitive như 7 hoặc 'foo', nó sẽ được chuyển đổi thành Object bằng cách sử dụng các constructor liên quan, do đó 7 sẽ được chuyển đổi thành đối tượng như tạo bằng new Number(7) và string 'foo' cũng được chuyển đổi thành đối tượng như tạo bằng new String('foo'), ví dụ:

- -
function bar() {
-  console.log(Object.prototype.toString.call(this));
-}
-
-bar.call(7);     // [object Number]
-bar.call('foo'); // [object String]
-
- -

The bind method

- -

ECMAScript 5 giới thiệu {{jsxref("Function.prototype.bind()")}}. Gọi f.bind(someObject) tạo ra một hàm mới với cùng thân hàm và phạm vi như hàm f, nhưng this chỉ xảy ra trong hàm ban đầu, trong những hàm mới nó bị ràng buộc vĩnh viễn với đối số đầu tiên của bind, bất kể các hàm được sử dụng thế nào..

- -
function f() {
-  return this.a;
-}
-
-var g = f.bind({a: 'azerty'});
-console.log(g()); // azerty
-
-var h = g.bind({a: 'yoo'}); // bind only works once!
-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
-
- -

Arrow functions

- -

Trong arrow functions, this giữ giá trị ?this của lexical context kèm theo. Trong đoạn mã toàn cục, nó sẽ được thiết lập là global object.

- -
var globalObject = this;
-var foo = (() => this);
-console.log(foo() === globalObject); // true
- -
-

 Lưu ý: nếu đối số  this được truyền vào call, bind, hoặc apply ?trong việc gọi một arrow function nó sẽ bị bỏ qua. Bạn vẫn có thể thêm các đối số cho việc gọi hàm nhưng đối số đầu tiên (thisArg) nên được đặt thành null.

-
- -
// Call as a method of an object
-var obj = {func: foo};
-console.log(obj.func() === globalObject); // true
-
-// Attempt to set this using call
-console.log(foo.call(obj) === globalObject); // true
-
-// Attempt to set this using bind
-foo = foo.bind(obj);
-console.log(foo() === globalObject); // true
- -

Không có vấn đề gì ở đây, this của foo vẫn giữ nguyên giá trị khi nó được tạo  (trong ví dụ trên, nó là global object). Điều tương tự cũng được áp dụng cho những arrow function được tạo bên trong hàm khác: this của chúng giữ giá trị this của lexical context kèm theo.

- -
// Tạo 1 đối tượng với phương thức bar trả về 1 hàm, hàm này sẽ
-// trả về this của nó. Hàm trả về là arrow function,
-// vì thế this của nó được ràng buộc vĩnh viễn với this của hàm kèm theo.
-// Giá trị của bar có thể được thiết lập trong khi gọi hàm,
-// lần lượt đặt giá của hàm trả về.
-var obj = {
-  bar: function() {
-    var x = (() => this);
-    return x;
-  }
-};
-
-// Gọi phương thức bar của obj, thiết lập this là obj.
-// Gán một tham chiếu tới hàm trả về là fn
-var fn = obj.bar();
-
-// Gọi hàm fn mà không thiết lập 'this',
-// thông thường sẽ mặc định cho global object hoặc undefined trong strict mode
-console.log(fn() === obj); // true
-
-// Nhưng hãy cẩn thận nếu bạn tham chiếu phương thức của đối tượng mà không gọi nó
-var fn2 = obj.bar;
-// Gọi hàm arrow function bên trong phương thức bar()
-// nó sẽ trả về window, bởi vì nó theo 'this' từ fn2.
-console.log(fn2()() == window); // true
-
- -

Trong ví dụ trên, hàm (gọi nó là hàm ẩn danh A) gán cho obj.bar trả về một hàm khác (gọi là hàm ẩn danh B) mà nó là một arrow function. Kết quả là, this của hàm B được thiết lập vĩnh viễn là this của obj.bar (hàm A) khi được gọi. Khi hàm trả về (hàm B)  được gọi, this của nó sẽ luôn là  những gì được thiết lập ban đầu. Trong đoạn mã trên, this của hàm B được thiết lập theo this của hàm A đó là obj, vì thế nó vẫn được thiết lập là obj ngay cả khi được gọi  theo cách thông thường thiết lập this thành undefined hoặc global object (hoặc bất kỳ phương thức nào khác như trong ví dụ trên được thực thi trong bối cảnh toàn cầu).

- -

As an object method

- -

Khi một hàm được gọi như là một phương thức của đối tượng,this được đặt thành đối tượng mà có phương thức được gọi trên.

- -

Trong ví dụ dưới đây, khi o.f() được gọi, this bên trong hàm sẽ liên kết với đối tượng o.

- -
var o = {
-  prop: 37,
-  f: function() {
-    return this.prop;
-  }
-};
-
-console.log(o.f()); // 37
-
- -

Lưu ý hành vi này hoàn toàn không bị ảnh hưởng bởi cách thức hoặc nơi chức năng được khai báo. Trong ví dụ ở trên, chúng ta khai báo hàm f bên trong đối tượng o. Tuy nhiên, chúng ta có thể dễ dàng khai báo hàm trước và đính kèm nó vào o.f. Làm như vậy sẽ có kết quả tương tự:

- -
var o = {prop: 37};
-
-function independent() {
-  return this.prop;
-}
-
-o.f = independent;
-
-console.log(o.f()); // 37
-
- -

Điều này chứng tỏ rằng vấn đề chỉ là việc gọi hàm f của o.

- -

Tương tự, ràng buộc với this chỉ bị ảnh hưởng bởi tham chiếu trực tiếp nhất. Trong ví dụ dưới, khi chúng ta gọi hàm, chúng ta gọi nó như là một phương thức g của đối tượng o.b. Khi thực thi, this bên trong hàm sẽ tham chiếu tới o.b. Thực tế đối tượng này là một thành viên của o không ảnh hưởng; tham chiếu trực tiếp nhất mới là quan trọng nhất.

- -
var o = {prop: 37};
-function independent() { return this.prop; }
-o.f = independent;
-console.log(o.f()); // 37 bởi vì tham chiếu trực tiếp nhất là o
-o.b = {g: independent, prop: 42};
-console.log(o.b.g()); // 42 bởi vì tham chiếu trực tiếp nhất là o.b
-
- -

this on the object's prototype chain

- -

The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, this refers to the object the method was called on, as if the method were on the object.

- -
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
-
- -

In this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype. But it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript's prototype inheritance.

- -

this with a getter or setter

- -

Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

- -
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
-
- -

As a constructor

- -

When a function is used as a constructor (with the {{jsxref("Operators/new", "new")}} keyword), its this is bound to the new object being constructed.

- -
-

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
-
- -

In the last example (C2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (This essentially makes the statement "this.a = 37;" dead code. It's not exactly dead because it gets executed, but it can be eliminated with no outside effects.)

- -

As a DOM event handler

- -

When a function is used as an event handler, its this is set to the element on which the listener is placed (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener()).

- -
// When called as a listener, turns the related element blue
-function bluify(e) {
-  // Always true
-  console.log(this === e.currentTarget);
-  // true when currentTarget and target are the same object
-  console.log(this === e.target);
-  this.style.backgroundColor = '#A5D9F3';
-}
-
-// Get a list of every element in the document
-var elements = document.getElementsByTagName('*');
-
-// Add bluify as a click listener so when the
-// element is clicked on, it turns blue
-for (var i = 0; i < elements.length; i++) {
-  elements[i].addEventListener('click', bluify, false);
-}
- -

In an inline event handler

- -

When the code is called from an inline on-event handler, its this is set to the DOM element on which the listener is placed:

- -
<button onclick="alert(this.tagName.toLowerCase());">
-  Show this
-</button>
-
- -

The above alert shows button. Note however that only the outer code has its this set this way:

- -
<button onclick="alert((function() { return this; })());">
-  Show inner this
-</button>
-
- -

In this case, the inner function's this isn't set so it returns the global/window object (i.e. the default object in non–strict mode where this isn't set by the call).

- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-this-keyword', 'The this keyword')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.this")}}

- -

See also

- - diff --git a/files/vi/web/javascript/reference/operators/typeof/index.html b/files/vi/web/javascript/reference/operators/typeof/index.html deleted file mode 100644 index e949879669..0000000000 --- a/files/vi/web/javascript/reference/operators/typeof/index.html +++ /dev/null @@ -1,271 +0,0 @@ ---- -title: typeof -slug: Web/JavaScript/Reference/Operators/typeof -translation_of: Web/JavaScript/Reference/Operators/typeof ---- -
{{jsSidebar("Operators")}}
- -

Phương thức typeof trả về kiểu dữ liệu của đối tượng nào đó.

- -
{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}
- - - -

Cú pháp

- -

Phương thức typeof được theo sau bởi toán hạng operand:

- -
typeof operand
-typeof(operand)
-
- -

Các tham số

- -
-
operand
-
Là một đối tượng cần kiểu tra kiểu dữ liệu hoặc một biểu thức đại điện cho đối tượng.
-
- -

Định nghĩa

- -

Bảng tóm tắt bên dưới mô tả các giá trị có thể trả về của typeof. Xem thêm thông tin tại trang JavaScript data structure.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TypeResult
{{glossary("Undefined")}}"undefined"
{{glossary("Null")}}"object" (see {{anch("null", "below")}})
{{glossary("Boolean")}}"boolean"
{{glossary("Number")}}"number"
{{glossary("BigInt")}}"bigint"
{{glossary("String")}}"string"
{{glossary("Symbol")}} (new in ECMAScript 2015)"symbol"
Host object (provided by the JS environment)Implementation-dependent
{{glossary("Function")}} object (implements [[Call]] in ECMA-262 terms)"function"
Any other object"object"
- -

Các ví dụ

- -
// Numbers
-typeof 37 === 'number';
-typeof 3.14 === 'number';
-typeof(42) === 'number';
-typeof Math.LN2 === 'number';
-typeof Infinity === 'number';
-typeof NaN === 'number'; // Mặc dù "Not-A-Number" nhưng lại là number :)
-typeof Number('1') === 'number'; // Number ép kiểu chuỗi thành kiểu number
-
-typeof 42n === 'bigint';
-
-
-// Strings
-typeof '' === 'string';
-typeof 'bla' === 'string';
-typeof `template literal` === 'string';
-typeof '1' === 'string'; // 1 là number nhưng khi nằm trong ngoặc '' sẽ thành kiểu string
-typeof (typeof 1) === 'string'; // typeof 1 sẽ trả về chữ number, bạn tự hiểu được hen
-typeof String(1) === 'string'; // String sẽ đổi kiểu số 1 từ number thành string
-
-// Booleans
-typeof true === 'boolean';
-typeof false === 'boolean';
-typeof Boolean(1) === 'boolean'; // Boolean() will convert values based on if they're truthy or falsy
-typeof !!(1) === 'boolean'; // two calls of the ! (logical NOT) operator are equivalent to Boolean()
-
-
-// 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';
-typeof /regex/ === 'object'; // See Regular expressions section for historical results
-
-
-// The following are confusing, dangerous, and wasteful. Avoid them.
-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';
-
- -

Additional information

- -

null

- -
// This stands since the beginning of JavaScript
-typeof null === 'object';
-
- -

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the "object" typeof return value. (reference)

- -

A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === 'null'.

- -

Using new operator

- -
// All constructor functions, with the exception of the Function constructor, will always be typeof 'object'
-var str = new String('String');
-var num = new Number(100);
-
-typeof str; // It will return 'object'
-typeof num; // It will return 'object'
-
-var func = new Function();
-
-typeof func; // It will return 'function'
-
- -

Need for parentheses in Syntax

- -
// Parentheses can be used for determining the data type of expressions.
-var iData = 99;
-
-typeof iData + ' Wisen'; // 'number Wisen'
-typeof (iData + ' Wisen'); // 'string'
-
- -

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
-
- -

Errors

- -

Before ECMAScript 2015, typeof was always guaranteed to return a string for any operand it was supplied with. Even with undeclared identifiers, typeof will return 'undefined'. Using typeof could never generate an error.

- -

But with the addition of block-scoped {{jsxref("Statements/let", "let")}} and {{jsxref("Statements/const")}} using typeof on let and const variables (or using typeof on a class) in a block before they are declared will throw a {{jsxref("ReferenceError")}}. Block scoped variables are in a "temporal dead zone" from the start of the block until the initialization is processed, during which, it will throw an error if accessed.

- -
typeof undeclaredVariable === 'undefined';
-
-typeof newLetVariable; // ReferenceError
-typeof newConstVariable; // ReferenceError
-typeof newClass; // ReferenceError
-
-let newLetVariable;
-const newConstVariable = 'hello';
-class newClass{};
- -

Exceptions

- -

All current browsers expose a non-standard host object {{domxref("document.all")}} with type undefined.

- -
typeof document.all === 'undefined';
-
- -

Although the specification allows custom type tags for non-standard exotic objects, it requires those type tags to be different from the predefined ones. The case of document.all having type 'undefined' is classified in the web standards as a "willful violation" of the original ECMA JavaScript standard.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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.
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.typeof")}}

- -

IE-specific notes

- -

On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:

- -
typeof alert === 'object'
- -

See also

- - diff --git a/files/vi/web/javascript/reference/statements/async_function/index.html b/files/vi/web/javascript/reference/statements/async_function/index.html deleted file mode 100644 index 3009b78083..0000000000 --- a/files/vi/web/javascript/reference/statements/async_function/index.html +++ /dev/null @@ -1,255 +0,0 @@ ---- -title: async function -slug: Web/JavaScript/Reference/Statements/async_function -translation_of: Web/JavaScript/Reference/Statements/async_function ---- -
-
{{jsSidebar("Statements")}}
-Việc tạo hàm với câu lệnh async function sẽ định nghĩa ra một hàm không đồng bộ (asynchronous function) - hàm này sẽ trả về một object {{jsxref("Global_Objects/AsyncFunction","AsyncFunction")}}
- -

Các hàm không đồng bộ sẽ hoạt động trong một thứ tự tách biệt so với phần còn lại của đoạn code thông qua một event loop, trả về kết quả là một {{jsxref("Promise")}} tiềm ẩn. Nhưng cú pháp và cấu trúc của đoạn code mà sử dụng các hàm async function trông cứ như những hàm đồng bộ tiêu chuẩn.

- -
-

Bạn cũng có thể định nghĩa các async function với một {{jsxref("Operators/async_function", "async function expression", "", 1)}}.

-
-
- -
{{EmbedInteractiveExample("pages/js/statement-async.html", "taller")}}
- - - -

Cú pháp

- -
async function name([param[, param[, ...param]]]) {
-   statements
-}
-
- -

Các thông số

- -
-
name
-
Tên của function.
-
param
-
Tên của một đối số được truyền vào function.
-
statements
-
Các câu lệnh bao hàm phần thân của function.
-
- -

Giá trị trả về

- -

Một Promise, cái mà sẽ được giải quyết với giá trị được trả về bởi async function, hoặc được đẩy ra ngoài với một exception không được bắt lại bên trong hàm async function.

- -

Mô tả

- -

Một hàm async có thể bao gồm một biểu thức {{jsxref("Operators/await", "await")}}, biểu thức này sẽ tạm dừng việc thực thi của hàm async để chờ cho Promise's resolution được truyền vào, sau đó tiếp tục việc thực thi của hàm async and evaluates as the resolved value.

- -

Từ khóa await chỉ có hiệu lực bên trong hàm async. Nếu bạn sử dụng nó bên ngoài phần thân của hàm async, bạn sẽ nhận một SyntaxError.

- -

Trong lúc hàm async tạm dừng, hàm được gọi sẽ tiếp tục chạy. (hàm mà nhận được Promise tiềm ẩn được trả về bởi hàm async).

- -
-

Mục đích của async/await là để đơn giả hóa việc sử dụng các promises một cách đồng bộ, và để triển khai một số hoạt động trên một nhóm của các Promises. Nếu Promises là tương tự như các callback có cấu trúc, async/await là tương tự với kết hợp các generators và promises.

-
- -

Ví dụ

- -

Async functions và thứ tự của việc thực thi

- -
function resolveAfter2Seconds() {
-  console.log("starting slow promise")
-  return new Promise(resolve => {
-    setTimeout(function() {
-      resolve("slow")
-      console.log("slow promise is done")
-    }, 2000)
-  })
-}
-
-function resolveAfter1Second() {
-  console.log("starting fast promise")
-  return new Promise(resolve => {
-    setTimeout(function() {
-      resolve("fast")
-      console.log("fast promise is done")
-    }, 1000)
-  })
-}
-
-async function sequentialStart() {
-  console.log('==SEQUENTIAL START==')
-
-  // 1. Execution gets here almost instantly
-  const slow = await resolveAfter2Seconds()
-  console.log(slow) // 2. this runs 2 seconds after 1.
-
-  const fast = await resolveAfter1Second()
-  console.log(fast) // 3. this runs 3 seconds after 1.
-}
-
-async function concurrentStart() {
-  console.log('==CONCURRENT START with await==');
-  const slow = resolveAfter2Seconds() // starts timer immediately
-  const fast = resolveAfter1Second() // starts timer immediately
-
-  // 1. Execution gets here almost instantly
-  console.log(await slow) // 2. this runs 2 seconds after 1.
-  console.log(await fast) // 3. this runs 2 seconds after 1., immediately after 2., since fast is already resolved
-}
-
-function concurrentPromise() {
-  console.log('==CONCURRENT START with Promise.all==')
-  return Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => {
-    console.log(messages[0]) // slow
-    console.log(messages[1]) // fast
-  })
-}
-
-async function parallel() {
-  console.log('==PARALLEL with await Promise.all==')
-
-  // Start 2 "jobs" in parallel and wait for both of them to complete
-  await Promise.all([
-      (async()=>console.log(await resolveAfter2Seconds()))(),
-      (async()=>console.log(await resolveAfter1Second()))()
-  ])
-}
-
-// This function does not handle errors. See warning below!
-function parallelPromise() {
-  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(concurrentPromise, 7000) // same as concurrentStart
-
-// wait again
-setTimeout(parallel, 10000) // truly parallel: after 1 second, logs "fast", then after 1 more second, "slow"
-
-// wait again
-setTimeout(parallelPromise, 13000) // same as parallel
-
- -

await và xử lý song song

- -

In sequentialStart, execution suspends 2 seconds for the first await, and then another second for the second await. The second timer is not created until the first has already fired, so the code finishes after 3 seconds.

- -

In concurrentStart, both timers are created and then awaited. The timers run concurrently, which means the code finishes in 2 rather than 3 seconds, i.e. the slowest timer.
- However, the await calls still run in series, which means the second await will wait for the first one to finish. In this case, the result of the fastest timer is processed after the slowest.

- -

If you wish to fully perform two or more jobs in parallel, you must use await Promise.all([job1(), job2()]), as shown in the parallel example.

- -
-

async/await vs Promise.then and error handling

- -

Most async functions can also be written as regular functions using Promises. However, async functions are less tricky when it comes to error handling.

- -

Both concurrentStart and concurrentPromise are functionally equivalent:

- -
    -
  • In concurrentStart, if either of the awaited calls fail, the exception will be automatically caught, the async function execution interrupted, and the Error propagated to the caller through the implicit return Promise.
  • -
  • For the same to happen in the Promise case, the function must take care of returning a Promise which captures the completion of the function. In concurrentPromise that means returning the promise from Promise.all([]).then(). As a matter of fact, a previous version of this example forgot to do this!
  • -
- -

It is, however, still possible for async functions to mistakenly swallow errors.

- -

Take, for example the parallel async function. If it didn't await (or return) the result of the Promise.all([]) call, any Error would not propagate.

- -

While the parallelPromise example seems simpler, it does not handle errors at all! Doing so would require a similar return Promise.all([]).

-
- -

Rewriting a Promise chain with an async function

- -

An API that returns a {{jsxref("Promise")}} will result in a promise chain, and it splits the function into many parts. Consider the following code:

- -
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
-    })
-}
-
- -

it can be rewritten with a single async function as follows:

- -
async function getProcessedData(url) {
-  let v
-  try {
-    v = await downloadData(url)
-  } catch(e) {
-    v = await downloadFallbackData(url)
-  }
-  return processDataInWorker(v)
-}
-
- -

In the above example, there is no await statement after the return keyword, because the return value of an async function is implicitly wrapped in {{jsxref("Promise.resolve")}}.

- -
-

return await promiseValue vs. return promiseValue

- -

The implicit wrapping of return values in {{jsxref("Promise.resolve")}} does not imply that return await promiseValue is functionally equivalent to return promiseValue.

- -

Consider the following rewrite of the above code. It returns null if processDataInWorker rejects with an error:

- -
async function getProcessedData(url) {
-  let v
-  try {
-    v = await downloadData(url)
-  } catch(e) {
-    v = await downloadFallbackData(url)
-  }
-  try {
-    return await processDataInWorker(v)  // Note the `return await` vs. just `return`
-  } catch (e) {
-    return null
-  }
-}
-
- -

Writing return processDataInWorker(v) would have caused the {{jsxref("Promise")}} returned by the function to reject, instead of resolving to null if processDataInWorker(v) rejects.

- -

This highlights the subtle difference between return foo; and return await foo;return foo immediately returns foo and never throws, even if foo is a Promise that rejects. return await foo will wait for foo to resolve or reject if it's a Promise, and throws before returning if it rejects.

-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}
- -

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/statements/continue/index.html b/files/vi/web/javascript/reference/statements/continue/index.html deleted file mode 100644 index d6afd506d7..0000000000 --- a/files/vi/web/javascript/reference/statements/continue/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: continue -slug: Web/JavaScript/Reference/Statements/continue -translation_of: Web/JavaScript/Reference/Statements/continue ---- -
{{jsSidebar("Statements")}}
- -

Câu lệnh continue chấm dứt việc thực thi của các câu lệnh trong lượt lặp hiện tại của vòng lặp hiện tại, hoặc của vòng lặp được gắn nhãn, và tiếp tục việc thực thi lượt lặp kế tiếp.

- -
{{EmbedInteractiveExample("pages/js/statement-continue.html")}}
- - - -

Cú pháp

- -
continue [label];
- -
-
label
-
Identifier gắn liền với nhãn của câu lệnh.
-
- -

Mô tả

- -

Trái ngược với câu lệnh {{jsxref("Statements/break", "break")}}, continue không chấm dứt việc thực thi của cả vòng lặp: thay vào đó,

- -
    -
  • Trong một vòng lặp {{jsxref("Statements/while", "while")}}, nó nhảy trở về biểu thức điều kiện.
  • -
  • Trong một vòng lặp {{jsxref("Statements/for", "for")}}, nó nhảy đến biểu thức tăng tiến (update expression).
  • -
- -

Câu lệnh continue có thể bao gồm một nhãn tùy chọn cho phép chương trình nhảy đến lượt lặp tiếp theo của một câu lệnh vòng lặp được gắn nhãn, thay vì nhảy đến lượt lặp tiếp theo của vòng lặp hiện tại. Trong trường hợp này, câu lệnh continue cần được lồng bên trong câu lệnh được gắn nhãn đó.

- -

Ví dụ

- -

Sử dụng continue với while

- -

Ví dụ sau thể hiện một vòng lặp {{jsxref("Statements/while", "while")}} có một câu lệnh continue mà sẽ được thực thi khi giá trị của i là 3. Vì vậy, n nhận các giá trị 1, 3, 7 và 12.

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

Sử dụng continue với một nhãn (label)

- -

Trong ví dụ sau đây, một câu lệnh được gắn nhãn checkiandj có chứa một câu lệnh được gắn nhãn checkj. Nếu gặp phải continue, chương trình sẽ tiếp tục tại phần đầu của câu lệnh checkj. Mỗi lần gặp phải continuecheckj sẽ chạy lại cho đến khi điều kiện của nó trả về false. Khi false được trả về, phần còn lại của câu lệnh checkiandj sẽ được hoàn thành.

- -

Nếu sau continue có một nhãn checkiandj, chương trình sẽ tiếp túc tại phần đầu của câu lệnh checkiandj.

- -

Xem thêm {{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);
-}
-
- -

Kết quả:

- -
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
-
- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-continue-statement', 'Continue statement')}}
- -

Browser compatibility

- - - -

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

- -

See also

- -
    -
  • {{jsxref("Statements/break", "break")}}
  • -
  • {{jsxref("Statements/label", "label")}}
  • -
diff --git a/files/vi/web/javascript/reference/statements/do...while/index.html b/files/vi/web/javascript/reference/statements/do...while/index.html deleted file mode 100644 index eef8cf1f08..0000000000 --- a/files/vi/web/javascript/reference/statements/do...while/index.html +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: do...while -slug: Web/JavaScript/Reference/Statements/do...while -translation_of: Web/JavaScript/Reference/Statements/do...while ---- -
{{jsSidebar("Statements")}}
- -

Vòng lặp do...while tạo ra vòng lặp thực thi các câu lệnh bên trong nó đến khi điều kiện không còn thoả mãn nữa. Điều kiện của vòng lặp sẽ được kiểm tra sau thực thi các câu lệnh, các câu lệnh của vòng lặp sẽ được thực thi ít nhất một lần.

- -
{{EmbedInteractiveExample("pages/js/statement-dowhile.html")}}
- - - -

Cú pháp

- -
do
-   // các câu lệnh
-while (// điều kiện);
-
- -
-
statement
-
A statement that is executed at least once and is re-executed each time the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block")}} statement ({ ... }) to group those statements.
-
- -
-
condition
-
An expression evaluated after each pass through the loop. If condition evaluates to true, the statement is re-executed. When condition evaluates to false, control passes to the statement following the do...while.
-
- -

Examples

- -

Using do...while

- -

In the following example, the do...while loop iterates at least once and reiterates until i is no longer less than 5.

- -

HTML content

- -
<div id="example"></div>
- -

JavaScript content

- -
var result = '';
-var i = 0;
-do {
-   i += 1;
-   result += i + ' ';
-} while (i < 5);
-document.getElementById('example').innerHTML = result;
- -

Result

- -

{{ EmbedLiveSample('Examples') }}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.6.1', 'do-while statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ES6')}}Trailing ; is now optional.
{{SpecName('ESDraft', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- - - -

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

- -

See also

- -
    -
  • {{jsxref("Statements/while", "while")}}
  • -
  • {{jsxref("Statements/for", "for")}}
  • -
diff --git a/files/vi/web/javascript/reference/statements/export/index.html b/files/vi/web/javascript/reference/statements/export/index.html deleted file mode 100644 index 0187b3dbfa..0000000000 --- a/files/vi/web/javascript/reference/statements/export/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: export -slug: Web/JavaScript/Reference/Statements/export -translation_of: Web/JavaScript/Reference/Statements/export ---- -
{{jsSidebar("Statements")}}
- -

Lệnh export được sử dụng khi tạo các module JavaScript để export các hàm, đối tượng hoặc giá trị nguyên thủy trong module để chúng có thể được sử dụng bởi các chương trình khác bằng lệnh {{jsxref("Statements/import", "import")}}.

- -
-

Tính năng này mới chỉ được triển khai trên Safari vào thời điểm hiện tại. Nó cũng được triển khai ở nhiều trình dịch (transpilers), ví dụ như Traceur Compiler, Babel hay Rollup.

-
- -

Cú pháp

- -
export { name1, name2, …, nameN };
-export { variable1 as name1, variable2 as name2, …, nameN };
-export let name1, name2, …, nameN; // còn có thể là var, function
-export let name1 = …, name2 = …, …, nameN; // còn có thể là var, const
-
-export default expression;
-export default function (…) { … } // còn có thể là class, function*
-export default function name1(…) { … } // còn có thể là class, function*
-export { name1 as default, … };
-
-export * from …;
-export { name1, name2, …, nameN } from …;
-export { import1 as name1, import2 as name2, …, nameN } from …;
- -
-
nameN
-
Định danh được export (để có thể được import thông qua lệnh {{jsxref("Statements/import", "import")}} ở trong script khác).
-
- -

Mô tả

- -

Có nhiều kiểu export khác nhau. Mỗi kiểu tương ứng với một trong các cú pháp ở phía trên:

- -
    -
  • Export tên: -
    // exports một hàm được định nghĩa phía trước
    -export { myFunction };
    -
    -// exports một hằng số
    -export const foo = Math.sqrt(2);
    -
  • -
  • Export giá trị mặc định (hàm): -
    export default function() {} 
    -
  • -
  • Export giá trị mặc định (lớp): -
    export default class {} 
    -
  • -
- -

Export tên hữu ích khi dùng để export một vài giá trị. Khi import, có thể dùng cùng tên đó để truy xuất đến giá trị tương ứng.

- -

Về export giá trị mặc định, chỉ có duy nhất một giá trị mặc định được export trên một module. Một giá trị được export mặc định có thể là một hàm, một lớp, một đối tượng hay bất cứ thứ gì khác. Giá trị này được coi là giá trị được export "chính" do nó sẽ là giá trị đơn giản nhất được import.

- -

Export các giá trị mặc định: Cú pháp sau đây không export một giá trị được export mặc định từ module được import:

- -
export * from …;
- -

Nếu bạn muốn export giá trị mặc định, hãy dùng cú pháp sau:

- -
import mod from "mod";
-export default mod;
- -

Ví dụ

- -

Sử dụng export tên

- -

Trong module, chúng ta có thể dùng code sau:

- -
// module "my-module.js"
-function cube(x) {
-  return x * x * x;
-}
-const foo = Math.PI + Math.SQRT2;
-export { cube, foo };
-
- -

Với cách này, trong script khác (cf. import), chúng ta có:

- -
import { cube, foo } from 'my-module';
-console.log(cube(3)); // 27
-console.log(foo);    // 4.555806215962888
- -

Sử dụng export giá trị mặc định

- -

Nếu chúng ta muốn export một giá trị duy nhất hay có một giá trị trả về mặc định từ module của mình, chúng ta có thể sử dụng export giá trị mặc định:

- -
// module "my-module.js"
-export default function cube(x) {
-  return x * x * x;
-}
-
- -

Sau đó, trong script khác, có thể import thẳng giá trị được export mặc định:

- -
import cube from 'my-module';
-console.log(cube(3)); // 27
-
- -

Chú ý là không thể dùng var, let hay const với export default.

- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiChú thích
{{SpecName('ES2015', '#sec-exports', 'Exports')}}{{Spec2('ES2015')}}Định nghĩa ban đầu.
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}} 
- -

Tương thích với trình duyệt

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
Tính năngChromeFirefox (Gecko)Internet ExplorerOperaSafari
Hỗ trợ cơ bản61 (60 w/ flag){{CompatNo}} (54 w/ flag){{CompatNo}} (15 w/flag){{CompatNo}}10.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
Tính năngAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Hỗ trợ cơ bản{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}10.3
-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/statements/for...of/index.html b/files/vi/web/javascript/reference/statements/for...of/index.html deleted file mode 100644 index 5bd72040eb..0000000000 --- a/files/vi/web/javascript/reference/statements/for...of/index.html +++ /dev/null @@ -1,318 +0,0 @@ ---- -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")}}
- -

Cú pháp for...of để chạy vòng lặp trên {{jsxref("String")}}, {{jsxref("Array")}}, đối tượng tương tự Array (như {{jsxref("Functions/arguments", "arguments")}} hoặc {{domxref("NodeList")}}), {{jsxref("TypedArray")}}, {{jsxref("Map")}}, {{jsxref("Set")}}.

- -
{{EmbedInteractiveExample("pages/js/statement-forof.html")}}
- - - -

Cú pháp

- -
for (tên-biến of đối-tượng-chạy-vòng-lặp) {
-  ...câu lệnh...
-}
-
- -
-
tên biến
-

- Trên mỗi lần lặp, một giá trị của một thuộc tính khác nhau được gán cho biến. biến có thể được khai báo với const, let hoặc var.
-
đối tượng để chạy vòng lặp
-
Đối tượng có các thuộc tính có thể được lặp lại (iterable).
-
- -

Ví dụ

- -

Lặp qua một {{jsxref("Array")}}

- -
let iterable = [10, 20, 30];
-
-for (let value of iterable ) {
-  value += 1;
-  console.log(value);
-}
-// 11
-// 21
-// 31
-
- -

Có thể khai báo bằng const thay cho let, nếu không có thay đổi biến bên trong vòng lặp.

- -
let iterable= [10, 20, 30];
-
-for (const value of iterable) {
-  console.log(value);
-}
-// 10
-// 20
-// 30
-
- -

Lặp qua một {{jsxref("String")}}

- -
const iterable = 'boo';
-
-for (const value of iterable) {
-  console.log(value);
-}
-// "b"
-// "o"
-// "o"
-
- -

Lặp qua {{jsxref("TypedArray")}}

- -
const iterable = new Uint8Array([0x00, 0xff]);
-
-for (const value of iterable) {
-  console.log(value);
-}
-// 0
-// 255
-
- -

Lặp qua một {{jsxref("Map")}}

- -
const iterable = new Map([['a', 1], ['b', 2], ['c', 3]]);
-
-for (const entry of iterable) {
-  console.log(entry);
-}
-// ['a', 1]
-// ['b', 2]
-// ['c', 3]
-
-for (const [key, value] of iterable) {
-  console.log(value);
-}
-// 1
-// 2
-// 3
-
- -

Loop qua một {{jsxref("Set")}}

- -
const iterable = new Set([1, 1, 2, 2, 3, 3]);
-
-for (const value of iterable) {
-  console.log(value);
-}
-// 1
-// 2
-// 3
-
- -

Lặp qua một đối tượng arguments

- -

Lặp qua đối tượng {{jsxref("Functions/arguments", "arguments")}} để có tất cả giá trị được truyền vào trong hàm:

- -
(function() {
-  for (const argument of arguments) {
-    console.log(argument);
-  }
-})(1, 2, 3);
-
-// 1
-// 2
-// 3
- -

Lặp qua một tập DOM

- -

Lặp qua một tập DOM như {{domxref("NodeList")}}: ví dụ bên dưới, thêm class read cho các đoạn văn bản nào là con trực tiếp của article:

- -
// Lưu ý: Chỉ hoạt động động trên các platforms có
-// hiện thực NodeList.prototype[Symbol.iterator]
-const articleParagraphs = document.querySelectorAll('article > p');
-
-for (const paragraph of articleParagraphs) {
-  paragraph.classList.add('read');
-}
-
- -

Đóng vòng lặp

- -

Trong vòng lặp for...of, có thể ngừng lặp giữa chừng bằng break, continue, throw hoặc return. Trong các trường hợp này, vòng lặp sẽ được ngưng lại.

- -
function* foo(){
-  yield 1;
-  yield 2;
-  yield 3;
-};
-
-for (const o of foo()) {
-  console.log(o);
-  break; // đóng vòng lặp, tiếp tục thực thi bên ngoài vòng lặp
-}
-console.log('Xong')
-
- -

Lặp qua generator

- -

Bạn cũng có thể lặp qua hàm generators, ví dụ:

- -
function* fibonacci() { // một hàm generator
-  let [prev, curr] = [0, 1];
-  while (true) {
-    [prev, curr] = [curr, prev + curr];
-    yield curr;
-  }
-}
-
-for (const n of fibonacci()) {
-  console.log(n);
-  // truncate the sequence at 1000
-  if (n >= 1000) {
-    break;
-  }
-}
-
- -

Không tái sử dụng generator

- -

Không nên re-used Generator, ngay cả khi vòng lặp for...of bị kết thúc sớm bằng {{jsxref("Statements/break", "break")}}. Khi thoát khỏi vòng lặp, generator sẽ kết thúc và cố lặp lại lần nữa sẽ không cho thêm bất kỳ kết quả yield nào khác.

- -
const gen = (function *(){
-  yield 1;
-  yield 2;
-  yield 3;
-})();
-for (const o of gen) {
-  console.log(o);
-  break;  // Closes iterator
-}
-
-// Không dùng lại generator, đoạn code như thế này không hợp lý!
-for (const o of gen) {
-  console.log(o); // Không bao giờ được gọi
-}
-
- -

Lặp qua các đối tượng khác

- -

Bạn cũng có thể loop qua các đối tượng tự định nghĩa, nếu có hiện thực iterable:

- -
const iterable = {
-  [Symbol.iterator]() {
-    return {
-      i: 0,
-      next() {
-        if (this.i < 3) {
-          return { value: this.i++, done: false };
-        }
-        return { value: undefined, done: true };
-      }
-    };
-  }
-};
-
-for (const value of iterable) {
-  console.log(value);
-}
-// 0
-// 1
-// 2
-
- -

Sự khác biệt giữa for...offor...in

- -

Cú pháp {{jsxref("Statements/for...in", "for...in")}} lặp qua các đối tượng được đếm, theo một thứ tự tùy ý.

- -

Cú pháp for...of lặp qua đối tượng dữ liệu có thể lặp.

- -

Ví dụ sau để thấy sự khác nhau giữa for...of và for...in khi sử dụng với {{jsxref("Array")}}.

- -
Object.prototype.objCustom = function() {};
-Array.prototype.arrCustom = function() {};
-
-const iterable = [3, 5, 7];
-iterable.foo = 'hello';
-
-for (const i in iterable) {
-  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
-}
-
-for (const i in iterable) {
-  if (iterable.hasOwnProperty(i)) {
-    console.log(i); // logs 0, 1, 2, "foo"
-  }
-}
-
-for (const i of iterable) {
-  console.log(i); // logs 3, 5, 7
-}
-
- -

Giải thích ví dụ trên

- -
Object.prototype.objCustom = function() {};
-Array.prototype.arrCustom = function() {};
-
-const iterable = [3, 5, 7];
-iterable.foo = 'hello';
- -

Tất cả object sẽ kế thừa thuộc tính objCustom và tất cả {{jsxref("Array")}} sẽ kết thừa thuộc tính arrCustom bởi vì chúng ta thêm nó vào bằng {{jsxref("Object.prototype")}} và {{jsxref("Array.prototype")}}. iterable kế thừa cả objCustomarrCustom.

- -
for (const i in iterable) {
-  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
-}
- -

Vòng vòng lặp này chỉ log thuộc tính được đếm của iterable, theo thứ tự được đưa vào. Nó không log các element của array 3, 5, 7 hoặc hello bởi vì nó là không thuộc tính được đếm. Nó log giá trị index cũng như arrCustomobjCustom.

- -
for (let i in iterable) {
-  if (iterable.hasOwnProperty(i)) {
-    console.log(i); // logs 0, 1, 2, "foo"
-  }
-}
- -

Vòng loop tương tự như ở trên, nhưng sử dụng {{jsxref("Object.prototype.hasOwnProperty()", "hasOwnProperty()")}} để kiểm tra, nếu tìm thấy một property của chính nó chứ không phải kế thừa và log kết quả ra. Các Property 0, 1, 2foo được log bởi vì nó không phải được kết thừa.

- -
for (const i of iterable) {
-  console.log(i); // logs 3, 5, 7
-}
- -

Vòng lặp và log ra giá trị bên trong đối tượng iterable như một iterable object được khai báo để lặp, chính là các element bên trong mảng 3, 5, 7 và không bao gồm các property của object.

- -

Đặc điểm

- - - - - - - - - - - - - - - - - - - -
Đặc điểmStatusGhi chú
{{SpecName('ES2015', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ESDraft')}}
- -

Trình duyệt hổ trợ

- - - -

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

- -

Xem thêm

- -
    -
  • {{jsxref("Array.prototype.forEach()")}}
  • -
  • {{jsxref("Map.prototype.forEach()")}}
  • -
diff --git a/files/vi/web/javascript/reference/statements/for/index.html b/files/vi/web/javascript/reference/statements/for/index.html deleted file mode 100644 index 613732de85..0000000000 --- a/files/vi/web/javascript/reference/statements/for/index.html +++ /dev/null @@ -1,137 +0,0 @@ ---- -title: for -slug: Web/JavaScript/Reference/Statements/for -translation_of: Web/JavaScript/Reference/Statements/for ---- -
{{jsSidebar("Statements")}}
- -

The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.

- -
{{EmbedInteractiveExample("pages/js/statement-for.html")}}
- - - -

Syntax

- -
for ([initialization]; [condition]; [final-expression])
-   statement
- -
-
initialization
-
An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.
-
The result of this expression is discarded.
-
condition
-
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.
-
final-expression
-
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
-
statement
-
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block", "", 0)}} statement ({ ... }) to group those statements. To execute no statement within the loop, use an {{jsxref("Statements/empty", "empty", "", 0)}} statement (;).
-
- -

Examples

- -

Using for

- -

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

- -
for (let i = 0; i < 9; i++) {
-   console.log(i);
-   // more statements
-}
-
- -

Optional for expressions

- -

All three expressions in the head of the for loop are optional.

- -

For example, in the initialization block it is not required to initialize variables:

- -
var i = 0;
-for (; i < 9; i++) {
-    console.log(i);
-    // more statements
-}
-
- -

Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

- -
for (let i = 0;; i++) {
-   console.log(i);
-   if (i > 3) break;
-   // more statements
-}
- -

You can also omit all three blocks. Again, make sure to use a {{jsxref("Statements/break", "break")}} statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

- -
var i = 0;
-
-for (;;) {
-  if (i > 3) break;
-  console.log(i);
-  i++;
-}
-
- -

Using for without a statement

- -

The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead.

- -
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;"
- -
Note: This is one of the few cases in JavaScript where the semicolon is mandatory. Indeed, without the semicolon the line that follows the cycle declaration will be considered a statement.
- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}
- -

Browser compatibility

- - - -

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

- -

Xem thêm

- -
    -
  • {{jsxref ("Báo cáo / trống", "tuyên bố trống", "", 0)}}
  • -
  • {{jsxref ("Tuyên bố / phá vỡ", "phá vỡ")}}
  • -
  • {{jsxref ("Tuyên bố / tiếp tục", "tiếp tục")}}
  • -
  • {{jsxref ("Tuyên bố / while", "while")}}
  • -
  • {{jsxref ("Tuyên bố / làm ... trong khi", "làm ... trong khi")}}
  • -
  • {{jsxref ("Tuyên bố / cho ... trong", "cho ... trong")}}
  • -
  • {{jsxref ("Tuyên bố / cho ... của", "cho ... của")}}
  • -
diff --git a/files/vi/web/javascript/reference/statements/function_star_/index.html b/files/vi/web/javascript/reference/statements/function_star_/index.html deleted file mode 100644 index 388e0f8b34..0000000000 --- a/files/vi/web/javascript/reference/statements/function_star_/index.html +++ /dev/null @@ -1,208 +0,0 @@ ---- -title: function* -slug: Web/JavaScript/Reference/Statements/function* -translation_of: Web/JavaScript/Reference/Statements/function* ---- -
{{jsSidebar("Statements")}}
- -

Khai báo function* (từ khóa function tiếp theo là dấu sao) định nghĩa một generator function, một phương thức trả về đối tượng {{jsxref("Global_Objects/Generator","Generator")}}.

- -
{{EmbedInteractiveExample("pages/js/statement-functionasterisk.html")}}
- - - -
-

Bạn cũng có thể khai báo generator functions bằng constructor {{jsxref("GeneratorFunction")}} , hoặc cú pháp function expression.

-
- -

Cú pháp

- -
function* name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
Tên phương thức
-
- -
-
param
-
Các tham số truyền vào cho phương thức.
-
- -
-
statements
-
Các câu lệnh bên trong phương thức
-
- -

Diễn giải

- -

Generators là một hàm có thể thoát và sau đó gọi lại lần nữa. Giá trị của biến trong các lần gọi được lưu lại trong các lần gọi tiếp theo.
-
- Pattern là cách hàm async được viết ra.

- -

Gọi một generator function không thực thi các lệnh bên trong hàm ngày lập tức; Thay vào đó, một object iterator được trả về. Khi iterator gọi đến phương thức next() , lúc này các lệnh bên trong hàm được thực thi cho đến khi gặp câu {{jsxref("Operators/yield", "yield")}} , sau câu lệnh {{jsxref("Operators/yield", "yield")}} là giá trị sẽ trả về, hoặc gọi đến một generator function khác. Phương thức next() trả về một object với property value chứa giá trị yielded và property done , giá trị kiểu boolean, xác định generator yielded trả về đã là cuối cùng chưa. Gọi phương thức next() với một tham số sẽ chạy hàm generator tiếp tục, thay thế câu yield nơi hàm đã dừng lại trước đó với tham số từ next()

- -

Câu lệnh return trong generator, khi chạy, sẽ kết thúc generator (ví dụ property done trả về sẽ có giá trị true). Nếu giá trị đã được trả về, nó sẽ được set cho property value.
- Giống như câu lệnh return , thrown error trong generator sẽ kết thúc generator  -- trừ khi bắt lại bằng bên trong generator.
- Khi một generator kết thúc, các câu gọi  next tiếp theo sau sẽ không được thực thi, nó chỉ trả về object có dạng: {value: undefined, done: true}.

- -

Ví dụ

- -

Ví dụ đơn giản

- -
function* idMaker() {
-  var index = 0;
-  while (index < index+1)
-    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); // 3
-// ...
- -

Ví dụ với 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
-
- -

Truyền tham số vào trong Generators

- -
function* logGenerator() {
-  console.log(0);
-  console.log(1, yield);
-  console.log(2, yield);
-  console.log(3, yield);
-}
-
-var gen = logGenerator();
-
-gen.next();             // 0
-gen.next('pretzel');    // 1 pretzel
-gen.next('california'); // 2 california
-gen.next('mayonnaise'); // 3 mayonnaise
-
- -

Return bên trong generator

- -
function* yieldAndReturn() {
-  yield "Y";
-  return "R";
-  yield "unreachable";
-}
-
-var gen = yieldAndReturn()
-console.log(gen.next()); // { value: "Y", done: false }
-console.log(gen.next()); // { value: "R", done: true }
-console.log(gen.next()); // { value: undefined, done: true }
-
- -

Generators không dùng constructable

- -
function* f() {}
-var obj = new f; // throws "TypeError: f is not a constructor
-
- -

Generator khai báo bằng expression

- -
const foo = function* () {
-  yield 10;
-  yield 20;
-};
-
-const bar = foo();
-console.log(bar.next()); // {value: 10, done: false}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator-function-definitions', 'function*')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-generator-function-definitions', 'function*')}}{{Spec2('ES2016')}}Changed that generators should not have [[Construct]] trap and will throw when used with new.
{{SpecName('ESDraft', '#sec-generator-function-definitions', 'function*')}}{{Spec2('ESDraft')}}
- -

Trình duyệt hỗ trợ

- -
- - -

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

-
- -

Lưu ý dành riêng cho Firefox

- -

Generators và iterators trước phiên bản Firefox 26

- -

Older Firefox versions implement an older version of the generators proposal. In the older version, generators were defined using a regular function keyword (without an asterisk) among other differences. See Legacy generator function for further information.

- -

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)}}).

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/statements/index.html b/files/vi/web/javascript/reference/statements/index.html deleted file mode 100644 index 460884b7d9..0000000000 --- a/files/vi/web/javascript/reference/statements/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: Statements and declarations -slug: Web/JavaScript/Reference/Statements -tags: - - JavaScript - - NeedsTranslation - - Reference - - TopicStub - - statements -translation_of: Web/JavaScript/Reference/Statements ---- -
{{jsSidebar("Statements")}}
- -

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.

- -

Statements and declarations by category

- -

For an alphabetical listing see the sidebar on the left.

- -

Control flow

- -
-
{{jsxref("Statements/block", "Block")}}
-
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
-
{{jsxref("Statements/break", "break")}}
-
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
-
{{jsxref("Statements/continue", "continue")}}
-
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
-
{{jsxref("Statements/Empty", "Empty")}}
-
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
-
{{jsxref("Statements/if...else", "if...else")}}
-
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
-
{{jsxref("Statements/switch", "switch")}}
-
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
-
{{jsxref("Statements/throw", "throw")}}
-
Throws a user-defined exception.
-
{{jsxref("Statements/try...catch", "try...catch")}}
-
Marks a block of statements to try, and specifies a response, should an exception be thrown.
-
- -

Declarations

- -
-
{{jsxref("Statements/var", "var")}}
-
Declares a variable, optionally initializing it to a value.
-
{{jsxref("Statements/let", "let")}}
-
Declares a block scope local variable, optionally initializing it to a value.
-
{{jsxref("Statements/const", "const")}}
-
Declares a read-only named constant.
-
- -

Functions and classes

- -
-
{{jsxref("Statements/function", "function")}}
-
Declares a function with the specified parameters.
-
{{jsxref("Statements/function*", "function*")}}
-
Generators functions enable writing iterators more easily.
-
{{jsxref("Statements/async_function", "async function")}}
-
Declares an async function with the specified parameters.
-
{{jsxref("Statements/return", "return")}}
-
Specifies the value to be returned by a function.
-
{{jsxref("Statements/class", "class")}}
-
Declares a class.
-
- -

Iterations

- -
-
{{jsxref("Statements/do...while", "do...while")}}
-
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
-
{{jsxref("Statements/for", "for")}}
-
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
-
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
-
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
-
{{jsxref("Statements/for...in", "for...in")}}
-
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
-
{{jsxref("Statements/for...of", "for...of")}}
-
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
-
{{jsxref("Statements/while", "while")}}
-
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
-
- -

Others

- -
-
{{jsxref("Statements/debugger", "debugger")}}
-
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
-
{{jsxref("Statements/export", "export")}}
-
Used to export functions to make them available for imports in external modules, another scripts.
-
{{jsxref("Statements/import", "import")}}
-
Used to import functions exported from an external module, another script.
-
{{jsxref("Statements/label", "label")}}
-
Provides a statement with an identifier that you can refer to using a break or continue statement.
-
- -
-
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
-
Extends the scope chain for a statement.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{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')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
- -

See also

- - diff --git a/files/vi/web/javascript/reference/statements/throw/index.html b/files/vi/web/javascript/reference/statements/throw/index.html deleted file mode 100644 index c3116c8847..0000000000 --- a/files/vi/web/javascript/reference/statements/throw/index.html +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: throw -slug: Web/JavaScript/Reference/Statements/throw -translation_of: Web/JavaScript/Reference/Statements/throw ---- -
{{jsSidebar("Statements")}}
- -

Câu lệnh throw  sẽ đưa ra một exception theo cách chúng ta định nghĩa. Các câu lệnh phía sau throw sẽ không được chạy, và sẽ gọi hàm callback catch đầu tiên tìm thấy. Nếu không có hàm catch, chương trình sẽ không chạy nữa.

- -
{{EmbedInteractiveExample("pages/js/statement-throw.html")}}
- - - -

Cú pháp

- -
throw expression; 
- -
-
expression
-
Một diễn giải.
-
- -

Giải thích

- -

Sử dụng câu lệnh throw để đưa ra một exception. Giá trị của expression trả về có thể string, number, boolean, hay Object. Mỗi câu throw chỉ trả về một exception

- -
throw 'Error2'; // 1 exception dạng string
-throw 42;       // 1 exception giá trị 42
-throw true;     // 1 exception với giá trị boolean là true
-throw new Error('Required');  // tạo một error object với nội dung Required
-
- -

Câu lệnh throw tuân thủ nguyên tắc automatic semicolon insertion (ASI) ,  nghĩa là không được phép xuống dòng giữa từ khóa throw và expression.

- -

Ví dụ

- -

Throw một object

- -

Exception có thể là một object. Lúc này có thể tham chiếu đến các property của object bên trong khối lệnh catch . Ví dụ sau, tạo một object với kiểu là UserException và sử dụng nó trong câu throw.

- -
function UserException(message) {
-   this.message = message;
-   this.name = 'UserException';
-}
-function getMonthName(mo) {
-   mo = mo - 1; // Thay đổi giá trị của index array tương ứng cho tháng (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 nằm ngoài giá trị cho phép
-   var monthName = getMonthName(myMonth);
-} catch (e) {
-   monthName = 'unknown';
-   console.log(e.message, e.name); // truyền exception object vào câu lệnh xử lý nếu có lỗi
-}
-
- -

Một ví dụ khác sử dụng  object

- -

Trong ví dụ sau, kiểm tra input, chỉ cho phép là giá trị U.S. zip code. Nếu giá trị zip code này không đúng format, throw một exception object là 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)) {
-      // giá trị zip code value sẽ là giá trị đầu tiên khớp trong 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;
-   };
-}
-
-/*
- * Đoạn script validate address theo kiểu 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 một exception

- -

Chúng ta có thể sử dụng throw để rethrow một exception sau khi đã catch nó. Trong ví dụ sau, catch lại exception nếu là giá trị lớn hơn 50 thì rethrow. Exception này sẽ được đưa lên hàm trên một cấp hoặc lên trên cùng cho các hàm catch khác.

- -
try {
-   throw n; // throws một exception với giá trị là số
-} catch (e) {
-   if (e <= 50) {
-      // câu lệnh xử lý cho exception từ 1-50
-   } else {
-      // không có xử lý cho trường hợp exception này, rethrow
-      throw e;
-   }
-}
-
- -

Specification

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Khởi tạo. Hiện thực trong 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')}} 
- -

Trình duyệt hổ trợ

- - - -

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

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/template_literals/index.html b/files/vi/web/javascript/reference/template_literals/index.html deleted file mode 100644 index 3626937740..0000000000 --- a/files/vi/web/javascript/reference/template_literals/index.html +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: Template literals (Template strings) -slug: Web/JavaScript/Reference/Template_literals -translation_of: Web/JavaScript/Reference/Template_literals ---- -
{{JsSidebar("More")}}
- -

Mẫu nguyên thủy là chuỗi string nguyên thủy cho phép áp dụng vào các biểu thức. Bạn có thể sử dụng các chuỗi nhiều dòng và các chuỗi chức năng nội suy với chúng. Chúng được gọi là "chuỗi mẫu" trong các phiên bản trước của đặc tả ES2015.

- -

Cú pháp

- -
`string text`
-
-`string text line 1
- string text line 2`
-
-`string text ${expression} string text`
-
-tag `string text ${expression} string text`
-
- -

Mô tả

- -

Mẫu nguyên thủy được đóng bởi dấu 'nháy-ngược' (` `)  (grave accent - nằm ở góc trái dưới phím Esc) thay vì sử dụng nháy đơn hoặc nháy kép. Mẫunguyên thủy có thể bao gồm placeholders (trong thẻ input có 1 thuộc tính placeholder). Chúng được biểu thị bằng ký hiệu đô la và dấu ngoặc nhọn (${expression}). Các biểu thức trong placeholders và văn bản giữa các dấu 'nháy-ngược' (` `) được đưa vào hàm. Hàm mặc định chỉ ghép các thành phần thành một chuỗi đơn. Nếu có một biểu thức thực hiện trước một mẫu nguyên thủy (tag - ở đây gọi là thẻ), thì được gọi là một "tagged template" (mẫu được gắn thẻ). Trong trường hợp này, biểu thức gắn thẻ (thường là một hàm) được gọi cùng với mẫu nguyên thủy, biểu thức mà sau đó bạn có thể thao tác trước khi trả ra kết quả. Để thoát dấu 'nháy-ngược' trong một mẫu nguyên thủy, hãy đặt dấu gạch chéo ngược \ trước dấu nháyngược (phần này nên note lại và cần tham khảo thêm các ví dụ sau).

- -
`\`` === '`' // --> true
- -

Các chuỗi nhiều dòng (chuỗi đa dòng)

- -

Bất kỳ các dòng ký tự mới được chèn vào trong nguồn (mã nguồn) đều là một phần của mẫu nguyên thủy. Việc sử dụng các chuỗi mặc định, bạn sẽ phải sử dụng các cú pháp dưới đây để có được các chuỗi đa dòng (sử dụng ký tự \n):

- -
console.log('string text line 1\n' +
-'string text line 2');
-// "string text line 1
-// string text line 2"
- -

Để có được kết quả tượng tự thì sử dụng cú pháp mẫu nguyên thủy, bạn có thể viết như sau:

- -
console.log(`string text line 1
-string text line 2`);
-// "string text line 1
-// string text line 2"
- -

Biểu thức nội suy

- -

Để nhúng các thiểu thức (hàm, phép tính, ...) vào trong chuỗi mặc định, bạn sẽ sử dụng cú pháp dưới đây:

- -
var a = 5;
-var b = 10;
-console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
-// "Fifteen is 15 and
-// not 20."
- -

Giờ đây, với các mẫu nguyên thủy, bạn có thể sử dụng các thay thế cú pháp như thế này để dễ đọc hơn:

- -
var a = 5;
-var b = 10;
-console.log(`Fifteen is ${a + b} and
-not ${2 * a + b}.`);
-// "Fifteen is 15 and
-// not 20."
- -

Các mẫu lồng nhau (mẫu nằm trong mẫu khác)

- -

Trong một số trường hợp nhất định, lồng một mẫu là cách dễ nhất và có thể dễ đọc hơn để có các chuỗi có khả năng cấu hình. Bên trong một mẫu được tạo, nó đơn giản để cho phép các dấu nháy ngược bên trong chỉ đơn giản bằng cách sử dụng chúng trong một placeholder ${ } bên trong mẫu. Ví dụ, nếu điều kiện đúng: thì trả về mẫu nguyên thủy.

- -

Trong ES5:

- -
var classes = 'header'
-classes += (isLargeScreen() ?
-   '' : item.isCollapsed ?
-     ' icon-expander' : ' icon-collapser');
-
- -

Trong ES2015 với mẫu nguyên thủy và không đặt lồng nhau:

- -
const classes = `header ${ isLargeScreen() ? '' :
-    (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`;
- -

Trong ES2015 với 2 mẫu nguyên thủy đặt lồng nhau:

- -
const classes = `header ${ isLargeScreen() ? '' :
- `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;
- -

Các mẫu được gắn thẻ

- -

Một hình thức nâng cao hơn của mẫu nguyên thủy là các mẫu được gắn thẻ. Các thẻ cho phép bạn chuyển đổi các mẫu nguyên thủy sử dụng hàm. Tham số đầu tiên của hàm gắn thẻ bao gồm một mảng các chuỗi. Các tham số còn lại được gắn với các biểu thức. Cuối cùng, hàm của bạn có thể trả về chuỗi được thao tác (hoặc nó có thể trả về bất kỳ kết quả gì theo mục đích lập trình trong ví dụ tiếp theo).  Tê của hàm được sử dụng cho thẻ bạn có thể đặt tên theo cách bạn muốn.

- -
var person = 'Mike';
-var age = 28;
-
-function myTag(strings, personExp, ageExp) {
-  var str0 = strings[0]; // "That "
-  var str1 = strings[1]; // " is a "
-
-  // There is technically a string after
-  // the final expression (in our example),
-  // but it is empty (""), so disregard.
-  // var str2 = strings[2];
-
-  var ageStr;
-  if (ageExp > 99){
-    ageStr = 'centenarian';
-  } else {
-    ageStr = 'youngster';
-  }
-
-  // We can even return a string built using a template literal
-  return `${str0}${personExp}${str1}${ageStr}`;
-}
-
-var output = myTag`That ${ person } is a ${ age }`;
-
-console.log(output);
-// That Mike is a youngster
- -

Các hàm gắn thẻ không cần trả về một chuỗi, như được hiển thị ở ví dụ dưới đây.

- -
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!"
-
- -

Các chuỗi chưa xử lý (chuỗi thô)

- -

thuộc tính raw khá đặc biệt, có thể trong tham số đầu tiên để gán thẻ hàm, nó cho phép bạn truy cập các chuỗi thô như khi chúng được đưa vào, không cần sử lý 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'
-
- -

Ngoài ra, phương thức {{jsxref("String.raw()")}} tồn tại để tạo các chuỗi thô giống như hàm mẫu mặc định và chuỗi nối.

- -
var str = String.raw`Hi\n${2+3}!`;
-// "Hi\n5!"
-
-str.length;
-// 6
-
-str.split('').join(',');
-// "H,i,\,n,5,!"
-
- -

Mẫu được gắn thẻ và trình tự thoát

- -

ES2016 behavior

- -

Trong ECMAScript 2016, các mẫu được gắn thẻ tuân theo quy tắc của các trình tự thoát sau đây:

- -
    -
  • Unicode escapes bắt đầu bởi  "\u", ví dụ \u00A9
  • -
  • Unicode code point escapes chỉ định bởi "\u{}", ví dụ \u{2F804}
  • -
  • Hexadecimal escapes bắt đầu bởi "\x", ví dụ \xA9
  • -
  • Octal nguyên thủy escapes bắt đầu bởi "\0o" và được gán thêm bằng một hay nhiều chữ số, ví dụ \0o251
  • -
- -

Điều này có nghĩa là một mẫu được gắn thẻ như sau là có vấn đề, bởi vì mỗi ngữ pháp ECMAScript, một phân tích trông như đúng trình tự Unicode escape:

- -
latex`\unicode`
-// Throws in older ECMAScript versions (ES2016 and earlier)
-// SyntaxError: malformed Unicode character escape sequence
- -

ES2018 sửa đổi các chuỗi thoát bất hợp pháp

- -

Các mẫu được gắn thẻ sẽ cho phép nhúng các ngôn ngữ (ví dụ DSLs, or LaTeX), trong đó các chuỗi thoát khác là phổ biến. ECMAScript đề xuất Template Literal Revision (giai đoạn 4, được tích hợp trong tiêu chuẩn ECMAScript 2018) xóa giới hạn cú pháp của chuỗi thoát ECMAScript khỏi các mẫu được gắn thẻ.

- -

Tuy nhiên, các chuỗi thoát bất hợp pháp vẫn phải được giữ lại. Chúng sẽ hiển thị như thành phần {{jsxref("undefined")}} trong mảng “cooked”:

- -
function latex(str) {
- return { "cooked": str[0], "raw": str.raw[0] }
-}
-
-latex`\unicode`
-
-// { cooked: undefined, raw: "\\unicode" }
- -

Chú ý rằng hạn chế trình tự thoát chỉ được loại bỏ khỏi các mẫu được gắn thẻ chứ không phải từ các mẫu chữ không được đánh dấu:

- -
let bad = `bad escape sequence: \unicode`;
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-template-literals', 'Template Literals')}}{{Spec2('ES2015')}}Initial definition. Defined in several section of the specification: Template Literals, Tagged Templates
{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}{{Spec2('ESDraft')}}Defined in several section of the specification: Template Literals, Tagged Templates
- -

Browser compatibility

- -
- - -

{{Compat("javascript.grammar.template_literals")}}

-
- -

See also

- - diff --git a/files/vi/web/reference/api/index.html b/files/vi/web/reference/api/index.html deleted file mode 100644 index 9701acb039..0000000000 --- a/files/vi/web/reference/api/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Tài liệu tham khảo Web API -slug: Web/Reference/API -translation_of: Web/Reference/API ---- -

Web cung cấp một loạt các API để thực hiện những công việc hữu ích khác nhau. Các API này có thể được truy cập bằng cách sử dụng mã JavaScript, cho phép bạn làm bất cứ điều gì trên Web, từ những điều chỉnh nhỏ cho tới bất kỳ {{domxref("window")}} hay là {{domxref("element")}}, để tạo ra những hiệu ứng đồ họa và âm thanh phức tạp với những API như WebGL và Web Audio.

- -

Mỗi giao diện cá nhân trên tất cả các API đã được liệt kê tại chỉ mục.

- -

Ngoài ra còn có một danh sách của tất cả các sự kiện có sẵn trong tài liệu tham khảo sự kiện.

- -
-
-
-
Document Object Model
-
DOM là một API cho phép truy cập và chỉnh sửa các tài liệu hiện hành. Nó cho phép thao tác tới {{domxref("Node")}} và {{domxref("Element")}} của tài liệu. HTML, XML và SVG đã mở rộng DOM để nó có thể thao tác được tới những phần tử cụ thể của chúng.
-
Những API thiết bị
-
Thiết lập từ những API này cho phép truy cập vào các tính năng phần cứng khác nhau có sẵn cho các trang Web và các phần mềm. Ví dụ: API cảm biến ánh sáng, API tình trạng pin, API định vị, API khóa con trỏ, API tiệm cận, API định hướng thiết bị, API định hướng màn hình, API rung.
-
Những API truyền tin
-
Là những API  để cho các trang Web và các ứng dụng có thể kết nối, giao tiếp với các trang khác hoặc các thiết bị khác. Ví dụ: API thông tin mạng, Thông báo Web (notifications), API đẩy đơn giản (push).
-
Những API quản lý dữ liệu
-
Dữ liệu người dùng có thể được lưu trữ và quản lý bằng cách sử dụng các thiết lập của các API. Ví dụ: API xử lý file (fileHandle), IndexedDB.
-
- -

Ngoài các API có sẵn cho bất kỳ trang Web hay ứng dụng nào, một tập các API mạnh hơn là có sẵn cho các ứng dụng đặc quyền và đã được chứng nhận.

- -
-
Những API đặc quyền
-
Một ứng dụng đặc quyền là một ứng dụng được cài đặt đã được trao quyền cụ thể từ người dùng. Các API đặc quyền bao gồm: TCP Socket API, API liên hệ, API lưu trữ dữ liệu, API trình duyệt, API máy ảnh.
-
Những API chứng nhận
-
Một ứng dụng chấng nhận là một ứng dụng cấp thấp thực hiện những hoạt động quan trọng trong một hệ điều hành như Firefox OS. Có ít các ứng dụng đặc quyền tương tác với các ứng dụng này thông qua Web Activities.  Các ứng dụng chứng nhận bao gồm: Bluetooth API, API kết nối di động, API thống kê số liệu mạng, gọi điện, WebSMS, API thông tin wifi, API quản lý năng lượng, API cài đặt, API không hoạt động, API quyền truy cập, API ngày giờ.
-
-
- -
-

Cộng đồng

- -

Tham gia cộng đồng Web API thông qua danh sách gửi thư hoặc nhóm thảo luận:

- - - -

Ngoài ra, hãy chắc chắn để tham gia vào các cuộc thảo luận trực tiếp ở kênh #webapi trên IRC.

- - - -

Những bài viết sau đây có thể sẽ thú vị:

- - -
-
- -

 

diff --git a/files/vi/web/reference/index.html b/files/vi/web/reference/index.html deleted file mode 100644 index 3e328a32a5..0000000000 --- a/files/vi/web/reference/index.html +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Web technology reference -slug: Web/Reference -tags: - - Landing - - NeedsTranslation - - Reference - - TopicStub - - Web -translation_of: Web/Reference ---- -

{{draft()}}
- The open Web is built using a number of technologies that require an adequate knowledge in order to use them. Below you'll find the links to our reference material for each of them.

- -

Web technologies

- -

It is recommended that you already got started with the web, however it isn't absolutely necessary.

- -
-
HTML — structuring the Web
-
The HyperText Markup Language is used to define and describe semantically the content (markup) of a Web page in a well-structured format.
- HTML provides a means to create structured documents, made up of blocks called HTML elements that are delineated by tags, written using angle brackets: some introduce content into the page directly, others provide information about document text and may include other tags as sub-elements. Obviously, browsers do not display them, since they are used to interpret the content of the page.
-
- Introduction to HTML | Learn HTML | HTML5 | Developer guide | Element reference | reference
-
CSS — styling the Web
-
The Cascading Style Sheets are used to describe the appearance of Web content.
-
- Introduction to CSS  | Getting started with CSS | Learn CSS | CSS3 | Developer guide | Common CSS questions | reference
-
diff --git a/files/vi/web/svg/index.html b/files/vi/web/svg/index.html deleted file mode 100644 index b342e1ceb9..0000000000 --- a/files/vi/web/svg/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: SVG -slug: Web/SVG -tags: - - 2D Graphics - - Graphics - - NeedsTranslation - - Reference - - SVG - - TopicStub - - Web - - 'l10n:priority' -translation_of: Web/SVG ---- -
Getting Started
-This tutorial will help get you started using SVG.
- -

Scalable Vector Graphics (SVG) is an XML-based markup language for describing two-dimensional vector graphics. SVG is essentially to graphics what HTML is to text.

- -

SVG is similar to Adobe's proprietary Flash technology, but it is a text-based open Web standard instead of a closed binary format. It is explicitly designed to work with other web standards such as CSS, DOM, and SMIL.

- -
-
-

Documentation

- -
-
SVG element reference
-
Details about each SVG element.
-
SVG attribute reference
-
Details about each SVG attribute.
-
SVG DOM interface reference
-
Details about the SVG DOM API, for interaction with JavaScript.
-
Applying SVG effects to HTML content
-
SVG works together with {{Glossary("HTML")}}, {{Glossary("CSS")}} and {{Glossary("JavaScript")}}. Use SVG to enhance a regular HTML page or web application.
-
- -

View All...

- -

Community

- -
    -
  • View Mozilla forums... {{DiscussionList("dev-tech-svg", "mozilla.dev.tech.svg")}}
  • -
- -

Tools

- - -
- -
- - - - -

Animation and interactions

- -

Like HTML, SVG has a document model (DOM) and events, and is accessible from JavaScript. This allows developers to create rich animations and interactive images.

- - - -

Mapping, charting, games & 3D experiments

- -

While a little SVG can go a long way to enhanced web content, here are some examples of heavy SVG usage.

- - -
-
diff --git a/files/vi/web/svg/tutorial/index.html b/files/vi/web/svg/tutorial/index.html deleted file mode 100644 index bc313966be..0000000000 --- a/files/vi/web/svg/tutorial/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: SVG Tutorial -slug: Web/SVG/Tutorial -tags: - - Intermediate - - NeedsContent - - NeedsHelp - - NeedsTranslation - - NeedsUpdate - - SVG - - 'SVG:Tutorial' - - TopicStub -translation_of: Web/SVG/Tutorial ---- -

Scalable Vector Graphics, SVG, is a W3C XML dialect to mark up graphics. It is partially implemented in Firefox, Opera, WebKit browsers, Internet Explorer and other browsers.

- -

This tutorial aims to explain the internals of SVG and is packed with technical details. If you just want to draw beautiful images, you might find more useful resources at Inkscape's documentation page. Another good introduction to SVG is provided by the W3C's SVG Primer.

- -
The tutorial is in an early stage of development. If you're able, please help out by chipping in and writing a paragraph or two. Extra points for writing a whole page!
- -
Introducing SVG from Scratch
- - - -

The following topics are more advanced and hence should get their own tutorials.

- -
Scripting SVG with JavaScript
- -

TBD

- -
SVG filters tutorial
- -

TBD

- -
Animations with SMIL in SVG
- -

TBD

- -
Creating fonts in SVG
- -

TBD

diff --git a/files/vi/web/svg/tutorial/svg_image_tag/index.html b/files/vi/web/svg/tutorial/svg_image_tag/index.html deleted file mode 100644 index 9b5c077b20..0000000000 --- a/files/vi/web/svg/tutorial/svg_image_tag/index.html +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: SVG image element -slug: Web/SVG/Tutorial/SVG_Image_Tag -translation_of: Web/SVG/Tutorial/SVG_Image_Tag ---- -

{{ PreviousNext("Web/SVG/Tutorial/SVG_Fonts", "Web/SVG/Tutorial/Tools_for_SVG") }}

- -

Element SVG {{ SVGElement("image") }} cho phép bạn hiển thị hình ảnh bên trong một object SVG:

- -

TRong ví dụ đơn giản này, một ảnh jpg được tham chiếu bởi một thuộc tính {{ SVGAttr("href") }} sẽ hiển thị bên trong một object SVG:

- -
<?xml version="1.0" standalone="no"?>
-<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
-  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
-<svg width="5cm" height="4cm" version="1.1"
-     xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink">
-	<image href="firefox.jpg" x="0" y="0" height="50px" width="50px"/>
-</svg>
- -

Đây là một vài điều quan trọng bạn cần lưu ý (được tham khảo từ W3 specs):

- -
    -
  • -

    Nếu bạn không đặt giá trị cho thuộc tính x hoặc y thì chúng sẽ có giá trị mặc định là 0.

    -
  • -
  • -

    Nếu bạn không đặt giá trị cho thuộc tính height hoặc width thì chúng sẽ có giá trị mặc định là 0.

    -
  • -
  • Nếu thuộc tính height hoặc width có có giá trị là 0, image sẽ không được render(không hiển thị).
  • -
- -

{{ PreviousNext("Web/SVG/Tutorial/SVG_Fonts", "Web/SVG/Tutorial/Tools_for_SVG") }}

diff --git a/files/vi/web/tutorials/index.html b/files/vi/web/tutorials/index.html deleted file mode 100644 index 8beb00b838..0000000000 --- a/files/vi/web/tutorials/index.html +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: Hướng dẫn -slug: Web/Tutorials -translation_of: Web/Tutorials ---- -

Những đường dẫn trong trang này sẽ đưa bạn đến với những hướng dẫn và các tài liệu luyện tập.Dù bạn vừa mới bắt đầu, đang học những bài vỡ lòng, hoặc là một nhà phát triển web kỳ cựu, bạn luôn có thể tìm được những tài nguyên hữu ích để làm tốt công việc của mình. Những tài nguyên này được tạo ra bởi những công ty luông hướng về tương lai và các nhà phát triển web.Họ là những người nắm giữ những ngôn ngữ mở và các bài thực hành phát triển web tốt nhất. Chính họ đã tài trợ và cho phép chuyển ngữ qua giấy phép nội dung mở và bản quyền miễn phí Creative Commons

- -

Cho những ai hoàn toàn mới với Web

- -
-
Làm quen với Web
-
Làm quen với Web là một chuỗi các bài viết xúc tích, thực tế giới thiệu về phát triển web. Bạn sẽ thiết đặt các công cụ cần thiết để xây dựng một trang web và chạy những dòng code đơn giản
-
- -

HTML Tutorials

- -

Cấp độ nhập môn

- -
-
-
-
Giới thiệu về HTML
-
Đây là bước nền tảng, giúp bạn làm quen với các khái niệm và cú pháp, cách áp dụng HTML vào văn bản, tạo những siêu dẫn , và cách sử dụng HTML để cấu trúc một trang web
-
-
- -
-
-
MDN Danh sách phần tử HTML
-
Một danh sách phần tử HTML hoàn chỉnh và cách các trình duyệt khác nhau hỗ trợ chúng
-
Tạo một Trang Web đơn giản với HTML(The Blog Starter)
-
An HTML guide for beginners that includes explanations of common tags, including HTML5 tags. Also includes a step-by-step guide to creating a basic web page with code examples.
-
HTML Challenges (Wikiversity)
-
Sử dụng những thử thách này để mài dũa kỹ năng HTML của bạn (Ví dụ, "Tôi có nên dùng phần tử <h2>  hay một phần tử <strong>?"), hãy sử dụng chúng có chủ ý.
-
-
-
- -

Intermediate level

- -
-
-
-
Multimedia and embedding
-
This module explores how to use HTML to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire other webpages.
-
-
- -
-
-
 
-
HTML tables
-
Representing tabular data on a webpage in an understandable, {{glossary("Accessibility", "accessible")}} way can be a challenge. This module covers basic table markup, along with more complex features such as implementing captions and summaries.
-
-
-
- -

Advanced level

- -
-
-
-
HTML forms
-
Forms are a very important part of the Web — these provide much of the functionality you need for interacting with web sites, e.g. registering and logging in, sending feedback, buying products, and more. This module gets you started with creating the client-side parts of forms.
-
Tips for authoring fast-loading HTML pages
-
Optimize web pages to provide a more responsive site for visitors and reduce the load on your web server and Internet connection.
-
-
-
- -

CSS Tutorials

- -

Introductory level

- -
-
-
-
CSS basics
-
CSS (Cascading Style Sheets) is the code you use to style your webpage. CSS Basics takes you through what you need to get started. We'll answer questions like: How do I make my text black or red? How do I make my content show up in such-and-such a place on the screen? How do I decorate my webpage with background images and colors?
-
Introduction to CSS
-
This module goes in depth with how CSS works, including selectors and properties, writing CSS rules, applying CSS to HTML, how to specify length, color, and other units in CSS, cascade and inheritance, box model basics, and debugging CSS.
-
-
- -
-
-
Styling boxes
-
Next up, we look at styling boxes, one of the fundamental steps towards laying out a web page. In this module we recap the box model then look at controlling box layouts by setting padding, borders and margins, setting custom background colors, images and other features, and fancy features such as drop shadows and filters on boxes.
-
Styling text
-
Here we look at text styling fundamentals, including setting font, boldness, and italics, line and letter spacing, and drop shadows and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links.
-
Common CSS Questions
-
Common questions and answers for beginners.
-
-
-
- -

Intermediate level

- -
-
-
-
CSS layout
-
At this point we've already looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it's time to look at how to place your boxes in the right place in relation to the viewport, and one another. We have covered the necessary prerequisites so can now dive deep into CSS layout, looking at different display settings, traditional layout methods involving float and positioning, and new fangled layout tools like flexbox.
-
CSS reference
-
Complete reference to CSS, with details on support by Firefox and other browsers.
-
-
- -
-
-
Fluid Grids (A List Apart)
-
Design layouts that fluidly resize with the browser window, while still using a typographic grid.
-
CSS Challenges (Wikiversity)
-
Flex your CSS skills, and see where you need more practice.
-
-
-
- -

Advanced level

- -
-
-
-
Using CSS transforms
-
Apply rotation, skewing, scaling, and translation using CSS.
-
CSS transitions
-
CSS transitions, part of the draft CSS3 specification, provide a way to animate changes to CSS properties, instead of having the changes take effect instantly.
-
-
- -
-
-
Quick Guide to Implement Web Fonts with @font-face (HTML5 Rocks)
-
The @font-face feature from CSS3 allows you to use custom typefaces on the web in an accessible, manipulatable, and scalable way.
-
Starting to Write CSS (David Walsh)
-
An introduction to tools and methodologies to write more succinct, maintainable, and scalable CSS.
-
-
-
- -
-
-
Canvas tutorial
-
Learn how to draw graphics using scripting using the canvas element.
-
HTML5 Doctor
-
Articles about using HTML5 right now.
-
-
- -

Javascript Tutorials

- -

Introductory level

- -
-
-
-
 
-
JavaScript first steps
-
In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key JavaScript features in detail, such as variables, strings, numbers and arrays.
-
JavaScript building blocks
-
In this module, we continue our coverage of all JavaScript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional statements, loops, functions, and events. You've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly.
-
-
- -
-
-
Getting started with JavaScript
-
What is JavaScript and how can it help you?
-
Codecademy (Codecademy)
-
Codecademy is a easy way to learn how to code JavaScript. It's interactive and you can do it with your friends.
-
-
-
- -

Intermediate level

- -
-
-
-
Introducing JavaScript objects
-
In JavaScript, most things are objects, from core JavaScript features like strings and arrays to the browser APIs built on top of JavaScript. You can even create your own objects to encapsulate related functions and variables into efficient packages. The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, look at how to create your own objects, and explain what JSON data is and how to work with it.
-
Client-side web APIs
-
When writing client-side JavaScript for web sites or applications, you won't go very far before you start to use APIs — interfaces for manipulating different aspects of the browser and operating system the site is running on, or even data from other web sites or services. In this module we will explore what APIs are, and how to use some of the most common APIs you'll come across often in your development work. 
-
-
- -
-
-
A re-Introduction to JavaScript
-
A recap of the JavaScript programming language aimed at intermediate-level developers.
-
Eloquent JavaScript
-
A comprehensive guide to intermediate and advanced JavaScript methodologies.
-
Speaking JavaScript (Dr. Axel Rauschmayer)
-
For programmers who want to learn JavaScript quickly and properly, and for JavaScript programmers who want to deepen their skills and/or look up specific topics.
-
Essential JavaScript Design Patterns (Addy Osmani)
-
An introduction to essential JavaScript design patterns.
-
-
-
- -

Advanced level

- -
-
-
-
JavaScript Guide
-
A comprehensive, regularly updated guide to JavaScript for all levels of learning from beginner to advanced.
-
You Don't Know JS (Kyle Simpson)
-
A series of books diving deep into the core mechanisms of the JavaScript language.
-
JavaScript Garden
-
Documentation of the most quirky parts of JavaScript.
-
Exploring ES6 (Dr. Axel Rauschmayer)
-
Reliable and in-depth information on ECMAScript 2015.
-
-
- -
Javascipt Patterns - -
-
A JavaScript pattern and antipattern collection that covers function patterns, jQuery patterns, jQuery plugin patterns, design patterns, general patterns, literals and constructor patterns, object creation patterns, code reuse patterns, DOM.
-
How browsers work
-
A detailed research article describing different modern browsers, their engines, page rendering etc.
-
JavaScript Videos (GitHub)
-
A collection of JavaScript videos to watch.
-
-
-
- -

Extension Development

- -
-
-
-
WebExtensions
-
WebExtensions is a cross-browser system for developing browser add-ons. To a large extent the system is compatible with the extension API supported by Google Chrome and Opera. Extensions written for these browsers will in most cases run in Firefox or Microsoft Edge with just a few changes. The API is also fully compatible with multiprocess Firefox.
-
-
-
-- cgit v1.2.3-54-g00ecf