From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../reference/classes/costruttore/index.html | 161 ++++++ .../reference/classes/extends/index.html | 175 ++++++ .../it/web/javascript/reference/classes/index.html | 270 +++++++++ .../javascript/reference/classes/static/index.html | 70 +++ .../it/web/javascript/reference/errors/index.html | 31 ++ .../errors/invalid_array_length/index.html | 77 +++ .../invalid_assignment_left-hand_side/index.html | 54 ++ .../missing_semicolon_before_statement/index.html | 78 +++ .../reference/errors/too_much_recursion/index.html | 72 +++ .../reference/errors/unexpected_token/index.html | 50 ++ .../reference/errors/unexpected_type/index.html | 67 +++ .../arguments/index.html | 224 ++++++++ .../arrow_functions/index.html | 394 +++++++++++++ .../functions_and_function_scope/get/index.html | 154 +++++ .../functions_and_function_scope/index.html | 617 +++++++++++++++++++++ .../functions_and_function_scope/set/index.html | 214 +++++++ .../global_objects/array/concat/index.html | 188 +++++++ .../global_objects/array/copywithin/index.html | 180 ++++++ .../global_objects/array/entries/index.html | 77 +++ .../global_objects/array/every/index.html | 184 ++++++ .../reference/global_objects/array/fill/index.html | 155 ++++++ .../global_objects/array/filter/index.html | 245 ++++++++ .../reference/global_objects/array/find/index.html | 216 ++++++++ .../global_objects/array/findindex/index.html | 182 ++++++ .../reference/global_objects/array/flat/index.html | 159 ++++++ .../global_objects/array/flatmap/index.html | 142 +++++ .../global_objects/array/foreach/index.html | 331 +++++++++++ .../reference/global_objects/array/from/index.html | 242 ++++++++ .../global_objects/array/includes/index.html | 162 ++++++ .../reference/global_objects/array/index.html | 480 ++++++++++++++++ .../global_objects/array/indexof/index.html | 226 ++++++++ .../global_objects/array/isarray/index.html | 133 +++++ .../reference/global_objects/array/join/index.html | 112 ++++ .../reference/global_objects/array/keys/index.html | 74 +++ .../global_objects/array/lastindexof/index.html | 169 ++++++ .../global_objects/array/length/index.html | 129 +++++ .../reference/global_objects/array/map/index.html | 323 +++++++++++ .../reference/global_objects/array/of/index.html | 92 +++ .../reference/global_objects/array/pop/index.html | 117 ++++ .../global_objects/array/prototype/index.html | 203 +++++++ .../reference/global_objects/array/push/index.html | 142 +++++ .../global_objects/array/reduce/index.html | 576 +++++++++++++++++++ .../global_objects/array/reverse/index.html | 133 +++++ .../global_objects/array/slice/index.html | 241 ++++++++ .../reference/global_objects/array/some/index.html | 202 +++++++ .../reference/global_objects/array/sort/index.html | 267 +++++++++ .../global_objects/array/splice/index.html | 163 ++++++ .../global_objects/array/tostring/index.html | 80 +++ .../global_objects/array/unshift/index.html | 98 ++++ .../global_objects/array/values/index.html | 87 +++ .../global_objects/arraybuffer/index.html | 147 +++++ .../reference/global_objects/atomics/index.html | 166 ++++++ .../global_objects/atomics/store/index.html | 91 +++ .../global_objects/date/getdate/index.html | 78 +++ .../global_objects/date/getday/index.html | 89 +++ .../global_objects/date/getfullyear/index.html | 84 +++ .../global_objects/date/gethours/index.html | 79 +++ .../global_objects/date/getmilliseconds/index.html | 77 +++ .../global_objects/date/getminutes/index.html | 77 +++ .../global_objects/date/getmonth/index.html | 90 +++ .../global_objects/date/getseconds/index.html | 79 +++ .../global_objects/date/gettime/index.html | 125 +++++ .../date/gettimezoneoffset/index.html | 99 ++++ .../reference/global_objects/date/index.html | 249 +++++++++ .../reference/global_objects/date/now/index.html | 96 ++++ .../reference/global_objects/date/utc/index.html | 135 +++++ .../reference/global_objects/decodeuri/index.html | 120 ++++ .../global_objects/decodeuricomponent/index.html | 124 +++++ .../reference/global_objects/encodeuri/index.html | 160 ++++++ .../global_objects/encodeuricomponent/index.html | 162 ++++++ .../reference/global_objects/escape/index.html | 126 +++++ .../reference/global_objects/eval/index.html | 231 ++++++++ .../global_objects/function/apply/index.html | 250 +++++++++ .../global_objects/function/arguments/index.html | 92 +++ .../global_objects/function/arity/index.html | 26 + .../global_objects/function/bind/index.html | 277 +++++++++ .../global_objects/function/call/index.html | 175 ++++++ .../reference/global_objects/function/index.html | 237 ++++++++ .../global_objects/function/length/index.html | 87 +++ .../reference/global_objects/generator/index.html | 187 +++++++ .../global_objects/generator/next/index.html | 157 ++++++ .../javascript/reference/global_objects/index.html | 182 ++++++ .../reference/global_objects/infinity/index.html | 114 ++++ .../reference/global_objects/isfinite/index.html | 136 +++++ .../reference/global_objects/isnan/index.html | 176 ++++++ .../reference/global_objects/json/index.html | 244 ++++++++ .../reference/global_objects/json/parse/index.html | 126 +++++ .../global_objects/json/stringify/index.html | 325 +++++++++++ .../reference/global_objects/map/clear/index.html | 76 +++ .../reference/global_objects/map/delete/index.html | 74 +++ .../global_objects/map/foreach/index.html | 88 +++ .../reference/global_objects/map/index.html | 439 +++++++++++++++ .../reference/global_objects/math/abs/index.html | 95 ++++ .../reference/global_objects/math/acos/index.html | 94 ++++ .../reference/global_objects/math/atan/index.html | 100 ++++ .../reference/global_objects/math/atan2/index.html | 155 ++++++ .../reference/global_objects/math/ceil/index.html | 161 ++++++ .../reference/global_objects/math/e/index.html | 79 +++ .../reference/global_objects/math/floor/index.html | 158 ++++++ .../reference/global_objects/math/index.html | 208 +++++++ .../reference/global_objects/math/max/index.html | 145 +++++ .../reference/global_objects/math/min/index.html | 160 ++++++ .../reference/global_objects/math/pow/index.html | 151 +++++ .../global_objects/math/random/index.html | 107 ++++ .../reference/global_objects/math/round/index.html | 100 ++++ .../reference/global_objects/math/sqrt/index.html | 136 +++++ .../reference/global_objects/nan/index.html | 79 +++ .../reference/global_objects/null/index.html | 89 +++ .../reference/global_objects/number/index.html | 188 +++++++ .../global_objects/object/assign/index.html | 268 +++++++++ .../global_objects/object/create/index.html | 234 ++++++++ .../object/defineproperties/index.html | 224 ++++++++ .../global_objects/object/freeze/index.html | 210 +++++++ .../object/getprototypeof/index.html | 130 +++++ .../object/hasownproperty/index.html | 164 ++++++ .../reference/global_objects/object/index.html | 224 ++++++++ .../reference/global_objects/object/is/index.html | 130 +++++ .../global_objects/object/isfrozen/index.html | 184 ++++++ .../global_objects/object/issealed/index.html | 146 +++++ .../global_objects/object/keys/index.html | 167 ++++++ .../global_objects/object/observe/index.html | 189 +++++++ .../global_objects/object/prototype/index.html | 214 +++++++ .../global_objects/object/seal/index.html | 157 ++++++ .../global_objects/object/tostring/index.html | 170 ++++++ .../reference/global_objects/parsefloat/index.html | 139 +++++ .../reference/global_objects/parseint/index.html | 190 +++++++ .../global_objects/promise/all/index.html | 110 ++++ .../global_objects/promise/catch/index.html | 124 +++++ .../reference/global_objects/promise/index.html | 248 +++++++++ .../global_objects/proxy/handler/apply/index.html | 119 ++++ .../global_objects/proxy/handler/index.html | 83 +++ .../reference/global_objects/proxy/index.html | 396 +++++++++++++ .../global_objects/proxy/revocabile/index.html | 86 +++ .../global_objects/set/entries/index.html | 113 ++++ .../reference/global_objects/set/index.html | 394 +++++++++++++ .../reference/global_objects/set/values/index.html | 114 ++++ .../global_objects/string/charat/index.html | 247 +++++++++ .../global_objects/string/includes/index.html | 188 +++++++ .../reference/global_objects/string/index.html | 410 ++++++++++++++ .../global_objects/string/indexof/index.html | 151 +++++ .../global_objects/string/length/index.html | 90 +++ .../global_objects/string/prototype/index.html | 178 ++++++ .../reference/global_objects/string/raw/index.html | 108 ++++ .../reference/global_objects/symbol/index.html | 230 ++++++++ .../reference/global_objects/undefined/index.html | 173 ++++++ .../reference/global_objects/unescape/index.html | 124 +++++ .../reference/global_objects/uneval/index.html | 112 ++++ files/it/web/javascript/reference/index.html | 49 ++ .../operators/destructuring_assignment/index.html | 451 +++++++++++++++ .../javascript/reference/operators/in/index.html | 198 +++++++ .../web/javascript/reference/operators/index.html | 282 ++++++++++ .../javascript/reference/operators/new/index.html | 186 +++++++ .../operators/operator_condizionale/index.html | 171 ++++++ .../operators/operatore_virgola/index.html | 105 ++++ .../operators/operatori_aritmetici/index.html | 291 ++++++++++ .../reference/operators/spread_syntax/index.html | 257 +++++++++ .../reference/operators/super/index.html | 181 ++++++ .../javascript/reference/operators/this/index.html | 410 ++++++++++++++ .../reference/operators/yield/index.html | 163 ++++++ .../reference/statements/break/index.html | 130 +++++ .../reference/statements/empty/index.html | 102 ++++ .../reference/statements/export/index.html | 259 +++++++++ .../reference/statements/for...of/index.html | 264 +++++++++ .../reference/statements/function_star_/index.html | 280 ++++++++++ .../reference/statements/import/index.html | 167 ++++++ .../web/javascript/reference/statements/index.html | 131 +++++ .../javascript/reference/statements/let/index.html | 208 +++++++ .../reference/statements/switch/index.html | 320 +++++++++++ .../reference/statements/throw/index.html | 195 +++++++ .../javascript/reference/statements/var/index.html | 221 ++++++++ .../reference/template_strings/index.html | 210 +++++++ 171 files changed, 29744 insertions(+) create mode 100644 files/it/web/javascript/reference/classes/costruttore/index.html create mode 100644 files/it/web/javascript/reference/classes/extends/index.html create mode 100644 files/it/web/javascript/reference/classes/index.html create mode 100644 files/it/web/javascript/reference/classes/static/index.html create mode 100644 files/it/web/javascript/reference/errors/index.html create mode 100644 files/it/web/javascript/reference/errors/invalid_array_length/index.html create mode 100644 files/it/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html create mode 100644 files/it/web/javascript/reference/errors/missing_semicolon_before_statement/index.html create mode 100644 files/it/web/javascript/reference/errors/too_much_recursion/index.html create mode 100644 files/it/web/javascript/reference/errors/unexpected_token/index.html create mode 100644 files/it/web/javascript/reference/errors/unexpected_type/index.html create mode 100644 files/it/web/javascript/reference/functions_and_function_scope/arguments/index.html create mode 100644 files/it/web/javascript/reference/functions_and_function_scope/arrow_functions/index.html create mode 100644 files/it/web/javascript/reference/functions_and_function_scope/get/index.html create mode 100644 files/it/web/javascript/reference/functions_and_function_scope/index.html create mode 100644 files/it/web/javascript/reference/functions_and_function_scope/set/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/copywithin/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/entries/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/every/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/fill/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/filter/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/findindex/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/flat/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/flatmap/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/foreach/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/indexof/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/keys/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/lastindexof/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/length/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/prototype/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/push/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/reduce/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/some/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/sort/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/tostring/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/it/web/javascript/reference/global_objects/array/values/index.html create mode 100644 files/it/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/it/web/javascript/reference/global_objects/atomics/index.html create mode 100644 files/it/web/javascript/reference/global_objects/atomics/store/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getdate/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getday/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getfullyear/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/gethours/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getmilliseconds/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getminutes/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getmonth/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/getseconds/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/gettime/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/it/web/javascript/reference/global_objects/date/utc/index.html create mode 100644 files/it/web/javascript/reference/global_objects/decodeuri/index.html create mode 100644 files/it/web/javascript/reference/global_objects/decodeuricomponent/index.html create mode 100644 files/it/web/javascript/reference/global_objects/encodeuri/index.html create mode 100644 files/it/web/javascript/reference/global_objects/encodeuricomponent/index.html create mode 100644 files/it/web/javascript/reference/global_objects/escape/index.html create mode 100644 files/it/web/javascript/reference/global_objects/eval/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/arguments/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/arity/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/bind/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/index.html create mode 100644 files/it/web/javascript/reference/global_objects/function/length/index.html create mode 100644 files/it/web/javascript/reference/global_objects/generator/index.html create mode 100644 files/it/web/javascript/reference/global_objects/generator/next/index.html create mode 100644 files/it/web/javascript/reference/global_objects/index.html create mode 100644 files/it/web/javascript/reference/global_objects/infinity/index.html create mode 100644 files/it/web/javascript/reference/global_objects/isfinite/index.html create mode 100644 files/it/web/javascript/reference/global_objects/isnan/index.html create mode 100644 files/it/web/javascript/reference/global_objects/json/index.html create mode 100644 files/it/web/javascript/reference/global_objects/json/parse/index.html create mode 100644 files/it/web/javascript/reference/global_objects/json/stringify/index.html create mode 100644 files/it/web/javascript/reference/global_objects/map/clear/index.html create mode 100644 files/it/web/javascript/reference/global_objects/map/delete/index.html create mode 100644 files/it/web/javascript/reference/global_objects/map/foreach/index.html create mode 100644 files/it/web/javascript/reference/global_objects/map/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/abs/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/acos/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/atan/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/atan2/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/e/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/floor/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/max/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/min/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/pow/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/random/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/round/index.html create mode 100644 files/it/web/javascript/reference/global_objects/math/sqrt/index.html create mode 100644 files/it/web/javascript/reference/global_objects/nan/index.html create mode 100644 files/it/web/javascript/reference/global_objects/null/index.html create mode 100644 files/it/web/javascript/reference/global_objects/number/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/create/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/defineproperties/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/freeze/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/hasownproperty/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/is/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/isfrozen/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/issealed/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/keys/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/observe/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/prototype/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/seal/index.html create mode 100644 files/it/web/javascript/reference/global_objects/object/tostring/index.html create mode 100644 files/it/web/javascript/reference/global_objects/parsefloat/index.html create mode 100644 files/it/web/javascript/reference/global_objects/parseint/index.html create mode 100644 files/it/web/javascript/reference/global_objects/promise/all/index.html create mode 100644 files/it/web/javascript/reference/global_objects/promise/catch/index.html create mode 100644 files/it/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/it/web/javascript/reference/global_objects/proxy/handler/apply/index.html create mode 100644 files/it/web/javascript/reference/global_objects/proxy/handler/index.html create mode 100644 files/it/web/javascript/reference/global_objects/proxy/index.html create mode 100644 files/it/web/javascript/reference/global_objects/proxy/revocabile/index.html create mode 100644 files/it/web/javascript/reference/global_objects/set/entries/index.html create mode 100644 files/it/web/javascript/reference/global_objects/set/index.html create mode 100644 files/it/web/javascript/reference/global_objects/set/values/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/charat/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/includes/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/length/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/prototype/index.html create mode 100644 files/it/web/javascript/reference/global_objects/string/raw/index.html create mode 100644 files/it/web/javascript/reference/global_objects/symbol/index.html create mode 100644 files/it/web/javascript/reference/global_objects/undefined/index.html create mode 100644 files/it/web/javascript/reference/global_objects/unescape/index.html create mode 100644 files/it/web/javascript/reference/global_objects/uneval/index.html create mode 100644 files/it/web/javascript/reference/index.html create mode 100644 files/it/web/javascript/reference/operators/destructuring_assignment/index.html create mode 100644 files/it/web/javascript/reference/operators/in/index.html create mode 100644 files/it/web/javascript/reference/operators/index.html create mode 100644 files/it/web/javascript/reference/operators/new/index.html create mode 100644 files/it/web/javascript/reference/operators/operator_condizionale/index.html create mode 100644 files/it/web/javascript/reference/operators/operatore_virgola/index.html create mode 100644 files/it/web/javascript/reference/operators/operatori_aritmetici/index.html create mode 100644 files/it/web/javascript/reference/operators/spread_syntax/index.html create mode 100644 files/it/web/javascript/reference/operators/super/index.html create mode 100644 files/it/web/javascript/reference/operators/this/index.html create mode 100644 files/it/web/javascript/reference/operators/yield/index.html create mode 100644 files/it/web/javascript/reference/statements/break/index.html create mode 100644 files/it/web/javascript/reference/statements/empty/index.html create mode 100644 files/it/web/javascript/reference/statements/export/index.html create mode 100644 files/it/web/javascript/reference/statements/for...of/index.html create mode 100644 files/it/web/javascript/reference/statements/function_star_/index.html create mode 100644 files/it/web/javascript/reference/statements/import/index.html create mode 100644 files/it/web/javascript/reference/statements/index.html create mode 100644 files/it/web/javascript/reference/statements/let/index.html create mode 100644 files/it/web/javascript/reference/statements/switch/index.html create mode 100644 files/it/web/javascript/reference/statements/throw/index.html create mode 100644 files/it/web/javascript/reference/statements/var/index.html create mode 100644 files/it/web/javascript/reference/template_strings/index.html (limited to 'files/it/web/javascript/reference') diff --git a/files/it/web/javascript/reference/classes/costruttore/index.html b/files/it/web/javascript/reference/classes/costruttore/index.html new file mode 100644 index 0000000000..afc6c44526 --- /dev/null +++ b/files/it/web/javascript/reference/classes/costruttore/index.html @@ -0,0 +1,161 @@ +--- +title: costruttore +slug: Web/JavaScript/Reference/Classes/costruttore +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +
{{jsSidebar("Classes")}}
+ +

Il metodo constructor è un metodo speciale usato per la creazione e l'inizializzazione di un oggetto creato da  una classe.

+ +

Sintassi

+ +
constructor([argomenti]) { ... }
+ +

Descrizione

+ +

In una classe ci può essere un solo metodo con il nome "constructor". Se una classe contiene una o più occorrenze del metodo constructor viene sollevato un errore di tipo {{jsxref("SyntaxError")}}. 

+ +

Un costruttore può usare la keyword super per chiamare il costruttore di una classe genitore.

+ +

Se non viene specificato un metodo constructor, verrà usato quello di default.

+ +

Esempi

+ +

Usare il metodo constructor

+ +

Questo pezzo di codice è stato preso da classes sample (live demo).

+ +
class Square extends Polygon {
+  constructor(length) {
+    // Chiama il costruttore della classe padre usando lo stesso valore length
+    // come altezza e come larghezza del Poligono
+    super(length, length);
+    // Nota: Nelle classi derivate, super() deve essere chiamato prima
+    // dell'utilizzo di 'this', altrimenti viene sollevato un reference error.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.area = value;
+  }
+}
+ +

Costruttori predefinito

+ +

Se non viene specificato un metodo costruttore, verrà usato quello di default. Per le classi base il costruttore di default è:

+ +
constructor() {}
+
+ +

Per le classi derivate invece è:

+ +
constructor(...args) {
+  super(...args);
+}
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES6', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto Base{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Costruttore predefinito{{CompatUnknown}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome per Android
Supporto Base{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
Costruttore predefinito{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/classes/extends/index.html b/files/it/web/javascript/reference/classes/extends/index.html new file mode 100644 index 0000000000..ccf0cab627 --- /dev/null +++ b/files/it/web/javascript/reference/classes/extends/index.html @@ -0,0 +1,175 @@ +--- +title: extends +slug: Web/JavaScript/Reference/Classes/extends +translation_of: Web/JavaScript/Reference/Classes/extends +--- +
{{jsSidebar("Classi")}}
+ +

La parola chiave extends è utilizzata nella dichiarazione o espressione di classe per creare una classe figlia di un'altra classe.

+ +

Sintassi

+ +
class ChildClass extends ParentClass { ... }
+
+/**
+*@desc La classe ChildClass estende la classe ParentClass
+*/
+
+ +

Descrizione

+ +

La parola chiave extends può essere utilizzata per creare una sottoclasse personalizzata basandosi su classi già esistenti e anche su oggetti nativi (cfr. Date object).

+ +

Il .prototype dell'estensione deve essere un {{jsxref("Object")}} oppure {{jsxref("null")}}.

+ +

Esempi

+ +

Utilizzare extends

+ +

Il primo esempio crea una classe chiamata Square dalla classe chiamata Polygon. Questo esempio è estratto da questo demo live (sorgente).

+ +

 

+ +
class Square extends Polygon {
+  constructor(length) {
+    // Qui chiama il constructor della classe che estende (parent)
+    // con le misure per la larghezza e altezza del poligono
+    super(length, length);
+    // Nota: In classi derivate, super() deve essere chiamato prima
+    // di poter utilizzare 'this', altrimenti causerà un errore di reference.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.height = this.width = Math.sqrt(value);
+    this.area = value;
+  }
+}
+ +

Utilizzare extends con oggetti nativi

+ +

Questo esempio estende l'oggetto nativo {{jsxref("Date")}}. Questo esempio è estratto da questo demo live (sorgente).

+ +
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();
+  }
+}
+ +

Estendere null

+ +

Estendere da {{jsxref("null")}} funziona come di norma, eccetto che l'oggetto prototipo non eredita da {{jsxref("Object.prototype")}}.

+ +
class nullExtends extends null {
+  constructor() {}
+}
+
+Object.getPrototypeOf(nullExtends); // Function.prototype
+Object.getPrototypeOf(nullExtends.prototype) // null
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-class-definitions', 'extends')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Array subclassing{{CompatChrome(43.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
Array subclassing{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/classes/index.html b/files/it/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..6b600be205 --- /dev/null +++ b/files/it/web/javascript/reference/classes/index.html @@ -0,0 +1,270 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +tags: + - Classes + - ECMAScript6 + - Experimental + - Inheritance + - Intermediate + - JavaScript + - NeedsContent + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Classes +--- +
{{JsSidebar("Classes")}}
+ +

Le classi JavaScript, introdotte in ECMAScript 2015, sono principalmente zucchero sintattico sull'esistente ereditarietà prototipale di JavaScript. La sintassi non introduce un nuovo modello di eredità orientata agli oggetti in JavaScript.

+ +

Definizione classi

+ +

Le classi sono di fatto delle "funzioni speciali", e così come puoi definire function expressions e function declarations, la sintassi per la classe ha due componenti: class expressionsclass declarations.

+ +

Dichiarazione classe

+ +

Un modo per definire una classe è quello di dichiararla. Per dichiarare una classe, usa la keyword class seguito dal nome della classe (in questo caso "Polygon").

+ +
class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

Hoisting

+ +

Un'importante differenza tra la dichiarazione di una funzione e la dichiarazione di una classe è che le dichiarazioni di funzione sono {{Glossary("Hoisting", "hoisted")}} mentre quelle per le classi no. Bisogna dichiarare la classe e poi si può usarla, altrimenti il codice solleva un'eccezione {{jsxref("ReferenceError")}}:

+ +
var p = new Polygon(); // ReferenceError
+
+class Polygon {}
+
+ +

Class expressions

+ +

Una class expression è un altro modo di definire una classe. In questo caso possono avere un nome o meno. Il nome dato è locale al corpo della classe.

+ +
// unnamed
+var Polygon = class {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+
+// named
+var Polygon = class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+
+ +

Nota: anche le Class expressions soffrono degli stessi problemi di hoisting menzionati per le dichiarazioni di Classi.

+ +

Corpo della classe e definizione dei metodi

+ +

Il corpo di una classe è la parte inclusa tra le parentesi graffe {}. Qui si definiscono i membri della classe come il costruttore o i metodi.

+ +

Strict mode

+ +

I corpi di class declarations e class expression sono eseguiti in strict mode.

+ +

Costruttore

+ +

Il costruttore è un metodo speciale usato per creare ed inizializzare un oggetto. Ci può essere un solo metodo con il nome "constructor" in una classe. Se la classe contiene più di un'occorrenza del costruttore verrà sollevato un {{jsxref("SyntaxError")}}.

+ +

Un costruttore può usare la parola chiave super per richiamare il costruttore della classe padre.

+ +

Prototipi

+ +

Guarda anche method definitions.

+ +
class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+
+  get area() {
+    return this.calcArea()
+  }
+
+  calcArea() {
+    return this.height * this.width;
+  }
+}
+ +

Metodi statici

+ +

La parola chiave static definisce un metodo statico. I metodi statici sono chiamati senza istanziare la loro classe e non possono essere chiamati su una classe istanziata. Vengono usati per creare funzioni di utilità.

+ +
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.sqrt(dx*dx + dy*dy);
+    }
+}
+
+const p1 = new Point(5, 5);
+const p2 = new Point(10, 10);
+
+console.log(Point.distance(p1, p2));
+ +

Inscatolamento con metodi prototipo e statico

+ +

Quando un metodo statico o prototipo è chiamato senza un oggetto valutato "this", allora il valore di "this" sarà undefined all'interno della funzione chiamata. L'autoinscatolamento non succederà. Il comportamento sarà lo stesso perfino se scriviamo il codice in modalità non-strict perché tutte le funzioni, metodi, costruttori, getter o setter sono eseguiti in modo strict. Così se non specifichiamo il valore this, allora sarà 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
+ +

Se scriviamo il codice soprascritto usando le tradizionali classi basate su funzioni, allora l'autoinscatolamento accadrà basato sul valore "this" peril quale la funzione è stata chiamata.

+ +
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
+ +

Sottoclassi con extends

+ +

La keyword extends viene usata nelle class declarations o class expressions per creare una classe figlia di un'altra classe.

+ +
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.');
+  }
+}
+
+ +

Si possono anche estendere le classi tradizionali basate su funzioni:

+ +
function Animal (name) {
+  this.name = name;
+}
+Animal.prototype.speak = function () {
+  console.log(this.name + ' makes a noise.');
+}
+
+class Dog extends Animal {
+  speak() {
+    super.speak();
+    console.log(this.name + ' barks.');
+  }
+}
+
+var d = new Dog('Mitzie');
+d.speak();
+ +

Sub classing built-in objects

+ +

TBD

+ +

Chiamare una superclasse con super

+ +

La keyword super è usata per chiamare le funzioni di un oggetto padre.

+ +
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.');
+  }
+}
+
+ +

ES5 inheritance syntax and ES6 classes syntax compared

+ +

TBD

+ +

Esempi

+ +

TBD

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
+ +

Browser compatibili

+ + + +

{{Compat("javascript.classes")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/classes/static/index.html b/files/it/web/javascript/reference/classes/static/index.html new file mode 100644 index 0000000000..7158316654 --- /dev/null +++ b/files/it/web/javascript/reference/classes/static/index.html @@ -0,0 +1,70 @@ +--- +title: static +slug: Web/JavaScript/Reference/Classes/static +translation_of: Web/JavaScript/Reference/Classes/static +--- +
{{jsSidebar("Classes")}}
+ +

La parola static è utilizzata per  definire un metodo statico di una classe.

+ +

Sintassi

+ +
static nomeMetodo() { ... }
+ +

Descrizione

+ +

La parola static definisce metodi statici per una classe. I metodi statici non sono invocati  sull'istanza della classe, ma sono invece invocati sulla classe stessa. Questi sono spesso metodi di supporto, as esempio funzioni per creare o clonare oggetti.

+ +

Esempi

+ +

Il seguente esempio mostra diversi aspetti interessanti. Mostra come un metodo statico è implementato in una classe, e come una classe con metodi statici può essere estesa da altre classi. Infine da una dimostrazione di come un metodo statico può essere o non può essere invocato.

+ +
class Triplica {
+  static triplica(n) {
+    n = n | 1;
+    return n * 3;
+  }
+}
+
+class TriplicaAncora extends Triplica {
+  static triplica(n) {
+    return super.triplica(n) * super.triplica(n);
+  }
+}
+
+console.log(Triplica.triplica()); // 3
+console.log(Triplica.triplica(6));  // 18
+console.log(TriplicaAncora.triplica(3)); // 81
+var tp = new Triplica();
+console.log(tp.triplica()); //Logga 'tp.triplica is not a function' perché la classe è instanziata
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
+ +

Browser compatibili

+ + + +

{{Compat("javascript.classes.static")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/errors/index.html b/files/it/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/it/web/javascript/reference/errors/index.html @@ -0,0 +1,31 @@ +--- +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/it/web/javascript/reference/errors/invalid_array_length/index.html b/files/it/web/javascript/reference/errors/invalid_array_length/index.html new file mode 100644 index 0000000000..61ee1cba5f --- /dev/null +++ b/files/it/web/javascript/reference/errors/invalid_array_length/index.html @@ -0,0 +1,77 @@ +--- +title: 'RangeError: invalid array length' +slug: Web/JavaScript/Reference/Errors/Invalid_array_length +tags: + - Errori + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length +--- +
{{jsSidebar("Errors")}}
+ +

Messaggio

+ +
RangeError: invalid array length (Firefox)
+RangeError: Invalid array length (Chrome)
+RangeError: Invalid array buffer length (Chrome)
+
+ +

Tipo di errore

+ +

{{jsxref("RangeError")}}

+ +

Cosa è andato storto?

+ +

Un invalid array length può comparire in queste situazioni:

+ + + +

Perché la lunghezza di Array e ArrayBuffer è limitata? La proprietà length di un Array o di un ArrayBuffer è rappresentata da un intero di 32-bit  senza segno, che quindi permette di memorizzare valori nell'intervallo da 0 a 232 - 1.

+ +

Se stai creando un Array utilizzando il costruttore, potresti invece utilizzare la notazione letterale dove il primo argomento è interpretato come la lunghezza dell' Array.

+ +

Altrimenti, potresti voler bloccare la lunghezza prima di settare la proprietà length, o utilizzarla come argomento del costruttore.

+ +

Esempi

+ +

Casi non validi

+ +
new Array(Math.pow(2, 40))
+new Array(-1)
+new ArrayBuffer(Math.pow(2, 32))
+new ArrayBuffer(-1)
+
+let a = [];
+a.length = a.length - 1;         // setta -1 alla proprietà length
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = b.length + 1;         // setta 2^32 alla proprietà length
+
+ +

Casi validi

+ +
[ Math.pow(2, 40) ]                     // [ 1099511627776 ]
+[ -1 ]                                  // [ -1 ]
+new ArrayBuffer(Math.pow(2, 32) - 1)
+new ArrayBuffer(0)
+
+let a = [];
+a.length = Math.max(0, a.length - 1);
+
+let b = new Array(Math.pow(2, 32) - 1);
+b.length = Math.min(0xffffffff, b.length + 1);
+
+// 0xffffffff è la notazione esadecimale di 2^32 - 1
+// che può essere riscritta come (-1 >>> 0)
+
+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html b/files/it/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html new file mode 100644 index 0000000000..d2412e48ce --- /dev/null +++ b/files/it/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html @@ -0,0 +1,54 @@ +--- +title: 'ReferenceError: invalid assignment left-hand side' +slug: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side +tags: + - Errori + - JavaScript + - ReferenceError +translation_of: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side +--- +
{{jsSidebar("Errors")}}
+ +

Messaggio

+ +
ReferenceError: invalid assignment left-hand side
+
+ +

Tipo di errore

+ +

{{jsxref("ReferenceError")}}.

+ +

Che cosa è andato storto?

+ +

C'è stato un assegnamento inaspettato da qualche parte. Ciò, ad esempio, potrebbe essere dovuto alla confusione tra  l' operatore d'assegnazione e l' operatore di confronto. Mentre un solo segno  di "=" assegna un valore ad una variabile, l'operatore "==" o "===" effettua il confronto tra valori.

+ +

Esempi

+ +
if (Math.PI = 3 || Math.PI = 4) {
+  console.log('niente!');
+}
+// ReferenceError: invalid assignment left-hand side
+
+var str = 'Ciao, '
++= 'sono io '
++= 'cosa stai cercando?';
+// ReferenceError: invalid assignment left-hand side
+
+ +

Nella dichiarazione if, puoi usare un operatore di confronto ("=="), e per la concatenazione di stringhe è necessario  l'operatore più ("+").

+ +
if (Math.PI == 3 || Math.PI == 4) {
+  console.log('niente!');
+}
+
+var str = 'Ciao, '
++ 'dall/' '
++ 'altra parte!';
+
+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/it/web/javascript/reference/errors/missing_semicolon_before_statement/index.html new file mode 100644 index 0000000000..c49646b4b1 --- /dev/null +++ b/files/it/web/javascript/reference/errors/missing_semicolon_before_statement/index.html @@ -0,0 +1,78 @@ +--- +title: 'SyntaxError: missing ; before statement' +slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +tags: + - Errore di Sintassi + - Errori + - JavaScript + - Oggetti + - SyntaxError + - Variabili +translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +--- +
{{jsSidebar("Errors")}}
+ +

Messaggio

+ +
SyntaxError: Expected - Previsto ';' (Edge)
+SyntaxError: missing  - Mancante; prima della dichiarazione (Firefox)
+
+ +

 

+ +

Tipo di errore

+ +

{{jsxref("SyntaxError")}}.

+ +

Cosa è andato storto?

+ +

C'è un punto e virgola (;) mancante. Le dichiarazioni in JavaScript devono essere determinate da il punto e virgola (;). Alcune di loro sono soggette all' Inserzione Automatica a Semicolonne (ASI), ma in questo caso è necessario specificare la semicolonna, in modo che JavaScript legga correttamente il codice sorgente.

+ +

In ogni caso, molto spesso, questo errore è solo una conseguenza di un altro, come lo scorretto uso degli apici, o l'uso errato di var. Potresti anche avere troppe parentesi da qualche parte. Ricontrolla la sintassi del codice quando appare questo errore.

+ +

Esempi

+ +

Stringhe senza escape (\)

+ +

Questo errore accade frequentemente quando si usa un apostrofo senza carattere di escape. Il motore di JavaScript si aspetta la fine di una stringa. Per esempio:

+ +
var foo = 'Tom's bar';
+// (') interrompe è atteso ("..'..") o ('..\'..')
+// SyntaxError: missing ; prima della dichiarazione
+ +

Per risolvere, usa le virgolette oppure un carattere di escape (backslash):

+ +
var foo = "Tom's bar"; <- in questo modo
+var foo = 'Tom\'s bar'; <- in questo modo
+
+ +

 

+ +

Dichiarare le proprietà con var

+ +

Non puoi dichiarare le proprietà di un oggetto o di un array con una dichiarazione var.

+ +
var obj = {};
+var obj.foo = 'hi';
+// SyntaxError missing ; before statement
+
+var array = [];
+var array[0] = 'there';
+// SyntaxError missing ; before statement
+
+ +

Prova invece ad omettere la parola chiave var:

+ +
var obj = {};
+obj.foo = 'hi';
+
+var array = [];
+array[0] = 'there';
+
+ +

Controlla anche

+ + diff --git a/files/it/web/javascript/reference/errors/too_much_recursion/index.html b/files/it/web/javascript/reference/errors/too_much_recursion/index.html new file mode 100644 index 0000000000..049ed04cf0 --- /dev/null +++ b/files/it/web/javascript/reference/errors/too_much_recursion/index.html @@ -0,0 +1,72 @@ +--- +title: 'InternalError: too much recursion' +slug: Web/JavaScript/Reference/Errors/Too_much_recursion +tags: + - Errore + - JavaScript +translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion +--- +
{{jsSidebar("Errors")}}
+ +

The JavaScript exception "too much recursion" or "Maximum call stack size exceeded" occurs when there are too many function calls, or a function is missing a base case.

+ +

Message

+ +
Error: Spazio nello stack esaurito (Edge)
+InternalError: Troppa ricorsione (Firefox)
+RangeError: Dimensioni massime dello stack superate (Chrome)
+
+ +

Error type

+ +

{{jsxref("InternalError")}}.

+ +

Cos'è andato storto?

+ +

Una funzione che si chiama da sola si chiama funzione ricorsiva. Una volta che la condizione è soddisfatta, la funzione smette di chiamarsi. Questo si chiama caso di base.

+ +

In certi versi, la ricorsione è analoga ai cicli. Entrambi eseguono lo stesso codice più volte, ed entrambi richiedono una condizione(per evitare cicli infiniti,o in questo caso, ricorsioni infinite). Quando ci sono troppe chiamate, o manca il caso di base , JavaScript lancerà questo errore.

+ +

Esempi

+ +

Questa funzione ricorsiva si chiama 10 volte, secondo le condizioni d'uscita

+ +
function ciclo(x) {
+  if (x >= 10) // "x >= 10" condizione d'uscita
+    return;
+  // do stuff
+  ciclo(x + 1); // chiamata ricorsiva
+}
+ciclo(0);
+ +

Impostare questa condizione a valori estremamente alti non funzionerà:

+ +
function ciclo(x) {
+  if (x >= 1000000000000)
+    return;
+  // fà cose
+  ciclo(x + 1);
+}
+ciclo(0);
+
+// Errore Interno: troppa ricorsione
+ +

Alla funzione manca un caso base.Visto che non c'è condizione di uscita, la funzione chiama se stessa all'infinito.

+ +
function ciclo(x) {
+ // Manca caso base
+
+ciclo(x + 1); // Chiamata ricorsiva
+}
+
+ciclo(0);
+
+// Errore Interno: troppa ricorsione
+ +

Vedi anche

+ + + + diff --git a/files/it/web/javascript/reference/errors/unexpected_token/index.html b/files/it/web/javascript/reference/errors/unexpected_token/index.html new file mode 100644 index 0000000000..17a9c78a4c --- /dev/null +++ b/files/it/web/javascript/reference/errors/unexpected_token/index.html @@ -0,0 +1,50 @@ +--- +title: 'SyntaxError: Unexpected token' +slug: Web/JavaScript/Reference/Errors/Unexpected_token +tags: + - Errori + - JavaScript + - Sintassi +translation_of: Web/JavaScript/Reference/Errors/Unexpected_token +--- +
{{jsSidebar("Errors")}}
+ +

Messaggio

+ +
SyntaxError: espressione prevista, si ottiene "x"
+SyntaxError: nome proprietà previsto, si ottiene "x"
+SyntaxError: target previsto, si ottiene "x"
+SyntaxError: nome dell'argomento rest previsto, si ottiene "x"
+SyntaxError: parentesi di chiusura prevista, si ottiene "x"
+SyntaxError: previsto '=>' dopo la lista degli argomenti, si ottiene "x"
+
+ +

Tipo di errore

+ +

{{jsxref("SyntaxError")}}

+ +

Cosa è andato storto?

+ +

Era atteso un costrutto specifico del linguaggio, ma è stato fornito qualcosa di diverso. Potrebbe trattarsi di un semplice errore di digitazione.

+ +

Esempi

+ +

Espressione prevista

+ +

Ad esempio, non è permesso terminare una lista di argomenti con la virgola, in quanto JavaScript si aspetta un altro argomento.

+ +
Math.max(2, 42,);
+// SyntaxError: expected expression, got ')'
+
+ +

Sarebbe invece corretto omettere la virgola o specificare un altro argomento (che potrebbe anche essere un espressione):

+ +
Math.max(2, 42);
+Math.max(2, 42, 13 + 37);
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/errors/unexpected_type/index.html b/files/it/web/javascript/reference/errors/unexpected_type/index.html new file mode 100644 index 0000000000..632b9bf756 --- /dev/null +++ b/files/it/web/javascript/reference/errors/unexpected_type/index.html @@ -0,0 +1,67 @@ +--- +title: 'TypeError: "x" is (not) "y"' +slug: Web/JavaScript/Reference/Errors/Unexpected_type +tags: + - Errori + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Unexpected_type +--- +
{{jsSidebar("Errors")}}
+ +

Messaggio

+ +
TypeError: "x" is (not) "y"
+
+Examples:
+TypeError: "x" is undefined
+TypeError: "x" is null
+TypeError: "undefined" is not an object
+TypeError: "x" is not an object or null
+TypeError: "x" is not a symbol
+
+ +

Tipo di errore

+ +

{{jsxref("TypeError")}}.

+ +

Cosa è andato storto?

+ +

C'è stato un tipo inaspettato. Questo accade spesso con valori {{jsxref("undefined")}} o {{jsxref("null")}}.

+ +

Inoltre, alcuni metodi, come {{jsxref("Object.create()")}} o {{jsxref("Symbol.keyFor()")}}, richiedono che sia fornito un tipo specifico.

+ +

Esempi

+ +

Casi non validi

+ +
// casi undefined e null in cui il metodo substring non funzionerà
+var foo = undefined;
+foo.substring(1); // TypeError: foo non è definita
+
+var foo = null;
+foo.substring(1); // TypeError: foo è null
+
+
+// Alcuni metodi potrebbero richiedere un tipo specifico
+var foo = {}
+Symbol.keyFor(foo); // TypeError: foo non è un simbolo
+
+var foo = 'bar'
+Object.create(foo); // TypeError: "foo" non è un oggetto o è null
+
+ +

Risolvere il problema

+ +

Per risolvere il problema di valori undefined o null, si può usare l'operatore typeof operator, ad esempio.

+ +
if (typeof foo !== 'undefined') {
+  // Ora sappiamo che foo è definita, possiamo procedere.
+}
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/functions_and_function_scope/arguments/index.html b/files/it/web/javascript/reference/functions_and_function_scope/arguments/index.html new file mode 100644 index 0000000000..c277074bca --- /dev/null +++ b/files/it/web/javascript/reference/functions_and_function_scope/arguments/index.html @@ -0,0 +1,224 @@ +--- +title: Oggetto 'arguments' +slug: Web/JavaScript/Reference/Functions_and_function_scope/arguments +translation_of: Web/JavaScript/Reference/Functions/arguments +--- +
+
{{jsSidebar("Functions")}}
+
+ +

L'oggetto arguments è un oggetto Array-like corrispondente agli argomenti passati in una funzione 

+ +

{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}

+ + + +

Sintassi

+ +
arguments
+ +

Descrizione

+ +

L'oggetto arguments è una variabile locale disponibile in tutte le funzioni (non-arrow). Si può fare riferimento agli argomenti di una funzione, al suo interno, usando l'oggetto  arguments. Questo oggetto contiene un elemento per ogni argomento passato alla funzione, il primo elemento è indicizzato a 0. Per esempio, se a una funzione sono passati tre argomenti, ci si può riferire ad essi come segue:

+ +
arguments[0]
+arguments[1]
+arguments[2]
+
+ +

Gli argomenti possono anche essere settati:

+ +
arguments[1] = 'nuovo valore';
+
+ +

L'oggetto arguments non è un {{jsxref("Array")}}. E' simile a un  Array, ma non ha le proprietà dell'Array, eccetto length. Per esempio, non ha il metodo pop. Tuttavia può essere convertito in un vero Array:

+ +
var args = Array.prototype.slice.call(arguments);
+var args = [].slice.call(arguments);
+
+// ES2015
+const args = Array.from(arguments);
+
+ +
+

Usare slice su arguments impedisce le ottimizzazioni in alcuni motori JavaScript (per esempio V8 - più informazioni). Se ne avete bisogno, provate a costruire un nuovo array iterando sull'oggetto arguments, piuttosto. Un'alternativa potrebbe essere usare l'odiato costruttore Array come una funzione:

+ +
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
+
+ +

Si può usare l'oggetto arguments se si chiama una funzione con più argomenti di quanti la funzione dichiari formalmente di accettare. Questa tecnica è utile per le funzioni cui possono essere passati un numero variabile di argomenti. Si usi arguments.length per determinare il numero di argomenti passati alla funzione, e quindi si processi ogni argomento usando l'oggetto arguments. Per determinare il numero di parametri presenti nella dichiarazione di una funzione, si usi la proprietà Function.length.

+ +

Usare typeof con Arguments

+ +

Il typeof di arguments ritorna 'object'. 

+ +
console.log(typeof arguments); // 'object' 
+ +

Il typeof di ogni signolo argomento può essere determinato con l'uso degli indici.

+ +
console.log(typeof arguments[0]); //this will return the typeof individual arguments.
+ +

Usare la sintassi Spread con Arguments

+ +

Come è possibile fare con qualsiasi oggetto Array-like, si può usare il metodo {{jsxref("Array.from()")}} o lo spread operator per convertire arguments in un vero Array:

+ +
var args = Array.from(arguments);
+var args = [...arguments];
+
+ +

Proprietà

+ +
+
arguments.callee
+
Riferimento alla funzione in esecuzione.
+
arguments.caller {{ Obsolete_inline() }}
+
Riferimento alla funzione che ha invocato la funzione in esecuzione.
+
arguments.length
+
Riferimento al numero di argomenti passati alla funzione.
+
arguments[@@iterator]
+
Ritorna un nuovo oggetto Array Iterator che contiene i valori per ogni indice in arguments.
+
+ +

Esempi

+ +

Definire una funzione che concatena divere stringhe 

+ +

Questo esempio definisce una funzione che concatena diverse stringhe. L'unico argomento formale per la funzione è una stringa che specifica il carattere di separazione per gli elementi da concatenare. La funzione si definisce come segue:

+ +
function myConcat(separator) {
+  var args = Array.prototype.slice.call(arguments, 1);
+  return args.join(separator);
+}
+ +

Si può passare un numero indefinito di argomenti a questa funzione, e lei creerà una lista inserendo ciascun argomento come item della lista. 

+ +
// 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');
+ +

Definire una funzione che crea liste HTML

+ +

Questo esempio definisce una funzione che crea una stringa contenente l'HTML di una lista. L'unico argomento formale della funzione è una  stringa che è "u" se la lista deve essere ordinata, e "o" se la lista deve essere ordinata (numerata). La funzione è definita come segue:

+ +
function list(type) {
+  var result = '<' + type + 'l><li>';
+  var args = Array.prototype.slice.call(arguments, 1);
+  result += args.join('</li><li>');
+  result += '</li></' + type + 'l>'; // end list
+
+  return result;
+}
+ +

Si può passare un numero indefinito di argomenti a questa funzione, e lei aggiungerà ogni argomento come un elemento della lista del tipo indicato. Per esempio:

+ +
var listHTML = list('u', 'One', 'Two', 'Three');
+
+/* listHTML is:
+
+"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
+
+*/
+ +

Parametri rest, default, e destructured

+ +

L'oggetto arguments può essere usato insieme a parametri rest, default, e destructured.

+ +
function foo(...args) {
+  return args;
+}
+foo(1, 2, 3); // [1,2,3]
+
+ +

Sebbene la presenza di parametri restdefault, o destructured non altera il comportamento dell'oggetto arguments nel codice scritto in strict mode, c'è una sottile differenza tra modalità strict e non-strict.

+ +

Quando una funzione non-strict non contiene parametri restdefault, o destructured, allora i valori nell'oggetto arguments  tracciano il valore degli argomenti (e vice versa). Si guardi il codice qui sotto:

+ +
function func(a) {
+  arguments[0] = 99; // updating arguments[0] also updates a
+  console.log(a);
+}
+func(10); // 99
+
+ +

e

+ +
function func(a) {
+  a = 99; // updating a also updates arguments[0]
+  console.log(arguments[0]);
+}
+func(10); // 99
+
+ +

Quando una funzione non-strict contiene parametri restdefault, o destructured, allora i valori nell'oggetto arguments non tracciano il valore degli argomenti (e vice versa). Al contrario, riflettono gli argomenti forniti al momento dell'invocazione:

+ +
function func(a = 55) {
+  arguments[0] = 99; // updating arguments[0] does not also update a
+  console.log(a);
+}
+func(10); // 10
+ +

e

+ +
function func(a = 55) {
+  a = 99; // updating a does not also update arguments[0]
+  console.log(arguments[0]);
+}
+func(10); // 10
+
+ +

e

+ +
function func(a = 55) {
+  console.log(arguments[0]);
+}
+func(); // undefined
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Impelementata 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')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.functions.arguments")}}

+ +

Si guardi anche

+ + diff --git a/files/it/web/javascript/reference/functions_and_function_scope/arrow_functions/index.html b/files/it/web/javascript/reference/functions_and_function_scope/arrow_functions/index.html new file mode 100644 index 0000000000..2dd258966d --- /dev/null +++ b/files/it/web/javascript/reference/functions_and_function_scope/arrow_functions/index.html @@ -0,0 +1,394 @@ +--- +title: Funzioni a freccia +slug: Web/JavaScript/Reference/Functions_and_function_scope/Arrow_functions +tags: + - ECMAScript6 + - Funzioni + - Intermediate + - JavaScript + - Reference +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +
{{jsSidebar("Functions")}}
+ +

Una funzione a freccia ha una sintassi più compatta rispetto alla notazione a funzione e non associa i propri thisargumentssuper o new.target. Le funzioni a freccia sono sempre anonime. Questa notazione è maggiormente indicata per le funzioni che non sono metodi, e non possono essere usate come costruttori.

+ +

Sintassi

+ +

Sintassi di base

+ +
(param1, param2, …, paramN) => { statements }
+(param1, param2, …, paramN) => expression
+// equivalente a: (param1, param2, …, paramN) => { return expression; }
+
+// Le Parentesi sono opzionali se è presente un solo parametro:
+(singleParam) => { statements }
+singleParam => { statements }
+
+// Una funzione senza parametri richiede comunque le parentesi:
+() => { statements }
+() => expression // equivalente a: () => { return expression; }
+
+ +

Sintassi avanzata

+ +
// Il body tra parentesi indica la restituzione di un oggetto:
+params => ({foo: bar})
+
+// Sono supportati ...rest e i parametri di default
+(param1, param2, ...rest) => { statements }
+(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }
+
+// Si può anche destrutturare all'interno della lista dei parametri
+var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
+f();  // 6
+
+ +

Esempi dettagliati di sintassi sono disponibili qui.

+ +

Descrizione

+ +

Vedi anche "ES6 In Depth: Arrow functions" su hacks.mozilla.org.

+ +

L'introduzione delle funzioni a freccia è stata influenzata da due fattori: sintassi più compatta e la non associazione di this.

+ +

Funzioni più corte

+ +

In alcuni pattern, è meglio avere funzioni più corte. Per comparazione:

+ +
var materials = [
+  "Hydrogen",
+  "Helium",
+  "Lithium",
+  "Beryllium"
+];
+
+materials.map(function(material) {
+  return material.length;
+}); // [8, 6, 7, 9]
+
+materials.map((material) => {
+  return material.length;
+}); // [8, 6, 7, 9]
+
+materials.map(material => material.length); // [8, 6, 7, 9]
+ +

Mancato binding di this

+ +

Prima delle funzioni a freccia, ogni nuova funzione definiva il proprio  this (un nuovo oggetto nel caso di un costruttore, undefined se una funzione viene chiamata in strict mode, l'oggetto di contesto se la funzione viene chiamata come "metodo", etc.). Questo è risultato fastidioso in uno stile di programmazione orientato agli oggetti.

+ +
function Person() {
+  // The Person() constructor defines `this` as an instance of itself.
+  this.age = 0;
+
+  setInterval(function growUp() {
+    // In non-strict mode, the growUp() function defines `this`
+    // as the global object, which is different from the `this`
+    // defined by the Person() constructor.
+    this.age++;
+  }, 1000);
+}
+
+var p = new Person();
+ +

In ECMAScript 3/5, questo problema veniva aggirato assegnando il valore this a una variabile.

+ +
function Person() {
+  var that = this;
+  that.age = 0;
+
+  setInterval(function growUp() {
+    // The callback refers to the `that` variable of which
+    // the value is the expected object.
+    that.age++;
+  }, 1000);
+}
+ +

In alternativa, poteva essere usato Function.prototype.bind per assegnare il valore corretto di this da usare nella funzione  growUp().

+ +

Una funziona a freccia invece non crea  il proprio this, e quindi this mantiene il significato che aveva all'interno dello scope genitore. Perciò il codice seguente funziona come ci si aspetta.

+ +
function Person(){
+  this.age = 0;
+
+  setInterval(() => {
+    this.age++; // |this| properly refers to the person object
+  }, 1000);
+}
+
+var p = new Person();
+ +

Relazione con strict mode

+ +

Poiché  this è lessicale, le regole di strict mode relative a this sono semplicemente ignorate.

+ +
var f = () => {'use strict'; return this};
+f() === window; // o l'oggetto globale
+ +

Il resto delle regole si applica normalmente.

+ +

Invocazione attraverso call or apply

+ +

Poiché this non viene assegnato nelle funzioni a freccia, i metodi call() o apply() possono passare solo come argomenti; this viene ignorato:

+ +
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));         // This would log to 2
+console.log(adder.addThruCall(1)); // This would log to 2 still
+ +

Mancato binding di arguments

+ +

Le funzioni a freccia non definiscono il proprio  argumentsPerciò, arguments è semplicemente una reference alla variabile nello scope genitore.

+ +
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
+ +

Le funzioni a freccia non hanno il proprio oggetto arguments, ma in molti casi  i parametri rest rappresentano una valida alternativa:

+ +
function foo() {
+  var f = (...args) => args[0];
+  return f(2);
+}
+
+foo(1); // 2
+ +

Funzioni a freccia come metodi

+ +

Come già citato, le funzioni a freccia sono sconsigliate come metodi. Vediamo cosa succede quando proviamo a usarle: 

+ +
'use strict';
+var obj = {
+  i: 10,
+  b: () => console.log(this.i, this),
+  c: function() {
+    console.log( this.i, this)
+  }
+}
+obj.b(); // prints undefined, Window
+obj.c(); // prints 10, Object {...}
+ +

Le funzioni a freccia non definiscono  ("bind") il proprio this. un altro esempio usando {{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; // represents global object 'Window', therefore 'this.a' returns 'undefined'
+  }
+});
+
+ +

Uso dell'operatore new 

+ +

Le funzioni a freccia non possono essere usate come costruttori, ed emetteranno un errore se usate con new.

+ +

Uso di yield 

+ +

La keyword yield non deve essere usata nel body di una funzione a freccia (eccetto quando permesso in eventuali funzioni al loro interno). Conseguentemente, le funzioni a freccia non possono essere usate come generatori.

+ +

Body della funzione

+ +

Le funzioni a freccia possono avere un "body conciso" o l'usuale "blocco body".

+ +

Nel primo caso è necessaria solo un'espressione, e il return è implicito. Nel secondo caso, devi usare esplicitamente return.

+ +
var func = x => x * x;                  // concise syntax, implied "return"
+var func = (x, y) => { return x + y; }; // with block body, explicit "return" needed
+
+ +

Restituire object literals

+ +

Tieni a mente che restituire oggetti letterali usando la sintassi concisa  params => {object:literal} non funzionerà:

+ +
var func = () => {  foo: 1  };               // Calling func() returns undefined!
+var func = () => {  foo: function() {}  };   // SyntaxError: function statement requires a name
+ +

Questo perché il codice all'interno delle parentesi graffe ({}) è processato come una sequenza di statement (i.e. foo è trattato come un label, non come una key di un oggetto).

+ +

Tuttavia, è sufficente racchiudere l'oggetto tra parentesi tonde:

+ +
var func = () => ({ foo: 1 });
+ +

Newline

+ +

Le funzioni a freccia non possono contenere un newline tra i parametri e la freccia.

+ +
var func = ()
+           => 1; // SyntaxError: expected expression, got '=>'
+ +

Ordine di parsing

+ +

La freccia in una funziona a freccia non è un'operatore, ma le funzioni a freccia hanno delle regole di parsing specifiche che interagiscono differentemente con la precedenza degli operatori, rispetto alle funzioni normali.

+ +
let callback;
+
+callback = callback || function() {}; // ok
+callback = callback || () => {};      // SyntaxError: invalid arrow-function arguments
+callback = callback || (() => {});    // ok
+
+ +

Altri esempi

+ +
// Una funzione a freccie vuota restituisce undefined
+let empty = () => {};
+
+(() => "foobar")() // IIFE, restituisce "foobar"
+
+var simple = a => a > 15 ? 15 : a;
+simple(16); // 15
+simple(10); // 10
+
+let max = (a, b) => a > b ? a : b;
+
+// Più semplice gestire filtering, mapping, ... di array
+
+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]
+
+// Le catene di promise sono più concise
+promise.then(a => {
+  // ...
+}).then(b => {
+   // ...
+});
+
+// le funzioni a freccia senza parametri sono più semplici da visualizzare
+setTimeout( _ => {
+  console.log("I happen sooner");
+  setTimeout( _ => {
+    // deeper code
+    console.log("I happen later");
+  }, 1);
+}, 1);
+
+ +

 

+ +

 

+ +

 

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità dei Browser 

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeIEOperaSafari
Basic support{{CompatChrome(45.0)}}{{CompatGeckoDesktop("22.0")}}{{CompatVersionUnknown}} +

{{CompatNo}}

+
{{CompatOpera(32)}}{{CompatSafari(10.0)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(45.0)}}{{CompatGeckoMobile("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatSafari(10.0)}}{{CompatChrome(45.0)}}
+
+ +

Note specifiche per Firefox

+ + + +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/functions_and_function_scope/get/index.html b/files/it/web/javascript/reference/functions_and_function_scope/get/index.html new file mode 100644 index 0000000000..0ed76cf469 --- /dev/null +++ b/files/it/web/javascript/reference/functions_and_function_scope/get/index.html @@ -0,0 +1,154 @@ +--- +title: getter +slug: Web/JavaScript/Reference/Functions_and_function_scope/get +translation_of: Web/JavaScript/Reference/Functions/get +--- +
{{jsSidebar("Functions")}}
+ +

La sintassi get  associa una proprietà dell'oggetto a una funzione che verrà chiamata quando la proprietà verrà richiesta.

+ +
{{EmbedInteractiveExample("pages/js/functions-getter.html")}}
+ + + +

Sintassi

+ +
{get prop() { ... } }
+{get [expression]() { ... } }
+ +

Parametri

+ +
+
prop
+
Il nome della proprietà da associare alla funzione specificata.
+
espressione
+
A partire da ECMAScript 2015, è anche possibile utilizzare espressioni per un nome di proprietà calcolato per associarsi alla funzione specificata.
+
+ +

Descrizione

+ +

A volte è preferibile consentire l'accesso a una proprietà che restituisce un valore calcolato in modo dinamico, oppure è possibile che si desideri riflettere lo stato di una variabile interna senza richiedere l'uso di chiamate esplicite al metodo. In JavaScript, questo può essere realizzato con l'uso di un getter. Non è possibile avere simultaneamente un getter legato a una proprietà e avere quella proprietà contenuta in un valore, anche se è possibile usare un getter e un setter insieme per creare un tipo di pseudo-proprietà.

+ +

Tieni presente quanto segue quando lavori con la sintassi get:

+ +
+ +
+ +

Un getter può essere rimosso usando l'operatore  delete

+ +

Esempi

+ +

Definizione di un getter sui nuovi oggetti negli inizializzatori di oggetti

+ +

Questo creerà una pseudo-proprietà latest più recente per object obj, che restituirà l'ultimo elemento dell'array in log.

+ +
var obj = {
+  log: ['example','test'],
+  get latest() {
+    if (this.log.length == 0) return undefined;
+    return this.log[this.log.length - 1];
+  }
+}
+console.log(obj.latest); // "test".
+
+ +

Si noti che il tentativo di assegnare un valore a latest non lo cambierà.

+ +

Cancellare un getter usando l'operatore delete

+ +

Se vuoi rimuovere il getter, puoi semplicemente usare delete :

+ +
delete obj.latest;
+
+ +

Definire un getter su un oggetto esistente usando defineProperty

+ +

Per aggiungere un getter a un oggetto esistente in un secondo momento, usa {{jsxref("Object.defineProperty()")}}.

+ +
var o = {a: 0};
+
+Object.defineProperty(o, 'b', { get: function() { return this.a + 1; } });
+
+console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
+ +

Utilizzando un nome di proprietà calcolato

+ +
var expr = 'foo';
+
+var obj = {
+  get [expr]() { return 'bar'; }
+};
+
+console.log(obj.foo); // "bar"
+ +

Smart / self-overwriting / lazy getters

+ +

I getter ti danno un modo per definire una proprietà di un oggetto, ma non calcolano il valore della proprietà finché non avviene l'accesso. Un getter rinvia il costo del calcolo del valore fino a quando il valore è necessario e, se non è mai necessario, non si paga mai il costo.

+ +

Un'ulteriore tecnica di ottimizzazione per lazificare o ritardare il calcolo di un valore di una proprietà e memorizzarla nella cache per un accesso successivo sono smart o memoized getters. Il valore viene calcolato la prima volta che viene chiamato il getter e viene quindi memorizzato nella cache in modo che gli accessi successivi restituiscano il valore memorizzato nella cache senza ricalcolarlo. Questo è utile nelle seguenti situazioni:

+ + + +

Ciò significa che non si dovrebbe usare un getter pigro per una proprietà il cui valore si prevede possa cambiare, poiché il getter non ricalcola il valore.

+ +

Nell'esempio seguente, l'oggetto ha un getter come proprietà propria. Quando si ottiene la proprietà, la proprietà viene rimossa dall'oggetto e riaggiunta, ma questa volta implicitamente come proprietà dei dati. Alla fine il valore viene restituito.

+ +
get notifier() {
+  delete this.notifier;
+  return this.notifier = document.getElementById('bookmarked-notification-anchor');
+},
+ +

Per il codice di Firefox, vedere anche il modulo del codice XPCOMUtils.jsm, che definisce la funzione defineLazyGetter().

+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}{{Spec2('ES5.1')}}Definizione iniziale.
{{SpecName('ES2015', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ES2015')}}Aggiunti nomi di proprietà calcolate.
{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con il browser

+ + + +

{{Compat("javascript.functions.get")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/functions_and_function_scope/index.html b/files/it/web/javascript/reference/functions_and_function_scope/index.html new file mode 100644 index 0000000000..8a5255282c --- /dev/null +++ b/files/it/web/javascript/reference/functions_and_function_scope/index.html @@ -0,0 +1,617 @@ +--- +title: Funzioni +slug: Web/JavaScript/Reference/Functions_and_function_scope +translation_of: Web/JavaScript/Reference/Functions +--- +
{{jsSidebar("Functions")}}
+ +

Parlando in termini generici, una funzione è un "sottopogramma" che può essere chiamato da un codice esterno (o interno nel caso di ricorsione) alla funzione stessa. Come il programma stesso, una funzione è composta da una sequenza di istruzioni chiamata corpo della funzione. Ad una funzione possono essere passati valori, e la funzione restituisce un valore.

+ +

In JavaScript, le funzioni sono oggetti di prima classe, perchè sono dotate di proprietà e di metodi, proprio come qualsiasi altro oggetto. Ciò che le distingue dagli altri oggetti è la possibilità di essere chiamate ( invocate ). Le funzioni sono oggetti di tipo Function.

+ +

Per maggiori esempi e spiegazioni, vedere anche JavaScript la guida sulle funzioni.

+ +

Descrizione

+ +

Ogni funzione in JavaScript è un oggetto di tipo Function. Vedi la pagina Function for informazioni su proprietà e metodi dell'oggetto Function.

+ +

Le funzioni non sono come le procedure. Una funzione restituisce sempre un valore, mentre una procedura può anche non restituire alcun valore.

+ +

Per restituire un valore specifico differente da quello di default, una fuzione deve avere un istruzione return che specifica il valore di ritorno. Una funzione senza un istruzione di ritorno restituirà il valore di  default. Nel caso di un costruttore invocato con la parola chiave new, il valore di default è il valore del suo parametro this. Per tutte le altre funzioni, il valore di ritorno di default è undefined.

+ +

I parametri di una chiamata di funzione sono gli argomenti della funzione. Gli argomenti sono passati alla funzione per valore. Se la funzione cambia il valore di un argomento, questo cambiamento non si riflette globalmente o nella funzione chiamante. Sebbene anche i riferimenti a oggetti siano valori, essi sono speciali: se una funzione cambia le proprietà di un oggetto a cui riferisce, quel cambiamento è visibile anche al di fuori della funzione, come dimostrato nel seguente esempio:

+ +
/* Dichiarazione della funzione 'myFunc' */
+function myFunc(theObject) {
+   theObject.brand = "Toyota";
+ }
+
+ /*
+  * Dichiarazione della variabile 'mycar';
+  * creazione e inizializzazione di un nuovo Object;
+  * associazione alla riferimento 'mycar'
+  */
+ var mycar = {
+   brand: "Honda",
+   model: "Accord",
+   year: 1998
+ };
+
+ /* Logs 'Honda' */
+ console.log(mycar.brand);
+
+ /* Passaggio del riferimento dell'oggetto alla funzione */
+ myFunc(mycar);
+
+ /*
+  * Logs 'Toyota' come il valore della proprietà 'brand'
+  * dell'oggetto, come è stato cambiato dalla funzione.
+  */
+ console.log(mycar.brand);
+
+ +

NB: l'oggetto console non è un oggetto standard. Non usatelo in un sito web, poichè potrebbe non funzionare correttamente. Per verificare il funzionamento dell'esempio precedente, usate, piuttosto:

+ +

           window.alert(mycar.brand);

+ +

La parola chiave this non fa riferimento alla funzione attualmente in esecuzione, per questo motivo si deve far riferimento ad oggetti Function  per nome, anche quando all'interno del corpo della funzione stessa.

+ +

Definizione di funzioni

+ +

Ci sono diversi modi per definire le funzioni:

+ +

La dichiarazione di funzione (istruzione function)

+ +

C'è una speciale sintassi per la dichiarazione di funzioni (per dettagli guarda function statement):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
Il nome della funzione
+
+ +
+
param
+
Il nome di un argomento da passare alla funzione. Una funzione può avere fino a 255 argomenti.
+
+ +
+
statements
+
Le istruzioni comprese nel corpo della funzione.
+
+ +

L'espressione di funzione (espressione function)

+ +

Una espressione di funzione è simile ed ha la stessa sintassi della dichiarazione di funzione (per dettagli guarda function expression):

+ +
function [name]([param] [, param] [..., param]) {
+   statements
+}
+
+ +
+
name
+
Il nome della funzione. Può essere omesso, in qual caso la funzione è nota come funzione anonima.
+
+ +
+
param
+
Il nome di un argomento da passare alla funzione. Una funzione può avere fino a 255 argomenti.
+
statements
+
Le istruzioni comprese nel corpo della funzione.
+
+ +

La dichiarazione di funzione generatrice (espressione function*)

+ +
+

Note: Le funzioni generatrici sono un tecnologia sperimentale, parte della proposta di specifica ECMAScript 6, e non sono ancora ampiamente supportate dai browsers.

+
+ +

C'è una sintassi speciale per le funzioni generatrici (per dettagli vedi function* statement ):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
Nome della funzione.
+
+ +
+
param
+
Nome dell'argomento da passare alla funzione. Una funzione può avere fino a 255 agromenti.
+
+ +
+
statements
+
Le istruzioni comprese nel corpo della funzione.
+
+ +

L'espressione di funzione generatrice (espressione function*)

+ +
+

Note: Le funzioni generatrici sono una tecnologia sperimentale, parte della proposta di specifica ECMAScript 6, e non sono ancora ampiamente supportamente dai browsers.

+
+ +

Una espressione di funzione generatrice è similare ed ha la stessa sintassi di una dichiarazione di funzione generatrice (per dettagli vedi function* expression ):

+ +
function* [name]([param] [, param] [..., param]) {
+   statements
+}
+
+ +
+
name
+
Nome della funzione. Può essere omesso, nel qual caso la funzione è nota come funzione anonima.
+
+ +
+
param
+
+
Nome dell'argomento da passare alla funzione. Una funzione può avere fino a 255 agromenti.
+
+
statements
+
Le istruzioni comprese nel corpo della funzione.
+
+ +

L'espressione di funzione a freccia (=>)

+ +
+

Note: L'espressione di funzione a freccia sono una tecnologia sperimentareparte della proposta di specifica ECMAScript 6, e non sono ancora ampiamente supportate dai browsers.

+
+ +

Un' espressione di funzione a freccia ha una sintassi ridotta e lessicalmnete associa il proprio valore this (per dettagli vedere arrow functions ):

+ +
([param] [, param]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
Il nome di un parametro. È necessario indicare l'assenza di parametri con (). Le parentesi non sono richieste nel caso in cui ci sia solo un parametro (come foo => 1).
+
statements or expression
+
Molteplici istruzioni devono essere racchiuse tra parentesi. Una singola espressione non necessita di parantesi. expression è anche l'implicito valore restituito dalla funzione.
+
+ +

Il costruttore Function

+ +
+

Nota: l'utilizzo del costruttore Function per creare funzioni non è raccomandato, poichè richiede che il corpo della funzione sia scritto come stringa, fatto che può comportare una mancata ottimizzazione da parte di alcuni motori javascript e causare altri problemi.

+
+ +

Come tutti gli altri oggetti, un oggetto Function può essere creato utilizzando l'operatore new:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero o più nomi da usare come nomi formali di argomenti. Ciascun nome deve essere rappresentato da una stringa testuale che sia conforme alle norme che regolano la definizione di identificatori JavaScript validi, oppure da una lista di stringhe testuali, separate da una virgola; per esempio: "x", "theValue", oppure "a,b".
+
+ +
+
functionBody
+
Una stringa testuale che contenga le istruzioni Javascript comprese nella definizione della funzione.
+
+ +

Invocare il costruttore Function come funzione ( senza utilizzare l'operatore new ) ha lo stesso effetto di quando lo si invoca come costruttore.

+ +

Il costruttore GeneratorFunction

+ +
+

Nota: le espressioni di funzione a freccia ( arrow function expression ) sono una tecnologia sperimentale, parte della proposta ECMAScript 6, e non sono ancora completamente supportate dai browser.

+
+ +
+

Nota: il costruttore GeneratorFunction non è un oggetto globale, ma può essere ottenuto dall'istanza della funzione generatrice ( vedi GeneratorFunction per maggiori dettagli ).

+
+ +
+

Nota: l'utilizzo del costruttore GeneratorFunction per creare funzioni non è raccomandato, poichè richiede che il corpo della funzione sia scritto come stringa, fatto che può comportare una mancata ottimizzazione da parte di alcuni motori javascript e causare altri problemi.

+
+ +

Come tutti gli altri oggetti, un oggetto GeneratorFunction può essere creato utilizzando l'operatore new:

+ +
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero o più nomi da usare come nomi formali di argomenti. Ciascun nome deve essere rappresentato da una stringa testuale che sia conforme alle norme che regolano la definizione di identificatori JavaScript validi, oppure da una lista di stringhe testuali, separate da una virgola; per esempio: "x", "theValue", oppure "a,b".
+
+ +
+
functionBody
+
Una stringa testuale che contenga le istruzioni Javascript comprese nella definizione della funzione.
+
+ +

Invocare il costruttore Function come funzione ( senza utilizzare l'operatore new ) ha lo stesso effetto di quando lo si invoca come costruttore.

+ +

I parametri di una funzione

+ +
+

Nota: i parametri di default ed i parametri rest sono tecnologie sperimentali, parte della proposta  ECMAScript 6, e non sono ancora completamente supportati dai browser.

+
+ +

Parametri di default

+ +

La sintassi per definire i valori di default dei parametri di una funzione permette di inizializzare i parametri formali con valori di default, sempre che non venga passato il valore undefined oppure non venga passato alcun valore. Per maggiori dettagli, vedi default parameters.

+ +

I parametri Rest

+ +

La sintassi per i parametri rest permette di rappresentare un indefinito numero di argomenti come un array. Per maggiori dettagli, vedi rest parameters.

+ +

L'oggetto arguments

+ +

È possibile riferirsi agli argomenti di una funzione, all'interno della funzione, utilizzando l'oggetto arguments. Vedi arguments.

+ + + +

Definire metodi

+ +

Funzioni Getter e setter

+ +

È possibile definire metodi getter ( accessor method: metodi per l'accesso al valore di una variabile privata ) e metodi setter ( mutator method: metodi per la modifica del valore di una variabile privata ) per qulasiasi oggetto standard built-in o per qualsiasi oggetto definito dall'utente che supporti l'aggiunta di nuove proprietà. La sintassi da usare per la definizione di metodi getter e setter utilizza la sintassi per la definizione di valori letterali.

+ +
+
get
+
+

Lega ( bind ) una proprietà di un oggetto ad una funzione, che verrà invocata ogni volta in cui si cercherà di leggere il valore di quella proprietà.

+
+
set
+
Lega ( bind ) una proprietà di un oggetto alla funzione da invocare ogni volta in cui si cercherà di modificare il valore di quella proprietà.
+
+ +

Sintassi per la definizione dei metodi

+ +
+

Nota: le definizioni dei metodi sono tecnologie sperimentali, parte della proposta  ECMAScript 6, e non sono ancora completamente supportate dai browser.

+
+ +

A partire da ECMAScript 6, è possibile definire propri metodi usando una sintassi più breve, simile alla sintassi usata per i metodi getter e setter. Vedi method definitions per maggiori informazioni.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

Il costruttore Function vs. la dichiarazione di funzione vs. l'espressione di funzione

+ +

Compara i seguenti esempi:

+ +

Una funzione definita con la dichiarazione di funzione:

+ +
function multiply(x, y) {
+   return x * y;
+}
+
+ +

Una espressione di funzione di una funzione anonima ( senza nome ), assegnata alla variabile multiply:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

Una espressione di funzione di una funzione chiamata func_name , assegnata alla variabile multiply:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

Differenze

+ +

Tutti e tre gli esempi fanno più o meno la stessa cosa, con qualche piccola differenza:

+ +

C'è una differenza tra il nome di una funzione e la variabile alla quale la funzione viene assegnata. Il nome di una funzione non può essere modificato, mentre la variabile alla quale viene assegnata la funzione può essere riassegnata. Il nome di una funzione può essere utilizzato solo all'interno del corpo della funzione. Tentare di utilizzarlo al di fuori del corpo della funzione genererà un errore ( oppure restituirà undefined se il nome della funzione era stato precedentemente dichiarato con un'istruzione var ). Per esempio:

+ +
var y = function x() {};
+alert(x); // throws an error
+
+ +

Il nome di una funzione appare anche quando la funzione viene serializzata usando il metodo toString applicato alla funzione.

+ +

Dall'altro lato, la variabile alla quale viene assegnata la funzione è limitata solo dal suo scope, la cui inclusione è garantita al momento della dichiarazione di funzione.

+ +

Come si può vedere dal quarto esempio, il nome della funzione può essere diverso dal nome della variabile alla quale la funzione viene assegnata. I due nomi non hanno alcuna relazione tra loro. Una dichiarazione di funzione crea anche una variabile con lo stesso nome della funzione. Quindi, diversamente dalle funzioni definite attraverso un'espressione di funzione, le funzioni definite attraverso una dichiarazione di funzione offrono la possibilità di accedere ad esse attraverso il loro nome, almeno all'interno dello scope in cui erano state definite.

+ +

Una funzione definita con il costruttore 'new Function' non possiede un nome. Tuttavia, nel motore JavaScript SpiderMonkey, la forma serializzata della funzione mostra il nome "anonymous". Per esempio, il codice alert(new Function()) restituisce:

+ +
function anonymous() {
+}
+
+ +

Poichè la funzione, in realtà, non ha un nome, anonymous non è una variabile alla quale si potrà accedere, all'interno della funzione. Per esempio, il seguente codice restituirebbe un errore:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

Diversamente da quanto accade con le funzioni definite con espressioni di funzione o con il costruttore Function, una funzione definita con una dichiarazione di funzione può essere usata prima della dichiarazione di funzione stessa. Per esempio:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

Una funzione definita da un'espressione di funzione eredita lo scope corrente. Vale a dire, la funzione forma una chiusura. Dall'altro lato, una funzione definita dal costruttore Function non eredita alcuno scope, se non quello globale ( che eredita qualsiasi funzione ).

+ +

Le funzioni definite con espressioni di funzione e dichiarazioni di funzione vengono analizzate ( parsed ) solo una volta, mentre quelle definite con il costruttore Function no. Vale a dire, la stringa testuale del corpo della funzione passata al costruttore Function deve essere analizzata ( parsed ) ogni volta in cui viene invocato il costruttore. Sebbene un'espressione di funzione crei ogni volta una chiusura, il corpo della funzione non viene rianalizzato ( reparsed ), così le espressioni di funzione sono ancora più veloci del "new Function(...)". Quindi, il costruttore Function dovrebbe, generalmente, essere evitato dove possibile.

+ +

Occorre tenere presente, tuttavia, che le espressioni di funzione e le dichiarazioni di funzione annidate in una funzione generata dall'analisi ( parsing ) di una stringa del costruttore Function non vengono analizzate ( parsed ) continuamente. Per esempio:

+ +
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.
+ +

Una dichiarazione di funzione è molto facilmente ( e spesso, anche non intenzionalmente ) convertita in un'espressione di funzione. Una dichiarazione di funzione cessa di essere tale quando:

+ + + +
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() {}
+   }
+}
+
+ +

Definire una funzione in modo condizionato

+ +

Le funzioni possono essere definite in modo condizionato, utilizzando sia le istruzioni di funzione ( un'estensione prevista nello standard ECMA-262 Edition 3 ), sia il costruttore Function. Da notare, però, che le  istruzioni di funzione non sono più accettate in ES5 strict mode. Inoltre, questa funzionalità non funziona bene attraverso più browser, quindi sarebbe meglio non farci affidamento.

+ +

Nello script seguente, la funzione zero non verrà mai definita e non potrà mai essere invocata, visto che 'if (0)' restituisce sempre false:

+ +
if (0) {
+   function zero() {
+      document.writeln("This is zero.");
+   }
+}
+
+ +

Se la condizione diventasse 'if (1)', la funzione zero verrebbe definita.

+ +

Nota: sebbene questo tipo di funzione sembri una dichiarazione di funzione, in realtà siamo di fronte ad una espressione ( o statement, o istruzione ), poichè la dichiarazione è annidata all'interno di un'altra istruzione. Vedi le differenze tra dichiarazioni di funzione ed espressioni di funzione.

+ +

Nota: alcuni motori JavaScript, eslcuso SpiderMonkey, trattano, non correttamente, qualsiasi espressione di funzione in modo da assegnare loro un nome, al momento della definizione. Questo comporterebbe che la funzione zero sarebbe comunque definita, anche nell'eventualità che la condizione if restituisse sempre false. Un modo più sicuro per definire le funzioni in modo condizionato è di definirle come funzioni anonime ed assegnarle, poi, ad una variabile:

+ +
if (0) {
+   var zero = function() {
+      document.writeln("This is zero.");
+   }
+}
+
+ +

Esempi

+ +

Restituire un numero formattato

+ +

La seguente funzione restituisce ( return ) una stringa contenente la rappresentazione formattata di un numero, completato ( padded ) con degli zero iniziali.

+ +
// 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;
+}
+
+ +

Queste istruzioni invocano la funzione padZeros.

+ +
var result;
+result = padZeros(42,4); // returns "0042"
+result = padZeros(42,2); // returns "42"
+result = padZeros(5,4);  // returns "0005"
+
+ +

Determinare l'esistenza di una funzione

+ +

È possibile determinare se una funzione esiste, utilizzando l'operatore typeof. Nell'esempio seguente, viene eseguito un test per determinare se l'oggetto window ha una proprietà, che sia una funzione, chiamata noFunc. Se così, la funzione verrà utilizzata; in caso contrario, verrà eseguita una qualsiasi altra azione.

+ +
 if ('function' == typeof window.noFunc) {
+   // use noFunc()
+ } else {
+   // do something else
+ }
+
+ +

Da notare che nel test if  viene usato un riferimento a noFunc  — senza usare le parentesi "()" dopo il nome della funzione: in questo modo, la funzione non viene invocata.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial 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('ES6', '#', 'function*')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ES6', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ES6')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator function39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow function{{CompatNo}}{{CompatGeckoDesktop("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator function{{CompatUnknown}}39{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow function{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/functions_and_function_scope/set/index.html b/files/it/web/javascript/reference/functions_and_function_scope/set/index.html new file mode 100644 index 0000000000..1af0f1c79d --- /dev/null +++ b/files/it/web/javascript/reference/functions_and_function_scope/set/index.html @@ -0,0 +1,214 @@ +--- +title: setter +slug: Web/JavaScript/Reference/Functions_and_function_scope/set +tags: + - Funzioni + - JavaScript + - setter +translation_of: Web/JavaScript/Reference/Functions/set +--- +
{{jsSidebar("Functions")}}
+ +

Il costrutto sintattico set collega una proprietà di un oggetto ad una funzione che viene chiamata quando si ha un tentativo di modifica di quella proprietà.

+ +

Sintassi

+ +
{set prop(val) { . . . }}
+{set [expression](val) { . . . }}
+ +

Parametri

+ +
+
prop
+
Il nome della proprietà da collegare alla funzione data.
+
+ +
+
val
+
Un alias per la variabile che contiene il valore che si sta cercando di assegnare a prop.
+
expression
+
A partire da ECMAScript 6, è possibile anche usare espressioni per nomi di proprietà computate da collegare alla funzione data.
+
+ +

Descrizione

+ +

In JavaScript, un setter può essere utilizzato per eseguire una funzione ogniqualvolta una proprietà specificata sta per essere modificata. I setters sono quasi sempre utilizzati insieme ai getters per creare un tipo di pseudo proprietà. Non è possibile avere un setter su una normale proprietà che contiene un valore.

+ +

Alcune note da considerare quando si utilizza il costrutto sintattico set:

+ +
+ +
+ +

Un setter può essere eliminato usando l'operatore delete.

+ +

Esempi

+ +

Definire un setter per nuovi oggetti in inizializzatori di oggetti

+ +

Questo snippet di codice definisce una pseudo proprietà current di un oggetto che, una volta che vi si assegna un valore, aggiornerà log con quel valore:

+ +
var o = {
+  set current (str) {
+    this.log[this.log.length] = str;
+  },
+  log: []
+}
+
+ +

Nota che  current non è definito ed ogni tentativo di accedervi risulterà in un undefined.

+ +

Rimuovere un setter con l'operatore delete

+ +

Se vuoi rimuovere il setter usato sopra, puoi semplicemente usare delete:

+ +
delete o.current;
+
+ +

Definire un setter su oggetti pre-esistenti usando defineProperty

+ +

Per aggiungere un setter ad un oggetto pre-esistente, usa{{jsxref("Object.defineProperty()")}}.

+ +
var o = { a:0 };
+
+Object.defineProperty(o, "b", { set: function (x) { this.a = x / 2; } });
+
+o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
+console.log(o.a) // 5
+ +

Usare il nome di una proprietà computata

+ +
+

Nota: Le proprietà computate sono una tecnologia sperimentale, parte dello standard proposto ECMAScript 6, e non sono ancora sufficientemente supportate dai browsers. L'uso di queste proprietà in ambienti che non le supportano produrrà un errore di sintassi.

+
+ +
var expr = "foo";
+
+var obj = {
+  baz: "bar",
+  set [expr](v) { this.baz = v; }
+};
+
+console.log(obj.baz); // "bar"
+obj.foo = "baz";      // run the setter
+console.log(obj.baz); // "baz"
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatusCommento
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}{{Spec2('ES5.1')}}Definizione iniziale.
{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ES6')}}Aggiunti i nomi di proprietà computate.
{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}{{Spec2('ESDraft')}}
+ +

Compatibilità dei browsers

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaratteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto base{{CompatChrome(1)}}{{ CompatGeckoDesktop("1.8.1") }}{{ CompatIE(9) }}9.53
Nomi di proprietà computate{{CompatNo}}{{ CompatGeckoDesktop("34") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaratteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("1.8.1") }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Nomi di proprietà computate{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("34.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Note specifiche per SpiderMonkey

+ + + +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/concat/index.html b/files/it/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..9d8d7d6629 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,188 @@ +--- +title: Array.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +tags: + - Array + - aggiungi elementi array + - concat +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +
{{JSRef}}
+ +

Il metodo concat() ritorna un nuovo array costituito dall'array sul quale è stato invocato (joined array) e dagli array e/o valori passati come argomenti.

+ +

Sintassi

+ +
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
+ +

Parametri

+ +
+
valueN
+
Array e/o valori da concatenare nel nuovo array. Vedere la descrizione sotto per i dettagli.
+
+ +

Valore restituito

+ +

Una nuova istanza di {{jsxref("Array")}}.

+ +

Descrizione

+ +

Il metodo concat crea un nuovo array costituito dagli elementi dell'oggetto su cui è stato invocato, seguiti in ordine da ciascun argomento o dagli elementi di ciascun argomento, se quest'ultimo è esso stesso un array.

+ +

Il metodo concat non altera l'oggetto this (l'array originale) o gli elementi passati come parametri, ma ritorna una copia degli stessi che contiene copie degli elementi costituenti gli argomenti. Gli elementi degli array originali sono copiati in quello nuovo secondo le seguenti regole:

+ + + +
var a = [1, 2]
+var b = {c:1}
+var d = a.concat(b)
+
+// d[2] is {c: 1}
+b.c=10
+// d[2] is now {c: 10}
+
+ + + +
+

Note: Concatenando i valori di diversi array o valori, si lasciano gli originali inalterati. Inoltre, qualsiasi operazione sui nuovi array (eccetto le operazioni su elementi che siano riferimenti a oggetti) non avrà effetto alcuno sugli originali e viceversa.

+
+ +

Esempi

+ +

Concatenare due array

+ +

Il codice seguente concatena due array:

+ +
var alpha = ['a', 'b', 'c'];
+var numeric = [1, 2, 3];
+
+alpha.concat(numeric);
+// Risultato: ['a', 'b', 'c', 1, 2, 3]
+
+ +

Concatenare tre array

+ +

Il codice seguente concatena tre array:

+ +
var num1 = [1, 2, 3],
+    num2 = [4, 5, 6],
+    num3 = [7, 8, 9];
+
+var nums = num1.concat(num2, num3);
+
+
+console.log(nums);
+// Risultato: [1, 2, 3, 4, 5, 6, 7, 8, 9]
+
+ +

Concatenare valori ad un array

+ +

Il codice seguente concatena dei valori a quelli presenti in un array:

+ +
var alpha = ['a', 'b', 'c'];
+
+var alphaNumeric = alpha.concat(1, [2, 3]);
+
+console.log(alphaNumeric);
+// Risultato: ['a', 'b', 'c', 1, 2, 3]
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificheStatoCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale, implementato in 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')}} 
+ +

Compatibilità con i Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
BrowserChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto Base{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
BrowserAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto Base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/copywithin/index.html b/files/it/web/javascript/reference/global_objects/array/copywithin/index.html new file mode 100644 index 0000000000..65e00abe47 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/copywithin/index.html @@ -0,0 +1,180 @@ +--- +title: Array.prototype.copyWithin() +slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +--- +
{{JSRef}}
+ +

Il metodo copyWithin() copia superficialmente una parte di un array in un'altra locazione dello stesso array e lo restituisce, senza modificare la sua dimensione.

+ +
{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}
+ + + +

Sintassi

+ +
arr.copyWithin(target)
+arr.copyWithin(target, start)
+arr.copyWithin(target, start, end)
+
+ +

Parametri

+ +
+
target
+
Indice zero-based fino al quale copiare la sequenza. Se negativo, target sarà impostato all'ultimo elemento dell'array.
+
Se target è pari o più grande di arr.length, non sarà copiato nulla. Se target è posizionato dopo start, la sequenza copiata, sarà ritagliata per poter rientrare in arr.length.
+
start {{optional_inline}}
+
Indice zero-based dal quale si comincia a copiare gli elementi. Se negativo, start comincerà a contare dalla fine.
+
Se start è omesso, copyWithin copierà dall'inizio (default 0).
+
end {{optional_inline}}
+
Indice zero-based che indica l'ultimo indice dal quale copiare. copyWithin copia fino ad end ma non lo include. Se negativo, end sarà contato dalla fine.
+
Se end è omesso, copyWithin copierà fino alla fine (default arr.length).
+
+ +

Valore di ritorno

+ +

L'array modificato.

+ +

Descrizione

+ +

copyWithin ha le stesse funzionalità di memmove provenienti da C e C++, ed è un metodo molto performante per spostare i dati di un {{jsxref("Array")}}. Questa modifica si applica specialmente a {{jsxref("TypedArray/copyWithin", "TypedArray")}} metodo con lo stesso nome. La sequenza è copiata e incollata come una singola operzione; la sequenza incollata avrà i valori copiati anche se essi si sovrappongono.

+ +

La funzione copyWithin è intenzionalmente generic, e non richiede che i suoi argomenti siano {{jsxref("Array")}} object.

+ +

copyWithin è un metodo mutabile. Non altera la lunghezza di this, ma cambia il suo contenuto e crea nuove proprietà se necessario..

+ +

Esempi

+ +
[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]
+
+ +

Polyfill

+ +
if (!Array.prototype.copyWithin) {
+  Array.prototype.copyWithin = function(target, start/*, end*/) {
+    // Steps 1-2.
+    if (this == null) {
+      throw new TypeError('this is null or not defined');
+    }
+
+    var O = Object(this);
+
+    // Steps 3-5.
+    var len = O.length >>> 0;
+
+    // Steps 6-8.
+    var relativeTarget = target >> 0;
+
+    var to = relativeTarget < 0 ?
+      Math.max(len + relativeTarget, 0) :
+      Math.min(relativeTarget, len);
+
+    // Steps 9-11.
+    var relativeStart = start >> 0;
+
+    var from = relativeStart < 0 ?
+      Math.max(len + relativeStart, 0) :
+      Math.min(relativeStart, len);
+
+    // Steps 12-14.
+    var end = arguments[2];
+    var relativeEnd = end === undefined ? len : end >> 0;
+
+    var final = relativeEnd < 0 ?
+      Math.max(len + relativeEnd, 0) :
+      Math.min(relativeEnd, len);
+
+    // Step 15.
+    var count = Math.min(final - from, len - to);
+
+    // Steps 16-17.
+    var direction = 1;
+
+    if (from < to && to < (from + count)) {
+      direction = -1;
+      from += count - 1;
+      to += count - 1;
+    }
+
+    // Step 18.
+    while (count > 0) {
+      if (from in O) {
+        O[to] = O[from];
+      } else {
+        delete O[to];
+      }
+
+      from += direction;
+      to += direction;
+      count--;
+    }
+
+    // Step 19.
+    return O;
+  };
+}
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ES2016', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ES2016')}} 
{{SpecName('ESDraft', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +
+ + +

{{Compat("javascript.builtins.Array.copyWithin")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/entries/index.html b/files/it/web/javascript/reference/global_objects/array/entries/index.html new file mode 100644 index 0000000000..31e156afb8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/entries/index.html @@ -0,0 +1,77 @@ +--- +title: Array.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Array/entries +translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries +--- +
{{JSRef}}
+ +

Il metodo entries() restituisce un nuovo oggetto Array Iterator contenente delle coppie chiave/valore per ogni indice presente nell'array.

+ +
{{EmbedInteractiveExample("pages/js/array-entries.html")}}
+ + + +

Sintassi

+ +
a.entries()
+ +

Valore ritornato

+ +

Un nuovo oggetto iterator {{jsxref("Array")}}.

+ +

Esempi

+ +

Utilizzo nel for…of

+ +
var a = ['a', 'b', 'c'];
+var iterator = a.entries();
+
+for (let e of iterator) {
+  console.log(e);
+}
+// [0, 'a']
+// [1, 'b']
+// [2, 'c']
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES2015', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con il browser

+ +
+ + +

{{Compat("javascript.builtins.Array.entries")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/every/index.html b/files/it/web/javascript/reference/global_objects/array/every/index.html new file mode 100644 index 0000000000..c1f3238ad6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/every/index.html @@ -0,0 +1,184 @@ +--- +title: Array.prototype.every() +slug: Web/JavaScript/Reference/Global_Objects/Array/every +translation_of: Web/JavaScript/Reference/Global_Objects/Array/every +--- +
{{JSRef}}
+ +

Il metodo every() controlla che tutti gli elementi all'interno dell'array passino il test implementato dalla funzione fornita.

+ +
{{EmbedInteractiveExample("pages/js/array-every.html")}}
+ + + +

Sintassi

+ +
arr.every(callback[, thisArg])
+ +

Parametri

+ +
+
callback
+
Funzione da testare per ciascun elemento, che prende tre argomenti: +
+
currentValue (required)
+
L'elemento corrente che viene elaborato all'interno dell'array.
+
index{{Optional_inline}}
+
L'indice dell'elemento corrente che viene elaborato all'interno dell'array.
+
array{{Optional_inline}}
+
L'array every chiamato.
+
+
+
thisArg{{Optional_inline}}
+
Opzionale. Valore da utilizzare come this durante l'esecuzione della callback.
+
+ +

Valore di ritorno

+ +

true se la funzione callback ritorna un valore {{Glossary("truthy")}} per ciascun elemento dell'array; altrimenti, false.

+ +

Descrizione

+ +

Il metodo every  esegue la funzione callback fornita una volta per ciascun elemento presente all'interno dell'array finché non ne trova uno per il quale la callback ritorna un valore {{Glossary("falsy")}}. Altrimenti, se la callback ritorna un valore {{Glossary("truthy")}} per tutti gli elementi, every ritorna truecallback viene invocata solo per gli indici dell'array che hanno un valore assegnato; non viene invocata per gli indici che sono stati eliminati o ai quali non è mai stato assegnato un valore.

+ +

callback viene invocata con tre argomenti: il valore dell'elemento, l'indice dell'elemento, e l'Array oggetto che viene attraversato. 

+ +

Se il parametro thisArg viene fornito a every, esso verrà usato come valore this per la callback. Altrimenti, il valore undefined verrà usato al suo posto come valore this.  Il valore this, ultimo osservabile dalla callback, viene determinato secondo le usuali regole per determinare il this visto da una funzione.

+ +

every non modifica l'array in cui viene chiamato.

+ +

Il range di elementi processati da every viene impostato prima della prima invocazione di callback. Gli elementi che vengono appesi all'inizio dell'array dopo la chiamata a every  non verranno visitati dalla callback. Se gli elementi esistenti dell'array vengono cambiati, il loro valore passato a callback sarà il valore al momento in cui every li visiterà; gli elementi cancellati non sono visitati.

+ +

every agisce come il quantificatore "for all" in matematica. In particolare, per un array vuoto, esso ritorna true. (E' vacuously true che tutti gli elementi dell' empty set soddisfano qualsiasi condizione data.)

+ +

Esempi

+ +

Controllo sulla grandezza di tutti gli elementi dell'array

+ +

Il seguente esempio controlla che tutti gli elementi dell'array siano maggiori di 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
+
+ +

Utilizzando arrow functions

+ +

Arrow functions forniscono una sintassi più breve per lo stesso test.

+ +
[12, 5, 8, 130, 44].every(x => x >= 10); // false
+[12, 54, 18, 130, 44].every(x => x >= 10); // true
+ +

Polyfill

+ +

every è stato aggiunto allo standard ECMA-262 nella 5a edizione; per questo motivo potrebbe non essere presente in altre implementazioni dello standard. Potrai aggirare il problema inserendo il seguente codice all'inizio dei tuoi scripts, permettendo così l'utilizzo di every in implementazioni che non lo supportano nativamente. Questo algoritmo è esattamente quello specificato in ECMA-262, 5a edizione, assumendo che Object e TypeError abbiano i loro valori originali e che callbackfn.call valuti sul valore originale di {{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') {
+      throw new TypeError();
+    }
+
+    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
+    if (arguments.length > 1) {
+      T = thisArg;
+    }
+
+    // 6. Let k be 0.
+    k = 0;
+
+    // 7. Repeat, while k < len
+    while (k < len) {
+
+      var kValue;
+
+      // a. Let Pk be ToString(k).
+      //   This is implicit for LHS operands of the in operator
+      // b. Let kPresent be the result of calling the HasProperty internal
+      //    method of O with argument Pk.
+      //   This step can be combined with c
+      // c. If kPresent is true, then
+      if (k in O) {
+
+        // i. Let kValue be the result of calling the Get internal method
+        //    of O with argument Pk.
+        kValue = O[k];
+
+        // ii. Let testResult be the result of calling the Call internal method
+        //     of callbackfn with T as the this value and argument list
+        //     containing kValue, k, and O.
+        var testResult = callbackfn.call(T, kValue, k, O);
+
+        // iii. If ToBoolean(testResult) is false, return false.
+        if (!testResult) {
+          return false;
+        }
+      }
+      k++;
+    }
+    return true;
+  };
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementata in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +
+ + +

{{Compat("javascript.builtins.Array.every")}}

+
+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/fill/index.html b/files/it/web/javascript/reference/global_objects/array/fill/index.html new file mode 100644 index 0000000000..043696f554 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/fill/index.html @@ -0,0 +1,155 @@ +--- +title: Array.prototype.fill() +slug: Web/JavaScript/Reference/Global_Objects/Array/fill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill +--- +
{{JSRef}}
+ +

Il metodo fill() assegna un valore statico a tutti gli elementi di un array compresi tra un indice iniziale ed un indice finale.

+ +
var numbers = [1, 2, 3]
+numbers.fill(1);
+
+// results in [1, 1, 1]
+ +

Sintassi

+ +
arr.fill(value)
+arr.fill(value, start)
+arr.fill(value, start, end)
+
+ +

Parametri

+ +
+
value
+
Valore statico da assegnare agli elementi dell'array.
+
start {{optional_inline}}
+
Indice iniziale, default uguale a 0.
+
end {{optional_inline}}
+
Indice finale, default uguale a this.length.
+
+ +

Valore di ritorno

+ +

L'array modificato.

+ +

Descrizione

+ +

L'intervallo di elementi da assegnare è compreso tra [start, end).

+ +

Il metodo  fill accetta fino a tre argomenti: value, start and end. Gli argomenti start e end  sono opzionali con valori di default rispettivamente di 0 di length dell'oggetto this .

+ +

Se start è negativo, viene interpretato come length+start dove length è la lunghezza dell'array. Se end è negativo, viene intrpretato come length+end.

+ +

La funzione fill è volutamente generica, non richiede che il suo valore this sia un Array.

+ +

Il metodo fill è mutabile, ovvero modifica l'oggetto this  e  lo restituisce modificato, ovvero non ne restituisce una copia modificata.

+ +

Quando al metodo fill viene passato un oggetto, il metodo effettuerà una copia dell'oggetto e  assegnerà agli elementi dell'Array un riferimento alla copia.

+ +

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, 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;
+    }
+  });
+}
+
+ +

Se hai necessità di supportare engine Javascript veramente obsolete che non supportano Object.defineProperty, è meglio non usare affatto il polyfill per il medoto Array.prototype perchè non è possibile renderlo non enumerabile.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
{{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")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/filter/index.html b/files/it/web/javascript/reference/global_objects/array/filter/index.html new file mode 100644 index 0000000000..33d24d38b6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,245 @@ +--- +title: Array.prototype.filter() +slug: Web/JavaScript/Reference/Global_Objects/Array/filter +translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter +--- +
{{JSRef}}
+ +

Il metodo filter() crea un nuovo array contentente tutti gli elementi che passano il test implementato dalla funzione. 

+ +
function isBigEnough(value) {
+  return value >= 10;
+}
+
+var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
+// filtered is [12, 130, 44]
+
+ +

Sintassi

+ +
var new_array = arr.filter(callback[, thisArg])
+ +

Parametri

+ +
+
callback
+
Funzione predicato per testare ciascun elemento dell'array. Restituisce true se l'elemento va mantenuto, false altrimenti. Essa prende in input tre argomenti:
+
+
+
element
+
L'elemento corrente nell'array processato.
+
index
+
L' indice dell'elemento corrente processato nell'array.
+
array
+
l'array su cui filter è stato chiamato.
+
+
+
thisArg
+
Opzionale. Valore da usare come this quando si esegue callback.
+
+ +

Valore restituito

+ +

Un nuovo array con gli elementi che hanno passato il test.

+ +

Descrizione

+ +

filter() chiama funzione ricorsiva (callback) fornita una volta per ciascun elemento dell'array e crea un nuovo array con tutti quei valori in cui la callback ha restituito un valore true.. callback viene invocata solo per gli indici dell'array a cui sono associati dei valori; non viene invocata per inidici in cui sono stati cancellati i valori o in cui non sono stati definiti valori. Gli elementi dell'array che non superano il test vengono semplicemente ignorati, non venendo così inseriti nel nuovo array.

+ +

callback viene invocata con tre argomenti:

+ +
    +
  1. il valore dell'elemento
  2. +
  3. l'indice dell'elemento
  4. +
  5. l' Array oggetto da passare
  6. +
+ +

Se viene fornito a filter un parametro thisArg , questo verrà passato a sua volta a callback quando verrà invocata per usarlo come valore di this . Altrimenti verrà passato un valore undefined per essere usato come valore di this. Il valore  this osservabile in definitiva dalla funzione callback viene scelto seguendo le usuali regole di determinazione dei this visti da una funzione.

+ +

filter() non muta l'array sul quale viene chiamata.

+ +

La gamma di element processati da filter() viene impostata prima della invocazione della callback. Gli elementi che vengono mesi nell'array da filtrare dopo l'invocazione di filter() non verranno esaminati dalla callback. Se ci sono elementi dell'array da fitrare i cui valori vengono cambiati o vengono cancellati dopo la applicazione di filter() ,  questi nel tempo di chamata di filter() verranno testati dalla  callback nello stato previo alla loro modifica. Elementi cancellati prima della applicazione di  filter()  non vengono visitati.

+ +

Esempi

+ +

Filtrare tutti i piccoli valori

+ +

Il seguente esempio usa filter() per realizzare un array filtrato che non contenga elementi di valore inferiore a 10.

+ +
function isBigEnough(value) {
+  return value >= 10;
+}
+
+var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
+// filtered is [12, 130, 44]
+
+ +

Filtrare entrate non valide in JSON

+ +

Il sequente esempio di utilizzo di filter() crea un json filtrato di elementi con valido  id numerico.

+ +
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)) {
+    return true;
+  }
+  invalidEntries++;
+  return false;
+}
+
+var arrByID = arr.filter(filterByID);
+
+console.log('Filtered Array\n', arrByID);
+// Array filtrato
+// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]
+
+console.log('Quantità di entrate non valide = ', invalidEntries);
+// Quantità di entrate non valide = 4
+
+ +

Polyfill

+ +

filter() è stato aggiunto allo standard ECMA-262 nella quinta edizione; potrebbe essere non presente in tutte le implementazioni dello standard. Puoi sempre inserire il seguente codice nei tuoi script per poter usare filter() nelle implementazioni ECMA-262 che non lo supportanto nativamente. Questo algoritmo è esattamente quello nella specifica ECMA-262, quinta edizione, assumendo che  fn.call valuti il valore originale di  {{jsxref("Function.prototype.call()")}},e che {{jsxref("Array.prototype.push()")}} abbia il suo valore originale.

+ +
if (!Array.prototype.filter) {
+  Array.prototype.filter = function(fun/*, thisArg*/) {
+    'use strict';
+
+    if (this === void 0 || this === null) {
+      throw new TypeError();
+    }
+
+    var t = Object(this);
+    var len = t.length >>> 0;
+    if (typeof fun !== 'function') {
+      throw new TypeError();
+    }
+
+    var res = [];
+    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
+    for (var i = 0; i < len; i++) {
+      if (i in t) {
+        var val = t[i];
+
+        // NOTE: Technically this should Object.defineProperty at
+        //       the next index, as push can be affected by
+        //       properties on Object.prototype and Array.prototype.
+        //       But that method's new, and collisions should be
+        //       rare, so use the more-compatible alternative.
+        if (fun.call(thisArg, val, i, t)) {
+          res.push(val);
+        }
+      }
+    }
+
+    return res;
+  };
+}
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}} +

Definizione iniziale. Implementato in javascript 1.6.

+
{{SpecName('ES6', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}}
+ +

Compatibilità Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8")}}{{CompatIE("9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/find/index.html b/files/it/web/javascript/reference/global_objects/array/find/index.html new file mode 100644 index 0000000000..c215ff79e7 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,216 @@ +--- +title: Array.prototype.find() +slug: Web/JavaScript/Reference/Global_Objects/Array/find +tags: + - Array + - ECMAScript 2015 + - ECMAScript6 + - JavaScript + - Prototype + - Riferimento + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/find +--- +
{{JSRef}}
+ +

Il metodo find() restituisce il valore del primo elemento nell'array che soddisfi la funzione di test passata come argomento. Altrimenti viene restituito {{jsxref("undefined")}}.

+ +
function isBigEnough(element) {
+  return element >= 15;
+}
+
+[12, 5, 8, 130, 44].find(isBigEnough); // 130
+ +

Vedi anche il metodo {{jsxref("Array.findIndex", "findIndex()")}}, che restituisce l'indice dell'elemento trovato nell'array invece del suo valore.

+ +

Se hai bisogno di trovare la posizione di un elemento o determinare se un elemento esiste o meno nell'array, puoi usare i metodi {{jsxref("Array.prototype.indexOf()")}} o {{jsxref("Array.prototype.includes()")}}.

+ +

Sintassi

+ +
arr.find(callback[, thisArg])
+ +

Parametri

+ +
+
callback
+
Funzione da eseguire per ogni valore contenuto nell'array, richiede tre argomenti: +
+
element
+
L'elemento nell'array che dev'essere testato.
+
index
+
L'indice dell'elemento nell'array che dev'essere testato.
+
array
+
L'array sul quale è stato chiamato il find.
+
+
+
thisArg
+
Opzionale. L'oggetto da utilizzare come this durante l'esecuzione della callback.
+
+ +

Valore restituito

+ +

Un valore dell'array se un elemento soddisfa la condizione; altrimenti, {{jsxref("undefined")}}.

+ +

Descrizione

+ +

Il metodo find esegue la funzione di callback una sola volta per ciascun elemento nell'array finché non ne trova uno per il quale la funzione di callback restituisca true. Se tale elemento viene trovato, find restituisce immediatamente il valore di quell'elemento. Altrimenti, find restituisce {{jsxref("undefined")}}. La funzione callback è invocata solo per quegli indici dell'array per i quali esiste un valore; non viene invocata per quegli indici che sono stati cancellati o ai quali non è mai stato assegnato alcun valore.

+ +

Alla funzione callback vengono passati tre parametri: il valore dell'elemento, l'indice dell'elemento e l'oggetto Array che si sta esplorando.

+ +

Se viene passato il parametro thisArg al metodo find, questo verrà usato come this per ciascuna invocazione della funzione callback. Altrimenti viene utilizzato {{jsxref("undefined")}}.

+ +

Il metodo find non modifica l'array sul quale viene chiamato.

+ +

L'intervallo di elementi analizzati dal metodo find è impostato prima della prima invocazione della callback. Gli elementi aggiunti all'array successivamente alla chiamata del metodo find non verranno analizzate dalla callback. Se un elemento dell'array esistente, ma non ancora visitato, viene modificato dalla callback, il valore passato alla funzione callback sarà il valore contenuto nel momento in cui il metodo find visita l'indice di quell'elemento; gli elementi eliminati non vengono visitati.

+ +

Esempi

+ +

Trova un oggetto in un array tramite una sua proprietà

+ +
var inventario = [
+    {name: 'mele', quantity: 2},
+    {name: 'banane', quantity: 0},
+    {name: 'ciliegie', quantity: 5}
+];
+
+function findCherries(fruit) {
+    return fruit.name === 'ciliegie';
+}
+
+console.log(inventario.find(findCherries));
+// { name: 'ciliegie', quantity: 5 }
+ +

Trova un numero primo in un array

+ +

L'esempio seguente trova un elemento nell'array che sia un numero primo (o restituisce {{jsxref("undefined")}} se non ce ne sono).

+ +
function isPrime(element, index, array) {
+  var start = 2;
+  while (start <= Math.sqrt(element)) {
+    if (element % start++ < 1) {
+      return false;
+    }
+  }
+  return element > 1;
+}
+
+console.log([4, 6, 8, 12].find(isPrime)); // undefined, non trovato
+console.log([4, 5, 8, 12].find(isPrime)); // 5
+
+ +

Polyfill

+ +

Questo metodo è stato aggiunto nella specifica ECMAScript 2015 e potrebbe non ancora essere disponibile in tutte le implementazioni JavaScript. Comunque, puoi aggiungere il metodo Array.prototype.find() utilizzando il seguente snippet:

+ +
if (!Array.prototype.find) {
+  Object.defineProperty(Array.prototype, 'find', {
+    value: function(predicate) {
+     'use strict';
+     if (this == null) {
+       throw new TypeError('Array.prototype.find called on null or undefined');
+     }
+     if (typeof predicate !== 'function') {
+       throw new TypeError('predicate must be a function');
+     }
+     var list = Object(this);
+     var length = list.length >>> 0;
+     var thisArg = arguments[1];
+
+     for (var i = 0; i !== length; i++) {
+       if (predicate.call(thisArg, this[i], i, list)) {
+         return this[i];
+       }
+     }
+     return undefined;
+    }
+  });
+}
+
+ +

Se hai la necessità di supportare motori JavaScript molto obsoleti che non supportano Object.defineProperty, sarebbe meglio non aggiungere per niente il metodo  Array.prototype.find(), poiché potresti renderli non-enumerabili.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatChrome(45.0)}}{{CompatGeckoDesktop("25.0")}}{{CompatNo}}12{{CompatOpera(32.0)}}{{CompatSafari("7.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileEdgeOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25.0")}}{{CompatNo}}12{{CompatNo}}8.0
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/findindex/index.html b/files/it/web/javascript/reference/global_objects/array/findindex/index.html new file mode 100644 index 0000000000..f9f2f65791 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/findindex/index.html @@ -0,0 +1,182 @@ +--- +title: Array.prototype.findIndex() +slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex +translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex +--- +
{{JSRef}}
+ +

Il metodo findIndex() restituisce l'indice del primo elemento nell'array che soddisfa la funzione di testing fornita. Altrimenti, restituisce -1, indicando che nessun elemento ha superato il test.

+ +
{{EmbedInteractiveExample("pages/js/array-findindex.html","shorter")}}
+ + + +

Guarda anche il metodo {{jsxref("Array.find", "find()")}}, che restituisce il valore dell'elemento anziché il suo indice.

+ +

Sintassi

+ +
arr.findIndex(callback( elemento[,indice[, array]] )[, thisArg])
+
+ +

Parametri

+ +
+
callback
+
+

Una funzione da eseguire su ognuno dei valori finché la funzione non resitituisce true, indicando che l'elemento che soddisfa la condizione è stato trovato.

+ +

Prende in input tre argomenti:

+ +
+
elemento
+
L'elemento dell'array che viene processato.
+
indice {{optional_inline}}
+
L'indice dell'elemento dell'array che viene processato.
+
array {{optional_inline}}
+
L'array su cui è stato chiamato findIndex().
+
+
+
thisArg {{optional_inline}}
+
Oggetto da usare come this quando viene eseguita la callback.
+
+ +

Valore restituito

+ +

L'indice dell primo elemento dell'array che supera il test. Altrimenti -1.

+ +

Descrizione

+ +

Il metodo findIndex() esegue la callback una volta per ogni indice nell'array finché non trova quello per cui la callback ritorna un valore {{Glossary("truthy")}}.

+ +

Se l'elemento viene trovato, findIndex()  restitutisce immediatamente l'idice dell'elemento. Se callback non restituisce mai un valore {{Glossary("truthy")}} (o la length dell'array è 0), findIndex() restituisce -1.

+ +
+

Caso limite: A differenza di altri metodi per array come {{jsxref("Array.some()")}}, callback viene eseguita anche per gli indici con valori non assegnati.

+
+ +

callback è invocata con tre argomenti:

+ +
    +
  1. Il valore dell'elemento
  2. +
  3. L'indice dell'elemento
  4. +
  5. L'oggetto Array che viene percorso
  6. +
+ +

Se viene passato a findIndex() un parametro thisArg, sarà usato come this in ogni invocazione di callback. Se non viene passato si usa {{jsxref("undefined")}}.

+ +

The range of elements processed by findIndex() is set before the first invocation of callback. callback will not process the elements appended to the array after the call to findIndex() begins. If an existing, unvisited element of the array is changed by callback, its value passed to the callback will be the value at the time findIndex() visits the element's index.

+ +

Elements that are deleted are still visited.

+ +

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;
+    },
+    configurable: true,
+    writable: true
+  });
+}
+
+ +

If you need to support truly obsolete JavaScript engines that do not support {{jsxref("Object.defineProperty")}}, it is best not to polyfill Array.prototype methods at all, as you cannot make them non-enumerable.

+ +

Examples

+ +

Find the index of a prime number in an array

+ +

The following example returns the index of the first element in the array that is a prime number, or -1 if there is no prime number.

+ +
function isPrime(num) {
+  for (let i = 2; num > i; i++) {
+    if (num % i == 0) {
+      return false;
+    }
+  }
+  return num > 1;
+}
+
+console.log([4, 6, 8, 9, 12].findIndex(isPrime)); // -1, not found
+console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2 (array[2] is 7)
+
+ +

Find index using arrow function

+ +

The following example finds the index of a fruit using an arrow function:

+ +
const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];
+
+const index = fruits.findIndex(fruit => fruit === "blueberries");
+
+console.log(index); // 3
+console.log(fruits[index]); // blueberries
+
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.findindex', 'Array.prototype.findIndex')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.findIndex")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/flat/index.html b/files/it/web/javascript/reference/global_objects/array/flat/index.html new file mode 100644 index 0000000000..3c5a81ed4b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/flat/index.html @@ -0,0 +1,159 @@ +--- +title: Array.prototype.flat() +slug: Web/JavaScript/Reference/Global_Objects/Array/flat +tags: + - Array + - JavaScript + - Prototype + - Referenza + - flat + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat +--- +
+ +
{{JSRef}}
+ +

Il metodo flat() crea un nuovo array con tutti gli elementi dei propri sotto-array concatenati ricorsivamente al suo interno fino alla profondità specificata.

+ + + + + +

Sintassi

+ +
var newArray = arr.flat([profondità]);
+ +

Parametri

+ +
+
profondità {{optional_inline}}
+
Il livello di profondità che specifica quanto a fondo la struttura di array annidati deve essere appianata. Default a 1.
+
+ +

Valore di ritorno

+ +

Un nuovo array con gli elementi dei sotto-array concatenati al suo interno.

+ +

Esempi

+ +

Appianare array annidati

+ +
var arr1 = [1, 2, [3, 4]];
+arr1.flat();
+// [1, 2, 3, 4]
+
+var arr2 = [1, 2, [3, 4, [5, 6]]];
+arr2.flat();
+// [1, 2, 3, 4, [5, 6]]
+
+var arr3 = [1, 2, [3, 4, [5, 6]]];
+arr3.flat(2);
+// [1, 2, 3, 4, 5, 6]
+
+ +

Appianamento e slot vuoti negli array

+ +

Il metodo flat rimuove gli slot vuoti in un array:

+ +
var arr4 = [1, 2, , 4, 5];
+arr4.flat();
+// [1, 2, 4, 5]
+
+ +

Alternative

+ +

reduce e concat

+ +
var arr1 = [1, 2, [3, 4]];
+arr1.flat();
+
+//appianare array di un livello
+arr1.reduce((acc, val) => acc.concat(val), []);// [1, 2, 3, 4]
+
+//o
+const flatSingle = arr => [].concat(...arr);
+
+ +
//abilitare appianamento a una certà profondità usando reduce e concat
+var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
+
+function flattenDeep(arr1) {
+   return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
+}
+flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
+
+ +
//appianamento profondo non ricorsivo usando uno stack
+var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
+function flatten(input) {
+  const stack = [...input];
+  const res = [];
+  while (stack.length) {
+    // rimozione valore dallo stack
+    const next = stack.pop();
+    if (Array.isArray(next)) {
+      // reinserimento degli elementi degli array, non modifica l'input originale
+      stack.push(...next);
+    } else {
+      res.push(next);
+    }
+  }
+  //reverse per ripristinare l'ordine originario
+  return res.reverse();
+}
+flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
+
+ +
//appianamento profondo ricorsivo
+function flatten(array) {
+  var flattend = [];
+  !(function flat(array) {
+    array.forEach(function(el) {
+      if (Array.isArray(el)) flat(el);
+      else flattend.push(el);
+    });
+  })(array);
+  return flattend;
+}
+
+ + + +

Specifiche

+ + + + + + + + + + + + + + +
SpecificaStatoCommenti
+

Array.prototype.flat proposal

+
Finished (4)
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Array.flat")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/flatmap/index.html b/files/it/web/javascript/reference/global_objects/array/flatmap/index.html new file mode 100644 index 0000000000..4397fd7c5d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/flatmap/index.html @@ -0,0 +1,142 @@ +--- +title: Array.prototype.flatMap() +slug: Web/JavaScript/Reference/Global_Objects/Array/flatMap +translation_of: Web/JavaScript/Reference/Global_Objects/Array/flatMap +--- +
{{JSRef}}
+ +

Il metodo flatMap() prima mappa ogni elemento eseguendo la funzione passata come parametro, poi appiattisce il risultato in un nuovo array. Il comportamento è identico a una chiamata a  {{jsxref("Array.prototype.map","map()")}} seguita da un {{jsxref("Array.prototype.flat","flat()")}} con profondità 1, ma flatMap() in questo caso è la soluzione migliore perché è più efficente delle due chiamate separate.

+ + + + + +

Sintassi

+ +
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
+    // restituisci un elemento per il nuovo array
+}[, thisArg])
+ +

Parametri

+ +
+
callback
+
Funzione per produrre un elemento del nuovo Array, prevede a sua volta tre parametri: +
+
+
currentValue
+
L'elemento che si sta processando.
+
index{{optional_inline}}
+
L'indice dell'elemento corrente.
+
array{{optional_inline}}
+
L'array che si sta processando con map.
+
+
+
thisArg{{optional_inline}}
+
Valore usato come this mentre si esegue la callback.
+
+ +

Risultato

+ +

Un nuovo array i cui elementi sono il risultato della chiamata a callback, "appiattiti" ad una profondità di 1

+ +

Descrizione

+ +

Guarda {{jsxref("Array.prototype.map()")}} per una descrizione dettagliata della funzione callback. flatMap è identico a una chiamata a map seguita da una chiamata flat con una profondità di 1.

+ +

Esempi

+ +

map()flatMap()

+ +
let arr1 = [1, 2, 3, 4];
+
+arr1.map(x => [x * 2]);
+// [[2], [4], [6], [8]]
+
+arr1.flatMap(x => [x * 2]);
+// [2, 4, 6, 8]
+
+// viene appiattito un solo elemento
+arr1.flatMap(x => [[x * 2]]);
+// [[2], [4], [6], [8]]
+
+ +

Lo stesso risultato lo si può ottenere anche con la sola chiamata a map, di seguito è riportato un esempio migliore di uso di flatMap.

+ +

Viene generata una lista di parole da una lista di frasi.

+ +
let arr1 = ["it's Sunny in", "", "California"];
+
+arr1.map(x => x.split(" "));
+// [["it's","Sunny","in"],[""],["California"]]
+
+arr1.flatMap(x => x.split(" "));
+// ["it's","Sunny","in", "", "California"]
+ +

Notare che, a differenza di map da solo, la lunghezza dell'output è diversa tra le due chiamate e in particolare il risultato di flatMap non avrà la stessa lunghezza dell'input.

+ +

Aggiungere e rimuovere elementi durante l'esecuzione di map()

+ +

flatMap può essere usato per aggiungere e rimuovere elementi durante l'esecuzione di map. In altre parole, offre la possibilità di mappare molti a molti (processando ogni input separatamente), anziché sempre uno a uno. In questo senso lavora come opposto di filter. Basta restituire un array con un solo elemento per mantenere l'oggetto invariato, un array con più elementi, invece, aggiungerà questi al risultato, un array vuoto per rimuovere l'elemento corrente.

+ +
// Per rimuovere i numeri negativi e dividere i numeri dispari in un numero pari e un 1
+let a = [5, 4, -3, 20, 17, -33, -4, 18]
+//       |\  \  x   |  | \   x   x   |
+//      [4,1, 4,   20, 16, 1,       18]
+
+a.flatMap( (n) =>
+  (n < 0) ?      [] :
+  (n % 2 == 0) ? [n] :
+                 [n-1, 1]
+)
+
+// expected output: [4, 1, 4, 20, 16, 1, 18]
+
+ +

Alternative

+ +

reduce() and concat()

+ +
var arr = [1, 2, 3, 4];
+
+arr.flatMap(x => [x, x * 2]);
+// si ottiene lo stesso risultato con
+arr.reduce((acc, x) => acc.concat([x, x * 2]), []);
+// [1, 2, 2, 4, 3, 6, 4, 8]
+
+ +

Notare che questa soluzione non è efficente e non dovrebbe essere usata per array di grandi dimensioni: in ogni iterazione viene creato un nuovo array temporaneo che dovrà essere deallocato dal garbae collector, e copia gli elementi dall'array corrente (acc), in un nuovo array ad ogni iterazione invece di aggiungerli ad uno preesistente.

+ + + +

Specifiche

+ + + + + + + + + + +
Specifica
{{SpecName('ESDraft', '#sec-array.prototype.flatmap', 'Array.prototype.flatMap')}}
+ +

Compatibilità browser

+ +
+ + +

{{Compat("javascript.builtins.Array.flatMap")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/foreach/index.html b/files/it/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..dbd4919852 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,331 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +tags: + - Array + - ECMAScript 5 + - JavaScript + - Prototype + - Referenza + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +
{{JSRef}}
+ +

Il metodo forEach() esegue una funzione fornita una volta per ogni elemento dell'array.

+ +
{{EmbedInteractiveExample("pages/js/array-foreach.html")}}
+ + + +

Sintassi

+ +
arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);
+ +

Parametri

+ +
+
callback
+
Funzione da eseguire per ciascun elemento, prendendo tre argomenti:
+
+
+
currentValue
+
L'elemento corrente in elaborazione nell'array.
+
index {{optional_inline}}
+
L'indice dell'elemento corrente in elaborazione nell'array.
+
array {{optional_inline}}
+
L'array a cui viene applicato forEach().
+
+
+
thisArg {{optional_inline}}
+
Valore da utilizzare come this quando si esegue callback.
+
+ +

Descrizione

+ +

forEach() esegue il callback fornito una volta per ciascun elemento presente nell'array in ordine crescente. Non è invocato per le proprietà dell'indice che sono state eliminate o non inizializzate (ad esempio su array sparsi).

+ +

callback viene invocato con tre argomenti:

+ + + +

Se viene fornito il parametro thisArg a forEach(), verrà utilizzato come valore this del callback. Altrimenti, il valore {{jsxref("undefined")}} sarà usato come valore this. Il valore this alla fine osservabile da callback è determinato secondo le consuete regole per determinare il this visto da una funzione.

+ +

L'intervallo di elementi elaborati da forEach() viene impostato prima della prima chiamata del callback. Gli elementi aggiunti all'array dopo che la chiamata forEach() inizia non saranno calcolati da callback. Se i valori degli elementi esistenti dell'array vengono modificati, il valore passato a callback sarà il valore al momento in cui forEach() li visita; gli elementi che vengono cancellati prima di essere visitati non vengono visitati. Se gli elementi già visitati vengono rimossi (ad esempio usando {{jsxref("Array.prototype.shift()", "shift()")}}) durante l'iterazione, gli elementi successivi verranno saltati - vedi l'esempio sotto.

+ +

forEach() esegue la funzione callback una volta per ogni elemento dell'array; a differenza di {{jsxref("Array.prototype.map()", "map()")}} o {{jsxref("Array.prototype.reduce()", "reduce()")}} restituisce sempre {{jsxref("undefined")}} e non è concatenabile. Il tipico caso d'uso è eseguire effetti collaterali alla fine del chain.

+ +

forEach() non muta l'array su cui è chiamato (sebbene callback, se invocato, possa farlo).

+ +
+

Non c'è modo di fermare o interrompere un loop forEach() se non lanciando un'eccezione. Se hai bisogno di un simile comportamento, il metodo forEach() è lo strumento sbagliato.

+ +

La risoluzione anticipata può essere eseguita con:

+ + + +

Gli altri metodi per array: {{jsxref("Array.prototype.every()")}}, {{jsxref("Array.prototype.some()")}}, {{jsxref("Array.prototype.find()")}}, e {{jsxref("Array.prototype.findIndex()")}} testano gli elementi dell'array con un predicato restituendo un valore di verità per determinare se è necessaria un'ulteriore iterazione.

+
+ +

Esempi

+ +

Convertire un loop for in forEach

+ +
const items = ['item1', 'item2', 'item3'];
+const copy = [];
+
+// prima
+for (let i=0; i<items.length; i++) {
+  copy.push(items[i]);
+}
+
+// dopo
+items.forEach(function(item) {
+  copy.push(item);
+});
+
+ +

Stampa del contenuto di un array

+ +
+

Note: Per visualizzare il contenuto di un array nella console, puoi utilizzare console.table() che stamperà una versione formattata dell'array. L'esempio seguente illustra un altro modo per farlo, usando forEach().

+
+ +

Il seguente codice logga una linea per ogni elemento in un array:

+ +
function logArrayElements(element, index, array) {
+  console.log('a[' + index + '] = ' + element);
+}
+
+// Nota che l'indice 2 viene saltato poiché non vi è alcun elemento
+// in quella posizione nell'array.
+[2, 5, , 9].forEach(logArrayElements);
+// logga:
+// a[0] = 2
+// a[1] = 5
+// a[3] = 9
+
+ +

Usare thisArg

+ +

Il seguente esempio (inventato) aggiorna le proprietà di un oggetto da ciascuna voce dell'array:

+ +
function Counter() {
+  this.sum = 0;
+  this.count = 0;
+}
+Counter.prototype.add = function(array) {
+  array.forEach(function(entry) {
+    this.sum += entry;
+    ++this.count;
+  }, this);
+  // ^---- Nota
+};
+
+const obj = new Counter();
+obj.add([2, 5, 9]);
+obj.count;
+// 3
+obj.sum;
+// 16
+
+ +

Poiché il parametro thisArg (this) viene fornito a forEach(), viene passato a callback ogni volta che viene richiamato, per essere utilizzato come valore this.

+ +
+

Se si passa l'argomento della funzione utilizzando un'espressione della funzione a freccia il parametro thisArg può essere omesso poiché le funzioni a freccia associano in modo lessicale il valore {{jsxref("Operators/this", "this")}}.

+
+ +

Una funzione di copia di oggetti

+ +

Il seguente codice crea una copia di un dato oggetto. Esistono diversi modi per creare una copia di un oggetto; il seguente è solo un modo e viene presentato per spiegare come funziona Array.prototype.forEach() usando le funzioni di meta proprietà ECMAScript 5 Object.*.

+ +
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
+
+ +

Se l'array viene modificato durante l'iterazione, altri elementi potrebbero essere saltati.

+ +

L'esempio seguente registra "uno", "due", "quattro". Quando viene raggiunta la voce contenente il valore "due", la prima voce dell'intero array viene spostata, il che comporta il trasferimento di tutte le voci rimanenti in una posizione. Poiché l'elemento "quattro" è ora in una posizione precedente nell'array, "tre" verrà saltato. forEach() non esegue una copia dell'array prima di iterare.

+ +
var words = ['uno', 'due', 'tre', 'quattro'];
+words.forEach(function(word) {
+  console.log(word);
+  if (word === 'due') {
+    words.shift();
+  }
+});
+// uno
+// due
+// quattro
+
+ +

Appiattire un array

+ +

Il seguente esempio è qui solo per scopi didattici. Se si desidera appiattire un array usando metodi built-in, è possibile utilizzare {{jsxref("Array.prototype.flat()")}} (che dovrebbe essere parte di ES2019 e già implementato in alcuni browser).

+ +
/**
+ * Flattens ha passato un array in un array dimensionale
+ *
+ * @params {array} arr
+ * @returns {array}
+ */
+function flatten(arr) {
+  const result = []
+
+  arr.forEach((i) => {
+    if (Array.isArray(i)) {
+      result.push(...flatten(i))
+    } else {
+      result.push(i)
+    }
+  })
+
+  return result
+}
+
+// Uso
+const problem = [1, 2, 3, [4, 5, [6, 7], 8, 9]]
+
+flatten(problem) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
+
+ +

Polyfill

+ +

forEach() è stato aggiunto allo standard ECMA-262 nella quinta edizione; in quanto tale potrebbe non essere presente in altre implementazioni dello standard. È possibile aggirare questo problema inserendo il seguente codice all'inizio degli script, consentendo l'uso di forEach() nelle implementazioni che non lo supportano in modo nativo. Questo algoritmo è esattamente quello specificato in ECMA-262, 5a edizione, assumendo {{jsxref("Object")}} e {{jsxref("TypeError")}} hanno i loro valori originali e quel callback.call() valuta il valore originale di {{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.
+  };
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}{{Spec2('ES5.1')}}Definizione iniziale Implementato 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')}}
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Array.forEach")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/from/index.html b/files/it/web/javascript/reference/global_objects/array/from/index.html new file mode 100644 index 0000000000..83baed1267 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,242 @@ +--- +title: Array.from() +slug: Web/JavaScript/Reference/Global_Objects/Array/from +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Referenza + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/from +--- +
{{JSRef}}
+ +

Il metodo Array.from() crea una nuova istanza Array copiata superficialmente da un oggetto array-like o iterabile.

+ +
{{EmbedInteractiveExample("pages/js/array-from.html")}}
+ + + +

Sintassi

+ +
Array.from(arrayLike[, mapFn[, thisArg]])
+
+ +

Parametri

+ +
+
arrayLike
+
Un oggetto array-like o iterabile da convertire in un array.
+
mapFn {{Optional_inline}}
+
Funzione map per chiamare su ogni elemento dell'array.
+
thisArg {{Optional_inline}}
+
Valore da utilizzare come this quando mapFn viene eseguita.
+
+ +

Valore di ritorno

+ +

Una nuova istanza {{jsxref("Array")}}.

+ +

Descrizione

+ +

Array.from() consente di creare Array da:

+ + + +

Array.from() ha un parametro opzionale mapFn, che ti permette di eseguire una funzione {{jsxref("Array.prototype.map", "map")}} su ogni elemento dell'array (o dell'oggetto sottoclasse) che si sta creando. Più chiaramente, Array.from(obj, mapFn, thisArg) ha lo stesso risultato di Array.from(obj).map(mapFn, thisArg), tranne che non crea un array intermedio. Questo è particolarmente importante per alcune sottoclassi di array, come gli array tipizzati, poiché l'array intermedio avrebbe necessariamente valori troncati per adattarsi al tipo appropriato.

+ +

La proprietà length del metodo from() è 1.

+ +

In ES2015, la sintassi della classe consente la sottoclassificazione di entrambe le classi predefinite e definite dall'utente; di conseguenza, i metodi statici come Array.from sono "ereditati" dalle sottoclassi di Array e creano nuove istanze della sottoclasse, non Array.

+ +

Esempi

+ +

Array da una String

+ +
Array.from('foo');
+// ["f", "o", "o"]
+ +

Array da un Set

+ +
var s = new Set(['foo', window]);
+Array.from(s);
+// ["foo", window]
+ +

Array da una 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'];
+
+ +

Array di un oggetto Array-like (arguments)

+ +
function f() {
+  return Array.from(arguments);
+}
+
+f(1, 2, 3);
+
+// [1, 2, 3]
+ +

Utilizzo delle funzioni a freccia e Array.from

+ +
// Utilizzando una funzione freccia come funzione map
+// per manipolare gli elementi
+Array.from([1, 2, 3], x => x + x);
+// [2, 4, 6]
+
+
+// Genera una sequenza di numeri
+// Poiché l'array è inizializzato con `undefined` su ogni posizione,
+// il valore di `v` sotto sarà `undefined`
+Array.from({length: 5}, (v, i) => i);
+// [0, 1, 2, 3, 4]
+
+ +

Generatore di sequenze (range)

+ +
// Funzione del generatore di sequenze (comunemente denominata "range", ad esempio Clojure, PHP ecc.)
+const range = (start, stop, step) => Array.from({ length: (stop - start) / step }, (_, i) => start + (i * step));
+
+// Genera numeri range 0..4
+range(0, 5, 1);
+// [0, 1, 2, 3, 4]
+
+// Genera l'alfabeto usando Array.from facendolo usare come sequenza
+range('A'.charCodeAt(0), 'Z'.charCodeAt(0) + 1, 1).map(x => String.fromCharCode(x));
+// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
+
+ +

Polyfill

+ +

Array.from è stato aggiunto allo standard ECMA-262 nella sesta edizione (ES2015); in quanto tale potrebbe non essere presente in altre implementazioni dello standard. È possibile aggirare questo problema inserendo il seguente codice all'inizio degli script, consentendo l'uso di Array.from in implementazioni che non lo supportano in modo nativo. Questo algoritmo è esattamente quello specificato in ECMA-262, 6a edizione, assumendo che Object e TypeError abbiano i loro valori originali e che callback.call valuti il valore originale di {{jsxref("Function.prototype.call")}}. Inoltre, poiché i veri iterabili non possono essere polyfilled, questa implementazione non supporta iterables generici come definito nella sesta edizione di ECMA-262.

+ +
// 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;
+    };
+  }());
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-array.from', 'Array.from')}}{{Spec2('ES2015')}}Definizione iniziale.
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.Array.from")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/includes/index.html b/files/it/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..04dc817974 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,162 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +
{{JSRef}}
+ +

Il metodo includes() determina se un array include un certo elemento, ritornando truefalse a seconda del caso

+ +

Sintassi

+ +
var boolean = array.includes(searchElement[, fromIndex])
+ +

Parametri

+ +
+
searchElement
+
L'elemento da cercare.
+
fromIndex
+
Opzionale. La posizione nell'array da cui partire per cercare l'elemento searchElement. Un valore negativo ricerca dal valore di array.length + fromIndex in maniera ascendente. Il valore di default è 0.
+
+ +

Valore di ritorno

+ +

Un {{jsxref("Boolean")}}.

+ +

Examples

+ +
[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
+
+ +

Polyfill

+ +
if (!Array.prototype.includes) {
+  Array.prototype.includes = function(searchElement /*, fromIndex*/) {
+    'use strict';
+    if (this == null) {
+      throw new TypeError('Array.prototype.includes called on null or undefined');
+    }
+
+    var O = Object(this);
+    var len = parseInt(O.length, 10) || 0;
+    if (len === 0) {
+      return false;
+    }
+    var n = parseInt(arguments[1], 10) || 0;
+    var k;
+    if (n >= 0) {
+      k = n;
+    } else {
+      k = len + n;
+      if (k < 0) {k = 0;}
+    }
+    var currentElement;
+    while (k < len) {
+      currentElement = O[k];
+      if (searchElement === currentElement ||
+         (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
+        return true;
+      }
+      k++;
+    }
+    return false;
+  };
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ES7')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support +

{{CompatChrome(47)}}

+
43{{CompatNo}}14279+349
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}} +

{{CompatChrome(47)}}

+
43{{CompatNo}}349 +

{{CompatChrome(47)}}

+
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/index.html b/files/it/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..844d1baf00 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,480 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +

Sommario

+ +

L'oggetto Array di JavaScript  è un oggetto globale che è utilizzato nella costruzione di array; che sono oggetti di alto-livello del tipo lista.

+ +

Creare un Array

+ +
var fruits = ["Apple", "Banana"];
+
+console.log(fruits.length);
+// 2
+
+ +

Accedere (index into) ad un Array item

+ +
var first = fruits[0];
+// Apple
+
+var last = fruits[fruits.length - 1];
+// Banana
+
+ +

Loop in un  Array

+ +
fruits.forEach(function (item, index, array) {
+  console.log(item, index);
+});
+// Apple 0
+// Banana 1
+
+ +

Aggiungere alla fine di  un Array

+ +
var newLength = fruits.push("Orange");
+// ["Apple", "Banana", "Orange"]
+
+ +

Rimuovere dalla fine di un Array

+ +
var last = fruits.pop(); // remove Orange (from the end)
+// ["Apple", "Banana"];
+
+ +

Rimuovere dall'inizio di un Array

+ +
var first = fruits.shift(); // remove Apple from the front
+// ["Banana"];
+
+ +

Aggiungere al'inizio di un Array

+ +
var newLength = fruits.unshift("Strawberry") // add to the front
+// ["Strawberry", "Banana"];
+
+ +

Trovare l'indice di un elemento nell'Array

+ +
fruits.push("Mango");
+// ["Strawberry", "Banana", "Mango"]
+
+var pos = fruits.indexOf("Banana");
+// 1
+
+ +

Rimuovere un elemento tramite la Posizione dell'Indice

+ +
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
+// ["Strawberry", "Mango"]
+
+ +

Copiare un Array

+ +
var shallowCopy = fruits.slice(); // this is how to make a copy
+// ["Strawberry", "Mango"]
+
+ +

Sintassi

+ +
[element0, element1, ..., elementN]
+new Array(element0, element1[, ...[, elementN]])
+new Array(arrayLength)
+ +
+
elementN
+
Un array JavaScript è inizializzato con gli elementi dati, eccetto nel caso in cui un argomento singolo è passato al costruttore dell'Array e l'argomento è un numero. (Vedere sotto.) Notare che questo caso speciale si applica solo agli array JavaScript creati con il costruttore Array, non array literals creati con la sintassi a parentesi.
+
arrayLength
+
Se l'unico argomento passato al costruttore Array è un integer tra  0 e 232-1 (inclusivo), questo restituisce un nuovo array JavaScript con la lunghezza settata su quel numero. Se l'argomento è un qualsiasi altro numero, un eccezione {{jsxref("Global_Objects/RangeError", "RangeError")}} è lanciata.
+
+ +

Descrizione

+ +

Gli Array sono come oggetti di tipo lista il cui prototipo ha metodi per performare operazioni trasversali e di mutazione. Nè la lunghezza di un array JavaScript o i tipi dei suoi elementi sono fissati. Poichè la grandezza della lunghezza di un array cresce o diminuisce in qualsiasi momento, gli array JavaScript non danno garanzia di essere compatti; questo dipende da come il programmatore sceglie di usarli. In generale, queste sono caratteristiche convenienti; ma se tali  caratteristiche non fossero desiderabili per un utilizzo particolare, si potrebbe considerare di utilizzare i typed arrays.

+ +

Alcuni pensano che non si dovrebbe un utilizzare un array come un associative array. In ogni  caso, si può utilizzare un semplice {{jsxref("Global_Objects/Object", "objects")}} invece, con i suoi avvertimenti. Vedere il post Lightweight JavaScript dictionaries with arbitrary keys come esempio.

+ +

Accedere ad elementi di  array 

+ +

Gli array JavaScript sono indicizzati a zero: il primo elemento di un array è all'indice 0, e l'ultimo elemento è all'indice uguale al valore della proprietà dell'array {{jsxref("Array.length", "length")}}  meno 1. Usare un numero di indice invalido restituisce undefined.

+ +
var arr = ['this is the first element', 'this is the second element'];
+console.log(arr[0]);              // logs 'this is the first element'
+console.log(arr[1]);              // logs 'this is the second element'
+console.log(arr[arr.length - 1]); // logs 'this is the second element'
+
+ +

Gli elementi dell'Array sono proprietà dell'oggetto allo stesso modo che toString è una proprietà, ma provare ad accedere ad un elemento di un array come segue, lancia un errore di sintassi, poichè la proprietà del nome non è valida:

+ +
console.log(arr.0); // a syntax error
+
+ +

Non c'è niente di speciale riguardo gli array JavaScript e la proprietà che causa questo. Le proprietà JavaScript che iniziano con un numero non possono essere referenziate con la notazione punto: e vi si deve accedere usando la notazione parentesi quadre. Per esempio, se si avesse un oggetto con una proprietà chiamata '3d', la si potrebbe referenziare solamente utilizzando la notazione parentesi quadre. E.g.:

+ +
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
+console.log(years.0);   // a syntax error
+console.log(years[0]);  // works properly
+
+ +
renderer.3d.setTexture(model, 'character.png');     // a syntax error
+renderer['3d'].setTexture(model, 'character.png');  // works properly
+
+ +

Notare che nell'esempio 3d, '3d' doveva essere messo tra virgolette. E' possibile mettere tra virgolette anche gli indici dell'array JavaScript (e.g., years['2'] invece di years[2]), anche se non necessario. Il 2 in years[2] è costretto in una stringa dal motore di JavaScript attraverso una implicita conversione toString. E' per questa ragione che  '2' e '02' riferirebbero a due differenti slot nell'oggetto years ed il seguente esempio potrebbe essere true:

+ +
console.log(years['2'] != years['02']);
+
+ +

Ugualmente, alle proprietà di oggetti che sono parole riservate(!) vi si può accedere come string literals in notazione parentesi quadrate (ma anche in notazione punto a partire dalla versione  40.0a2 di firefox):

+ +
var promise = {
+  'var'  : 'text',
+  'array': [1, 2, 3, 4]
+};
+
+console.log(promise['var']);
+ +

Relzione tra length e proprietà numeriche

+ +

Una proprietà di un array JavaScript {{jsxref("Array.length", "length")}} e proprietà numeriche sono connesse. Molti dei metodi integrati di array(e.g., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, etc.) tengono in conto del valore della proprietà dell'array {{jsxref("Array.length", "length")}} quando sono chiamati. Altri metodi(e.g., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, etc.) risultano nell'aggiornamento della proprietà{{jsxref("Array.length", "length")}} dell'array.

+ +
var fruits = [];
+fruits.push('banana', 'apple', 'peach');
+
+console.log(fruits.length); // 3
+
+ +

Quando si setta una proprietà su un array JavaScript, quando la proprietà è un valido indice di array e quell'iindice è al di fuori dei limiti dell'array, il motore aggiornerà la proprietà {{jsxref("Array.length", "length")}} in accordo:

+ +
fruits[5] = 'mango';
+console.log(fruits[5]); // 'mango'
+console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
+console.log(fruits.length); // 6
+
+ +

Aumentando{{jsxref("Array.length", "length")}}.

+ +
fruits.length = 10;
+console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
+console.log(fruits.length); // 10
+
+ +

Diminuendo la proprietà {{jsxref("Array.length", "length")}}, comunque cancella gli elementi.

+ +
fruits.length = 2;
+console.log(Object.keys(fruits)); // ['0', '1']
+console.log(fruits.length); // 2
+
+ +

La spiegazione è ampliata nella pagina{{jsxref("Array.length")}}.

+ +

Creare un array utilizzando il risultato di un match

+ +

Il risultato di una corrispondenza tra una espressione regolare e una stringa può creare un array JavaScript. Tale array ha proprietà ed elementi che provvedono informazioni riguardo il match. Questo tipo di array è restituito da {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, e {{jsxref("String.replace")}}. Per aiutare a spiegare queste proprietà ed elementi, vedere l'esempio seguente e fare riferimento alla tavola sottostante:

+ +
// Match one d followed by one or more b's followed by one d
+// Remember matched b's and the following d
+// Ignore case
+
+var myRe = /d(b+)(d)/i;
+var myArray = myRe.exec('cdbBdbsbz');
+
+ +

Le proprietà ed elementi restituiti da questo match sono le seguenti:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property/ElementDescriptionExample
inputUna proprietà read-only che riflette la stinga originale verso la quale l'espressione irregolare era stata abbinata.cdbBdbsbz
indexUna proprietà read-only su indice base-zeroindex dell'abbinamento nella stringa.1
[0]Un elemento read-only che specifica gli ultimi caratteri abbinati.dbBd
[1], ...[n]Elementi read-only  che specificano gli abbinamenti di sottostringa in parentesi, se inclusi nella espressione regolare. Il numero di possibili sottostringhe in parentesi è illimitato.[1]: bB
+ [2]: d
+ +

Proprietà

+ +
+
Array.length
+
Il costruttore della proprietà lunghezza  Array il cui valore è 1.
+
{{jsxref("Array.@@species", "get Array[@@species]")}}
+
La funzione del costruttore che è usata per creare oggetti derivati.
+
{{jsxref("Array.prototype")}}
+
Permette l'addizione  di proprietà a tutti gli oggetti array.
+
+ +

Metodi

+ +
+
{{jsxref("Array.from()")}} {{experimental_inline}}
+
Crea una nuova istanza Array da un oggetto del tipo array o iterabile.
+
{{jsxref("Array.isArray()")}}
+
Restituisce true se una variabile è un array, altrimenti false.
+
{{jsxref("Array.observe()")}} {{experimental_inline}}
+
In modo asincrono osserva i cambiamenti agli Arrays, come{{jsxref("Object.observe()")}} per gli oggetti. Provvede un flusso di cambiamenti in ordine di occorrenza.
+
{{jsxref("Array.of()")}} {{experimental_inline}}
+
Crea una nuova istanza Array con un variabile numero di argomenti, nonostante il numero o i tipi di argomenti.
+
+ +

Istanze di Array 

+ +

Tutte le istanze di Array ereditano da {{jsxref("Array.prototype")}}. L'oggetto prototype del costruttore Array può essere modificato per influenzare tutte le istanze di  Array.

+ +

Proprietà

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
+ +

Metodi

+ +

Metodi mutatori

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
+ +

Metodi per accedere

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
+ +

Metodi di iterazione

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}} 
+ +

Metodi generici Array 

+ +
+

Array generics are non-standard, deprecated and will get removed near future. Note that you can not rely on them cross-browser. However, there is a shim available on GitHub.

+
+ +

A volte si vorrebbe applicare metodi di array alle stringhe o altri oggetti del tipo array (come {{jsxref("Functions/arguments", "arguments", "", 1)}}). Facendo ciò, si tratta una stringa come un array di caratteri(o altrimenti trattare un non array come array). Per esempio, per controllare che ogni carattere nella variabile str sia una lettera, si scriverebbe:

+ +
function isLetter(character) {
+  return character >= 'a' && character <= 'z';
+}
+
+if (Array.prototype.every.call(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

Tale notazione è dispersiva e JavaScript 1.6 ha introdotto un generico shorthand:

+ +
if (Array.every(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("Global_Objects/String", "String")}}.

+ +

Queste no fanno parte dello standard ECMAScript (anche se ES2015 {{jsxref("Array.from()")}} può essere utilizzato per raggingere tale scopo). Ciò che segue è un aiuto per permetterene l'utilizzo in tutti i browser:

+ +
// Assumes Array extras already present (one may use polyfills for these as well)
+(function() {
+  'use strict';
+
+  var i,
+    // We could also build the array of methods with the following, but the
+    //   getOwnPropertyNames() method is non-shimable:
+    // Object.getOwnPropertyNames(Array).filter(function(methodName) {
+    //   return typeof Array[methodName] === 'function'
+    // });
+    methods = [
+      'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
+      'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
+      'forEach', 'map', 'reduce', 'reduceRight', 'filter',
+      'some', 'every', 'find', 'findIndex', 'entries', 'keys',
+      'values', 'copyWithin', 'includes'
+    ],
+    methodCount = methods.length,
+    assignArrayGeneric = function(methodName) {
+      if (!Array[methodName]) {
+        var method = Array.prototype[methodName];
+        if (typeof method === 'function') {
+          Array[methodName] = function() {
+            return method.call.apply(method, arguments);
+          };
+        }
+      }
+    };
+
+  for (i = 0; i < methodCount; i++) {
+    assignArrayGeneric(methods[i]);
+  }
+}());
+
+ +

Esempi

+ +

Creare un array

+ +

Il seguente esempio crea un array, msgArray, con una lunghezza di 0, poi assegna valori a  msgArray[0] e msgArray[99], cambiando la lunghezza dell'array a 100.

+ +
var msgArray = [];
+msgArray[0] = 'Hello';
+msgArray[99] = 'world';
+
+if (msgArray.length === 100) {
+  console.log('The length is 100.');
+}
+
+ +

Creare un array bidimensionale

+ +

Ciò che segue crea una scacchiera come un array bidiensionale di stringhe. La prima mossa è fatta copiando la 'p' in (6,4) in (4,4). La vecchia posizione (6,4) è resa bianca.

+ +
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');
+
+// Move King's Pawn forward 2
+board[4][4] = board[6][4];
+board[6][4] = ' ';
+console.log(board.join('\n'));
+
+ +

Ecco l'output:

+ +
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
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}Nuovi metodi aggiunti: {{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('ES2015', '#sec-array-objects', 'Array')}}{{Spec2('ES2015')}}Nuovi metodi aggiunti: {{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")}}
+ +

Compatibilità Browser 

+ +
{{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}}
+
+ +

Vedere anche:

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/indexof/index.html b/files/it/web/javascript/reference/global_objects/array/indexof/index.html new file mode 100644 index 0000000000..658957c67d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/indexof/index.html @@ -0,0 +1,226 @@ +--- +title: Array.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf +tags: + - Array + - JavaScript + - Prototype + - Referenza + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf +--- +
{{JSRef}}
+ +

Il metodo indexOf() restituisce il primo indice in cui è possibile trovare un determinato elemento nell'array o -1 se non è presente.

+ +
+

Note: Per il metodo String, consultare {{jsxref("String.prototype.indexOf()")}}.

+
+ +
{{EmbedInteractiveExample("pages/js/array-indexof.html")}}
+ + + +

Sintassi

+ +
arr.indexOf(searchElement[, fromIndex])
+ +

Parametri

+ +
+
searchElement
+
Elemento da localizzare nell'array.
+
fromIndex {{optional_inline}}
+
L'indice per iniziare la ricerca. Se l'indice è maggiore o uguale alla lunghezza dell'array, viene restituito -1, il che significa che l'array non verrà cercato. Se il valore dell'indice fornito è un numero negativo, viene preso come offset dalla fine dell'array. Nota: se l'indice fornito è negativo, l'array viene comunque ricercato da fronte a retro. Se l'indice fornito è 0, verrà cercato l'intero array. Predefinito: 0 (viene cercato l'intero array).
+
+ +

Valore di ritorno

+ +

Il primo indice dell'elemento nell'array; -1 se non trovato.

+ +

Descrizione

+ +

indexOf() compara searchElement con gli elementi dell'array usando strict equality (lo stesso metodo utilizzato dall'operatore === o triple-equals).

+ +

Esempi

+ +

Usare indexOf()

+ +

Nell'esempio seguente viene utilizzato indexOf() per individuare i valori in un array.

+ +
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
+
+ +

Trovare tutte le occorrenze di un elemento

+ +
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]
+
+ +

Trovare se un elemento esiste nell'array o meno ed aggiornare l'array

+ +
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() è stato aggiunto allo standard ECMA-262 nella quinta edizione; in quanto tale potrebbe non essere presente in tutti i browser. Puoi aggirare questo problema utilizzando il seguente codice all'inizio degli script. Questo ti permetterà di usare indexOf() quando non c'è ancora alcun supporto nativo. Questo algoritmo corrisponde a quello specificato in ECMA-262, 5a edizione, assumendo che {{jsxref("Global_Objects/TypeError", "TypeError")}} e {{jsxref("Math.abs()")}} abbiano i loro valori originali.

+ +
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){ for(; i !== Len; ++i) if(that[i]===void 0 && i in that) return i; // undefined
+    }else if(member !== member){   for(; i !== Len; ++i) if(that[i] !== that[i]) return i; // NaN
+    }else                           for(; i !== Len; ++i) if(that[i] === member) return i; // all else
+
+    return -1; // if the value was not found, then return -1
+  };
+})(Object, Math.max, Math.min);
+
+ +

Tuttavia, se sei più interessato a tutti i piccoli bit tecnici definiti dallo standard ECMA e meno preoccupati per le prestazioni o la concisione, potresti trovare questo polifratura più descrittivo per essere più utile.

+ +
// 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;
+  };
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}{{Spec2('ES5.1')}}Definizione iniziale Implementato in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Array.indexOf")}}

+
+ +

Note di compatibilità

+ + + +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/isarray/index.html b/files/it/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..d7aaf864bf --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,133 @@ +--- +title: Array.isArray() +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +tags: + - Array + - ECMAScript 5 + - JavaScript + - Referenza + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +
{{JSRef}}
+ +

Il metodo Array.isArray() determina se il valore passato è un {{jsxref("Array")}}.

+ +
Array.isArray([1, 2, 3]);  // true
+Array.isArray({foo: 123}); // false
+Array.isArray('foobar');   // false
+Array.isArray(undefined);  // false
+
+ +

Sintassi

+ +
Array.isArray(value)
+ +

Parametri

+ +
+
value
+
Il valore da verificare.
+
+ +

Valore di ritorno

+ +

true se il valore è un {{jsxref("Array")}}; altrimenti, false.

+ +

Descrizione

+ +

Se il valore è un {{jsxref("Array")}}, viene ritornato true; altrimenti viene ritornato false.

+ +

Vedi l'articolo “Determining with absolute accuracy whether or not a JavaScript object is an array” per maggiori dettagli. Data un'istanza {{jsxref("TypedArray")}}, viene ritornato sempre false.

+ +

Esempi

+ +
// tutte le seguenti chiamate ritornano true
+Array.isArray([]);
+Array.isArray([1]);
+Array.isArray(new Array());
+Array.isArray(new Array('a', 'b', 'c', 'd'));
+Array.isArray(new Array(3));
+// Fatto poco noto: Array.prototype stesso è un array:
+Array.isArray(Array.prototype);
+
+// tutte le seguenti chiamate ritornano 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(new Uint8Array(32));
+Array.isArray({ __proto__: Array.prototype });
+
+ +

instanceof vs isArray

+ +

Quando si verifica l'istanza ArrayArray.isArray è preferito su instanceof perché funziona attraverso gli 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]
+
+// Verifica corretta dell'array
+Array.isArray(arr);  // true
+// Considerato dannoso, perché non funziona attraverso iframe
+arr instanceof Array; // false
+
+ +

Polyfill

+ +

L'esecuzione del seguente codice prima di qualsiasi altro codice creerà Array.isArray() se non è nativamente disponibile.

+ +
if (!Array.isArray) {
+  Array.isArray = function(arg) {
+    return Object.prototype.toString.call(arg) === '[object Array]';
+  };
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Definizione iniziale Implementato in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}}
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Array.isArray")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/join/index.html b/files/it/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..8483c817ac --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,112 @@ +--- +title: Array.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - Array + - JavaScript + - Prototype + - Referenza + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +
{{JSRef}}
+ +

Il metodo join() unisce tutti gli elementi di un array (o di un array di oggetti) in una stringa che viene restituita.

+ +
var a = ['Wind', 'Rain', 'Fire'];
+a.join();    // 'Wind,Rain,Fire'
+a.join('-'); // 'Wind-Rain-Fire'
+ +

Sintassi

+ +
arr.join()
+arr.join(separatore)
+ +

Parametri

+ +
+
separatore {{optional_inline}}
+
Specifica una stringa che separa ogni coppia di elementi adiacenti dell'array. Il separatore è trasformato in una stringa, se necessario. Se omesso, gli elementi dell'array saranno separati da una virgola (","). Se il separatore è una stringa vuota, tutti gli elementi sono uniti senza alcun carattere intemedio.
+
+ +

Valore di risposta

+ +

Una stringa con tutti con tutti gli elementi dell'array uniti. Se arr.length è 0, viene restituita una stringa vuota.

+ +

Descrizione

+ +

Le stringe ottenute dalla conversione di tutti gli elementi dell'array sono unite in un unica stringa.

+ +
+

Se un elemento è undefinednull, sarà convertito in una stringa vuota.

+
+ +

Esempi

+ +

Quattro modi per concatenare un array

+ +

Il seguente esempio crea un array, a, con tre elementi, quindi unisce gli elementi dell'array quattro volte: usando l'operatore di default, poi una virgola e uno spazio, poi un più e infine una stringa vuota.

+ +
var a = ['Wind', 'Rain', 'Fire'];
+a.join();      // 'Wind,Rain,Fire'
+a.join(', ');  // 'Wind, Rain, Fire'
+a.join(' + '); // 'Wind + Rain + Fire'
+a.join('');    // 'WindRainFire'
+ +

Unione di un oggetto di tipo array

+ +

Il seguente esempio unisce un oggetto di tipo array (arguments), chiamando {{jsxref("Function.prototype.call")}} con 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);
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificheStatoCommenti
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementato in 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')}} 
+ +

Compatibilità browser

+ +
+ + +

{{Compat("javascript.builtins.Array.join")}}

+
+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/keys/index.html b/files/it/web/javascript/reference/global_objects/array/keys/index.html new file mode 100644 index 0000000000..78212d221f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/keys/index.html @@ -0,0 +1,74 @@ +--- +title: Array.prototype.keys() +slug: Web/JavaScript/Reference/Global_Objects/Array/keys +translation_of: Web/JavaScript/Reference/Global_Objects/Array/keys +--- +
{{JSRef}}
+ +

Il metodo keys() ritorna un nuovo oggetto Array Iterator contenente le chiavi di ogni indice dell'array.

+ +
var arr = ['a', 'b', 'c'];
+var iterator = arr.keys();
+
+console.log(iterator.next()); // { value: 0, done: false }
+console.log(iterator.next()); // { value: 1, done: false }
+console.log(iterator.next()); // { value: 2, done: false }
+console.log(iterator.next()); // { value: undefined, done: true }
+
+ +

Sintassi

+ +
arr.keys()
+ +

Valore di ritorno

+ +

Un nuovo oggetto {{jsxref("Array")}}.

+ +

Esempi

+ +

I Key iterator non ignorano gli elementi vuoti

+ +
var arr = ['a', , 'c'];
+var sparseKeys = Object.keys(arr);
+var denseKeys = [...arr.keys()];
+console.log(sparseKeys); // ['0', '2']
+console.log(denseKeys);  // [0, 1, 2]
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
{{SpecName('ES2015', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.keys")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/lastindexof/index.html b/files/it/web/javascript/reference/global_objects/array/lastindexof/index.html new file mode 100644 index 0000000000..c4170455f6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/lastindexof/index.html @@ -0,0 +1,169 @@ +--- +title: Array.prototype.lastIndexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +tags: + - Array + - ECMAScript 5 + - JavaScript + - Protototipo + - Prototype + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +--- +
{{JSRef}}
+ +

Il metodo lastIndexOf() ritorna l'ultimo indice nel quale l'elemento dato può essere trovato nell' array, o -1 se non presente. L'array verrà controllato al contrario, partendo da fromIndex.

+ +
{{EmbedInteractiveExample("pages/js/array-lastindexof.html")}}
+ + + +

Sintassi

+ +
arr.lastIndexOf(searchElement)
+arr.lastIndexOf(searchElement, fromIndex)
+
+ +

Parametri

+ +
+
searchElement
+
Elemento da trovare nell' array.
+
fromIndex {{optional_inline}}
+
L'indice da cui iniziare a cercare al contrario. Di defaults la lunghezza dell' array meno uno (arr.length - 1), quindi cercherà in tutto l'array. Se l'indice è uguale o maggiore alla lunghezza dell' array, l' elemento sarà cercato in tutto l'array. Se negativo, Verrà preso come offset dalla fine dell' array. Nota che anche se l'indice è negativo, l'array sarà controllato comunque al contrario. ISe l'indice calcolato è minore di 0, verrà ritornato -1, quindi non verrà effettuata la ricerca.
+
+ +

Valori restituiti

+ +

L'ultimo indice dell' elemento nell' array; -1 se non trovato.

+ +

Descrizione

+ +

lastIndexOf compara searchElement a gli elementi dell' array usando strict equality (lo stesso metodo usato ===, o triple-equals, operator).

+ +

Esempi

+ +

Utilizzo di lastIndexOf

+ +

L'esempio seguente usa lastIndexOf per trovare i valori in un array.

+ +
var numbers = [2, 5, 9, 2];
+numbers.lastIndexOf(2);     // 3
+numbers.lastIndexOf(7);     // -1
+numbers.lastIndexOf(2, 3);  // 3
+numbers.lastIndexOf(2, 2);  // 0
+numbers.lastIndexOf(2, -2); // 0
+numbers.lastIndexOf(2, -1); // 3
+
+ +

Trovare tutte le posizioni di un elemento

+ +

Il seguente esempio usa lastIndexOf per trovare tutti gli elementi nell' array, usando {{jsxref("Array.prototype.push", "push")}} per essere aggiunti in un array come vengono trovati.

+ +
var indices = [];
+var array = ['a', 'b', 'a', 'c', 'a', 'd'];
+var element = 'a';
+var idx = array.lastIndexOf(element);
+while (idx != -1) {
+  indices.push(idx);
+  idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1);
+}
+
+console.log(indices);
+// [4, 2, 0]
+
+ +

Nota che non abbiamo considerato idx == 0perchè l'elemento sarà sempre troavto indipendemente da il parametro fromIndex se è il primo elemento dell'array. TQuesto è diveso dal metodo {{jsxref("Array.prototype.indexOf", "indexOf")}}.

+ +

Polyfill

+ +

lastIndexOf è stato aggiunto nello standard ECMA-262 nella 5° edizione; come può non essere trovato in altre implementazioni nello standard. Puoi aggirare questa cosa inserendo il seguente codice all' inizio del tuo script, permettendoti di usare lastIndexOf anche se non supportato nativamente.Questo algorittmo è esattamente quello descritto da ECMA-262, 5° edizione, assumendo{{jsxref("Object")}}, {{jsxref("TypeError")}}, {{jsxref("Number")}}, {{jsxref("Math.floor")}}, {{jsxref("Math.abs")}}, e {{jsxref("Math.min")}} abbiano il loro valore originale.

+ +
// Production steps of ECMA-262, Edition 5, 15.4.4.15
+// Reference: http://es5.github.io/#x15.4.4.15
+if (!Array.prototype.lastIndexOf) {
+  Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
+    'use strict';
+
+    if (this === void 0 || this === null) {
+      throw new TypeError();
+    }
+
+    var n, k,
+      t = Object(this),
+      len = t.length >>> 0;
+    if (len === 0) {
+      return -1;
+    }
+
+    n = len - 1;
+    if (arguments.length > 1) {
+      n = Number(arguments[1]);
+      if (n != n) {
+        n = 0;
+      }
+      else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
+        n = (n > 0 || -1) * Math.floor(Math.abs(n));
+      }
+    }
+
+    for (k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) {
+      if (k in t && t[k] === searchElement) {
+        return k;
+      }
+    }
+    return -1;
+  };
+}
+
+ +

Ancora, nota che questa implementazione mira alla compatibilità assoluta con lastIndexOf in Firefox e SpiderMonkey JavaScript engine, includendo alcuni casi che sono considerati estremi. ISe hai intenzione di usare questo in applicazioni reali, potresti calcolare from con un codice meno complicato se ignori questi casi.

+ +

Descrizione

+ + + + + + + + + + + + + + + + + + + + + + + + +
DescrizioneStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.15', 'Array.prototype.lastIndexOf')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con il browser

+ +
+ + +

{{Compat("javascript.builtins.Array.lastIndexOf")}}

+
+ +

Note di compatibilità

+ + + +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/length/index.html b/files/it/web/javascript/reference/global_objects/array/length/index.html new file mode 100644 index 0000000000..a36a6b5204 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/length/index.html @@ -0,0 +1,129 @@ +--- +title: Array.length +slug: Web/JavaScript/Reference/Global_Objects/Array/length +translation_of: Web/JavaScript/Reference/Global_Objects/Array/length +--- +
{{JSRef}}
+ +
La proprieta' length setta o restituisce il numero di elementi in un array. E' un intero a 32 bit, sempre maggiore del piu' grande indice dell'array.
+ +
 
+ +
var items = ['shoes', 'shirts', 'socks', 'sweaters'];
+items.length;
+
+// returns 4
+ +

Descrizione

+ +

Puoi impostare la proprietà length di un array per troncare o estendere l'array stesso.

+ +
var a = [1,2,3];
+a.length=2;
+// a is now [1, 2]
+
+a.length = 10
+// a is now [1, 2, undefined × 8]
+
+ +

 

+ +

Esempi

+ +

Iterare su un array

+ +

Nel seguente esempio, l'array numbers viene iterarato e ciascun elemento viene moltiplicato per 2.

+ +
var numbers = [1, 2, 3, 4, 5];
+var length = numbers.length;
+for (var i = 0; i < length; i++) {
+  numbers[i] *= 2;
+}
+// numbers is now [2, 4, 6, 8, 10]
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificheStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

diff --git a/files/it/web/javascript/reference/global_objects/array/map/index.html b/files/it/web/javascript/reference/global_objects/array/map/index.html new file mode 100644 index 0000000000..808b4fc728 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,323 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +tags: + - Array + - ECMAScript 5 + - JavaScript + - Prototype + - Referenza + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +
{{JSRef}}
+ +

Il metodo map() crea un nuovo array con i risultati della chiamata di una funzione fornita su ogni elemento dell'array chiamante.

+ +
{{EmbedInteractiveExample("pages/js/array-map.html")}}
+ + + +

Sintassi

+ +
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
+    // Ritorna un elemento per new_array
+}[, thisArg])
+ +

Parametri

+ +
+
callback
+
Funzione che produce un elemento del nuovo array, prendendo tre argomenti: +
+
 
+
currentValue
+
L'elemento corrente in elaborazione nell'array.
+
index{{optional_inline}}
+
L'indice dell'elemento corrente in elaborazione nell'array.
+
array{{optional_inline}}
+
L'array a cui viene applicato map.
+
+
+
thisArg{{optional_inline}}
+
Valore da utilizzare come this quando viene eseguito callback.
+
+ +

Valore di ritorno

+ +

Un nuovo array con ciascun elemento che è il risultato della funzione di callback.

+ +

Descrizione

+ +

map chiama il callback fornito una volta per ciascun elemento in un array, in ordine, e costruisce un nuovo array dai risultati. callback viene invocato solo per gli indici dell'array che hanno valori assegnati, incluso undefined. Non viene chiamato per gli elementi mancanti dell'array (ovvero, gli indici che non sono mai stati impostati, che sono stati cancellati o a cui non è mai stato assegnato un valore).

+ +

Poichè map costruisce un nuovo array, usarlo quando non si utilizza l'array restituito è un anti-pattern; usa forEachfor-of invece. Segni che non dovresti usare map: A) Non stai usando l'array restituito, e/o B) Non stai restituendo un valore dal callback.

+ +

callback viene invocato con tre argomenti: il valore dell'elemento, l'indice dell'elemento e l'oggetto Array che viene iterato.

+ +

Se viene fornito il parametro thisArg a map, verrà utilizzato come valore this del callback. Altrimenti, il valore {{jsxref("undefined")}} sarà usato come valore this. Il valore this alla fine osservabile da callback è determinato secondo le consuete regole per determinare il this visto da una funzione.

+ +

map non muta l'array su cui è chiamato (sebbene callback, se invocato, possa farlo).

+ +

L'intervallo di elementi elaborati da map viene impostato prima della prima chiamata del callback. Gli elementi aggiunti all'array dopo che la chiamata a map inizia non saranno calcolati da callback. Se i valori degli elementi esistenti dell'array vengono modificati, il valore passato a callback sarà il valore al momento in cui map li visita. Gli elementi che vengono cancellati dopo che la chiamata a map inizia e prima di essere visitati non vengono visitati.

+ +

A causa dell'algoritmo definito nella specifica, se l'array su cui è stata chiamato map è sparso, l'array risultante sarà sparso, mantenendo vuoti gli stessi indici.

+ +

Esempi

+ +

Mappare una serie di numeri ad un array di radici quadrate

+ +

Il seguente codice accetta un array di numeri e crea un nuovo array contenente le radici quadrate dei numeri nel primo array.

+ +
var numbers = [1, 4, 9];
+var roots = numbers.map(function(num) {
+return Math.sqrt(num)
+});
+// roots è ora [1, 2, 3]
+// numbers è ancora [1, 4, 9]
+
+ +

Usare map per riformattare gli oggetti in un array

+ +

Il seguente codice accetta un array di oggetti e crea un nuovo array contenente gli oggetti appena riformattati.

+ +
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 è ora [{1: 10}, {2: 20}, {3: 30}],
+
+// kvArray è ancora:
+// [{key: 1, value: 10},
+//  {key: 2, value: 20},
+//  {key: 3, value: 30}]
+
+ +

Mappare un array di numeri usando una funzione che contiene un argomento

+ +

Il codice seguente mostra come funziona map quando viene utilizzata una funzione che richiede un argomento. L'argomento verrà assegnato automaticamente da ciascun elemento dell'array mentre map itera l'array originale.

+ +
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]
+
+ +

Usare map genericamente

+ +

Questo esempio mostra come usare map su una {{jsxref("String")}} per ottenere un array di byte nella codifica ASCII che rappresenta i valori dei caratteri:

+ +
var a = Array.prototype.map.call('Hello World', function(x) {
+  return x.charCodeAt(0);
+});
+// a ora equivale a [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
+
+ +

Usare map con querySelectorAll

+ +

Questo esempio mostra come iterare attraverso una raccolta di oggetti raccolti da querySelectorAll. Questo perchè querySelectorAll restituisce una NodeList che è una raccolta di oggetti.
+ In questo caso restituiamo sullo schermo tutti i valori delle opzioni selezionate:

+ +
var elems = document.querySelectorAll('select option:checked');
+var values = Array.prototype.map.call(elems, function(obj) {
+  return obj.value;
+});
+
+ +

Il modo più semplice sarebbe utilizzare il metodo {{jsxref("Array.from()")}}.

+ +

Caso d'uso ingannevole

+ +

(inspired by this blog post)

+ +

È normale utilizzare il callback con un argomento (l'elemento che viene attraversato). Alcune funzioni sono anche comunemente utilizzate con un argomento, anche se accettano argomenti opzionali aggiuntivi. Queste abitudini possono portare a comportamenti confusi.

+ +
// Consider:
+['1', '2', '3'].map(parseInt);
+// Mentre ci si potrebbe aspettare [1, 2, 3]
+// Il risultato effettivo è [1, NaN, NaN]
+
+// parseInt è spesso usato con un argomento, ma ne prende due.
+// Il primo è un'espressione e il secondo è la radice.
+// Alla funzione di callback, Array.prototype.map passa 3 argomenti:
+// l'elemento, l'indice e l'array
+// Il terzo argomento è ignorato da parseInt, ma non il secondo,
+// da qui l'eventuale confusione. Vedi il post del blog per maggiori dettagli
+// Se il link non funziona
+// ecco un esempio conciso dei passaggi di iterazione:
+// parseInt(string, radix) -> map(parseInt(value, index))
+// first iteration (index is 0): parseInt('1', 0) // results in parseInt('1', 0) -> 1
+// second iteration (index is 1): parseInt('2', 1) // results in parseInt('2', 1) -> NaN
+// third iteration (index is 2): parseInt('3', 2) // results in parseInt('3', 2) -> NaN
+
+function returnInt(element) {
+  return parseInt(element, 10);
+}
+
+['1', '2', '3'].map(returnInt); // [1, 2, 3]
+// Il risultato effettivo è un array di numeri (come previsto)
+
+// Come sopra, ma usando la sintassi della funzione a freccia concisa
+['1', '2', '3'].map( str => parseInt(str) );
+
+// Un modo più semplice per ottenere quanto sopra, evitando il "gotcha":
+['1', '2', '3'].map(Number); // [1, 2, 3]
+// ma a differenza di `parseInt` restituirà anche una notazione esponenziale mobile o (risolta):
+['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]
+
+ +

Un output alternativo del metodo map che viene chiamato con parseInt come parametro viene eseguito come segue:

+ +
var xs = ['10', '10', '10'];
+
+xs = xs.map(parseInt);
+
+console.log(xs);
+// Il risultato effettivo di 10,NaN,2 potrebbe essere inaspettato in base alla descrizione precedente.
+ +

Polyfill

+ +

map è stato aggiunto allo standard ECMA-262 nella 5a edizione; in quanto tale potrebbe non essere presente in tutte le implementazioni dello standard. Puoi aggirare questo problema inserendo il seguente codice all'inizio degli script, consentendo l'uso di map in implementazioni che non lo supportano in modo nativo. Questo algoritmo è esattamente quello specificato in ECMA-262, 5a edizione, assumendo {{jsxref("Object")}}, {{jsxref("TypeError")}}, e {{jsxref("Array")}} hanno i loro valori originali e che callback.call restituisce il valore originale di {{jsxref("Function.prototype.call")}}.

+ +
// 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;
+  };
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}{{Spec2('ES5.1')}}Definizione iniziale Implementato in 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')}} 
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Array.map")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/of/index.html b/files/it/web/javascript/reference/global_objects/array/of/index.html new file mode 100644 index 0000000000..808c1dda2c --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,92 @@ +--- +title: Array.of() +slug: Web/JavaScript/Reference/Global_Objects/Array/of +translation_of: Web/JavaScript/Reference/Global_Objects/Array/of +--- +
{{JSRef}}
+ +

Il metodo Array.of() crea una nuova istanza di Array  accettando un numero variabile di argomenti, indipendentemente dal numero o dal tipo degli argomenti.

+ +

La differenza tra Array.of() ed il costruttore Array è nella gestione degli argomenti di tipo intero: Array.of(7) crea un array con un singolo elemento, 7, mentre Array(7) crea un array vuoto con la proprietà length settata a  7 (Nota: questo implica un array di 7 elementi vuoti, non elementi col valore undefined assegnato).

+ +
Array.of(7);       // [7]
+Array.of(1, 2, 3); // [1, 2, 3]
+
+Array(7);          // [ , , , , , , ]
+Array(1, 2, 3);    // [1, 2, 3]
+
+ +

Syntax

+ +
Array.of(element0[, element1[, ...[, elementN]]])
+ +

Parameteri

+ +
+
elementN
+
Gli elementi da assegnare all'array.
+
+ +

Valore di ritorno

+ +

Una nuova istanz di {{jsxref("Array")}}.

+ +

Descrizione

+ +

Questa funzione fa parte dello standard ECMAScript 2015. Per maggiori informazioni vedi le proposal Array.of e Array.from  e il polyfill Array.of.

+ +

Esempi

+ +
Array.of(1);         // [1]
+Array.of(1, 2, 3);   // [1, 2, 3]
+Array.of(undefined); // [undefined]
+
+ +

Polyfill

+ +

Eseguendo il codice seguente prima di qualsiasi altro codice verrà creato il metodo Array.of() se non era precedentemente esistente.

+ +
if (!Array.of) {
+  Array.of = function() {
+    return Array.prototype.slice.call(arguments);
+  };
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.of")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/pop/index.html b/files/it/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..6feabb5f14 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,117 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +tags: + - Array + - JavaScript + - Prototype + - Referenza + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +
{{JSRef}}
+ +

Il metodo pop() rimuove l'ultimo elemento da un array e restituisce quell'elemento. Questo metodo modifica la lunghezza dell'array.

+ +
{{EmbedInteractiveExample("pages/js/array-pop.html")}}
+ + + +

Sintassi

+ +
arr.pop()
+ +

Valore di ritorno

+ +

L'elemento rimosso dall'array; {{jsxref("undefined")}} se l'array è vuoto.

+ +

Descrizione

+ +

Il metodo pop rimuove l'ultimo elemento da un array e restituisce quel valore al chiamante.

+ +

pop è intenzionalmente generico; questo metodo può essere {{jsxref("Function.call", "chiamato", "", 1)}} o {{jsxref("Function.apply", "applicato", "", 1)}} ad oggetti che assomigliano agli array. Gli oggetti che non contengono una proprietà length che riflette l'ultimo di una serie di proprietà numeriche consecutive basate su zero potrebbero non comportarsi in alcun modo significativo.

+ +

Se chiami pop() su un array vuoto, ritorna {{jsxref("undefined")}}.

+ +

{{jsxref("Array.prototype.shift()")}} ha un comportamento simile a pop, ma applicato al primo elemento di un array.

+ +

Esempi

+ +

Rimozione dell'ultimo elemento di un array

+ +

Il seguente codice crea l'array myFish contenente quattro elementi, dopo rimuove il suo ultimo elemento.

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+
+var popped = myFish.pop();
+
+console.log(myFish); // ['angel', 'clown', 'mandarin' ]
+
+console.log(popped); // 'sturgeon'
+ + + +

Usare apply( ) o call ( ) sugli array-like objects

+ +

Il codice seguente crea l'array-like object myFish contenente quattro elementi e un parametro length, poi rimuove il suo ultimo elemento e decrementa il parametro length.

+ +
var myFish = {0:'angel', 1:'clown', 2:'mandarin', 3:'sturgeon', length: 4};
+
+var popped = Array.prototype.pop.call(myFish); //same syntax for using apply( )
+
+console.log(myFish); // {0:'angel', 1:'clown', 2:'mandarin', length: 3}
+
+console.log(popped); // 'sturgeon'
+
+ + + +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale Implementato in 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')}}
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Array.pop")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/prototype/index.html b/files/it/web/javascript/reference/global_objects/array/prototype/index.html new file mode 100644 index 0000000000..d4989792a8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/prototype/index.html @@ -0,0 +1,203 @@ +--- +title: Array.prototype +slug: Web/JavaScript/Reference/Global_Objects/Array/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/prototype +--- +
{{JSRef}}
+ +

La proprietà Array.prototype rappresenta il prototipo per il costruttore {{jsxref("Array")}} .

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrizione

+ +

Le istanze {{jsxref("Array")}} ereditano da Array.prototype. Come con gli altri costruttori, si può cambiare il prototipo propagando i cambiamenti su tutte le sue istanze.

+ +

Piccola curiosità: Array.prototype è un {{jsxref("Array")}}:

+ +
Array.isArray(Array.prototype); // true
+
+ +

Proprietà

+ +
+
Array.prototype.constructor
+
Restituisce il costruttore.
+
{{jsxref("Array.prototype.length")}}
+
Restituisce il numero di elementi in un array.
+
+ +

Metodi

+ +

Metodi mutator

+ +

Questi metodi modificano l'array:

+ +
+
{{jsxref("Array.prototype.copyWithin()")}} {{experimental_inline}}
+
Copia una sequenza di elementi dell'array all'interno dello stesso.
+
{{jsxref("Array.prototype.fill()")}} {{experimental_inline}}
+
Riempie le posizioni dell'array contenute tra 2 indici con un valore fisso.
+
{{jsxref("Array.prototype.pop()")}}
+
Rimuove e restituisce l'ultimo elemento dell'array.
+
{{jsxref("Array.prototype.push()")}}
+
Accoda uno o più elementi all'array e restituisce la lunghezza aggiornata dello stesso.
+
{{jsxref("Array.prototype.reverse()")}}
+
Inverte l'ordine delle posizioni degli elementi all'interno dell'array.
+
{{jsxref("Array.prototype.shift()")}}
+
Rimuove e resistuisce il primo elemento di un array.
+
{{jsxref("Array.prototype.sort()")}}
+
Ordina gli elementi di un array all'interno di esso e restituisce l'array.
+
{{jsxref("Array.prototype.splice()")}}
+
Aggiunge e/o rimuove elementi da un array.
+
{{jsxref("Array.prototype.unshift()")}}
+
Aggiunge uno o più elementi all'inizio di un array e restituisce la lunghezza aggiornata dello stesso.
+
+ +

Metodi accessor

+ +

Questi metodi non modificano l'array e ne restituiscono una sua rappresentazione.

+ +
+
{{jsxref("Array.prototype.concat()")}}
+
Restituisce un nuovo array costituito dall'array stesso insieme ad altri array/valori.
+
{{jsxref("Array.prototype.includes()")}} {{experimental_inline}}
+
Restituisce true se l'array contiene un certo elemento, false altrimenti.
+
{{jsxref("Array.prototype.join()")}}
+
Resituisce i valori dell'array come stringa.
+
{{jsxref("Array.prototype.slice()")}}
+
Restituisce un nuovo array cosituito da elementi dell'array originale.
+
{{jsxref("Array.prototype.toSource()")}} {{non-standard_inline}}
+
Returns an array literal representing the specified array; you can use this value to create a new array. Overrides the {{jsxref("Object.prototype.toSource()")}} method.
+
{{jsxref("Array.prototype.toString()")}}
+
Returns a string representing the array and its elements. Overrides the {{jsxref("Object.prototype.toString()")}} method.
+
{{jsxref("Array.prototype.toLocaleString()")}}
+
Returns a localized string representing the array and its elements. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.
+
{{jsxref("Array.prototype.indexOf()")}}
+
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
+
{{jsxref("Array.prototype.lastIndexOf()")}}
+
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
+
+ +

Iteration methods

+ +

Several methods take as arguments functions to be called back while processing the array. When these methods are called, the length of the array is sampled, and any element added beyond this length from within the callback is not visited. Other changes to the array (setting the value of or deleting an element) may affect the results of the operation if the method visits the changed element afterwards. While the specific behavior of these methods in such cases is well-defined, you should not rely upon it so as not to confuse others who might read your code. If you must mutate the array, copy into a new array instead.

+ +
+
{{jsxref("Array.prototype.forEach()")}}
+
Calls a function for each element in the array.
+
{{jsxref("Array.prototype.entries()")}} {{experimental_inline}}
+
Returns a new Array Iterator object that contains the key/value pairs for each index in the array.
+
{{jsxref("Array.prototype.every()")}}
+
Returns true if every element in this array satisfies the provided testing function.
+
{{jsxref("Array.prototype.some()")}}
+
Returns true if at least one element in this array satisfies the provided testing function.
+
{{jsxref("Array.prototype.filter()")}}
+
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
+
{{jsxref("Array.prototype.find()")}} {{experimental_inline}}
+
Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found.
+
{{jsxref("Array.prototype.findIndex()")}} {{experimental_inline}}
+
Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.
+
{{jsxref("Array.prototype.keys()")}} {{experimental_inline}}
+
Returns a new Array Iterator that contains the keys for each index in the array.
+
{{jsxref("Array.prototype.map()")}}
+
Creates a new array with the results of calling a provided function on every element in this array.
+
{{jsxref("Array.prototype.reduce()")}}
+
Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
+
{{jsxref("Array.prototype.reduceRight()")}}
+
Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
+
{{jsxref("Array.prototype.values()")}} {{experimental_inline}}
+
Returns a new Array Iterator object that contains the values for each index in the array.
+
{{jsxref("Array.prototype.@@iterator()", "Array.prototype[@@iterator]()")}} {{experimental_inline}}
+
Returns a new Array Iterator object that contains the values for each index in the array.
+
+ +

Generic methods

+ +

Many methods on the JavaScript Array object are designed to be generally applied to all objects which “look like” Arrays. That is, they can be used on any object which has a length property, and which can usefully be accessed using numeric property names (as with array[5] indexing). TODO: give examples with Array.prototype.forEach.call, and adding the method to an object like {{jsxref("Global_Objects/JavaArray", "JavaArray")}} or {{jsxref("Global_Objects/String", "String")}}. Some methods, such as {{jsxref("Array.join", "join")}}, only read the length and numeric properties of the object they are called on. Others, like {{jsxref("Array.reverse", "reverse")}}, require that the object's numeric properties and length be mutable; these methods can therefore not be called on objects like {{jsxref("String")}}, which does not permit its length property or synthesized numeric properties to be set.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4.3.1', 'Array.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype', 'Array.prototype')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/push/index.html b/files/it/web/javascript/reference/global_objects/array/push/index.html new file mode 100644 index 0000000000..ad34c3da2d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/push/index.html @@ -0,0 +1,142 @@ +--- +title: Array.prototype.push() +slug: Web/JavaScript/Reference/Global_Objects/Array/push +translation_of: Web/JavaScript/Reference/Global_Objects/Array/push +--- +
{{JSRef}}
+ +

Il metodo push() aggiunge uno o più elementi alla fine di un array e ne restituisce la nuova lunghezza.

+ +
var numbers = [1, 2, 3];
+numbers.push(4);
+
+console.log(numbers); // [1, 2, 3, 4]
+
+numbers.push(5, 6, 7);
+
+console.log(numbers); // [1, 2, 3, 4, 5, 6, 7]
+
+ +

Sintassi

+ +
arr.push([elemento1[, ...[, elementoN]]])
+ +

Parametri

+ +
+
elementoN
+
Gli elementi da aggiungere alla fine dell'array.
+
+ +

Valore di ritorno

+ +

La nuova proprietà {{jsxref("Array.length", "length")}} dell'oggetto su cui è stato richiamato il metodo.

+ +

Descrizione

+ +

Il metodo push aggiunge valori all'array.

+ +

push è intenzionalmente generico. Questo metodo può essere utilizzato con {{jsxref("Function.call", "call()")}} o {{jsxref("Function.apply", "apply()")}} su oggetti che assomigliano a un array. Il metodopush si basa sulla proprietà length per determinare da dove iniziare l'inserimento dei valori indicati. Se la proprietà length non può essere convertita in un numero, l'indice utilizzato è 0. Ciò include la possibilità che length sia inesistente, in tale caso length verrà creata.

+ +

Gli unici oggetti nativi simili agli array sono {{jsxref("Global_Objects/String", "strings", "", 1)}}, anche se non adatti alle applicazioni di questo metodo, in quanto le stringhe sono immutabili.

+ +

Esempi

+ +

Aggiungere elementi a un array

+ +

Il seguente codice crea l'array sports che contiene due elementi, poi aggiunge ulteriori due elementi allo stesso. La variabile total contiene la nuova lunghezza dell'array.

+ +
var sports = ['calcio', 'baseball'];
+var total = sports.push('football americano', 'nuoto');
+
+console.log(sports); // ['calcio', 'baseball', 'football americano', 'nuoto']
+console.log(total); // 4
+
+ +

Unire due arrays

+ +

Questo esempio utilizza {{jsxref("Function.apply", "apply()")}} per aggiungere tutti gli elementi da un secondo array.

+ +

Non utilizzare questo metodo se il secondo array (moreVegs in questo esempio) è molto grande, perché il numero massimo di parametri che una funzione può assumere è limitato nella pratica. Vedere {{jsxref("Function.apply", "apply()")}} per ulteriori dettagli.

+ +
var vegetables = ['pastinaca', 'patata'];
+var moreVegs = ['sedano', 'barbabietola'];
+
+// Unire il secondo array nel primo
+// Equivalente a vegetables.push('sedano', 'barbabietola');
+Array.prototype.push.apply(vegetables, moreVegs);
+
+console.log(vegetables); // ['pastinaca', 'patata', 'sedano', 'barbabietola']
+
+ +

Utilizzo di un oggetto come un array

+ +

Come accennato in precedenza, push è intenzionalmente generica e possiamo usarla a nostro vantaggio. Array.prototype.push può funzionare benissimo su un oggetto, come mostra questo esempio. Si noti che non creiamo un array per memorizzare la raccolta di oggetti. Al contrario, memorizziamo la raccolta sull'oggetto stesso e utilizziamo call su Array.prototype.push per ingannare il metodo e fargli pensare che siamo di fronte a un array, e funziona solo grazie al modo in cui JavaScript ci permette di stabilire il contesto di esecuzione come preferiamo.

+ +
var obj = {
+    length: 0,
+
+    addElem: function addElem(elem) {
+        // obj.length viene automaticamente incrementato
+        // ogni volta che viene aggiunto un elemento.
+        [].push.call(this, elem);
+    }
+};
+
+// Aggiungiamo alcuni oggetti vuoti solo per illustrare.
+obj.addElem({});
+obj.addElem({});
+console.log(obj.length);
+// → 2
+
+ +

Si noti che anche se obj non è un array, il metodo push ha incrementato la proprietà di length diobj come se si trattasse di un array vero e proprio.

+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioneStatoCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale. Implementato in 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')}}
+ +

Compatibilità di Browser

+ +
+ + +

{{Compat("javascript.builtins.Array.push")}}

+
+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/reduce/index.html b/files/it/web/javascript/reference/global_objects/array/reduce/index.html new file mode 100644 index 0000000000..de063df929 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/reduce/index.html @@ -0,0 +1,576 @@ +--- +title: Array.prototype.reduce() +slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce +tags: + - Array + - Array method + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reduce + - Referenza +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce +--- +
{{JSRef}}
+ +

Il metodo reduce() esegue una funzione reducer (che tu fornisci) su ogni elemento dell'array, risultante in un unico output.

+ +
{{EmbedInteractiveExample("pages/js/array-reduce.html")}}
+ +
I sorgenti per questo esempio interattivo è disponibile su un repository GitHub. Se desideri contribuire al progetto, clona https://github.com/mdn/interactive-examples e inviaci una pull request.
+ +

La funzione reducer accetta quattro argomenti:

+ +
    +
  1. Accumulatore (acc)
  2. +
  3. Valore corrente (cur)
  4. +
  5. Indice corrente (idx)
  6. +
  7. Array sul quale viene eseguito il metodo (src)
  8. +
+ +

Il valore restituito della funzione reducer viene assegnato all'accumulatore, il cui valore viene memorizzato attraverso ogni iterazione nell'intero array e in definitiva, diventa il valore finale finale singolo.

+ +

Sintassi

+ +
arr.reduce(callback(accumulator, currentValue[, index[, array]]) [, initialValue])
+ +

Parametri

+ +
+
callback
+
Una funzione da eseguire su ogni elemento dell'array (tranne il primo, se non viene fornita initialValue), accetta 4 argomenti: +
+
accumulator
+
L'accumulatore accumula i valori di ritorno del callback. È il valore accumulato precedentemente restituito nell'ultima chiamata del callback o initialValue, se fornito (vedere di seguito).
+
currentValue
+
L'elemento corrente in elaborazione nell'array.
+
index {{optional_inline}}
+
L'indice dell'elemento corrente in elaborazione nell'array. Inizia dall'indice 0 se viene fornito initialValue Altrimenti, inizia dall'indice 1.
+
array {{optional_inline}}
+
L'array a cui viene applicato reduce().
+
+
+
initialValue {{optional_inline}}
+
Un valore da utilizzare come primo argomento della prima chiamata del callback. Se non viene fornito initialValue il primo elemento dell'array verrà utilizzato e saltato. Chiamare reduce() su un array vuoto senza initialValue genererà un TypeError.
+
+ +

Valore di ritorno

+ +

Il singolo valore che risulta dalla riduzione.

+ +

Descrizione

+ +

Il metodo reduce() esegue il callback una volta per ogni valore assegnato presente nell'array, prendendo quattro argomenti:

+ + + +

La prima volta che viene chiamato il callback, accumulator e currentValue possono essere uno dei due valori. Se initialValue viene fornito nella chiamata a reduce(), accumulator sarà uguale a initialValue, e currentValue sarà uguale al primo valore nell'array. Se non viene fornito alcun valore initialValue, accumulator sarà uguale al primo valore dell'array e currentValue sarà uguale al secondo.

+ +
+

Note: Se non viene fornito initialValue, reduce() eseguirà la funzione di callback a partire dall'indice 1, saltando il primo indice. Se viene fornito initialValue, inizierà dall'indice 0.

+
+ +

Se l'array è vuoto e non viene fornito initialValue verrà generato un {{jsxref("TypeError")}}. Se l'array ha solo un elemento (indipendentemente dalla posizione) e non viene fornito initialValue, o se è fornito initialValue ma l'array è vuoto, il valore solo verrà restituito senza chiamare callback.

+ +

Di solito è più sicuro fornire initialValue perché ci sono tre output possibili senza initialValue, come mostrato nell'esempio seguente.

+ +
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
+var maxCallback2 = ( max, cur ) => Math.max( max, cur );
+
+// reduce() without initialValue
+[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
+[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }
+[                      ].reduce( maxCallback ); // TypeError
+
+// map/reduce; better solution, also works for empty or larger arrays
+[ { x: 22 }, { x: 42 } ].map( el => el.x )
+                        .reduce( maxCallback2, -Infinity );
+
+ +

Come funziona reduce()

+ +

Supponiamo che si sia verificato il seguente uso di reduce():

+ +
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
+  return accumulator + currentValue;
+});
+
+ +

Il callback verrebbe invocato quattro volte, con gli argomenti e i valori restituiti in ogni chiamata come segue:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
callbackaccumulatorcurrentValuecurrentIndexarrayvalore ritornato
prima chiamata011[0, 1, 2, 3, 4]1
seconda chiamata122[0, 1, 2, 3, 4]3
terza chiamata333[0, 1, 2, 3, 4]6
quarta chiamata644[0, 1, 2, 3, 4]10
+ +

Il valore restituito da reduce() sarà quello dell'ultima chiamata del callback (10).

+ +

È inoltre possibile fornire una {{jsxref("Functions/Arrow_functions", "Arrow Function","",1)}} al posto di una funzione completa. Il seguente codice produrrà lo stesso output del codice nel blocco sopra riportato:

+ +
[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue );
+
+ +

Se dovessi fornire initialValue come secondo argomento a reduce(), il risultato sarebbe simile a questo:

+ +
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
+    return accumulator + currentValue;
+}, 10);
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
callbackaccumulatorcurrentValuecurrentIndexarrayvalore restituito
prima chiamata1000[0, 1, 2, 3, 4]10
seconda chiamata1011[0, 1, 2, 3, 4]11
terza chiamata1122[0, 1, 2, 3, 4]13
quarta chiamata1333[0, 1, 2, 3, 4]16
quinta chiamata1644[0, 1, 2, 3, 4]20
+ +

Il valore restituito da reduce() in questo caso sarebbe 20.

+ +

Esempi

+ +

Sommare tutti i valori di un array

+ +
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
+  return accumulator + currentValue;
+}, 0);
+// sum è 6
+
+
+ +

In alternativa scritto con una arrow function:

+ +
var total = [ 0, 1, 2, 3 ].reduce(
+  ( accumulator, currentValue ) => accumulator + currentValue,
+  0
+);
+ +

Somma dei valori in un array di oggetti

+ +

Per riassumere i valori contenuti in un array di oggetti, devi fornire initialValue, in modo che ogni elemento passi attraverso la tua funzione

+ +
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
+
+ +

In alternativa scritto con una 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
+ +

Appiattire una serie di array

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+  function(accumulator, currentValue) {
+    return accumulator.concat(currentValue);
+  },
+  []
+);
+// flattened is [0, 1, 2, 3, 4, 5]
+
+ +

In alternativa scritto con una arrow function:

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+  ( accumulator, currentValue ) => accumulator.concat(currentValue),
+  []
+);
+
+ +

Conteggio delle istanze di valori in un oggetto

+ +
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 }
+
+ +

Raggruppamento di oggetti in base a una proprietà

+ +
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 }]
+// }
+
+ +

Array di legame contenuti in una serie di oggetti che utilizzano lo spread operator e 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'
+// ]
+ +

Rimuovi gli elementi duplicati nell'array

+ +
+

Note: Se si utilizza un ambiente compatibile con {{jsxref("Set")}} e {{jsxref("Array.from()")}}, è possibile utilizzare let orderedArray = Array.from(new Set(myArray)); per ottenere un array in cui sono stati rimossi gli elementi duplicati.

+
+ +
var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];
+var myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
+  if (accumulator.indexOf(currentValue) === -1) {
+    accumulator.push(currentValue);
+  }
+  return accumulator
+}, [])
+
+console.log(myOrderedArray);
+ +

Eseguire le Promises in Sequenza

+ +
/**
+ * Esegue promises da un array di funzioni che possono restituire promises
+ * in modo concatenato
+ *
+ * @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  - sarà avvolta in una promise risolta da .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
+
+ +

Composizione funzionale per tubazioni

+ +
// Elementi da utilizzare per la composizione
+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
+);
+
+// Funzioni composte per la moltiplicazione di valori specifici
+const multiply6 = pipe(double, triple);
+const multiply9 = pipe(triple, triple);
+const multiply16 = pipe(quadruple, quadruple);
+const multiply24 = pipe(double, triple, quadruple);
+
+// Utilizzo
+multiply6(6); // 36
+multiply9(9); // 81
+multiply16(16); // 256
+multiply24(10); // 240
+
+
+ +

Scrivere map usando 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;
+    }
+  });
+}
+
+ +

Se hai bisogno di supportare motori JavaScript veramente obsoleti che non supportano Object.defineProperty(), è meglio non applicare polyfills ai metodi di Array.prototype, poiché non puoi renderli non enumerabili.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}{{Spec2('ES5.1')}}Definizione iniziale Implementato in JavaScript 1.8.
{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ESDraft')}}
+ +

Compatibilità con i browser

+ +

La tabella di compatibilità in questa pagina è generata a partire da dati strutturati. Se desideri contribuire ai dati, visita https://github.com/mdn/browser-compat-data e inviaci una pull request.

+ +
+

{{Compat("javascript.builtins.Array.reduce")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/reverse/index.html b/files/it/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..750befde61 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,133 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +
{{JSRef}}
+ +

Il metodo reverse()  inverte ua matrice (array) sul posto. Il primo elemento di matrice diventa l'ultima, e l'ultimo elemento di matrice diventa il primo.

+ +
var a = ['one', 'two', 'three'];
+a.reverse();
+
+console.log(a); // ['three', 'two', 'one']
+
+ +

Sintassi

+ +
a.reverse()
+ +

Valore prodotto. 

+ +

La matrice invertita.

+ +

Descrizione

+ +

Il metodo reverse traspone gli elementi della matrice chiamata, mutando la matrice, e restituendo un riferimento alla matrice.

+ +

Esempi

+ +

Inversione degli elementi nella matrice

+ +

L'esempio seguente crea una matrice a, contenente tre elementi, quindi inverte la matrice. La chiamata ad invertire () restituisce un riferimento alla matrice invertita a.

+ +
var a = ['one', 'two', 'three'];
+var reversed = a.reverse();
+
+console.log(a);        // ['three', 'two', 'one']
+console.log(reversed); // ['three', 'two', 'one']
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatusCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}definizione iniziale. Implementata in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}}
+ +

Compatibilità browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaratteristicaChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Supporto base{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatVersionUnknown}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/slice/index.html b/files/it/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..419da77ae4 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,241 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +
{{JSRef}}
+ +

Il metodo slice() ritorna la copia di una porzione dell'array contenente gli elementi compresi tra inzio e fine (fine escluso). Il metodo slice() ritorna la copia dell'intero array se non  contiene gli elementi di inizio e fine. L'array di partenza non viene modificato.

+ +
var a = ['zero', 'one', 'two', 'three'];
+var sliced = a.slice(1, 3);
+
+console.log(a);      // ['zero', 'one', 'two', 'three']
+console.log(sliced); // ['one', 'two']
+
+ +

Sintassi

+ +
arr.slice()
+arr.slice(inizio)
+arr.slice(inizio, fine)
+
+ +

Parametri

+ +
+
begin {{optional_inline}}
+
L'indice zero-based indica da dove inizia l'intervallo da selezionare.
+
Può essere utilizzato un indice negativo, indicante l'offset dall'ultimo elemento dell'array. slice(-2) seleziona gli ultimi due elementi della sequenza.
+
Se begin non viene impostato , slice parte dall'indice 0.
+
end {{optional_inline}}
+
L' indice zero-base indica dove finisce l'intervallo da selezionare. slice seleziona gli elementi fino a quell'indice ma non l'elemento all'indice end.
+
Per esempio, slice(1,4)estrae dal secondo elemento dell'array al quarto escluso (elementi con indice 1, 2 e 3).
+
Puo essere utilizzato un indice negativo, tale indice indicherebbe l'offset dall'ultimo elemento dell'array. slice(2,-1) estrae dal terzo elemento della sequenza al penuntimo.
+
Se end non viene impostato, slice continua l'estrazione sino al termine dell'array (arr.length).
+
Se end è maggiore della lunghezza della sequenza , slice continua l'estrazione sino al termine dell'array (arr.length).
+
+ +

Return value

+ +

Un nuovo array che contiene gli elementi estratti.

+ +

Descrizione

+ +

slice non modifica l'array originale. Restituisce una copia superficiale degli elementi dell'array originale. Gli elementi dell'array originale vengono copiati nell'array restituito come segue:

+ + + +

Se viene aggiunto un nuovo elemento in uno degli array, l'altro non viene modificato.

+ +

Esempi

+ +

Restituire una porzione dell'array esistente

+ +
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
+var citrus = fruits.slice(1, 3);
+
+// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+// citrus contains ['Orange','Lemon']
+
+ +

Utilizzare slice

+ +

Nell'esempio che segue, slice crea un nuovo array, newCar, da myCar. Entrambi includono un riferimento all'oggetto myHonda. Quando il colore di myHonda diventa viola, entrambi gli array riflettono la modifica.

+ +
// Creare newCar da myCar utilizzando slice.
+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);
+
+// Mostrare i valori di myCar, newCar, e il colore di myHonda
+//  riferiti da entrambi gli array.
+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);
+
+// Modificare il colore di myHonda.
+myHonda.color = 'purple';
+console.log('The new color of my Honda is ' + myHonda.color);
+
+// Mostrare il colore di myHonda riferito da entrambi gli array.
+console.log('myCar[0].color = ' + myCar[0].color);
+console.log('newCar[0].color = ' + newCar[0].color);
+
+ +

Lo script scrive:

+ +
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
+
+ +

Oggetti Array-like

+ +

Il metodo slice può essere chiamato anche per convertire gli oggetti o le collezioni Array-like in un nuovo Array. Basta legare il metodo all'oggetto. {{jsxref("Functions/arguments", "arguments")}} all'interno di una funzione è un esempio di 'array-like object'.

+ +
function list() {
+  return Array.prototype.slice.call(arguments);
+}
+
+var list1 = list(1, 2, 3); // [1, 2, 3]
+
+ +

Il binding può essere effettuato con la funzione .call di {{jsxref("Function.prototype")}} e può anche essere ridotto utilizzando [].slice.call(arguments) invece di Array.prototype.slice.call. Ad ogni modo, può essere semplificato utilizzando {{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]
+
+ +

Streamlining cross-browser behavior

+ +

Although host objects (such as DOM objects) are not required by spec to follow the Mozilla behavior when converted by Array.prototype.slice and IE < 9 does not do so, versions of IE starting with version 9 do allow this. “Shimming” it can allow reliable cross-browser behavior. As long as other modern browsers continue to support this ability, as currently do IE, Mozilla, Chrome, Safari, and Opera, developers reading (DOM-supporting) slice code relying on this shim will not be misled by the semantics; they can safely rely on the semantics to provide the now apparently de facto standard behavior. (The shim also fixes IE to work with the second argument of slice() being an explicit {{jsxref("null")}}/{{jsxref("undefined")}} value as earlier versions of IE also did not allow but all modern browsers, including IE >= 9, now do.)

+ +
/**
+ * 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;
+    };
+  }
+}());
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in 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')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.slice")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/some/index.html b/files/it/web/javascript/reference/global_objects/array/some/index.html new file mode 100644 index 0000000000..3befa8a8b0 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/some/index.html @@ -0,0 +1,202 @@ +--- +title: Array.prototype.some() +slug: Web/JavaScript/Reference/Global_Objects/Array/some +translation_of: Web/JavaScript/Reference/Global_Objects/Array/some +--- +
{{JSRef}}
+ +

Il metodo some() verifica se almeno un elemento nell'array passa la verifica implementata dalla funzione fornita.

+ +
+

Note: Questo metodo ritorna false per qualsiasi condizione passata ad un array vuoto.

+
+ + + +
{{EmbedInteractiveExample("pages/js/array-some.html")}}
+ + + +

Sintassi

+ +
arr.some(callback[, thisArg])
+ +

Parametri

+ +
+
callback
+
Funzione di test per ogni elemento, prende tre elementi: +
+
valoreCorrente
+
Il valore corrente dell'elemento che deve essere processato nell'array.
+
indice {{Optional_inline}}
+
l'indice dell'elemento corrente dell'array.
+
array{{Optional_inline}}
+
l'array completo alla quale è stato chiamato il some().
+
+
+
thisArg{{Optional_inline}}
+
Valore da usare come this quando si esegue la callback.
+
+ +

Valore ritornato

+ +

true se la funzione di callback ha ritornato un valore {{Glossary("truthy")}} per almeno un elemento nell'array; altrimenti, false.

+ +

Descrizione

+ +

some() esegue la funzione di callback per ogni elemento presente nell'array finchè non ne trova uno dove la callback retorna un valore truthy (un valore che ritorna true se convertito in un Booleano). Se viene trovato un elemento di questo genere allora some() ritorna immediatamente true. altrimenti, some() ritorna false. callback viene invocato solamente solamente per gli elementi che hanno un valore assegnato; quindi non viene chiamato per elementi eliminati o mai assegnati.

+ +

callback è invocato con tre argomenti: il valore dell'elemento, l'indice dell'elemento nell'array, e l'array dalla quale è stato invocato.

+ +

se viene passato un parametro thisArg al metodo some(), verrà usato come valore this per le callbacks. altrimenti, verrà usato il valore {{jsxref("undefined")}} come valore di this. Il valore di this nella callback è determinato in accordo con le normali regole per determinare il valore di this nelle funzioni.

+ +

some() non muta l'array dalla quale è stato evocato.

+ +

Il range di elementi processati da some() è impostato prima della prima chiamata alla callback. Gli elementi che vengono attaccati o aggiunti all'array dopo che è stata effettuata la chiamata al metodo some() non verranno tenuti in considerazione. Se al contrario un elemento viene cambiato prima che venga processato dalla callback, il valore passato sarà quello modificato.  Elementi eliminati invece non verranno controllati. 

+ +

Esempi

+ +

Testare i valori all'interno di un array

+ +

L'esempio seguente testa se almeno un elemento dell'array è maggiore di 10.

+ +
function isBiggerThan10(element, index, array) {
+  return element > 10;
+}
+
+[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
+[12, 5, 8, 1, 4].some(isBiggerThan10); // true
+
+ +

Testing array elements using arrow functions

+ +

Arrow functions provide a shorter syntax for the same test.

+ +
[2, 5, 8, 1, 4].some(x => x > 10);  // false
+[12, 5, 8, 1, 4].some(x => x > 10); // true
+
+ +

Checking whether a value exists in an array

+ +

To mimic the function of the includes() method, this custom function returns true if the element exists in the array:

+ +
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
+ +

Checking whether a value exists using an 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
+ +

Converting any value to 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; as such 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;
+
+    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
+    for (var i = 0; i < len; i++) {
+      if (i in t && fun.call(thisArg, t[i], i, t)) {
+        return true;
+      }
+    }
+
+    return false;
+  };
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.17', 'Array.prototype.some')}}{{Spec2('ES5.1')}}Initial definition. Implemented in 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')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.some")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/sort/index.html b/files/it/web/javascript/reference/global_objects/array/sort/index.html new file mode 100644 index 0000000000..6c16c7dd6b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/sort/index.html @@ -0,0 +1,267 @@ +--- +title: Array.prototype.sort() +slug: Web/JavaScript/Reference/Global_Objects/Array/sort +tags: + - Array + - JavaScript + - Metodi + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort +--- +
{{JSRef}}
+ +

Il metodo sort() ordina gli elementi di un array in place e ritorna l'array. L'ordinamento non è necessariamente stable. L'ordinamento predefinito è in base ai punti di codice Unicode della stringa.

+ +

Il tempo e la complessità dell'ordinamento dipendono dall'implementazione, perciò non possono essere garantiti.

+ +
var fruit = ['cherries', 'apples', 'bananas'];
+fruit.sort(); // ['apples', 'bananas', 'cherries']
+
+var scores = [1, 10, 21, 2];
+scores.sort(); // [1, 10, 2, 21]
+// Nota che 10 viene prima di 2,
+// perché '10' è l'insieme di due caratteri '1' e '0' così '10' viene prima di '2' nell'ordine dei codici Unicode code .
+
+var things = ['word', 'Word', '1 Word', '2 Words'];
+things.sort(); // ['1 Word', '2 Words', 'Word', 'word']
+// In Unicode, i numeri vengono prima delle lettere maiuscole,
+// che vengono prima delle lettere minuscole.
+
+ +

Sintassi

+ +
arr.sort()
+arr.sort([compareFunction])
+
+ +

Parametri

+ +
+
compareFunction {{optional_inline}}
+
Specifica una funzione che definisce il tipo di ordinamento. Se viene omessa, l'array è ordinato in base ai valori dei suoi caratteri Unicode code , basandosi sulle stringhe di ogni elemento convertito.
+
+ +

Valore ritornato

+ +

L'array ordinato. Nota che l'array è ordinato in place, e non viene fatta alcuna copia.

+ +

Descrizione

+ +

Se non viene fornita una compareFunction , gli elementi vengono ordinati convertendoli in stringhe e confrontando le stringhe nell'ordine dei codici Unicode . Per esempio, "Banana" viene prima di "cherry". In ordine numerico, 9 arriva prima dell'80, ma poiché i numeri vengono convertiti in stringhe, "80" viene prima di "9" nell'ordine Unicode.

+ +

Se viene fornita una compareFunction , gli elementi dell'array vengono ordinati in base al valore restituito della funzione di confronto. Se a e b sono due elementi da confrontare, allora:

+ + + +

Quindi, la funzione di confronto ha la seguente forma:

+ +
function compare(a, b) {
+  if (a è inferiore a b secondo un criterio di ordinamento) {
+    return -1;
+  }
+  if (a è maggiore di b secondo un criterio di ordinamento) {
+    return 1;
+  }
+  // a deve essere uguale a b
+  return 0;
+}
+
+ +

Per confrontare i numeri anziché le stringhe, la funzione di confronto può semplicemente sottrarre b da a. La seguente funzione ordinerà l'array in ordine crescente (se non contiene Infinity e NaN):

+ +
function compareNumbers(a, b) {
+  return a - b;
+}
+
+ +

Il metodo sort può essere usato bene con {{jsxref("Operators/function", "function expressions", "", 1)}} ( e closures):

+ +
var numbers = [4, 2, 5, 1, 3];
+numbers.sort(function(a, b) {
+  return a - b;
+});
+console.log(numbers);
+
+// [1, 2, 3, 4, 5]
+
+ +

ES2015 fornisce le {{jsxref("Functions_and_function_scope/Arrow_functions", "arrow function", "", 1)}}, che consentono una sintassi più compatta:

+ +
let numbers = [4, 2, 5, 1, 3];
+numbers.sort((a, b) => a - b);
+console.log(numbers);
+
+// [1, 2, 3, 4, 5]
+ +

Gli Object possono essere ordinati passando il valore di una delle loro proprietà.

+ +
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 }
+];
+
+// ordinamento per valore
+items.sort(function (a, b) {
+  return a.value - b.value;
+});
+
+// ordinamento per nome
+items.sort(function(a, b) {
+  var nameA = a.name.toUpperCase(); // ignora maiuscole e minuscole
+  var nameB = b.name.toUpperCase(); // ignora maiuscole e minuscole
+  if (nameA < nameB) {
+    return -1;
+  }
+  if (nameA > nameB) {
+    return 1;
+  }
+
+  // i nomi devono essere uguali
+  return 0;
+});
+ +

Esempi

+ +

Creare, visualizzare, ed ordinare un array

+ +

L'esempio seguente crea quattro array , visualizza l'array originale e successivamente l'array ordinato. Gli array numerici sono ordinati prima senza e poi con una funzione di comparazione .

+ +
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('Ordinato:', stringArray.sort());
+
+console.log('numberArray:', numberArray.join());
+console.log('Ordinato senza funzione compare:', numberArray.sort());
+console.log('Ordinato con compareNumbers:', numberArray.sort(compareNumbers));
+
+console.log('numericStringArray:', numericStringArray.join());
+console.log('Ordinato senza funzione compare:', numericStringArray.sort());
+console.log('Ordinato con compareNumbers:', numericStringArray.sort(compareNumbers));
+
+console.log('mixedNumericArray:', mixedNumericArray.join());
+console.log('Ordinato senza funzione compare:', mixedNumericArray.sort());
+console.log('Ordinato con compareNumbers:', mixedNumericArray.sort(compareNumbers));
+
+ +

Questo esempio produce il seguente output. Come viene mostrato, quando viene usata una funzione comparativa, i numeri vengono ordinati correttamente sia nel caso siano numeri che nel caso siano stringhe di numeri.

+ +
stringArray: Blue,Humpback,Beluga
+Ordinato: Beluga,Blue,Humpback
+
+numberArray: 40,1,5,200
+Ordinato senza funzione compare: 1,200,40,5
+Ordinato con compareNumbers: 1,5,40,200
+
+numericStringArray: 80,9,700
+Ordinato senza funzione compare: 700,80,9
+Ordinato con compareNumbers: 9,80,700
+
+mixedNumericArray: 80,9,700,40,1,5,200
+Ordinato senza funzione compare: 1,200,40,5,700,80,9
+Ordinato con compareNumbers: 1,5,9,40,80,200,700
+
+ +

Ordinare caratteri non-ASCII 

+ +

Per ordinare stringhe con caratteri non-ASCII, cioè stringhe con caratteri accentati (e, é, è, a, ä, etc.), stringhe da lingue diverse dall'inglese: si usa {{jsxref("String.localeCompare")}}. Questa funzione può confrontare quei caratteri in modo che compaiano nel giusto ordine.

+ +
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é']
+
+ +

Ordinare con map

+ +

La compareFunction può essere invocata più volte per elemento all'interno dell'array. In base alla natura della compareFunction, si potrebbe produrre un sovraccarico elevato. Maggiore è il lavoro svolto da compareFunction e maggiori sono gli elementi da ordinare, potrebbe essere saggio utilizzare una map per l'ordinamento. L'idea è di percorrere una volta l'array per estrarre i valori effettivi usati per l'ordinamento in un array temporaneo, ordinare l'array temporaneo e quindi percorrere l'array temporaneo per ottenere l'ordine giusto.

+ +
// l'array da ordinare
+var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
+
+// l'array temporaneo contiene oggetti con posizione e valore di ordinamento
+var mapped = list.map(function(el, i) {
+  return { index: i, value: el.toLowerCase() };
+})
+
+// ordinamento dell'array mappato contenente i valori ridotti
+mapped.sort(function(a, b) {
+  if (a.value > b.value) {
+    return 1;
+  }
+  if (a.value < b.value) {
+    return -1;
+  }
+  return 0;
+});
+
+// contenitore per l'ordine risultante
+var result = mapped.map(function(el){
+  return list[el.index];
+});
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoOsservazione
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{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')}}
+ +

Compatibilità con il browser

+ +
+ + +

{{Compat("javascript.builtins.Array.sort")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/splice/index.html b/files/it/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..a68058baf8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,163 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +tags: + - Aggiunta + - Array + - JavaScript + - Method + - Prototype + - Reference + - Rimozione + - splice +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +
{{JSRef}}
+ +

Il metodo splice() modifica il contenuto di un array rimuovendo o sostituendo elementi esistenti e/o aggiungendo nuovi elementi in place.

+ +
{{EmbedInteractiveExample("pages/js/array-splice.html")}}
+ + + +

Sintassi

+ +
var arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
+
+ +

Parametri

+ +
+
start
+
L'indice al quale iniziare a cambiare l'array. Se maggiore della lunghezza dell'array, start sarà impostato sulla lunghezza dell'array. Se negativo, inizierà molti elementi dalla fine dell'array (con origine -1, che significa -n è l'indice dell'ultimo elemento dell'ennesima ed è quindi equivalente all'indice di array.length - n). Se il valore assoluto di  start è maggiore della lunghezza dell'array, inizierà dall'indice 0.
+
deleteCount {{optional_inline}}
+
Un numero intero che indica il numero di elementi nell'array da rimuovere da start.
+
Se deleteCount viene omesso, o se il suo valore è uguale o maggiore di array.length - start (cioè, se è uguale o maggiore del numero di elementi rimasti nell'array, a partire da start), tutti gli elementi da start alla fine dell'array verranno eliminati.
+
Se deleteCount è 0 o negativo, non vengono rimossi elementi. In questo caso, devi specificare almeno un nuovo elemento (vedi sotto).
+
item1, item2, ... {{optional_inline}}
+
Gli elementi da aggiungere all'array, a partire da start. Se non viene specificato alcun elemento, splice() rimuoverà solo gli elementi dall'array.
+
+ +

Valore di ritorno

+ +

Un array contenente gli elementi eliminati. Se viene rimosso solo un elemento, viene restituito un array di un elemento. Se non vengono rimossi elementi, viene restituito un array vuoto.

+ +

Descrizione

+ +

Se il numero specificato di elementi da inserire differisce dal numero di elementi da rimuovere, la lunghezza dell'array sarà diversa alla fine della chiamata.

+ +

Esempi

+ +

Rimuovi 0 (zero) elementi dall'indice 2 e inserisci "drum"

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2, 0, 'drum');
+
+// myFish è ["angel", "clown", "drum", "mandarin", "sturgeon"]
+// removed è [], nessun elemento rimosso
+ +

Rimuovi 0 (zero) elementi dall'indice 2 e inserisci "drum" e "guitar"

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2, 0, 'drum', 'guitar');
+
+// myFish è ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
+// removed è [], nessun elemento rimosso
+
+ +

Rimuovi 1 elemento dall'indice 3

+ +
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(3, 1);
+
+// removed è ["mandarin"]
+// myFish è ["angel", "clown", "drum", "sturgeon"]
+
+ +

Rimuovi 1 elemento dall'indice 2 e inserisci "trumpet"

+ +
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
+var removed = myFish.splice(2, 1, 'trumpet');
+
+// myFish è ["angel", "clown", "trumpet", "sturgeon"]
+// removed è ["drum"]
+ +

Rimuovere 2 elementi dall'indice 0 e inserire "parrot", "anemone" e "blue"

+ +
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
+var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
+
+// myFish è ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
+// removed è ["angel", "clown"]
+ +

Rimuovere 2 elementi dall'indice 2

+ +
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
+var removed = myFish.splice(myFish.length - 3, 2);
+
+// myFish è ["parrot", "anemone", "sturgeon"]
+// removed è ["blue", "trumpet"]
+ +

Rimuovere 1 elemento dall'indice -2

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(-2, 1);
+
+// myFish è ["angel", "clown", "sturgeon"]
+// removed è ["mandarin"]
+ +

Rimuovere tutti gli elementi dopo l'indice 2 (incl.)

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2);
+
+// myFish è ["angel", "clown"]
+// removed è ["mandarin", "sturgeon"]
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale Implementato in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ESDraft')}}
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Array.splice")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/tostring/index.html b/files/it/web/javascript/reference/global_objects/array/tostring/index.html new file mode 100644 index 0000000000..a5b8dcaa1e --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/tostring/index.html @@ -0,0 +1,80 @@ +--- +title: Array.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Array/toString +tags: + - Array + - JavaScript + - Prototype + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/toString +--- +
{{JSRef}}
+ +

Il metodo toString() restituisce una stringa che rappresenta l'array specificato e i suoi elementi.

+ +
{{EmbedInteractiveExample("pages/js/array-tostring.html")}}
+ +

Sintassi

+ +
arr.toString()
+ +

Valore di ritorno

+ +

Una stringa che rappresenta gli elementi dell'array.

+ +

Descrizione

+ +

L'oggetto {{jsxref("Array")}} sovrascrive il metodo toString di {{jsxref("Object")}}. Per gli oggetti Array, il metodo toString unisce l'array e restituisce una stringa contenente ciascun elemento dell'array separato da virgole.

+ +

JavaScript chiama automaticamente il metodo toString quando un array deve essere rappresentato come un valore di testo o quando viene fatto riferimento a un array in una concatenazione di stringhe.

+ +

ECMAScript 5 semantics

+ +

A partire da JavaScript 1.8.5 (Firefox 4) e coerente con la semantica ECMAScript 5th edition, il metodo toString() è generico e può essere utilizzato con qualsiasi oggetto. {{jsxref("Object.prototype.toString()")}} sarà chiamato e verrà restituito il valore risultante.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale Implementato in 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')}} 
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Array.toString")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/unshift/index.html b/files/it/web/javascript/reference/global_objects/array/unshift/index.html new file mode 100644 index 0000000000..ca4597e973 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,98 @@ +--- +title: Array.prototype.unshift() +slug: Web/JavaScript/Reference/Global_Objects/Array/unshift +translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift +--- +
{{JSRef}}
+ +
Il metodo unshift() aggiunge uno o più elementi all'inizio di un array e restitusce la nuova lunghezza dell'array stesso.
+ +
 
+ +
{{EmbedInteractiveExample("pages/js/array-unshift.html")}}
+ +

Sintassi

+ +
arr.unshift(element1[, ...[, elementN]])
+ +

Parameters

+ +
+
elementN
+
Gli elementi da aggiungere all'inizio dell'array.
+
+ +

Return value

+ +
+
La nuova proprietà {{jsxref("Array.length", "length")}} dell'oggetto su cui è stato chiamato il metodo.
+
+ +

Descrizione

+ +

Il metodo unshift inserisce i valori passati come parametri all'inizio di un oggetto array-like.

+ +

unshift è instenzionalmente generico; questo metodo può essere {{jsxref("Function.call", "chiamato", "", 1)}} o {{jsxref("Function.apply", "applicato", "", 1)}} su oggetti che assomigliano ad un array. Oggetti che non contengono una proprietà length che rifletta l'ultimo di una serie di consecutive proprietà numeriche zero-based potrebbero non comportarsi in alcun modo significativo.

+ +

Esempi

+ +
var arr = [1, 2];
+
+arr.unshift(0); // result of call is 3, the new array length
+// arr is [0, 1, 2]
+
+arr.unshift(-2, -1); // = 5
+// arr is [-2, -1, 0, 1, 2]
+
+arr.unshift([-3]);
+// arr is [[-3], -2, -1, 0, 1, 2]
+
+ +

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

+ + diff --git a/files/it/web/javascript/reference/global_objects/array/values/index.html b/files/it/web/javascript/reference/global_objects/array/values/index.html new file mode 100644 index 0000000000..f3019ef144 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/array/values/index.html @@ -0,0 +1,87 @@ +--- +title: Array.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Array/values +translation_of: Web/JavaScript/Reference/Global_Objects/Array/values +--- +
{{JSRef}}
+ +

 

+ +

Il metodo values() restituisce un nuovo oggetto Array Iterator che contiene i valori per ogni indice nell'array.

+ +

{{EmbedInteractiveExample("pages/js/array-values.html")}}

+ +
var a = ['a', 'b', 'c', 'd', 'e'];
+var iterator = a.values();
+
+console.log(iterator.next().value); // a
+console.log(iterator.next().value); // b
+console.log(iterator.next().value); // c
+console.log(iterator.next().value); // d
+console.log(iterator.next().value); // e
+ +

Sintassi

+ +
arr.values()
+ +

Valore di ritorno

+ +

Un nuovo oggetto iteratore {{jsxref("Array")}}.

+ +

Esempi

+ +

Iterazione utilizzando il  for...of loop

+ +
var arr = ['a', 'b', 'c', 'd', 'e'];
+var iterator = arr.values();
+
+for (let letter of iterator) {
+  console.log(letter);
+}
+
+ +

Array.prototype.values è una implementazionde di default di Array.prototype[Symbol.iterator].

+ +
Array.prototype.values === Array.prototype[Symbol.iterator]      //true
+ +

TODO: please write about why we need it, use cases.

+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Array.values")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/arraybuffer/index.html b/files/it/web/javascript/reference/global_objects/arraybuffer/index.html new file mode 100644 index 0000000000..118b3d2801 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,147 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +tags: + - Array tipizzati + - ArrayBuffer + - Constructor + - Costruttore + - JavaScript + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +
{{JSRef}}
+ +

L'oggetto ArrayBuffer viene utilizzato per rappresentare un buffer di lunghezza fissa di dati non elaborati. Non è possibile manipolare il contenuto di un ArrayBuffer, è possibile invece creare un array di oggetti tipizzati o un oggetto di tipo {{jsxref("DataView")}} che rappresenta il buffer in uno specifico formato ed utilizzare questo per leggere e scrivere il contenuto del buffer.

+ +
{{EmbedInteractiveExample("pages/js/arraybuffer-constructor.html")}}
+ + + +

Sintassi

+ +
new ArrayBuffer(length)
+
+ +

Parametri

+ +
+
length
+
La dimensione, in bytes, dell'array buffer da creare.
+
+ +

Valori di ritorno

+ +

Un nuovo oggetto di tipo ArrayBuffer della dimensione specificata. Il suo contenuto è inzializzato a 0.

+ +

Eccezioni

+ +

Un {{jsxref("RangeError")}} viene generato se la lunghezza è maggiore di di {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) oppure è negativa.

+ +

Descrizione

+ +

Il costruttore ArrayBuffer crea un nuovo ArrayBuffer di lunghezza specificata in bytes.

+ +

Ottenere un array buffer da dati pre-esistenti

+ + + +

Proprietà

+ +
+
ArrayBuffer.length
+
La dimensione del costruttore ArrayBuffer il cui valore è 1.
+
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
+
La funzione costruttore utilizzata per creare oggetti derivati.
+
{{jsxref("ArrayBuffer.prototype")}}
+
Permette di aggiungere proprietà a tutti gli oggetti di tipo ArrayBuffer.
+
+ +

Metodi

+ +
+
{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}
+
Restituisce true se args è una delle viste di ArrayBuffer, come un array di oggetti tipizzato o un {{jsxref("DataView")}}. Altrimenti restituisce false.
+
{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}
+
Restituisce un nuovo ArrayBuffer i cui contenuti sono presi dai dati dell'oggetto oldBuffer e successivamente troncato o esteso a zero tramite newByteLength.
+
+ +

Istanze

+ +

Tutte le istanze di ArrayBuffer ereditano da {{jsxref("ArrayBuffer.prototype")}}.

+ +

Proprietà

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Properties')}}

+ +

Metodi

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Methods')}}

+ +
+
{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}
+
Esegue le stesse operazioni di {{jsxref("ArrayBuffer.prototype.slice()")}}.
+
+ +

Esempio

+ +

In questo esempio viene creato un buffer di 8 byte con una vista di tipo {{jsxref("Global_Objects/Int32Array", "Int32Array")}} che si riferisce al buffer

+ +
var buffer = new ArrayBuffer(8);
+var view   = new Int32Array(buffer);
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}Sostituito da ECMAScript 6.
{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ES6')}} +

Definizione iniziale con standard ECMA. Specifica che new è richiesto.

+
{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.ArrayBuffer")}}

+ +

Note sulla compatibilità

+ +

Con ECMAScript 2015, ArrayBuffer deve essere inizializzato con l'operatore  {{jsxref("Operators/new", "new")}}. Inizializzare ArrayBuffer senza l'operatore new genererà un {{jsxref("TypeError")}}.

+ +
var dv = ArrayBuffer(10);
+// TypeError: inizializzaree un ArrayBuffer senza il costruttore new
+// genererà un errore
+
+ +
var dv = new ArrayBuffer(10);
+ +

Leggi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/atomics/index.html b/files/it/web/javascript/reference/global_objects/atomics/index.html new file mode 100644 index 0000000000..56c3ed5ecc --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/atomics/index.html @@ -0,0 +1,166 @@ +--- +title: Atomics +slug: Web/JavaScript/Reference/Global_Objects/Atomics +translation_of: Web/JavaScript/Reference/Global_Objects/Atomics +--- +
{{JSRef}}
+ +

L' oggetto Atomics fornisce operazioni atomiche come metodi statici. Sono utilizzati con gli oggetti {{jsxref("SharedArrayBuffer")}}.

+ +

Le operazioni atomiche sono implementate nel modulo Atomics. Diversamente dagli altri oggetti global, Atomics non è un constructor. Non è, quindi, possibile utilizzarlo con new operator o invocare l'oggetto Atomics come una funzione. Tutte le proprietà ed i metodi di Atomics sono statici (come per esempio nel caso dell'oggetto {{jsxref("Math")}}).

+ +

Propertà

+ +
+
Atomics[Symbol.toStringTag]
+
Il valore di questa proprietà è "Atomics".
+
+ +

Metodi

+ +

Operazioni Atomiche

+ +

Quando la memoria è condivisa, molti thread possono leggere e scrivere gli stessi dati in memoria. Le operazioni atomiche fanno in modo che: siano scritti e letti valori predicibili, che ciscuna operazione termini prima che la successiva abbia inizio e che ciascuna operazione non sia interrotta.

+ +
+
{{jsxref("Atomics.add()")}}
+
Aggiunge un determinato valore in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
{{jsxref("Atomics.and()")}}
+
Calcola un "bitwise AND" in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
{{jsxref("Atomics.compareExchange()")}}
+
Memorizza un dato valore in una posizione dell'array, se questo valore è uguale ad un altro determinato valore. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
{{jsxref("Atomics.exchange()")}}
+
Memorizza un dato valore in una determinata posizione nell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
+ +
+
{{jsxref("Atomics.load()")}}
+
Restituisce il valore di una determinata posizione nell'array.
+
{{jsxref("Atomics.or()")}}
+
Calcola un "bitwise OR" in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
{{jsxref("Atomics.store()")}}
+
Memorizza un dato valore in una determinata posizione dell'array. Restituisce lo stesso valore momorizzato.
+
{{jsxref("Atomics.sub()")}}
+
Sottrae un determinato valore ad una data posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
{{jsxref("Atomics.xor()")}}
+
Calcola un "bitwise XOR" in una determinata posizione dell'array. Restituisce il vecchio valore che occupava la medesima posizione nell'array.
+
+ +

Wait and wake

+ +

I metodi wait() e wake() sono modellati sul futexes ("fast user-space mutex") di Linux e forniscono metodi di attesa finchè una certa condizione non diventa vera e sono tipicamente utilizzati in costrutti bloccanti.

+ +
+
{{jsxref("Atomics.wait()")}}
+
+

Verifica che una certa posizione dell'array continui a contenere un determinato valore e si mette in attesa o va in time-out. Restituisce i valori "ok", "not-equal", oppure "timed-out". Se l'attesa non è consentita dall'agente che effettua la chiamata, allora il metodo innesca una "Error Exception" (molti browsers non consentiranno wait() nel loro thread principale)

+
+
{{jsxref("Atomics.wake()")}}
+
"Sveglia" gli agenti dormienti nella coda di wait in una determinata posizione dell'array. Restituisce il numero degli agenti "svegliati".
+
{{jsxref("Atomics.isLockFree()", "Atomics.isLockFree(size)")}}
+
+

Un primitiva di ottimizzazione che può essere utilizzata per determinare quando utilizzare "lock" o operazioni atomiche. Restituisce true, se un operazione atomica su un array di una data dimensione può essere implementata utilizzando operazioni atomiche hardware (invece del "lock"). Solo per esperti.

+
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificheStatusCommenti
{{SpecName('ESDraft', '#sec-atomics-object', 'Atomics')}}{{Spec2('ESDraft')}}Definizione Iniziale in ES2017.
{{SpecName('ES8', '#sec-atomics-object', 'Atomics')}}{{Spec2('ES8')}} 
+ +

Compatibilità con i Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}} [2]{{CompatGeckoDesktop("55")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("55")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] In Firefox, dalla versione 46 alla versione 54 questa feature è disabilitata da una configurazione avenzata. In about:config, configurare javascript.options.shared_memory a true

+ +

[2] L' implementazione è in via di sviluppo e richiede i flag di runtime: --js-flags=--harmony-sharedarraybuffer --enable-blink-feature=SharedArrayBuffer

+ +

Note di Compatibilità

+ +

Prima di SpiderMonkey 48 {{geckoRelease(48)}}, i nomi e le semantiche delle API non erano ancora state implementate. Le modifiche tra la versione 46 e la versione 48 di Firefox, sono:

+ + + +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/atomics/store/index.html b/files/it/web/javascript/reference/global_objects/atomics/store/index.html new file mode 100644 index 0000000000..5c8a466c0f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/atomics/store/index.html @@ -0,0 +1,91 @@ +--- +title: Atomics.store() +slug: Web/JavaScript/Reference/Global_Objects/Atomics/store +tags: + - Atomics + - JavaScript + - Memoria condivisa + - Store + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Atomics/store +--- +
{{JSRef}}
+ +

Il metodo statico Atomics.store() memorizza un determinato valore nella posizione data nell'array e restituisce quel valore.

+ +
{{EmbedInteractiveExample("pages/js/atomics-store.html")}}
+ + + +

Sintassi

+ +
Atomics.store(typedArray, indice, valore)
+
+ +

Parameters

+ +
+
typedArray
+
Un array con numero intero condiviso. Uno di {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, o {{jsxref("Uint32Array")}}.
+
indice
+
La posizione in typedArray per memorizzare un  value in.
+
valore
+
Numero da memorizzare.
+
+ +

Valore di Ritorno

+ +

The value that has been stored
+ // Il valore memorizzato.

+ +

Eccezioni

+ + + +

Esempio

+ +
var buffer = new ArrayBuffer(4);         // common buffer
+var float32 = new Float32Array(buffer);  // floating point
+var uint32 = new Uint32Array(buffer);    // IEEE754 representation
+
+float32[0] = 0.5;
+console.log("0x" + uint32[0].toString(16));
+
+uint32[0] = 0x3f000000;   /// IEEE754 32-bit representation of 0.5
+console.log(float32[0]);
+
+
+ +

Specificazioni

+ + + + + + + + + + + + + + +
SpecificazioniStatoCommenti
{{SpecName('ESDraft', '#sec-atomics.store', 'Atomics.store')}}{{Spec2('ESDraft')}}definizione inizile in ES2017.
+ +

Browser compatibili

+ + + +

{{Compat("javascript.builtins.Atomics.store")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getdate/index.html b/files/it/web/javascript/reference/global_objects/date/getdate/index.html new file mode 100644 index 0000000000..32c3d5fa57 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getdate/index.html @@ -0,0 +1,78 @@ +--- +title: Date.prototype.getDate() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDate +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDate +--- +
{{JSRef}}
+ +

Il metodo getDate()  resituisce il giorno del mese per la data specificata in accordo con l'ora locale.

+ +
{{EmbedInteractiveExample("pages/js/date-getdate.html")}}
+ + + +

Sintassi

+ +
dateObj.getDate()
+ +

Valore di ritorno

+ +

Un numero  integer,  tra 1 e 31, rappresentante il giorno del mese per la data fornita in accordo con l'ora locale.

+ +

Esempi

+ +

Utilizzando getDate()

+ +

La seconda dichiarazione qui sotto assegna il valore 25 alla variabile day,  basata sul valore dell'oggetto {{jsxref("Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var day = Xmas95.getDate();
+
+console.log(day); // 25
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.prototype.getdate', 'Date.prototype.getDate')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.5.14', 'Date.prototype.getDate')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.1.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getDate")}}

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getday/index.html b/files/it/web/javascript/reference/global_objects/date/getday/index.html new file mode 100644 index 0000000000..c5fd48bca7 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getday/index.html @@ -0,0 +1,89 @@ +--- +title: Date.prototype.getDay() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDay +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDay +--- +
{{JSRef}}
+ +

Il metodo getDay()  restituisce il giorno della settimana per la data specificata in accordo con l'ora locale, dove 0 rappresenta Domenica. Per il giorno del mese, vedere {{jsxref("Date.prototype.getDate()")}}.

+ +
{{EmbedInteractiveExample("pages/js/date-getday.html")}}
+ + + +

Sintassi

+ +
dateObj.getDay()
+ +

Valore di ritorno

+ +

Un numero di tipo  integer,  tra 0 e 6, corrispondente al giorno della settimana per la data fornita, in accordo con l'ora locale: 0 for Domenica, 1 per Lunedi, 2 for Martedi e cosi' via.

+ +

Esempi

+ +

Utilizzando  getDay()

+ +

La seconda dichiarazione qui sotto assegna il valore 1 a weekday, basato sul valore dell'oggetto {{jsxref("Date")}} Xmas95. December 25, 1995, è un Lunedi.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var weekday = Xmas95.getDay();
+
+console.log(weekday); // 1
+
+ +
+

Note: Se necessitato il nome completo di un giorno ("Monday" per esempio ) può essere ottenuto utilizzando {{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}} con un parametro options . Utilizzando questo metodo,  l'internazionalizzazione risulta più semplice:

+ +
var options = { weekday: 'long'};
+console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95));
+// Monday
+console.log(new Intl.DateTimeFormat('de-DE', options).format(Xmas95));
+// Montag
+
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.5.16', 'Date.prototype.getDay')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getDay")}}

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getfullyear/index.html b/files/it/web/javascript/reference/global_objects/date/getfullyear/index.html new file mode 100644 index 0000000000..57d1c5efc7 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getfullyear/index.html @@ -0,0 +1,84 @@ +--- +title: Date.prototype.getFullYear() +slug: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getFullYear +--- +
{{JSRef}}
+ +

 

+ +

Il metodo  getFullYear() restituisce l'anno della data specificata in accordo con l'ora locale.

+ +

Utilizza questo metodo invece di quello {{jsxref("Date.prototype.getYear()", "getYear()")}}.

+ +
{{EmbedInteractiveExample("pages/js/date-getfullyear.html")}}
+ + + +

Sintassi

+ +
dateObj.getFullYear()
+ +

Valore di ritorno

+ +

Un numero corrispondente all'anno della data fornita, in accordo con l'ora locale.

+ +

Descrizione

+ +

Il valore restituito da getFullYear() è un numero assoluto. Per le date tra gli anni 1000 e 9999, getFullYear() restituisce un numero a 4 cifre, per esempio, 1995. Usa quetsa funzione per essere sicuro che un anno sia compiacente con gli anni dopo il 2000.

+ +

Esempi

+ +

Utilizzando getFullYear()

+ +

Il seguente esempio assegna il valore a quattro cifre dell'anno corrente alla variabile year.

+ +
var today = new Date();
+var year = today.getFullYear();
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.10', 'Date.prototype.getFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ + + +

{{Compat("javascript.builtins.Date.getFullYear")}}

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/gethours/index.html b/files/it/web/javascript/reference/global_objects/date/gethours/index.html new file mode 100644 index 0000000000..7e04a04d3f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/gethours/index.html @@ -0,0 +1,79 @@ +--- +title: Date.prototype.getHours() +slug: Web/JavaScript/Reference/Global_Objects/Date/getHours +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getHours +--- +
{{JSRef}}
+ +

 

+ +

Il metodo  getHours() restituisce l'ora per la data specificata in accordo con l'ora locale.

+ +
{{EmbedInteractiveExample("pages/js/date-gethours.html")}}
+ + + +

Sintassi

+ +
dateObj.getHours()
+ +

Valore di ritorno

+ +

Un numero di tipo integer, tra 0 e 23, rappresentante l'ora per la data fornita in accordo con l'ora locale.

+ +

Esempi

+ +

Utilizzando getHours()

+ +

La seconda dichiarazione qui sotto assegna il valore 23 alla variabile hours, basata sul valore dell'oggetto {{jsxref("Global_Objects/Date", "Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var hours = Xmas95.getHours();
+
+console.log(hours); // 23
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.18', 'Date.prototype.getHours')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.gethours', 'Date.prototype.getHours')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getHours")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getmilliseconds/index.html b/files/it/web/javascript/reference/global_objects/date/getmilliseconds/index.html new file mode 100644 index 0000000000..68825e21ca --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getmilliseconds/index.html @@ -0,0 +1,77 @@ +--- +title: Date.prototype.getMilliseconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds +--- +
{{JSRef}}
+ +

 

+ +

Il metodo getMilliseconds() restituisce i millisecondi nella data specificata in accordo con l'ora locale.

+ +
{{EmbedInteractiveExample("pages/js/date-getmilliseconds.html")}}
+ + + +

Sintassi

+ +
dateObj.getMilliseconds()
+ +

Valore di ritorno

+ +

Un numero, tra  0 e 999, rappresentante i millisecondi per la data fornita in accordo con l'ora locale.

+ +

Esempi

+ +

Utilizzando  getMilliseconds()

+ +

Il seguente esempio assegna la porzione di millisecondi del tempo corrente alla variabile milliseconds:

+ +
var today = new Date();
+var milliseconds = today.getMilliseconds();
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.24', 'Date.prototype.getMilliseconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getmilliseconds', 'Date.prototype.getMilliseconds')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getMilliseconds")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getminutes/index.html b/files/it/web/javascript/reference/global_objects/date/getminutes/index.html new file mode 100644 index 0000000000..91f458cbda --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getminutes/index.html @@ -0,0 +1,77 @@ +--- +title: Date.prototype.getMinutes() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMinutes +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMinutes +--- +
{{JSRef}}
+ +

 

+ +

Il metodo getMinutes() restituisce i minuti nella data specificata in accordo con l'ora locale.

+ +
{{EmbedInteractiveExample("pages/js/date-getminutes.html")}}
+ +

Sintassi

+ +
dateObj.getMinutes()
+ +

Valore di ritorno

+ +

Un numero di tipo integer, tra 0 e 59, rappresentante i minuti nella data fornita in accordo con l'ora locale.

+ +

Esempi

+ +

Utilizzando getMinutes()

+ +

La seconda dichiarazione qui soto assegna il valore 15 alla variabile minutes, basata sul valore dell'oggetto {{jsxref("Global_Objects/Date", "Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var minutes = Xmas95.getMinutes();
+
+console.log(minutes); // 15
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.20', 'Date.prototype.getMinutes')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getminutes', 'Date.prototype.getMinutes')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getminutes', 'Date.prototype.getMinutes')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getMinutes")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getmonth/index.html b/files/it/web/javascript/reference/global_objects/date/getmonth/index.html new file mode 100644 index 0000000000..3d954b4ed5 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getmonth/index.html @@ -0,0 +1,90 @@ +--- +title: Date.prototype.getMonth() +slug: Web/JavaScript/Reference/Global_Objects/Date/getMonth +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getMonth +--- +
{{JSRef}}
+ +

 

+ +

Il metodo  getMonth() restituisce il mese nella data specificata in accordo con l'ora locale, come un valore in base zero (dove zero indica il primo mese dell'anno).

+ +
{{EmbedInteractiveExample("pages/js/date-getmonth.html")}}
+ + + +

Sintassi

+ +
dateObj.getMonth()
+ +

Valore di ritorno

+ +

Un numero di tipo  integer, tra 0 e 11, rappresentante il mese nella data fornita in accordo con l'ora locale. 0 corrisponde a Gennaio, 1 a Febbraio , e cosi' via.

+ +

Esempi

+ +

Utilizzando getMonth()

+ +

La seconda dichiarazione qui sotto assegna il valore 11 alla variabile month, basata sul valore dell'oggetto {{jsxref("Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var month = Xmas95.getMonth();
+
+console.log(month); // 11
+
+ +
+

Note: Se necessitato , il nome completo di un mese ("January" per esempio ) può essere ottenuto utilizzando Intl.DateTimeFormat() con un prametro options .  Utilizzando questo metodo, l'internazionalizzazione risulta più semplice:

+ +
var options = { month: 'long'};
+console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95));
+// December
+console.log(new Intl.DateTimeFormat('de-DE', options).format(Xmas95));
+// Dezember
+
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.12', 'Date.prototype.getMonth')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getmonth', 'Date.prototype.getMonth')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getmonth', 'Date.prototype.getMonth')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getMonth")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/getseconds/index.html b/files/it/web/javascript/reference/global_objects/date/getseconds/index.html new file mode 100644 index 0000000000..3faac2c56e --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/getseconds/index.html @@ -0,0 +1,79 @@ +--- +title: Date.prototype.getSeconds() +slug: Web/JavaScript/Reference/Global_Objects/Date/getSeconds +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getSeconds +--- +
{{JSRef}}
+ +

 

+ +

Il metodo getSeconds() restituisce i secondi nella data specificata in accordo con l'ora locale.

+ +
{{EmbedInteractiveExample("pages/js/date-getseconds.html")}}
+ + + +

Sintassi

+ +
dateObj.getSeconds()
+ +

Valore di ritorno

+ +

Un numero di tipo integer, tra 0 e 59, rappresentante i secondi nella data fonita in accordo con l'ora locale.

+ +

Esempi

+ +

Utilizzando  getSeconds()

+ +

La seconda dichiarazione qui sotto assegna il valore  30 alla variabile seconds, basata sul valore dell'oggetto {{jsxref("Global_Objects/Date", "Date")}} Xmas95.

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var seconds = Xmas95.getSeconds();
+
+console.log(seconds); // 30
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.22', 'Date.prototype.getSeconds')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getseconds', 'Date.prototype.getSeconds')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getSeconds")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/gettime/index.html b/files/it/web/javascript/reference/global_objects/date/gettime/index.html new file mode 100644 index 0000000000..0424faa8a4 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/gettime/index.html @@ -0,0 +1,125 @@ +--- +title: Date.prototype.getTime() +slug: Web/JavaScript/Reference/Global_Objects/Date/getTime +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getTime +--- +
 {{JSRef}}
+ +
 
+ +
Il metodo getTime() restituisce il numero di millisecondi a partire dalla Unix Epoch.
+ +

 

+ +

* JavaScript utilizza i millisecondi come unità di misura, mentre lo Unix Time è in secondi.

+ +

getTime() utilizza sempre lo UTC per la rappresentazione del  tempo. Ad esempio, un client browser in un fuso orario, getTime() sarà lo stesso come un client browser in qualsiasi altro fuso orario.

+ +

Puoi utilizzare questo metodo per aiutare ad assegnare una data ed un orario ad un altro oggetto {{jsxref("Date")}} . Questo metodo è funzionalmente equivalente al metodo {{jsxref("Date.valueof", "valueOf()")}}.

+ +
{{EmbedInteractiveExample("pages/js/date-gettime.html")}}
+ + + +

Sintassi

+ +
dateObj.getTime()
+ +

Valore di Ritorno

+ +

Un numero rappresentante i millisecondi trascorsi tra il  1 Gennaio 1970 00:00:00 UTC e la data utilizzata.

+ +

Esempi

+ +

Utilizzare getTime() per copiare le date

+ +

Costruire un oggetto data con lo stesso valore di tempo.

+ +
// Poichè il mese è in base zero, birthday sarà January 10, 1995
+var birthday = new Date(1994, 12, 10);
+var copy = new Date();
+copy.setTime(birthday.getTime());
+
+ +

Misurare il tempo di esecuzione

+ +

Sottrarre due susseguenti chiamate getTime() su nuovi oggetti {{jsxref("Date")}} generati, dà il lasso di tempo tra queste due chiamate. Ciò può essere usato per calcolare il tempo di esecuzione di alcune operazioni. Vedere anche {{jsxref("Date.now()")}} per prevenire la non necessaria instanziazione di oggetti {{jsxref("Date")}}.

+ +
var end, start;
+
+start = new Date();
+for (var i = 0; i < 1000; i++) {
+  Math.sqrt(i);
+}
+end = new Date();
+
+console.log('Operation took ' + (end.getTime() - start.getTime()) + ' msec');
+
+ +

Precisione di tempo ridotta

+ +

Per offrire protezione contro attacchi di tipo timing e fingerprinting, la precisione di new Date().getTime() potrebbe essere arrotondata a seconda dei settings del browser. In Firefox, la preferenza privacy.reduceTimerPrecision  è abilitata di default e predefinita a 20µs in Firefox 59; in 60 sarà  2ms.

+ +
// precisione di tempo ridotta (2ms) in Firefox 60
+new Date().getTime();
+// 1519211809934
+// 1519211810362
+// 1519211811670
+// ...
+
+
+// precisione di tempo ridotta con  `privacy.resistFingerprinting` abilitata
+new Date().getTime();
+// 1519129853500
+// 1519129858900
+// 1519129864400
+// ...
+
+ +

In Firefox, puoi anche abilitare privacy.resistFingerprinting, la precisione sarà 100ms oppure il valore di  privacy.resistFingerprinting.reduceTimerPrecision.microseconds, qualunque sia superiore.

+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioneStatusCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.9', 'Date.prototype.getTime')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.gettime', 'Date.prototype.getTime')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.gettime', 'Date.prototype.getTime')}}{{Spec2('ESDraft')}} 
+ +

 Compatibilità Browser

+ + + +

{{Compat("javascript.builtins.Date.getTime")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html b/files/it/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html new file mode 100644 index 0000000000..0f583c099f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html @@ -0,0 +1,99 @@ +--- +title: Date.prototype.getTimezoneOffset() +slug: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset +--- +
{{JSRef}}
+ +

 

+ +

Il metodo getTimezoneOffset() restituisce la differenza di fuso orario, in minuti, da corrente locale (host system settings) a UTC.

+ +
{{EmbedInteractiveExample("pages/js/date-gettimezoneoffset.html")}}
+ + + +

Sintassi

+ +
dateObj.getTimezoneOffset()
+ +

Valore di ritorno

+ +

Un numero rappresentante  l'offset del fuso orario, in minuti, dalla data basata sul current host system settings a UTC.

+ +

Descrizione

+ +

Il time-zone offset è la differenza, in minuti, dall'ora locale a UTC. Nota che questo significa che l'offset è positivo se l'ora locale è indietro allo UTC e negativo se è avanti. Per esempio, per il fuso orario UTC+10:00 (Australian Eastern Standard Time, Vladivostok Time, Chamorro Standard Time), sarà restituito -600.

+ + + + + + + + + + + + + + + + +
Current LocaleUTC-8UTCUTC+3
Return Value4800-180
+ +

L'offset di fuso orario restituito è quello che si applica per la Data su cui è chiamato. Dove l'host system è configurato per l'ora legale, l'offset cambierà in base alla data e al tempo che la Data rappresenta e a cui si applica l'ora legale.

+ +

Esempi

+ +

Utilizzando getTimezoneOffset()

+ +
// Get current timezone offset for host device
+var x = new Date();
+var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
+// 1
+
+// Get timezone offset for International Labour Day (May 1) in 2016
+// Be careful, the Date() constructor uses 0-indexed month so May is
+// represented with 4 (and not 5)
+var labourDay = new Date(2016, 4, 1)
+var labourDayOffset = labourDay.getTimezoneOffset() / 60;
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.5.26', 'Date.prototype.getTimezoneOffset')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.gettimezoneoffset', 'Date.prototype.getTimezoneOffset')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.gettimezoneoffset', 'Date.prototype.getTimezoneOffset')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.getTimezoneOffset")}}

diff --git a/files/it/web/javascript/reference/global_objects/date/index.html b/files/it/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..1fc4c3d9d8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,249 @@ +--- +title: Date +slug: Web/JavaScript/Reference/Global_Objects/Date +tags: + - Date + - Epoch + - JavaScript + - NeedsTranslation + - Time + - TopicStub + - Unix Epoch + - timeStamp +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +
{{JSRef}}
+ +

Creates a JavaScript Date instance that represents a single moment in time in a platform-independent format. Date objects use a Unix Time Stamp, an integer value that is the number of milliseconds since 1 January 1970 UTC.

+ +
{{EmbedInteractiveExample("pages/js/date-constructor.html")}}
+ + + +

Instantiating Date objects

+ +

The only way to create a new JavaScript Date object is to use the {{jsxref("new")}} operator:

+ +
let now = new Date();
+ +

If you simply call the {{jsxref("Date", "Date()")}} object directly, the returned value is a string instead of a Date object. There's no Date literal syntax in JavaScript.

+ +

Syntax

+ +
new Date();
+new Date(value);
+new Date(dateString);
+new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
+
+ +

Parameters

+ +

There are four basic forms for the Date() constructor:

+ +

No parameters

+ +

When no parameters are provided, the newly-created Date object represents the current date and time, specified in the local time zone, as of the time of instantiation.

+ +

Unix timestamp

+ +
+
value
+
A Unix Time Stamp which is an integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the Unix epoch), with leap seconds ignored. Keep in mind that most Unix timestamp functions are only accurate to the nearest second.
+
+ +

Timestamp string

+ +
+
dateString
+
A string value representing a date, specified in a format recognized by the {{jsxref("Date.parse()")}} method (these formats are IETF-compliant RFC 2822 timestamps and also strings in a version of ISO8601). +
+

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

+
+
+
+ +

Individual date and time component values

+ +

Given at least a year and month, this form of Date() returns a Date object whose component values (year, month, day, hour, minute, second, and millisecond) all come from the following parameters. Any missing fields are given the lowest possible value (1 for the day and 0 for every other component).

+ +
+
year
+
Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999; all other values are the actual year. See the {{anch("Two_digit_years_map_to_1900_-_1999", "example below")}}.
+
monthIndex
+
Integer value representing the month, beginning with 0 for January to 11 for December.
+
day {{optional_inline}}
+
Integer value representing the day of the month. If not specified, the default value of 1 is used.
+
hours {{optional_inline}}
+
Integer value representing the hour of the day. The default is 0 (midnight).
+
minutes {{optional_inline}}
+
Integer value representing the minute segment of a time. The default is 0 minutes past the hour.
+
seconds {{optional_inline}}
+
Integer value representing the second segment of a time. The default is zero seconds past the minute.
+
milliseconds {{optional_inline}}
+
Integer value representing the millisecond segment of a time. The default is 0 milliseconds past the second.
+
+ +

User notes

+ +

The Unix epoch and timestamps

+ +

A JavaScript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on January 1, 1970, UTC. This date and time is called the Unix epoch, which is the predominant base value for computer-recorded date and time values.

+ +
+

Note: It's important to keep in mind that the date and time is stored in the local time zone, and that the basic methods to fetch the date and time or its components all work in the local time zone as well.

+
+ +

A day is made up of 86,400,000 milliseconds. Given that and the size of the underlying number used to record the timestamp, and it can be calculated that the Date object can represent dates within ±100,000,000 (one hundred million) days relative to January 1, 1970 UTC. That means that in the year 293,742, we'll have to think about fixing this.

+ +

Date format and time zone conversions

+ +

There are a number of methods available to obtain the date in various formats, as well as to do time zone conversions. Especially useful are the functions that output the date and time in Coordinated Universal Time (UTC), the global standard time defined by the World Time Standard. This time is historically known as Greenwich Mean Time, as UTC lies along the meridian that includes London and nearby Greenwhich in the United Kingdom. The user's device provides the local time.

+ +

In addition to methods to read and alter individual components of the local date and time, such as {{jsxref("Date.getDay", "getDay()")}} and {{jsxref("Date.setHours", "setHours()")}}, there are also versions of the same methods that read and maniuplate the date and time using UTC, such as {{jsxref("Date.getUTCDay()", "getUTCDay()")}} and {{jsxref("Date.setHoursUTC", "setUTCHours()")}}.

+ +

Properties

+ +
+
{{jsxref("Date.prototype")}}
+
Allows the addition of properties to a JavaScript Date object.
+
Date.length
+
The value of Date.length is 7. This is the number of arguments handled by the constructor. It's not generally a useful result.
+
+ +

Methods

+ +
+
{{jsxref("Date.now()")}}
+
Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored.
+
{{jsxref("Date.parse()")}}
+
Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC, with leap seconds ignored. +
+

Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.

+
+
+
{{jsxref("Date.UTC()")}}
+
Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored.
+
+ +

JavaScript Date instances

+ +

All Date instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the Date constructor can be modified to affect all Date instances.

+ +

Date.prototype Methods

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}
+ +

Examples

+ +

Several ways to create a Date object

+ +

The following examples show several ways to create JavaScript dates:

+ +
+

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

+
+ +
var today = new Date();
+var birthday = new Date('December 17, 1995 03:24:00');
+var birthday = new Date('1995-12-17T03:24:00');
+var birthday = new Date(1995, 11, 17);
+var birthday = new Date(1995, 11, 17, 3, 24, 0);
+
+ +

Two digit years map to 1900 - 1999

+ +

In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.

+ +
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+// Deprecated method, 98 maps to 1998 here as well
+date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
+
+ +

Calculating elapsed time

+ +

The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds.

+ +

Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.

+ +
// 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;
+}
+
+var yourFunctionReturn = printElapsedTime(yourFunction);
+
+ +
+

Note: In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.

+
+ +

Get the number of seconds since Unix Epoch

+ +
var seconds = Math.floor(Date.now() / 1000);
+
+ +

In this case it's important to return only an integer (so a simple division won't do), and also to only return actually elapsed seconds (that's why this code uses {{jsxref("Math.floor()")}} and not {{jsxref("Math.round()")}}).

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date", 3)}}

diff --git a/files/it/web/javascript/reference/global_objects/date/now/index.html b/files/it/web/javascript/reference/global_objects/date/now/index.html new file mode 100644 index 0000000000..dcf3650fd0 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,96 @@ +--- +title: Date.now() +slug: Web/JavaScript/Reference/Global_Objects/Date/now +translation_of: Web/JavaScript/Reference/Global_Objects/Date/now +--- +
{{JSRef}}
+ +

Il metodo Date.now() restituisce il numero di millisecondi trascori dal Gennaio 1, 1970 00:00:00 UTC.

+ +
{{EmbedInteractiveExample("pages/js/date-now.html")}}
+ +

Sintassi

+ +
var timeInMs = Date.now();
+ +

Valore di ritorno

+ +

Un {{jsxref("Number")}} rappresentante i millisecondi trascorsi fin dall'epoca UNIX.

+ +

Descrizione

+ +

Poichè now() è un metodo statico di  {{jsxref("Date")}}, lo utilizzerai sempre come Date.now().

+ +

Pecisione di tempo ridotta

+ +

Per offrire protezione contro attacchi di tipo timing e fingerprinting, la precisione di  Date.now() potrebbe essere arrotondata  a seconda dei settings del browser.
+ In Firefox,  la preferenza di  privacy.reduceTimerPrecision  è abilitata di default e predefinita a 20ms in Firefox 59; in 60 sarà 2ms.

+ +
// precisione di tempo ridotta (2ms) in Firefox 60
+Date.now()
+// 1519211809934
+// 1519211810362
+// 1519211811670
+// ...
+
+
+//  precisione di tempo ridotta con `privacy.resistFingerprinting` abilitata
+Date.now();
+// 1519129853500
+// 1519129858900
+// 1519129864400
+// ...
+
+ +

In Firefox, puoi anche abiliytare privacy.resistFingerprinting, la precisione sarà 100ms oppure il valore di privacy.resistFingerprinting.reduceTimerPrecision.microseconds, qualunque sia più grande.

+ +

Polyfill

+ +

Tale metodo è stato standardizzato in ECMA-262 5th edition. Motori che non sono stati aggiornati al supporto di questo metodo possono ovviare alla sua assenza utilizzando il seguente shim:

+ +
if (!Date.now) {
+  Date.now = function now() {
+    return new Date().getTime();
+  };
+}
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementata in JavaScript 1.5.
{{SpecName('ES6', '#sec-date.now', 'Date.now')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ + + +

{{Compat("javascript.builtins.Date.now")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/date/utc/index.html b/files/it/web/javascript/reference/global_objects/date/utc/index.html new file mode 100644 index 0000000000..cfbf1abb10 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/date/utc/index.html @@ -0,0 +1,135 @@ +--- +title: Date.UTC() +slug: Web/JavaScript/Reference/Global_Objects/Date/UTC +translation_of: Web/JavaScript/Reference/Global_Objects/Date/UTC +--- +
{{JSRef}}
+ +

Il metodo Date.UTC() accetta gli stessi parametri del costruttore {{jsxref("Date")}}, ma li tratta come UTC. Restituisce  il numero di millisecondi fin dal Gennaio 1, 1970, 00:00:00 UTC.

+ +
{{EmbedInteractiveExample("pages/js/date-utc.html")}}
+ + + +

Sintassi

+ +

ECMAScript 2017 e successivi:

+ +
Date.UTC(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]])
+ +

ECMAScript 2016 e anteriori: (utilizzo di month richiesto)

+ +
Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])
+ +

Parametri

+ +
+
year
+
Un anno intero.
+
month
+
Un integer tra 0 (Gennaio) e 11 (Dicembre) rappresentante il mese. (Fino a ECMAScript 2016, month era un parametro richiesto. Con ES2017, non lo è più.)
+
day {{optional_inline}}
+
Opzionalel. Un integer tra 1 e 31 rappresentante il giorno del mese. Se omesso, è predefinito a 1.
+
hour {{optional_inline}}
+
Un integer tra  0 e 23 rappresentante le ore. Se omesso è predefinito a 0.
+
minute {{optional_inline}}
+
Un  integer tra 0 e 59 rappresentante i minuti.  Se omesso, è predefinito a 0.
+
second {{optional_inline}}
+
Un integer tra  0 e 59 rappresentante i secondi. Se omesso, è predefinito a 0.
+
millisecond {{optional_inline}}
+
Un  integer tra 0 e 999 rappresentante i millisecondi. Se omesso, è predefinito a 0.
+
+ +

Valore di ritorno

+ +

Un numero rappresentante i umeri di millisecondi per la data fornita sin dal Gennaio 1, 1970, 00:00:00, UTC.

+ +

Descrizione

+ +

UTC() prende date delimitate da virgola e parametri tempo e restituisce il numero di millisecondi tra Gennaio 1, 1970, 00:00:00, tempo universale ed il tempo e la data specificata.

+ +

Gli anni tra 0 e 99 sono convertiti ad un anno nel 20mo secolo(1900 + year); per esempio, 95 è convertito  all'anno 1995.

+ +

Il metodo UTC() differisce dal costruttore {{jsxref("Date")}} in due modi.

+ + + +

Se un parametro è fuori dal range previsto, il metodo UTC() aggiorna gli altri parametri per adattare il valore. Per esempio, se 15 è usato per il mese, l'anno sarà incrementato di 1 (year + 1) e 3 sarà usato per il mese.

+ +

UTC() è un metodo statico di {{jsxref("Date")}}, per questo è chiamato come Date.UTC() invece che come un metodo di istanza {{jsxref("Date")}}.

+ +

Esempi

+ +

Utilizzando Date.UTC()

+ +

La seguente dichiarazione crea un oggetto {{jsxref("Date")}} con gli argomenti trattati come  UTC invece di local:

+ +
var utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0));
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.4.3', 'Date.UTC')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}} Definizione iniziale. Implementata in JavaScript 1.0.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Date.UTC")}}

+ +

Note di compatibilità

+ +

Date.UTC con meno di due argomenti

+ +

Quando si provvedono meno di due argomenti a Date.UTC, ECMAScript 2017 richiede che  {{jsxref("NaN")}} sia restituito. Motori che non supportavano tale comportamento sono stati aggiornati (vedere {{bug(1050755)}}, ecma-262 #642).

+ +
Date.UTC();
+Date.UTC(1);
+
+// Safari: NaN
+// Chrome/Opera/V8: NaN
+
+// Firefox <54: non-NaN
+// Firefox 54+: NaN
+
+// IE: non-NaN
+// Edge: NaN
+
+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/decodeuri/index.html b/files/it/web/javascript/reference/global_objects/decodeuri/index.html new file mode 100644 index 0000000000..40a65b0c57 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/decodeuri/index.html @@ -0,0 +1,120 @@ +--- +title: decodeURI() +slug: Web/JavaScript/Reference/Global_Objects/decodeURI +translation_of: Web/JavaScript/Reference/Global_Objects/decodeURI +--- +
{{jsSidebar("Objects")}}
+ +

Sommario

+ +

La funzione decodeURI() decodifica un {{Glossary("URI")}} creato da {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} o una funzione simile.

+ +

Sintassi

+ +
decodeURI(encodedURI)
+ +

Parametri

+ +
+
encodedURI
+
Un {{Glossary("URI")}} completo.
+
+ +

Descrizione

+ +

Sostituisce ogni sequenza di escape nell'{{Glossary("URI")}} codificato con il carattere che la rappresenta, ma non decodifica sequenze di escape che non potrebbero essere state create dalla {{jsxref("Global_Objects/encodeURI", "encodeURI()")}}, come il carattere #.

+ +

Esempi

+ +

Decodificare un URL in Cirillico

+ +
decodeURI("https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
+// "https://developer.mozilla.org/ru/docs/JavaScript_шеллы"
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
ECMAScript 3rd Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.3.1', 'decodeURI')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-decodeuri-encodeduri', 'decodeURI')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/decodeuricomponent/index.html b/files/it/web/javascript/reference/global_objects/decodeuricomponent/index.html new file mode 100644 index 0000000000..243bd14a93 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/decodeuricomponent/index.html @@ -0,0 +1,124 @@ +--- +title: decodeURIComponent() +slug: Web/JavaScript/Reference/Global_Objects/decodeURIComponent +translation_of: Web/JavaScript/Reference/Global_Objects/decodeURIComponent +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La funzione decodeURIComponent() decodifica una parte di {{Glossary("URI")}} creata da {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}} o una funzione simile.

+ +

Sintassi

+ +
decodeURIComponent(encodedURIComponent)
+ +

Parametri

+ +
+
encodedURIComponent
+
Una parte codificata di un {{Glossary("URI")}}
+
+ +

Descrizione

+ +

Sostituisce ogni sequenza di escape nella parte di {{Glossary("URI")}} codificata con il carattere che la rappresenta.

+ +

Esempio

+ +

Decodificare una parte di URL in Cirillico

+ +
decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
+// "JavaScript_шеллы"
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 3rd Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.3.2', 'decodeURIComponent')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-decodeuricomponent-encodeduricomponent', 'decodeURIComponent')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/encodeuri/index.html b/files/it/web/javascript/reference/global_objects/encodeuri/index.html new file mode 100644 index 0000000000..24118aec60 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/encodeuri/index.html @@ -0,0 +1,160 @@ +--- +title: encodeURI() +slug: Web/JavaScript/Reference/Global_Objects/encodeURI +translation_of: Web/JavaScript/Reference/Global_Objects/encodeURI +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La funzione encodeURI() codifica un {{Glossary("URI")}} sostituendo alcuni specifici caratteri con una, due, tre o quattro sequenze di escape, che rappresentano il carattere codificato in {{Glossary("UTF-8")}} (le sequenze di quattro caratteri di escape verrano solo create per i caratteri composti da due caratteri "surrogati").

+ +

Sintassi

+ +
encodeURI(uri)
+ +

Parametri

+ +
+
uri
+
Un {{Glossary("URI")}} completo.
+
+ +

Descrizione

+ +

Questa funzione assume che uri sia un {{Glossary("URI")}} completo, quindi non codifica i caratteri riservati che hanno un significato particolare nell'{{Glossary("URI")}}.

+ +

encodeURI sostituisce tutti i caratteri con la sequenza di escape UTF-8 appropriata, ecceto i seguenti:

+ + + + + + + + + + + + + + + + + + + + +
TipoCaratteri
Caratteri riservati; , / ? : @ & = + $
Caratteri non codificatilettere, cifre, - _ . ! ~ * ' ( )
Score#
+ +

encodeURI non prepara una richiesta HTTP GET o POST, ad esempio per {{domxref("XMLHttpRequest")}}, perché "&", "+" e "=" non vengono codificati, ma sono trattati come caratteri speciali nelle richieste GET e POST. Se è necessario codificarli, usare la funzione {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}.

+ +

Se si tenta di codificare un surrogato che non è parte di una coppia, verrà generato un {{jsxref("Global_Objects/URIError", "URIError")}}.

+ +
// Coppia surrogata: Ok
+encodeURI("\uD800\uDFFF");
+
+// Solo il primo carattere surrogato:
+// Viene generato un "URIError: malformed URI sequence"
+encodeURI("\uD800");
+
+// Solo il secondo carattere surrogato:
+// Viene generato un "URIError: malformed URI sequence"
+encodeURI("\uDFFF"); 
+ +

Se uno desidera seguire il più recente standard per gli {{Glossary("URL")}} RFC3986, nel quale le parentesi quadre sono caratteri riservati (per gli indirizzi {{Glossary("IPv6")}}), può essere utile il seguente codice:

+ +
function fixedEncodeURI(str) {
+    return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
+}
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 3rd Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.3.3', 'encodeURI')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-encodeuri-uri', 'encodeURI')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/encodeuricomponent/index.html b/files/it/web/javascript/reference/global_objects/encodeuricomponent/index.html new file mode 100644 index 0000000000..66b290ccb4 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/encodeuricomponent/index.html @@ -0,0 +1,162 @@ +--- +title: encodeURIComponent() +slug: Web/JavaScript/Reference/Global_Objects/encodeURIComponent +translation_of: Web/JavaScript/Reference/Global_Objects/encodeURIComponent +--- +
{{jsSidebar("Objects")}}
+ +

Sommario

+ +

La funzione encodeURIComponent() codifica un componente di un {{Glossary("URI")}} sostituendo alcuni specifici caratteri con una, due, tre o quattro sequenze di escape, che rappresentano il carattere codificato in {{Glossary("UTF-8")}} (le sequenze di quattro caratteri di escape verrano solo create per i caratteri composti da due caratteri "surrogati").

+ +

Sintassi

+ +
encodeURIComponent(uriComponent);
+ +

Parametri

+ +
+
uriComponent
+
Una parte di un {{Glossary("URI")}}
+
+ +

Descrizione

+ +

encodeURIComponent sostituisce tutti i caratteri esclusi i seguenti: lettere, cifre, - _ . ! ~ * ' ( )

+ +

Se si tenta di codificare un surrogato che non è parte di una coppia, verrà generato un {{jsxref("Global_Objects/URIError", "URIError")}}.

+ +
// Coppia surrogata: Ok
+encodeURIComponent("\uD800\uDFFF");
+
+// Solo il primo carattere surrogato:
+// Viene generato un "URIError: malformed URI sequence"
+encodeURIComponent("\uD800");
+
+// Solo il secondo carattere surrogato:
+// Viene generato un "URIError: malformed URI sequence"
+encodeURIComponent("\uDFFF");
+ +

Per evitare problemi inaspettati durante le richieste al server, bisognerebbe richiamare encodeURIComponent su ogni dato inserito dall'utente che verrà passato come parte di un {{Glossary("URI")}}. Per esempio, un un utente potrebbe digitare "Cani&Gatti = animali". Senza utilizzare la funzione encodeURIComponent, la richiesta verrebbe costruita in modo simile a "commento=Cani&Gatti%20=%20animali". Notare che sono due variabili separate: "commento" e "Gatti%20". Utilizzando quuesta funzione verrebbe invece costruita come "commento=Cani%26Gatti%20%3D%20animali​".

+ +

Utilizzando application/x-www-form-urlencoded, gli spazi devono essere sostituiti da un "+"., quindi si potrebbe usare la funzione encodeURIComponent seguita da un altra sostituzione da "%20" a "+".

+ +

Per aderire con più precisione allo standard RFC 3986 (secondo il quale !'() e * sono caratteri riservati), si può usare la seguente funzione:

+ +
function fixedEncodeURIComponent(str) {
+  return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
+    return '%' + c.charCodeAt(0).toString(16);
+  });
+}
+
+ +

Esempi

+ +

Il seguente esempio fornisce un metodo per codificare come richiesto dall'header Content-Disposition:

+ +
var fileName = 'my file(2).txt';
+var header = "Content-Disposition: attachment; filename*=UTF-8''"
+             + encodeRFC5987ValueChars(fileName);
+
+console.log(header);
+// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
+
+
+function encodeRFC5987ValueChars (str) {
+    return encodeURIComponent(str).
+        // Notare che anche se per l'RFC3986 "!" è riservato, non lo è per
+        // l' RFC5987, quindi non viene sostituito
+        replace(/['()]/g, escape). // i.e., %27 %28 %29
+        replace(/\*/g, '%2A').
+            // Per l'RFC5987 questi caratteri non necessitano di essere codificati,
+            // quindi possiamo consentire un po' più di leggibilità: |`^
+            replace(/%(?:7C|60|5E)/g, unescape);
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 3rd Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.3.4', 'encodeURIComponent')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-encodeuricomponent-uricomponent', 'encodeURIComponent')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/escape/index.html b/files/it/web/javascript/reference/global_objects/escape/index.html new file mode 100644 index 0000000000..77fa1e5bf0 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/escape/index.html @@ -0,0 +1,126 @@ +--- +title: escape() +slug: Web/JavaScript/Reference/Global_Objects/escape +translation_of: Web/JavaScript/Reference/Global_Objects/escape +--- +
+
+
{{jsSidebar("Objects")}} {{deprecated_header}}
+
+
+ +

Sommario

+ +

La funzione escape(), deprecata, crea una nuova stringa nella quale alcuni caratteri vengono sostituiti con una sequenza di escape esadecimale. È preferibile usare le funzioni {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} o {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}.

+ +

Sintassi

+ +
escape(string)
+ +

Parametri

+ +
+
string
+
La stringa da codificare.
+
+ +

Descrizione

+ +

La funzione escape() è una proprietà dell'oggetto globale. Vengono codificati tutti i caratteri speciali, ad eccezione di: @ * _ + - . /

+ +

I caratteri vengono sostituiti con codici esadecimali che possono avere due caratteri, se il loro valore è minore o ugugale a 0xFF, (%xx) oppure quattro (%uxxxx).

+ +

Esempi

+ +
escape("abc123");     // "abc123"
+escape("äöü");        // "%E4%F6%FC"
+escape("ć");          // "%u0107"
+
+// Caratteri speciali
+escape("@*_+-./");    // "@*_+-./"
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-B.2.1', 'escape')}}{{Spec2('ES5.1')}}Definita nell'appendice B, "Compatibility"
{{SpecName('ES6', '#sec-escape-string', 'escape')}}{{Spec2('ES6')}}Definita nell'appendice B, "Additional ECMAScript Features for Web Browsers"
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/eval/index.html b/files/it/web/javascript/reference/global_objects/eval/index.html new file mode 100644 index 0000000000..22e3c70bb6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/eval/index.html @@ -0,0 +1,231 @@ +--- +title: eval() +slug: Web/JavaScript/Reference/Global_Objects/eval +translation_of: Web/JavaScript/Reference/Global_Objects/eval +--- +

{{jsSidebar("Objects")}}

+ +

Riassunto

+ +

Il metodo eval() esegue il codice JavaScript rappresentato come una stringa.

+ +

Sintassi

+ +
eval(stringa)
+ +

Parametri

+ +
+
string
+
Una stringa che rappresenta un'espressione JavaScript, dichiarazione o sequenza di istruzioni. L'espressione può includere le variabili e le proprietà degli oggetti esistenti.
+
+ +

Descrizione

+ +

eval() è una funzione dell'oggetto globale.

+ +

L'argomento della funzione eval() è una stringa. Se la stringa rappresenta un'espressione, eval() esegue l'espressione. Se l'argomento rappresenta una o più dichiarazioni Javascript, eval()esegue le dichiarazioni. Non chiamare eval() per eseguire un'operazione aritmetica, JavaScript la esegue automaticamente.

+ +

Se si costruisce un'espressione aritmetica come una stringa, è possibile usare eval() per eseguirla in un secondo momento. Ad esempio, supponiamo di avere una variabile x. E' possibile rinviare il valore di un'espressione che coinvolge x  assegnando il valore della stringa dell'espressione, tipo "3 * x + 2", ad una variabile, e quindi chiamare eval() in un punto successivo dello script.

+ +

Se l'argomento di eval() non è una stringa, eval() restituisce l'argomento immutato. Nell'esempio qui sotto, il costrutto String viene specificato, e eval() ritorna un oggetto String piuttosto che il risultato della stringa.

+ +
eval(new String("2 + 2")); // returns a String object containing "2 + 2"
+eval("2 + 2");             // returns 4
+
+ +

E' possibile aggirare questa limitazione in modo generico utilizzando toString().

+ +
var expression = new String("2 + 2");
+eval(expression.toString());
+
+ +

Non è possibile utilizzare la funzione eval indirettamente, invocandola con un nome diverso da eval(); se lo fai , potrebbe verificarsi un errore di sintassi. Per esempio, non si dovrebbe usare il seguente codice:

+ +
var x = 2;
+var y = 4;
+var myEval = eval;
+myEval("x + y");
+
+ +

Non usate eval inutilmente!

+ +

eval()è una funzione pericolosa, che esegue il codice con i privilegi dell'amministratore della pagina. Se si esegue eval() con una stringa che potrebbe essere interessata da un malintenzionato, si può interrompere l'esecuzione del codice dannoso sul computer dell'utente con il permesso della pagina Web. Ancora più importante, codici di terze parti possono vedere come eval() è stata invocata, che può portare a possibili attacchi come {{jsxref("Global_Objects/Function", "Function")}}.

+ +

eval() è generalmente più lenta rispetto alle alternative, dal momento che deve chiamare l'interprete di JS, mentre moltri altri costrutti sono ottimizzati da moderni "motori" JS.

+ +

Queste sono alternative più sicure (e veloci! ) ad eval() per comuni impieghi.

+ +

Accesso alle proprietà utente

+ +

Si consiglia si non utilizzare eval() per conventire i nomi di proprietà in proprietà. Consideriamo l'esempio qui sotto, dove le proprietà dell'oggetto acui accedere non è nota fino a quando viene eseguito il codice. Questo può essere fatto con eval:

+ +
var obj = { a: 20, b: 30 };
+var propname = getPropName();  //returns "a" or "b"
+
+eval( "var result = obj." + propname );
+
+ +

Tuttavia, eval () non è necessario qui. In realtà, il suo uso è sconsigliato qui. Invece, utilizzare gli operatori membri, che sono molto più veloci e sicuri:

+ +
var obj = { a: 20, b: 30 };
+var propname = getPropName();  //returns "a" or "b"
+var result = obj[ propname ];  //  obj[ "a" ] is the same as obj.a
+
+ +

Utilizzare le funzioni invece di eseguire frammenti di codice

+ +

JavaScript ha funzioni di prima classe, il che significa che è possibile passare funzioni come argomenti ad altre API, memorizzarli in variabili e le proprietà degli oggetti, e così via. Molte API DOM sono progettate con questo in mente, in modo da poter (e devono) scrivere a:

+ +
// instead of setTimeout(" ... ", 1000) use:
+setTimeout(function() { ... }, 1000);
+
+// instead of elt.setAttribute("onclick", "...") use:
+elt.addEventListener("click", function() { ... } , false); 
+ +

Le chiusure sono utili anche come un modo per creare funzioni parametrizzate senza concatenazioni di stringhe.

+ +

Analisi di JSON (conversione di stringhe in oggetti JavaScript)

+ +

Se la stringa che si sta chiamando eval() contiene dati (per esempio un array: "[1, 2, 3]"), al ontrario del codice, si dovrebbe considerareil passaggio a JSON, che permette la stringa di utilizzre un sottoinsieme della sintassi Javascript per rappresentare i dati. Vedi anche Downloading JSON and JavaScript in extensions.

+ +

Notare che, poichè la sintassi JSON è limitata rispetto alla sintassi di Javascript, molti letterali Javascript validi non analizzare come JSON. Ad esempio, le virgole finali non sono ammessi in JSON, e nomi di proprietà (chiavi) in letterali oggetto devono essere racchiusi tra virgolette. Assicurarsi di utilizzare un serializzatore JSON per generare le stringhe che vrranno successivamente analizzate come JSON.

+ +

Paasare i dati al posto di codici

+ +

Ad esempio, un'estensione progettata per raschiare contenuti delle pagine Web potrebbe avere le regole di raschiatura definite in  XPath invece di codice Javascript.

+ +

Eseguire codice con privilegi limitati

+ +

Se devi eseguire il codice, considerare di eseguirlo con privilegi ridotti. Questo consilio vale soprattutto per le estensioni e le applicazioni XUL, che possono utilizzare  Components.utils.evalInSandbox per questo.

+ +

Esempio

+ +

Il seguente esempio mostra output utilizzando document.write. Nel server-side JavaScript, è possibile visualizzare la stessa uscita chiamando la funzione write() invece di utilizzare il document.write().

+ +

Esempio: Usare eval

+ +

Nel codice seguente, entrambe le dichiarazioni contenenti  eval() restituiscono 42. La prima restituisce la stringa  "x + y + 1" ; la seconda esegue la stringa "42".

+ +
var x = 2;
+var y = 39;
+var z = "42";
+eval("x + y + 1"); // returns 42
+eval(z);           // returns 42
+
+ +

Esempio: Usare eval Per eseguire una serie di istruzioni JavaScript.

+ +

Il seguente esempio utilizza  eval() per eseguire la stringa str. Questa stringa consiste in una serie di istruzioni JavaScript che aprono una finestra di avviso e assegnano a z un valore 42 se x è di cinque, e assegna 0 a z altrimenti. Quando viene eseguita la seconda istruzione, eval() farà si che questa dichiarazioni da effettuare, e sarà anche eseguire l'insieme di istruzioni e restituire il valore che viene assegnato a z.

+ +
var x = 5;
+var str = "if (x == 5) {alert('z is 42'); z = 42;} else z = 0; ";
+
+document.write("<P>z is ", eval(str));
+ +

Esempio: L'ultima espressione viene eseguita

+ +

eval()restituisce il valore dell'ultima espressione valutata.

+ +
var str = "if ( a ) { 1+1; } else { 1+2; }";
+var a = true;
+var b = eval(str);  // returns 2
+
+alert("b is : " + b);
+
+a = false;
+b = eval(str);  // returns 3
+
+alert("b is : " + b);
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.1.2.1', 'eval')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-eval-x', 'eval')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome per AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Gecko-specific notes

+ + + +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/apply/index.html b/files/it/web/javascript/reference/global_objects/function/apply/index.html new file mode 100644 index 0000000000..1c0d04272d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/apply/index.html @@ -0,0 +1,250 @@ +--- +title: Function.prototype.apply() +slug: Web/JavaScript/Reference/Global_Objects/Function/apply +tags: + - JavaScript + - funzione + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply +--- +
+

{{JSRef}}

+ +

Il metodo apply() chiama una funzione passandole il "this" ed i parametri forniti sottoforma di array (o array-like object).

+ +

Nota: Mentre la sintassi di questa funzione è quasi completamente identica a quella di {{jsxref("Function.call", "call()")}}, la fondamentale differenza è che call() accetta una lista di parametri, mentre apply() accetta un singolo array contenente una lista di parametri.

+ +

Sintassi

+ +
fun.apply(thisArg, [argsArray])
+ +

Parametri

+ +
+
thisArg
+
Il valore del this da fornire alla chiamata a fun. Nota che questo potrebbe non essere l'effettivo valore visto dal metodo: se il metodo non è eseguito in {{jsxref("Strict_mode", "strict mode", "", 1)}}, {{jsxref("null")}} ed {{jsxref("undefined")}} saranno rimpiazzati dall'oggetto globale.
+
argsArray
+
Un array-like object che specifica i parametri con la quale la funzione fun deve essere chiamata. Può essere anche {{jsxref("null")}} o {{jsxref("undefined")}} nel caso nessun parametro dovesse essere passato. A partire da ECMAScript 5 questi parametri possono essere un qualunque array-like object invece di un semplice array. Vedi sotto per le {{anch("Browser_compatibility", "compatibilità nei browser")}}.
+
+ +

Descrizione

+ +

this solitamente si riferisce all'oggetto corrente, ma grazie ad apply è possibile scrivere un metodo una sola volta e riusarlo più volte su oggetti differenti passando ad apply, appunto, un this differente. Cosi viene eliminata la necessità di riscrivere di nuovo lo stesso metodo per un oggetto diverso.

+ +

apply è molto simile a {{jsxref("Function.call", "call()")}}, eccezion fatta per il modo in cui i parametri vengono passati. Puoi utilizzare un array di parametri invece della solita lista. Con apply, ad esempio, puoi utilizzare il seguente array literal: fun.apply(this, ['eat', 'bananas']), o il seguente oggetto {{jsxref("Array")}}: fun.apply(this, new Array('eat', 'bananas')).

+ +

Puoi anche utilizzare {{jsxref("Functions/arguments", "arguments")}} per il parametro argsArrayarguments è una variabile locale di tutte le funzioni. Può essere utilizzata per tutti i parametri non specificati dell'oggetto chiamato. In più, non è necessario che si conoscano i parametri dell'oggetto chiamato quando si utilizza apply.

+ +

Da ECMAScript 5 puoi anche usare qualunque tipo di array-like object. Ad esempio puoi utilizzare un {{domxref("NodeList")}} o un oggetto come { 'length': 2, '0': 'eat', '1': 'bananas' }.

+ +

{{note("La maggior parte dei browser, incluso Chrome 14 ed Internet Explorer 9, non accetto array-like objects e lanceranno una eccezione.")}}

+ +

Esempi

+ +

Utilizzare apply per concatenare costruttori

+ +

Puoi utilizzare apply per concatenare {{jsxref("Operators/new", "costruttori", "", 1)}} per un oggetto, in maniera simile a Java. Nel seguente esempio creeremo una {{jsxref("Function")}} globale chiamata construct, che ti permetterà di utilizzare un array-like object con un costruttore anziché una lista di argomenti.

+ +
Function.prototype.construct = function (aArgs) {
+  var oNew = Object.create(this.prototype);
+  this.apply(oNew, aArgs);
+  return oNew;
+};
+
+ +

Note: Il metodo Object.create() usato nell'esempio sovrastante è relativamente nuovo. Per un alternativa che utilizza le closures considera questo pezzo di codice:

+ +
Function.prototype.construct = function(aArgs) {
+  var fConstructor = this, fNewConstr = function() {
+    fConstructor.apply(this, aArgs);
+  };
+  fNewConstr.prototype = fConstructor.prototype;
+  return new fNewConstr();
+};
+ +

Esempio d'uso:

+ +
function MyConstructor() {
+  for (var nProp = 0; nProp < arguments.length; nProp++) {
+    this['property' + nProp] = arguments[nProp];
+  }
+}
+
+var myArray = [4, 'Hello world!', false];
+var myInstance = MyConstructor.construct(myArray);
+
+console.log(myInstance.property1);                // logs 'Hello world!'
+console.log(myInstance instanceof MyConstructor); // logs 'true'
+console.log(myInstance.constructor);              // logs 'MyConstructor'
+
+ +

Note: Il metodo non nativo Function.construct non funzionerà con alcuni costruttori nativi (come {{jsxref("Date")}}). In questi casi devi usare {{jsxref("Function.prototype.bind")}}. Immagina ad esempio di avere un array come il seguente da utilizzare con il costruttore {{jsxref("Global_Objects/Date", "Date")}}: [2012, 11, 4]; In questo caso dovresti scrivere qualcosa come: new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))() — ad ogni modo questo non è il miglior modo di fare le cose e non andrebbe mai usato in produzione.

+ +

Utilizzare apply combinato alle funzioni built-in

+ +

Un intelligente uso di apply ti permette di utilizzare delle funzioni built-in per dei compiti che altrimenti sarebbero stati fatti, nel caso sottostante, ciclando l'array e scorrendo ogni suo elemento e sottoponendolo a dei controlli. L'esempio seguente dimostra come trovare il massimo / minimo valore all'interno di un array utilizzando Math.max/Math.min.

+ +
// min/max number in an array
+var numbers = [5, 6, 2, 3, 7];
+
+// using Math.min/Math.max apply
+var max = Math.max.apply(null, numbers);
+// This about equal to Math.max(numbers[0], ...)
+// or Math.max(5, 6, ...)
+
+var min = Math.min.apply(null, numbers);
+
+// vs. simple loop based algorithm
+max = -Infinity, min = +Infinity;
+
+for (var i = 0; i < numbers.length; i++) {
+  if (numbers[i] > max) {
+    max = numbers[i];
+  }
+  if (numbers[i] < min) {
+    min = numbers[i];
+  }
+}
+
+ +

Ma tieni a mente che nell'usare apply in questo modo si corre il rischio di superare il limite imposto dal motore JavaScript degli argomenti che possono essere passati ad una funzione.
+ Le conseguenze nel fare ciò variano da motore a motore (ad esempio JavaScriptCore ha il limite settato a mano di 65536 parametri), perché il limite non è specificato. Alcuni motori lanceranno una eccezione. Altri invece limiteranno arbitrariamente il numero dei parametri passati alla funzione su cui viene usato il metodo apply(). (Un esempio di quest'ultimo caso potrebbe essere quello di un motore che ha questo limite settato a 4 e, nell'esempio sovrastante, gli unici parametri che effettivamente saranno passati alla funzione saranno 5, 6, 2, 3, piuttosto che l'intero array.) Una decisione saggia, nel caso si prevede la possibilità di raggiungere un enorme numero di parametri, sarebbe quella di parzializzare il numero di parametri per lotti:

+ +
function minOfArray(arr) {
+  var min = Infinity;
+  var QUANTUM = 32768;
+
+  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
+    var submin = Math.min.apply(null, arr.slice(i, Math.min(i+QUANTUM, len)));
+    min = Math.min(submin, min);
+  }
+
+  return min;
+}
+
+var min = minOfArray([5, 6, 2, 3, 7]);
+
+ +

Usare apply come "monkey-patch"

+ +

L'attività del "monkey-patching" consiste nel modificare il funzionamento di un metodo senza dover andare a mettere mano al codice sorgente (cosa da evitare sempre e comunque). Difatti Apply può rivelarsi il modo migliore di modificare il funzionamento, ad esempio, di una funzione interna a Firefox o di una qualunque altra libreria JS. Data una funzione someobject.foo, è possibile modificarne il funzionamento in questo modo:

+ +
var originalfoo = someobject.foo;
+someobject.foo = function() {
+  // Do stuff before calling function
+  console.log(arguments);
+  // Call the function as it would have been called normally:
+  originalfoo.apply(this, arguments);
+  // Run stuff after, here.
+}
+
+ +

Questo metodo ritorna particolarmente utile quando vuoi debuggare eventi e interfacce con qualcosa che non espone API come i diversi eventi .on([event]... (usabili anche dal Devtools Inspector).

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale. Implementato in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generico array-like object come {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatGeckoDesktop("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generico array-like object come {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ +

Vedi anche

+ + +
diff --git a/files/it/web/javascript/reference/global_objects/function/arguments/index.html b/files/it/web/javascript/reference/global_objects/function/arguments/index.html new file mode 100644 index 0000000000..949e5f9cdb --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/arguments/index.html @@ -0,0 +1,92 @@ +--- +title: Function.arguments +slug: Web/JavaScript/Reference/Global_Objects/Function/arguments +tags: + - Deprecated + - Function + - JavaScript + - Property + - arguments +translation_of: Web/JavaScript/Reference/Global_Objects/Function/arguments +--- +
{{JSRef}} {{deprecated_header}}
+ +

La proprieta' function.arguments fa riferimento ad un oggetto simile ad un array corrispondente ai parametri passati ad una funzione. Usa questa semplice variabile {{jsxref("Functions/arguments", "arguments")}} invece. Questa proprieta' non e' disponibile in strict mode.

+ +

Descrizione

+ +

La sintassi function.arguments e' deprecata. Il metodo consigliato per accedere all'oggetto {{jsxref("Functions/arguments", "arguments")}}, disponibile all'interno delle funzioni e' semplicemente mediante l'utilizzo di {{jsxref("Functions/arguments", "arguments")}}.

+ +

In caso di ricorsione, per esempio, se la funzione f e' presente diverse volte nello stack, il valore di f.arguments rappresenta i parametri corrispondenti alla chiamata alla funzione piu' recente.

+ +

Il valore della proprieta' arguments e' normalmente null se non c'e' una sua chiamata durante l'esecuzione della funzione (ovvero quando la funzione e' stata chiamata ma non ha ancora ritornato nessun valore).

+ +

Esempi

+ +
function f(n) { g(n - 1) }
+
+function g(n) {
+  console.log('before: ' + g.arguments[0])
+  if (n > 0) { f(n) }
+  console.log('after: ' + g.arguments[0])
+}
+
+f(2)
+
+console.log('returned: ' + g.arguments)
+
+// Output
+
+// before: 1
+// before: 0
+// after: 0
+// after: 1
+// returned: null
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0. Deprecated in favor of {{jsxref("Functions/arguments", "arguments")}} in ES3.
{{SpecName('ES5.1', '#sec-10.6', 'arguments object')}}{{Spec2('ES5.1')}}{{jsxref("Functions/arguments", "arguments")}} object
{{SpecName('ES6', '#sec-arguments-object', 'arguments object')}}{{Spec2('ES6')}}{{jsxref("Functions/arguments", "arguments")}} object
{{SpecName('ESDraft', '#sec-arguments-object', 'arguments object')}}{{Spec2('ESDraft')}}{{jsxref("Functions/arguments", "arguments")}} object
+ +

Compatibilita' Browser

+ +
+ + +

{{Compat("javascript.builtins.Function.arguments")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/arity/index.html b/files/it/web/javascript/reference/global_objects/function/arity/index.html new file mode 100644 index 0000000000..fec2d9e988 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/arity/index.html @@ -0,0 +1,26 @@ +--- +title: Function.arity +slug: Web/JavaScript/Reference/Global_Objects/Function/arity +translation_of: Archive/Web/JavaScript/Function.arity +--- +

{{JSRef}}{{Obsolete_Header}}

+ +
+

La proprieta' arity ritornava il numero di parametri richiesta da una funzione. Ad ogni modo non esiste piu' ed e' stata rimpiazzata dalla proprieta' {{JSxRef("Function.prototype.length")}}.

+
+ +

Specifiche

+ +

Implementato in JavaScript 1.2. Deprecato in JavaScript 1.4.

+ +

Compatibilita' Browser

+ + + +

{{Compat("javascript.builtins.Function.arity")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/bind/index.html b/files/it/web/javascript/reference/global_objects/function/bind/index.html new file mode 100644 index 0000000000..38187ac5e6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/bind/index.html @@ -0,0 +1,277 @@ +--- +title: Function.prototype.bind() +slug: Web/JavaScript/Reference/Global_Objects/Function/bind +translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind +--- +
{{JSRef}}
+ +

Il metodo bind() crea una nuova funzione che, quando chiamata, ha parola chiave this impostata sul valore fornito, con una data sequenza di argomenti che precede quella fornita quando viene chiamata la nuova funzione

+ +

{{EmbedInteractiveExample("pages/js/function-bind.html", "taller")}}

+ + + +

Sintassi

+ +
function.bind(thisArg[, arg1[, arg2[, ...]]])
+ +

Parametri

+ +
+
thisArg
+
Il valore va passato come parametro alla funzione target quando viene chiamata la funzione associata. Il valore viene ignorato se la funzione associata viene costruita utilizzando l'operatore {{jsxref("Operators/new", "new")}}. Quando si utilizza bind per creare una funzione (fornita come callback) all'interno di un setTimeout, qualsiasi valore primitivo passato come thisArg viene convertito in oggetto. Se non vengono forniti argomenti per vincolarlo, l'esecuzione viene considerata come thisArg per la nuova funzione.
+
arg1, arg2, ...
+
Argomenti da anteporre agli argomenti forniti alla funzione associata quando si richiama la funzione di destinazione.
+
+ +

Valore restituito

+ +

Una copia della funzione data con specificato this valore e gli argomenti iniziali.

+ +

Descrizione

+ +

La funzione bind() crea una nuova funzione associata (BF, bound function). Un BF è un exotic function object (oggetto funzione esotico, un termine di ECMAScript 2015) che racchiude l'oggetto funzione originale. Chiamare un BF generalmente comporta l'esecuzione della sua funzione wrapped (avvolta).
+ Un BF ha le seguenti proprietà interne:

+ + + +

Quando viene chiamata la funzione associata, chiama il metodo interno [[Call]] su [[BoundTargetFunction]], con i seguenti argomenti call(boundThis, ...args). Dove, boundThis è [[BoundThis]], args è [[BoundArguments]] seguito dagli argomenti passati dalla chiamata alla funzione.

+ +

Una funzione associata (bound function) può anche essere costruita usando l'operatore new: agendo in tal modo si comporta come se la funzione obiettivo fosse stata invece costruita. Il valore this fornito viene ignorato, mentre gli argomenti preposti sono forniti alla funzione emulata.

+ +

Esempi

+ +

Creare una funzione associata

+ +

L'uso più semplice di bind() è di creare una funzione che, indipendentemente da come viene chiamata, viene chiamata con un particolare valore. Un errore comune per i nuovi programmatori JavaScript consiste nell'estrarre un metodo da un oggetto, in seguito chiamare tale funzione e aspettarsi che utilizzi l'oggetto originale come tale (ad esempio, utilizzando tale metodo nel codice basato sul callback). Senza particolare cura, tuttavia, l'oggetto originale viene solitamente perso. La creazione di una funzione associata dalla funzione, utilizzando l'oggetto originale, risolve in modo chiaro questo problema:

+ +
this.x = 9;    // questo si riferisce all'oggetto "finestra" globale qui nel browser
+var module = {
+  x: 81,
+  getX: function() { return this.x; }
+};
+
+module.getX(); // 81
+
+var retrieveX = module.getX;
+retrieveX();
+// returns 9 - restituisce 9 - La funzione viene richiamata nell'ambito globale
+
+// Create a new function with 'this' bound to module
+// Crea una nuova funzione con 'this' associato al modulo
+// I nuovi programmatori potrebbero confondere il
+// global var x con la proprietà del modulo x var boundGetX = retrieveX.bind(module);
+boundGetX(); // 81
+
+ +

Funzioni parzialmente applicate

+ +

Il prossimo uso più semplice di bind() è quello di creare una funzione con argomenti iniziali pre-specificati. Questi argomenti (se presenti) seguono il valore fornito e vengono quindi inseriti all'inizio degli argomenti passati alla funzione di destinazione, seguiti dagli argomenti passati alla funzione associata, ogni volta che viene chiamata la funzione associata.

+ +
function list() {
+  return Array.prototype.slice.call(arguments);
+}
+
+var list1 = list(1, 2, 3); // [1, 2, 3]
+
+// Crea una funzione con un argomento principale preimpostato
+var leadingThirtysevenList = list.bind(null, 37);
+
+var list2 = leadingThirtysevenList();
+// [37]
+
+var list3 = leadingThirtysevenList(1, 2, 3);
+// [37, 1, 2, 3]
+
+ +

Con setTimeout

+ +

Di default all'interno di {{domxref("window.setTimeout()")}}, la parola chiave this verrà impostata sull'oggetto {{ domxref("window") }} (or global). Quando si lavora con metodi di classe che richiedono questo this riferimento alle istanze di classe, è possibile associarlo esplicitamente alla funzione di callback, al fine di mantenere l'istanza.

+ +
function LateBloomer() {
+  this.petalCount = Math.floor(Math.random() * 12) + 1;
+}
+
+// Dichiarare apertura dopo un ritardo di 1 secondo
+LateBloomer.prototype.bloom = function() {
+  window.setTimeout(this.declare.bind(this), 1000);
+};
+
+LateBloomer.prototype.declare = function() {
+  console.log('Sono un bel fiore con ' +
+    this.petalCount + ' petali!');
+};
+
+var flower = new LateBloomer();
+flower.bloom();
+// dopo 1 secondo, attiva il metodo 'declare'
+ +

Funzioni associate utilizzate come costruttori

+ +
+

Warning: Questa sezione dimostra capacità JavaScript e documenta alcuni casi limite del metodo bind(). I metodi mostrati di seguito non sono il modo migliore di fare le cose e probabilmente non dovrebbero essere usati in nessun ambiente di produzione.

+
+ +

Le funzioni associate sono automaticamente utilizzabili con l'operatore {{jsxref("Operators/new", "new")}} per costruire nuove istanze create dalla funzione target. Quando una funzione associata viene utilizzata per costruire un valore, la condizione viene ignorata. Tuttavia, gli argomenti forniti sono ancora preposti alla chiamata del costruttore:

+ +
function Point(x, y) {
+  this.x = x;
+  this.y = y;
+}
+
+Point.prototype.toString = function() {
+  return this.x + ',' + this.y;
+};
+
+var p = new Point(1, 2);
+p.toString(); // '1,2'
+
+// non supportato nel polyfill di seguito,
+// funziona bene con il bind nativo:
+
+var YAxisPoint = Point.bind(null, 0/*x*/);
+
+
+var emptyObj = {};
+var YAxisPoint = Point.bind(emptyObj, 0/*x*/);
+
+var axisPoint = new YAxisPoint(5);
+axisPoint.toString(); // '0,5'
+
+axisPoint instanceof Point; // true
+axisPoint instanceof YAxisPoint; // true
+new Point(17, 42) instanceof YAxisPoint; // true
+
+ +

Note that you need do nothing special to create a bound function for use with {{jsxref("Operators/new", "new")}}. The corollary is that you need do nothing special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using {{jsxref("Operators/new", "new")}}.

+ +
// Example can be run directly in your JavaScript console
+// ...continuing from above
+
+// Can still be called as a normal function
+// (although usually this is undesired)
+YAxisPoint(13);
+
+emptyObj.x + ',' + emptyObj.y;
+// >  '0,13'
+
+ +

If you wish to support the use of a bound function only using {{jsxref("Operators/new", "new")}}, or only by calling it, the target function must enforce that restriction.

+ +

Creating shortcuts

+ +

bind() is also helpful in cases where you want to create a shortcut to a function which requires a specific this value.

+ +

Take {{jsxref("Array.prototype.slice")}}, for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this:

+ +
var slice = Array.prototype.slice;
+
+// ...
+
+slice.apply(arguments);
+
+ +

With bind(), this can be simplified. In the following piece of code, slice is a bound function to the {{jsxref("Function.prototype.apply()", "apply()")}} function of {{jsxref("Function.prototype")}}, with the this value set to the {{jsxref("Array.prototype.slice()", "slice()")}} function of {{jsxref("Array.prototype")}}. This means that additional apply() calls can be eliminated:

+ +
// same as "slice" in the previous example
+var unboundSlice = Array.prototype.slice;
+var slice = Function.prototype.apply.bind(unboundSlice);
+
+// ...
+
+slice(arguments);
+
+ +

Polyfill

+ +

You can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of bind() in implementations that do not natively support it.

+ +
if (!Function.prototype.bind) {
+  Function.prototype.bind = function(oThis) {
+    if (typeof this !== 'function') {
+      // closest thing possible to the ECMAScript 5
+      // internal IsCallable function
+      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
+    }
+
+    var aArgs   = Array.prototype.slice.call(arguments, 1),
+        fToBind = this,
+        fNOP    = function() {},
+        fBound  = function() {
+          return fToBind.apply(this instanceof fNOP
+                 ? this
+                 : oThis,
+                 aArgs.concat(Array.prototype.slice.call(arguments)));
+        };
+
+    if (this.prototype) {
+      // Function.prototype doesn't have a prototype property
+      fNOP.prototype = this.prototype;
+    }
+    fBound.prototype = new fNOP();
+
+    return fBound;
+  };
+}
+
+ +

Some of the many differences (there may well be others, as this list does not seriously attempt to be exhaustive) between this algorithm and the specified algorithm are:

+ + + +

If you choose to use this partial implementation, you must not rely on those cases where behavior deviates from ECMA-262, 5th edition! With some care, however (and perhaps with additional modification to suit specific needs), this partial implementation may be a reasonable bridge to the time when bind() is widely implemented according to the specification.

+ +

Please check https://github.com/Raynos/function-bind for a more thorough solution!

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES2015', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Function.bind")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/call/index.html b/files/it/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..54acd401ca --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,175 @@ +--- +title: Function.prototype.call() +slug: Web/JavaScript/Reference/Global_Objects/Function/call +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +
{{JSRef}}
+ +

Il metodo call() esegue una funzione con un dato valore this e argomenti passati singolarmente.

+ +
+

Note: Mentre la sintassi di questa funzione è quasi identica a quella di {{jsxref("Function.prototype.apply", "apply()")}}, la differenza fondamentale è che call() accetta una lista di argomenti mentre apply() accetta un singolo array di argomenti.

+
+ +
{{EmbedInteractiveExample("pages/js/function-call.html")}}
+ + + +

Sintassi

+ +
func.call([thisArg[, arg1, arg2, ...argN]])
+ +

Parametri

+ +
+
thisArg {{optional_inline}}
+
+

Il valore da usare come this quando si esegue func.

+ +
+

Attenzione: In certi casi, thisArg potrebbe non essere il valore reale visto dal metodo.

+ +

Se il metodo è una funzione in {{jsxref("Strict_mode", "non-strict mode", "", 1)}}, {{jsxref("Global_Objects/null", "null")}} e {{jsxref("Global_Objects/undefined", "undefined")}} sarà sostituito dall'oggetto globale e i valori di tipo primitiva verranno convertiti in oggetti.

+
+
+
arg1, arg2, ...argN {{optional_inline}}
+
Argomenti per la funzione.
+
+ +

Valore restituito

+ +

Il risultato dell'esecuzione della funzione con il this e gli argomenti specificati.

+ +

Descrizione

+ +

Il metodo call() consente a una funzione/metodo appartenente a un oggetto di essere essere assegnata e chiamata per un oggetto diverso..

+ +

call() fornisce un nuova valore di this alla funzione/metodo. Con call(), si può scrivere un metodo una volta ed ereditarlo in un altro oggetto senza dover riscrivere il metodo per il nuovo oggetto.

+ +

Esempi

+ +

Usare call per collegare costruttori per un oggetto

+ +

Si può usare call per collegare costruttori per un oggetto (simile a Java).

+ +

Nell'esempio seguente, il costruttore per l'oggetto Product è definito con 2 parametri: name e price.

+ +

Due altre funzioni, Food e Toy, invocano Product, passando this, name, e price. Product inizializza le proprietà name e price. Entrambe le funzioni specializzate definiscono la 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';
+}
+
+const cheese = new Food('feta', 5);
+const fun = new Toy('robot', 40);
+
+ +

Usare call per invocare una funzione anonima

+ +

In questo esempio, viene create una funzione anonima e usato call per invocarla su ogni oggetto di un array.

+ +

Lo scopo principale della funzione anonima qui è di aggiungere una funzione print o ogni oggetto il quale è in grado di stampare il corretto indice dell'oggetto nell'array.

+ +
+

Passare l'oggetto come valore this non è strettamente necessario ma è fatto a scopo esplicativo.

+
+ +
const animals = [
+  { species: 'Lion', name: 'King' },
+  { species: 'Whale', name: 'Fail' }
+];
+
+for (let i = 0; i < animals.length; i++) {
+  (function(i) {
+    this.print = function() {
+      console.log('#' + i + ' ' + this.species
+                  + ': ' + this.name);
+    }
+    this.print();
+  }).call(animals[i], i);
+}
+
+ +

Usare call per invocare una funzione e specificare il contesto per  'this'

+ +

Nell'esempio sotto, quando viene eseguita greet, il valore di this verrà legato all'oggetto obj.

+ +
function greet() {
+  const reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
+  console.log(reply);
+}
+
+const obj = {
+  animal: 'cats', sleepDuration: '12 and 16 hours'
+};
+
+greet.call(obj);  // cats typically sleep between 12 and 16 hours
+
+ +

Usare call per invocare una funzione senza specificare il primo parametro

+ +

Nell'esempio sotto, viene invocata la funzione display senza passare il primo parametro. Se il primo parametro non è passato il valore di this è legato all'oggetto globale.

+ +
var sData = 'Wisen';
+
+function display() {
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call();  // sData value is Wisen
+ +
+

Attenzione: In strict mode il valore di this sarà undefined. Vedere sotto.

+
+ +
'use strict';
+
+var sData = 'Wisen';
+
+function display() {
+  console.log('sData value is %s ', this.sData);
+}
+
+display.call(); // Cannot read the property of 'sData' of undefined
+ +

Specifiche

+ + + + + + + + + + + + +
Specifiche
{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Function.call")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/function/index.html b/files/it/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..4ef63fb80b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,237 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

The Function constructor creates a new Function object. In JavaScript every function is actually a Function object.

+ +

gge

+ +

Syntax

+ +
new Function ([arg1[, arg2[, ...argN]],] functionBody)
+ +

Parameters

+ +
+
arg1, arg2, ... argN
+
Names to be used by the function as formal argument names. Each must be a string that corresponds to 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.
+
+ +

Description

+ +

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code, because such functions are parsed with the rest of the code.

+ +

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

+ +
+

Note: Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.

+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Properties and Methods of Function

+ +

The global Function object has no methods or properties of its own, however, since it is a function itself it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.

+ +

Function prototype object

+ +

Properties

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
+ +

Methods

+ +
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
+ +

Function instances

+ +

Function instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all Function instances.

+ +

Examples

+ +

Specifying arguments with the Function constructor

+ +

The following code creates a Function object that takes two arguments.

+ +
// Example can be run directly in your JavaScript console
+
+// Create a function that takes two arguments and returns the sum of those arguments
+var adder = new Function('a', 'b', 'return a + b');
+
+// Call the function
+adder(2, 6);
+// > 8
+
+ +

The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".

+ +

A recursive shortcut to massively modify the DOM

+ +

Creating functions with the Function constructor is one of the ways to dynamically create an indeterminate number of new objects with some executable code into the global scope from a function. The following example (a recursive shortcut to massively modify the DOM) is impossible without the invocation of the Function constructor for each new query if you want to avoid closures.

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example - a recursive shortcut to massively modify the DOM</title>
+<script type="text/javascript">
+var domQuery = (function() {
+  var aDOMFunc = [
+    Element.prototype.removeAttribute,
+    Element.prototype.setAttribute,
+    CSSStyleDeclaration.prototype.removeProperty,
+    CSSStyleDeclaration.prototype.setProperty
+  ];
+
+  function setSomething(bStyle, sProp, sVal) {
+    var bSet = Boolean(sVal), fAction = aDOMFunc[bSet | bStyle << 1],
+        aArgs = Array.prototype.slice.call(arguments, 1, bSet ? 3 : 2),
+        aNodeList = bStyle ? this.cssNodes : this.nodes;
+
+    if (bSet && bStyle) { aArgs.push(''); }
+    for (
+      var nItem = 0, nLen = this.nodes.length;
+      nItem < nLen;
+      fAction.apply(aNodeList[nItem++], aArgs)
+    );
+    this.follow = setSomething.caller;
+    return this;
+  }
+
+  function setStyles(sProp, sVal) { return setSomething.call(this, true, sProp, sVal); }
+  function setAttribs(sProp, sVal) { return setSomething.call(this, false, sProp, sVal); }
+  function getSelectors() { return this.selectors; };
+  function getNodes() { return this.nodes; };
+
+  return (function(sSelectors) {
+    var oQuery = new Function('return arguments.callee.follow.apply(arguments.callee, arguments);');
+    oQuery.selectors = sSelectors;
+    oQuery.nodes = document.querySelectorAll(sSelectors);
+    oQuery.cssNodes = Array.prototype.map.call(oQuery.nodes, function(oInlineCSS) { return oInlineCSS.style; });
+    oQuery.attributes = setAttribs;
+    oQuery.inlineStyle = setStyles;
+    oQuery.follow = getNodes;
+    oQuery.toString = getSelectors;
+    oQuery.valueOf = getNodes;
+    return oQuery;
+  });
+})();
+</script>
+</head>
+
+<body>
+
+<div class="testClass">Lorem ipsum</div>
+<p>Some text</p>
+<div class="testClass">dolor sit amet</div>
+
+<script type="text/javascript">
+domQuery('.testClass')
+  .attributes('lang', 'en')('title', 'Risus abundat in ore stultorum')
+  .inlineStyle('background-color', 'black')('color', 'white')('width', '100px')('height', '50px');
+</script>
+</body>
+
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in 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')}}
+ +

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/it/web/javascript/reference/global_objects/function/length/index.html b/files/it/web/javascript/reference/global_objects/function/length/index.html new file mode 100644 index 0000000000..6e305fb3ed --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/function/length/index.html @@ -0,0 +1,87 @@ +--- +title: Function.length +slug: Web/JavaScript/Reference/Global_Objects/Function/length +translation_of: Web/JavaScript/Reference/Global_Objects/Function/length +--- +
{{JSRef}}
+ +

La proprietà length indica il numero di parametri che la funzione si aspetta di ricevere.

+ +

{{EmbedInteractiveExample("pages/js/function-length.html")}}

+ + + +
{{js_property_attributes(0,0,1)}}
+ +

Description

+ +

length è una proprietà di un oggetto {{jsxref("Function")}} che indica quanti argomenti la funzione si aspetta, cioè il numero di parametri formali. Questo numero esclude il {{jsxref("rest_parameters", "rest parameter", "", 1)}} e include solo i parametri prima del primo con un valore predefinito. Al contrario, {{jsxref("Functions_and_function_scope/arguments/length", "arguments.length")}} è locale a una funzione e fornisce il numero di argomenti effettivamente passati alla funzione.

+ +

Data property of the Function constructor

+ +

Il costruttore  {{jsxref("Function")}} è esso stesso un oggetto {{jsxref("Function")}}. La sua proprietà length ha valore 1. Gli attributi delle proprietà sono: Writable: false, Enumerable: false, Configurable: false.

+ +

Property of the Function prototype object

+ +

La proprietà length del prototype di un oggetto {{jsxref("Function")}} ha valore 0.

+ +

Examples

+ +
console.log(Function.length); /* 1 */
+
+console.log((function()        {}).length); /* 0 */
+console.log((function(a)       {}).length); /* 1 */
+console.log((function(a, b)    {}).length); /* 2 etc. */
+
+console.log((function(...args) {}).length);
+// 0, rest parameter is not counted
+
+console.log((function(a, b = 1, c) {}).length);
+// 1, only parameters before the first one with
+// a default value is counted
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ES6')}}Gli attributi configurabili di queste proprietà diventano true.
{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Function.length")}}

+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/generator/index.html b/files/it/web/javascript/reference/global_objects/generator/index.html new file mode 100644 index 0000000000..b950dd8216 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/generator/index.html @@ -0,0 +1,187 @@ +--- +title: Generator +slug: Web/JavaScript/Reference/Global_Objects/Generator +tags: + - ECMAScript 2015 + - Generator + - JavaScript + - Legacy Generator + - Legacy Iterator + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Generator +--- +
{{JSRef}}
+ +

The Generator object is returned by a {{jsxref("Statements/function*", "generator function", "", 1)}} and it conforms to both the iterable protocol and the iterator protocol.

+ +

Syntax

+ +
function* gen() {
+  yield 1;
+  yield 2;
+  yield 3;
+}
+
+var g = gen(); // "Generator { }"
+ +

Methods

+ +
+
{{jsxref("Generator.prototype.next()")}}
+
Returns a value yielded by the {{jsxref("Operators/yield", "yield")}} expression.
+
{{jsxref("Generator.prototype.return()")}}
+
Returns the given value and finishes the generator.
+
{{jsxref("Generator.prototype.throw()")}}
+
Throws an error to a generator.
+
+ +

Example

+ +

An infinite iterator

+ +
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
+// ...
+ +

Legacy generator objects

+ +

Firefox (SpiderMonkey) also implements an earlier version of generators in JavaScript 1.7, where the star (*) in the function declaration was not necessary (you just use the yield keyword in the function body). However, legacy generators are deprecated. Do not use them; they are going to be removed ({{bug(1083482)}}).

+ +

Legacy generator methods

+ +
+
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')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(39.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(39.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(39.0)}}
+
+ +

See also

+ +

Legacy generators

+ + + +

ES2015 generators

+ + diff --git a/files/it/web/javascript/reference/global_objects/generator/next/index.html b/files/it/web/javascript/reference/global_objects/generator/next/index.html new file mode 100644 index 0000000000..03408534d5 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/generator/next/index.html @@ -0,0 +1,157 @@ +--- +title: Generator.prototype.next() +slug: Web/JavaScript/Reference/Global_Objects/Generator/next +translation_of: Web/JavaScript/Reference/Global_Objects/Generator/next +--- +
{{JSRef}}
+ +

Il metodo  next() ritorna un oggetto con due  proprietà  done and value. Puoi anche fornire un parametro al metodo next per trasmettere un valore al generatore.

+ +

Syntassi

+ +
gen.next(value)
+ +

Parametri

+ +
+
value
+
Il valore trasmesso al generatore
+
+ +

Return value

+ +

Un Oggetto con due proprietà:

+ + + +

Examples

+ +

Using next()

+ +

Il seguente esempio mostra semplice generatore e un oggetto che il metodo next ritorna:

+ +
function* gen() {
+  yield 1;
+  yield 2;
+  yield 3;
+}
+
+var g = gen(); // "Generator { }"
+g.next();      // "Object { value: 1, done: false }"
+g.next();      // "Object { value: 2, done: false }"
+g.next();      // "Object { value: 3, done: false }"
+g.next();      // "Object { value: undefined, done: true }"
+
+ +

Mandare valori al generatore

+ +

In questo esempio, next è stato chiamato con un valore. Nota che la prima chiamata non ha registrato nulla, perche il generatore non ha raccolto nulla inizialmente. 

+ +

 

+ +
function* gen() {
+  while(true) {
+    var value = yield null;
+    console.log(value);
+  }
+}
+
+var g = gen();
+g.next(1);
+// "{ value: null, done: false }"
+g.next(2);
+// "{ value: null, done: false }"
+// 2
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator.prototype.next', 'Generator.prototype.next')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator.prototype.next', 'Generator.prototype.next')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}13{{CompatGeckoDesktop(26)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatSafari(10)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support5.1{{CompatVersionUnknown}}{{CompatGeckoMobile(26)}}{{CompatUnknown}}{{CompatUnknown}}10
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/index.html b/files/it/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..3cddb3fc08 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/index.html @@ -0,0 +1,182 @@ +--- +title: Standard built-in objects +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - Refernce + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects +--- +
{{jsSidebar("Objects")}}
+ +

Sommario

+ +

Questo capitolo documenta tutti gli oggetti standard predefiiti di JavaScript, con i loro metodi e le loro proprietà.

+ +

Il termine "oggetti globali" (o oggetti standard predefiniti) non va confuso con il termine oggetto globale. In questa documentazione, "oggetti globali" si riferisce agli oggetti nel contesto globale (ma solo se non viene utilizzata la modalità strict di ECMAScript5, altrimenti restituisce {{jsxref("Global_Objects/undefined", "undefined")}}). Si piuò accedere all'oggetto globale usando l'operatore {{jsxref("Operators/this", "this")}} nel contesto globale. Infatti il contesto globale consiste nell'insieme di tutte le properietà dell'oggetto globale.

+ +

Altri oggetti nel contesto globale possono essere creati dallo script o dall'applicazione utilizzata (ad esempio, un browser). Gli oggetti forniti dal browser sono documentati nella sezione API reference. Per altre informazioni riguardo la differenza tra il DOM e JavaScript base, vedi la panoramica sulle tecnologie JavaScript.

+ +
+

Oggetti standard (per categoria)

+ +

Valori

+ +

Varabili globali che rappresentano un valore semplice, non hanno altre proprietà o metodi.

+ + + +

Funzioni

+ +

Queste funzioni globali che vengono richiamate direttamente restituiscono direttamente il risultato al chiamante

+ + + +

Oggetti fondamentali

+ +

Oggetti generali di Javascrpt, sui quali sono basati tutti gli altri oggetti. Rappresentano oggetti, funzioni ed errori.

+ + + +

Numeri e date

+ +

Oggetti usati per rappresentare numeri, date e calcoli matematici.

+ + + +

Elaborazione del testo

+ +

Oggetti che rappresentano le stringe o il supporto per manipolarle.

+ + + +

Collezioni ordinate

+ +

Questi oggetti rappresentano delle collezioni di dati che sono ordinati secondo un indice. Includono array tipizzati ed costruttori simili ad array.

+ + + +

Collezioni chiave-valore

+ +

Oggetti che rappresentano collezzioni che usano delle chiavi per identificarne gli elementi; si può iterare attraverso gli elementi nell'ordine in cui sono stati inseriti.

+ + + +

Dati strutturati

+ +

Oggetti che rappresentano e interagiscono con buffer di dati e con dati codificati utilizzando JavaScript Object Notation (JSON).

+ + + +

Oggetti di controllo dell'astrazione

+ + + +

Reflection

+ + + +

Internazionalizzazione

+ +

Oggetti aggiunti a ECMAScript per le funzionalità che dipendono dalla lingua.

+ + + +

 

+ +

WebAssembly

+ + + +

 

+ +

Altro

+ + +
+ +

 

diff --git a/files/it/web/javascript/reference/global_objects/infinity/index.html b/files/it/web/javascript/reference/global_objects/infinity/index.html new file mode 100644 index 0000000000..48b983e107 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/infinity/index.html @@ -0,0 +1,114 @@ +--- +title: Infinity +slug: Web/JavaScript/Reference/Global_Objects/Infinity +translation_of: Web/JavaScript/Reference/Global_Objects/Infinity +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La proprietà globale Infinity è un valore numerico che rappresenta l'infinito.

+ +

{{js_property_attributes(0,0,0)}}

+ +

Sintassi

+ +
Infinity 
+ +

Descrizione

+ +

Infinity è una proprietà dell'oggetto globale, ossia una variabile nell'ambito globale.

+ +

Il valore iniziale di Infinity è {{jsxref("Number.POSITIVE_INFINITY")}}. Il valore Infinity (infinito positivo) è maggiore di ogni altro numero. Matematicamente questo valore si comporta come l'infinito: per esempio, qualsiasi numero positivo moltipilicato per Infinity è uguale a Infinity, e qualsiasi numero diviso per Infinity è uguale a 0.

+ +

Secondo la specifica ECMAScript5, Infinity è accessibile in sola lettura (implementato in JavaScript 1.8.5 / Firefox 4).

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition.StandardDefinizione iniziale. Implementato in 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')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/isfinite/index.html b/files/it/web/javascript/reference/global_objects/isfinite/index.html new file mode 100644 index 0000000000..ee250b9410 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/isfinite/index.html @@ -0,0 +1,136 @@ +--- +title: isFinite() +slug: Web/JavaScript/Reference/Global_Objects/isFinite +translation_of: Web/JavaScript/Reference/Global_Objects/isFinite +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La funzione globale isFinite() determina se il parametro passatole è un numero finito. Se necessario, il parametro viene prima convertito in un valore numerico.

+ +

Sintassi

+ +
isFinite(number)
+ +

Parametri

+ +
+
number
+
Il valore da controllare che sia finito.
+
+ +

Descrizione

+ +

isFinite è una funzione globale.

+ +

Puoi usare questa funzione per determinare se un numero è finito. La funzione isFinite restituisce false se il valore passatole è {{jsxref("NaN")}}, {{jsxref("Infinity")}} (infinito positivo) o -{{jsxref("Infinity")}} (infinito negativo); altrimenti restituisce true.

+ +

Esempi

+ +
isFinite(Infinity);  // false
+isFinite(NaN);       // false
+isFinite(-Infinity); // false
+
+isFinite(0);         // true
+isFinite(2e64);      // true
+
+
+isFinite("0");       // true, perché `"0"` viene convertito
+                     //       in un valore numerico, quindi
+                     //       in `0` e poi valutato.
+                     //       La funzione Number.isFinite("0"),
+                     //       più robusta, restituirebbe false.
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 2nd Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.2.5', 'isFinite')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/isnan/index.html b/files/it/web/javascript/reference/global_objects/isnan/index.html new file mode 100644 index 0000000000..db6ebc85d8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/isnan/index.html @@ -0,0 +1,176 @@ +--- +title: isNaN() +slug: Web/JavaScript/Reference/Global_Objects/isNaN +translation_of: Web/JavaScript/Reference/Global_Objects/isNaN +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La funzione isNaN() determina se un valore è {{jsxref("NaN")}} o no.

+ +
+

Nota: le conversioni di tipo nella funzione isNaN seguono delle regole {{jsxref("Global_Objects/isNaN", "particolari", "#Description", 1)}}: alternativamente per determinare se un valore non è un numero si può usare la funzione {{jsxref("Number.isNaN()")}}, definito in ECMAScript 6, o l'operatore {{jsxref("Operators/typeof", "typeof")}}.

+
+ +

Sintassi

+ +
isNaN(number)
+ +

Parametri

+ +
+
number
+
Il valore da controllare.
+
+ +

Descrizione

+ +

La necessità di una funzione isNaN()

+ +

A differenza di tutti gli altri valori in JavaScript, non è possibile usare gli operatori di uguaglianza (== e ===) per determinare se un valore è {{jsxref("NaN")}} oppure no, perché entrambe le uguaglianze NaN == NaN e NaN === NaN vengono considerate false. Ecco perché è necessaria una funzione isNaN().

+ +

L'origine del valore NaN

+ +

Il valore NaN è generato da un'operazione aritmetica il cui risultato è {{jsxref("undefined")}} o un valore non rappresentabile. Tali valori non rappresentano necessariamente un valore oltre i limiti. NaN può anche essere il risultato del trasformare valori non-numerici dai quali non è possibile ottenere un numero in numeri.

+ +

Per esempio, dividere zero per zero restituisce NaN, ma dividere un qualsiasi altro numero per zero no.

+ +

Comportamenti particolari

+ +

Già dalla prima versione della specifica della funzione isNaN, il suo comportamento con valori non-numerici può confondere. Quando il parametro della funzione isNaN non è di tipo {{jsxref("Number")}}, questo viene prima trasformato in un numero. Il test per determinare se il parametro è {{jsxref("NaN")}} viene effettuato sul valore convertito. Quindi per i valori non-numerici che possono essere trasformati in un numero diverso da NaN la funzione restituisce false. La stringa vuota, per esempio, suciramente non è un numero, ma la funzione restituisce false. La confusione nasce dal fatto che il termine "not a number" (rappresentato da NaN) ha un significato per i numeri rappresentati come valori a virgola mobile IEEE-754. La funzione dovrebbe quindi essere interpretata come "È questo valore, quando convertito in un numero, un valore "Not a Number" secondo lo standard IEEE-754?"

+ +

La prossima versione di ECMAScript (ES6) definiesce la funzione {{jsxref("Number.isNaN()")}}. Number.isNaN(), che ritorna false per tutti i valori non-numerici, sarà un metodo affidabile per sapere se un numero è NaN o no. In assenza di Number.isNaN, l'espressione (x !== x) è il metodo più affidabile per determinare se un numero è NaN oppure no, perché evita i falsi positivi generati dalla funzione isNaN().

+ +

Esempi

+ +
var x = NaN;
+isNaN(x);        // true
+Number.isNaN(x); // true
+x !== x;         // true
+
+var x = undefined;
+isNaN(x);        // true, perché undefined viene convertito in NaN
+Number.isNaN(x); // false
+x !== x;         // false
+
+var x = {};
+isNaN(x);        // true, perché {} viene convertito in NaN
+Number.isNaN(x); // false
+x !== x;         // false
+
+isNaN(true);     // false, perché true viene convertito in 1
+isNaN(null);     // false, perché null viene convertito in 0
+isNaN(37);       // false
+
+// Stringhe
+isNaN("37");     // false, perché "37" viene convertito in 37
+isNaN("37.37");  // false, perché "37.37" viene convertito in 37.37
+isNaN("");       // false, perché una stringa vuota viene convertita in 0
+isNaN(" ");      // false, perché una stringa con soli spazi viene convertita in 0
+
+// !!! Ecco un esempio di falso positivo
+var x = "37ab";
+isNaN(x);        // true, perché "37ab" viene convertito in NaN
+Number.isNaN(x); // false
+x !== x;         // false
+
+// Date
+isNaN(new Date()); // false, perché una data che viene convertita in un
+                   //        numero ritorna un valore intero
+
+var x = new Date().toString();
+isNaN(x);        // true, perché il metodo new Date().toString() restituisce una
+                 //       stringa alfanumerica, che viene convertita in NaN
+Number.isNaN(x); // false
+x !== x;         // false
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.2.4', 'isNaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isnan-number', 'isNaN')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/json/index.html b/files/it/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..caa08b766f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,244 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +tags: + - JSON + - JavaScript + - NeedsTranslation + - Object + - Reference + - TopicStub + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +
{{JSRef}}
+ +

The JSON object contains methods for parsing JavaScript Object Notation ({{glossary("JSON")}}) and converting values to JSON. It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.

+ +

Description

+ +

JavaScript Object Notation

+ +

JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and {{jsxref("null")}}. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON, and some JSON is not JavaScript. See also JSON: The JavaScript subset that isn't.

+ + + + + + + + + + + + + + + + + + + + + + + +
JavaScript and JSON differences
JavaScript typeJSON differences
Objects and ArraysProperty names must be double-quoted strings; trailing commas are forbidden.
NumbersLeading zeros are prohibited; a decimal point must be followed by at least one digit.
Strings +

Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted. See the following example where {{jsxref("JSON.parse()")}} works fine and a {{jsxref("SyntaxError")}} is thrown when evaluating the code as JavaScript:

+ +
+var code = '"\u2028\u2029"';
+JSON.parse(code); // works fine
+eval(code); // fails
+
+
+ +

The full JSON syntax is as follows:

+ +
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
+
+ +

Insignificant whitespace may be present anywhere except within a JSONNumber (numbers must contain no whitespace) or JSONString (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.

+ +

Methods

+ +
+
{{jsxref("JSON.parse()")}}
+
Parse a string as JSON, optionally transform the produced value and its properties, and return the value.
+
{{jsxref("JSON.stringify()")}}
+
Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.
+
+ +

Polyfill

+ +

The JSON object is not supported in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of JSON object in implementations which do not natively support it (like Internet Explorer 6).

+ +

The following algorithm is an imitation of the native JSON object:

+ +
if (!window.JSON) {
+  window.JSON = {
+    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
+    stringify: (function () {
+      var toString = Object.prototype.toString;
+      var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
+      var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
+      var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
+      var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
+      return function stringify(value) {
+        if (value == null) {
+          return 'null';
+        } else if (typeof value === 'number') {
+          return isFinite(value) ? value.toString() : 'null';
+        } else if (typeof value === 'boolean') {
+          return value.toString();
+        } else if (typeof value === 'object') {
+          if (typeof value.toJSON === 'function') {
+            return stringify(value.toJSON());
+          } else if (isArray(value)) {
+            var res = '[';
+            for (var i = 0; i < value.length; i++)
+              res += (i ? ', ' : '') + stringify(value[i]);
+            return res + ']';
+          } else if (toString.call(value) === '[object Object]') {
+            var tmp = [];
+            for (var k in value) {
+              if (value.hasOwnProperty(k))
+                tmp.push(stringify(k) + ': ' + stringify(value[k]));
+            }
+            return '{' + tmp.join(', ') + '}';
+          }
+        }
+        return '"' + value.toString().replace(escRE, escFunc) + '"';
+      };
+    })()
+  };
+}
+
+ +

More complex well-known polyfills for the JSON object are JSON2 and JSON3.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/json/parse/index.html b/files/it/web/javascript/reference/global_objects/json/parse/index.html new file mode 100644 index 0000000000..f5c823ddf1 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/json/parse/index.html @@ -0,0 +1,126 @@ +--- +title: JSON.parse() +slug: Web/JavaScript/Reference/Global_Objects/JSON/parse +tags: + - ECMAScript5 + - JSON + - JavaScript + - Riferimento + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse +--- +
{{JSRef}}
+ +

Il metodo JSON.parse() analizza una stringa JSON, costruendo il valore JavaScript o l'oggetto descritto dalla stringa. È possibile fornire una funzione reviver opzionale per eseguire una trasformazione sull'oggetto risultante prima che venga restituito.

+ +
{{EmbedInteractiveExample("pages/js/json-parse.html")}}
+ + + +

Sintassi

+ +
JSON.parse(text[, reviver])
+ +

Parametri

+ +
+
text
+
La stringa da analizzare come JSON. Vedi l'oggetto {{jsxref("JSON")}} per una descrizione della sintassi JSON.
+
reviver {{optional_inline}}
+
Se una funzione, questo prescrive come viene trasformato il valore originariamente prodotto dall'analisi, prima di essere restituito.
+
+ +

Valore di ritorno

+ +

{{jsxref("Object")}} corrispondente al parametro JSON text dato.

+ +

Eccezione

+ +

Genera un errore {{jsxref("SyntaxError")}} se la stringa da analizzare non è JSON valida.

+ +

Esempi

+ +

Utilizzare JSON.parse()

+ +
JSON.parse('{}');              // {}
+JSON.parse('true');            // true
+JSON.parse('"foo"');           // "foo"
+JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
+JSON.parse('null');            // null
+
+ +

Usare il parametro reviver

+ +

Se viene specificato un reviver, il valore calcolato dall'analisi viene trasformato prima di essere restituito. In particolare, il valore calcolato e tutte le sue proprietà (che iniziano con le proprietà più nidificate e procedono al valore originale stesso) vengono eseguite individualmente attraverso il reviver. Quindi viene chiamato, con l'oggetto contenente la proprietà da elaborare come this, e con il nome della proprietà come stringa e il valore della proprietà come argomenti. Se la funzione  reviver restituisce {{jsxref("undefined")}} (o non restituisce alcun valore, ad esempio, se l'esecuzione cade al termine della funzione), la proprietà viene cancellata dall'oggetto. In caso contrario, la proprietà viene ridefinita come il valore restituito.

+ +

Se reviver trasforma solo alcuni valori e non altri, sii certo di restituire tutti i valori non trasformati così come sono, altrimenti verranno eliminati dall'oggetto risultante.

+ +
JSON.parse('{"p": 5}', (key, value) =>
+  typeof value === 'number'
+    ? value * 2 // ritorna: value * 2 per i numeri
+    : value     // restituisce tutto il resto invariato
+);
+
+// { p: 10 }
+
+JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
+  console.log(key); // registra il nome della proprietà corrente, l'ultimo è "".
+  return value;     // restituisce il valore della proprietà invariato.
+});
+
+// 1
+// 2
+// 4
+// 6
+// 5
+// 3
+// ""
+
+ +

JSON.parse() non consente virgole finali

+ +
// both will throw a SyntaxError
+JSON.parse('[1, 2, 3, 4, ]');
+JSON.parse('{"foo" : 1, }');
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ESDraft')}} 
+ +

Compatiblità con i browser

+ +
+ + +

{{Compat("javascript.builtins.JSON.parse")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/json/stringify/index.html b/files/it/web/javascript/reference/global_objects/json/stringify/index.html new file mode 100644 index 0000000000..9a0bf5f812 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/json/stringify/index.html @@ -0,0 +1,325 @@ +--- +title: JSON.stringify() +slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify +--- +
{{JSRef}}
+ +
 
+ +

Il metodo JSON.stringify() converte un oggetto o un valore JavaScript in una stringa JSON, sostituendo facoltativamente i valori se viene specificata una funzione sostitutiva o facoltativamente includendo solo le proprietà specificate se viene specificato un array replacer.

+ +
{{EmbedInteractiveExample("pages/js/json-stringify.html")}}
+ + + +

Sintassi

+ +
JSON.stringify(value[, replacer[, space]])
+ +

Parametri

+ +
+
value
+
Il valore da convertire in stringa JSON.
+
replacer{{optional_inline}}
+
Una funzione che altera il processo di conversione, o un array di {{jsxref("String")}} e {{jsxref("Number")}} che contiene le proprietà dell'oggetto che devono essere incluse nella stringa JSON. Se il valore è null o non è specificato, tutte le proprietà dell'oggetto sono incluse nel risultato.
+
space{{optional_inline}}
+
Un oggetto {{jsxref("String")}} o {{jsxref("Number")}} che viene utilizzato per inserire uno spazio bianco nella stringa JSON di output a fini di leggibilità.Se questo è un Number, indica il numero di caratteri dello spazio da usare come spazio bianco; questo numero è limitato a 10 (se è maggiore, il valore è solo 10).Valori inferiori a 1 indicano che non deve essere usato alcuno spazio.
+
+

Se si tratta di una  String, la stringa (i primi 10 caratteri della stringa, se è più lunga di quella) viene utilizzata come spazio bianco. Se questo parametro non viene fornito (o è {{JSxRef("null")}}), non viene utilizzato alcuno spazio bianco.

+ +

Valore di ritorno

+ +

Una stringa JSON che rappresenta il valore dato.

+ +

Eccezioni

+ +

Genera un'eccezione {{JSxRef("TypeError")}} ("valore dell'oggetto ciclico") quando viene trovato un riferimento circolare.

+
+
+ +

Descrizione

+ +

JSON.stringify() converte un valore in notazione JSON che lo rappresenta:

+ + + +
JSON.stringify({});                  // '{}'
+JSON.stringify(true);                // 'true'
+JSON.stringify('foo');               // '"foo"'
+JSON.stringify([1, 'false', false]); // '[1,"false",false]'
+JSON.stringify({ x: 5 });            // '{"x":5}'
+
+JSON.stringify({ x: 5, y: 6 });
+// '{"x":5,"y":6}' or '{"y":6,"x":5}'
+JSON.stringify([new Number(1), new String('false'), new Boolean(false)]);
+// '[1,"false",false]'
+
+// Simboli:
+JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
+// '{}'
+JSON.stringify({ [Symbol('foo')]: 'foo' });
+// '{}'
+JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
+// '{}'
+JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
+  if (typeof k === 'symbol') {
+    return 'a symbol';
+  }
+});
+// '{}'
+
+// Proprietà non enumerabili:
+JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) );
+// '{"y":"y"}'
+
+
+ +

Il parametro replacer

+ +

Il parametro replacer può essere una funzione o un array.

+ +

Come una funzione, prende due parametri: la chiave e il valore che si sta stringendo. L'oggetto in cui è stata trovata la chiave viene fornito come il parametro this del replacer.

+ +

Inizialmente, la funzione replacer viene chiamata con una stringa vuota come chiave che rappresenta l'oggetto da stringificare. Viene quindi chiamato per ogni proprietà sull'oggetto o sull'array da stringificare.

+ + + +
Nota: Non è possibile utilizzare la replacerfunzione per rimuovere i valori da una matrice. Se si restituisce undefinedo una funzione, nullviene invece utilizzata.
+ +
Se desideri che il replacer distingua un oggetto iniziale da una chiave con una proprietà stringa vuota (poiché entrambi fornirebbero la stringa vuota come chiave e potenzialmente un oggetto come valore), sarà necessario tenere traccia del conteggio dell'iterazione (se è al di là della prima iterazione, è una vera e propria chiave di stringa vuota).
+ +

Esempio di replacer, come funzione

+ +
function replacer(key, value) {
+  // Filtraggio delle proprietà
+  if (typeof value === 'string') {
+    return undefined;
+  }
+  return value;
+}
+
+var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
+JSON.stringify(foo, replacer);
+// Risultato: '{"week":45,"month":7}'
+
+ +

Esempio di replacer, come array

+ +

Se replacer è un array, i valori dell'array indicano i nomi delle proprietà nell'oggetto che dovrebbero essere incluse nella stringa JSON risultante.

+ +
JSON.stringify(foo, ['week', 'month']);
+// '{"week":45,"month":7}', mantiene solo le proprietà "week" e "month"
+
+ +

Il parametro space

+ +

L'argomento space può essere usato per controllare la spaziatura nella stringa finale.

+ + + +
JSON.stringify({ a: 2 }, null, ' ');
+// '{
+//  "a": 2
+// }'
+ +

L'utilizzo di un carattere di tabulazione simula l'aspetto standard di tipo "pretty-print":

+ +
JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
+// restituisce la stringa:
+// '{
+//     "uno": 1,
+//     "dos": 2
+// }'
+
+ +

Comportamento di toJSON()

+ +

Se un oggetto da stringificare ha una proprietà denominata il toJSON cui valore è una funzione, il metodo toJSON() personalizza il comportamento di stringificazione JSON: invece dell'oggetto serializzato, il valore restituito dal metodo toJSON() quando chiamato verrà serializzato. JSON.stringify() chiama toJSON con un parametro:

+ + + +

Per esempio:

+ +
var obj = {
+    data: 'data',
+
+    toJSON(key){
+        if(key)
+            return `Ora sono un oggetto nidificato sotto chiave '${key}'`;
+
+        else
+            return this;
+    }
+};
+
+JSON.stringify(obj);
+// '{"data":"data"}'
+
+JSON.stringify({ obj })
+// '{"obj":"Ora sono un oggetto nidificato sotto chiave 'obj'"}'
+
+JSON.stringify([ obj ])
+// '["Ora sono un oggetto nidificato sotto chiave '0'"]'
+
+ +

Problema con JSON.stringify() durante la serializzazione di riferimenti circolari

+ +

Nota che poiché il Formato JSON non supporta i riferimenti agli oggetti (sebbene esista una bozza IETF), {{JSxRef("TypeError")}} verrà generato un se si tenta di codificare un oggetto con riferimenti circolari.

+ +
const circularReference = {};
+circularReference.myself = circularReference;
+
+// La serializzazione dei riferimenti circolari genera "TypeError: valore dell'oggetto ciclico"
+JSON.stringify(circularReference);
+
+ +

Per serializzare i riferimenti circolari è possibile utilizzare una libreria che li supporta (ad es. cycle.js di Douglas Crockford) o implementare una soluzione autonomamente, che richiederà la ricerca e la sostituzione (o la rimozione) dei riferimenti ciclici mediante valori serializzabili.

+ +

Problema con plain  JSON.stringify per l'uso come JavaScript

+ +

Storicamente, JSON non era un sottoinsieme completamente rigido di JavaScript. I punti del codice letterale U + 2028 LINE SEPARATOR e U + 2029 PARAGRAPH SEPARATOR potrebbero apparire letteralmente in stringhe letterali e nomi di proprietà nel testo JSON. Ma non potevano apparire letteralmente in un contesto simile nel testo JavaScript - solo usando escape Unicode come \u2028\u2029.  Questo è cambiato di recente: ora entrambi i punti di codice possono apparire letteralmente nelle stringhe in JSON e JavaScript entrambi.

+ +

Pertanto, se è richiesta la compatibilità con i motori JavaScript precedenti, è pericoloso sostituire direttamente la stringa restituita da JSON.stringify una stringa JavaScript da passare a eval new Function o come parte di un URL JSONP e può essere utilizzata la seguente utility:

+ +
function jsFriendlyJSONStringify (s) {
+    return JSON.stringify(s).
+        replace(/\u2028/g, '\\u2028').
+        replace(/\u2029/g, '\\u2029');
+}
+
+var s = {
+    a: String.fromCharCode(0x2028),
+    b: String.fromCharCode(0x2029)
+};
+try {
+    eval('(' + JSON.stringify(s) + ')');
+} catch (e) {
+    console.log(e); // "SyntaxError: unterminated string literal"
+}
+
+// No need for a catch
+eval('(' + jsFriendlyJSONStringify(s) + ')');
+
+// console.log in Firefox scolla l'Unicode se
+//   connesso alla console, quindi usiamo alert
+alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}
+
+ +
+

Note: Non è garantito che le proprietà degli oggetti non array vengano sottoposte a stringa in qualsiasi ordine particolare. Non fare affidamento sull'ordinamento di proprietà all'interno dello stesso oggetto all'interno della stringa.

+
+ +
var a = JSON.stringify({ foo: "bar", baz: "quux" })
+//'{"foo":"bar","baz":"quux"}'
+var b = JSON.stringify({ baz: "quux", foo: "bar" })
+//'{"baz":"quux","foo":"bar"}'
+console.log(a !== b) // true
+
+// alcune funzioni di memoizzazione usano JSON.stringify per serializzare gli argomenti,
+// mancando la cache quando si incontra lo stesso oggetto come sopra
+
+ +

Esempio di utilizzo JSON.stringify() con localStorage

+ +

Nel caso in cui desideri archiviare un oggetto creato dall'utente e consentirne il ripristino anche dopo la chiusura del browser, nell'esempio seguente è disponibile un modello per l'applicabilità di JSON.stringify():

+ +
// Creare un esempio di JSON
+var session = {
+  'screens': [],
+  'state': true
+};
+session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 });
+session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 });
+session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 });
+session.screens.push({ 'name': 'screenD', 'width': 250, 'height': 60 });
+session.screens.push({ 'name': 'screenE', 'width': 390, 'height': 120 });
+session.screens.push({ 'name': 'screenF', 'width': 1240, 'height': 650 });
+
+// Conversione della stringa JSON con JSON.stringify()
+// quindi salva con localStorage nel nome della sessione
+localStorage.setItem('session', JSON.stringify(session));
+
+// Esempio di come trasformare la stringa generata tramite
+// JSON.stringify() e salvare nuovamente in localStorage nell'oggetto JSON
+var restoredSession = JSON.parse(localStorage.getItem('session'));
+
+// Ora la variabile restoreSession contiene l'oggetto che è stato salvato
+// in localStorage
+console.log(restoredSession);
+
+ +

Well-formed JSON.stringify()

+ +

Engines implementing the well-formed JSON.stringify specification will stringify lone surrogates -- any code point from U+D800 to U+DFFF -- using Unicode escape sequences rather than literally.  Before this change JSON.stringify would output lone surrogates if the input contained any lone surrogates; such strings could not be encoded in valid UTF-8 or UTF-16:

+ +
JSON.stringify("\uD800"); // '"�"'
+ +

Ma con questo cambiamento JSON.stringify rappresentano surrogati solitari usando sequenze di escape JSON che possono essere codificate in UTF-8 o UTF-16 validi:

+ +
JSON.stringify("\uD800"); // '"\\ud800"'
+ +

Questo cambiamento dovrebbe essere retrocompatibile fin tanto che si passa il risultato di JSON.stringify API come JSON.parse quella che accetterà qualsiasi testo JSON valido, in quanto tratterà le escape Unicode dei surrogati soli come identici ai surrogati solitari stessi.  Solo se stai interpretando direttamente il risultato di JSON.stringify hai bisogno di gestire attentamente JSON.stringify le due possibili codifiche di questi punti di codice.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}{{Spec2('ES5.1')}}Definzione iniziale. Implementato su JavaScript 1.7.
{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ESDraft')}} 
+ +

Compatiblità con i browser

+ +
+ + +

{{Compat("javascript.builtins.JSON.stringify")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/map/clear/index.html b/files/it/web/javascript/reference/global_objects/map/clear/index.html new file mode 100644 index 0000000000..85918279ad --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/map/clear/index.html @@ -0,0 +1,76 @@ +--- +title: Map.prototype.clear() +slug: Web/JavaScript/Reference/Global_Objects/Map/clear +tags: + - ECMAScript 2015 + - JavaScript + - Map + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Map/clear +--- +
{{JSRef}}
+ +

Il metodo clear() rimuove tutti gli elementi di un oggetto Map.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-clear.html")}}
+ + + +

Sintassi

+ +
myMap.clear();
+ +

Valore di ritorno

+ +

{{jsxref("undefined")}}.

+ +

Esempi

+ +

Utilizzare il metodo clear

+ +
var myMap = new Map();
+myMap.set('bar', 'baz');
+myMap.set(1, 'foo');
+
+myMap.size;       // 2
+myMap.has('bar'); // true
+
+myMap.clear();
+
+myMap.size;       // 0
+myMap.has('bar')  // false
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ + + +

{{Compat("javascript.builtins.Map.clear")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/map/delete/index.html b/files/it/web/javascript/reference/global_objects/map/delete/index.html new file mode 100644 index 0000000000..18c511b3eb --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/map/delete/index.html @@ -0,0 +1,74 @@ +--- +title: Map.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/Map/delete +translation_of: Web/JavaScript/Reference/Global_Objects/Map/delete +--- +
{{JSRef}}
+ +

Il metododelete() rimuove l'elemento specificato da un oggetto Map selezionandolo in base alla chiave.

+ +
{{EmbedInteractiveExample("pages/js/map-prototype-delete.html")}}
+ + + +

Sintassi

+ +
myMap.delete(key);
+ +

Parametri

+ +
+
key
+
La chiave dell'elemento da rimuovere dall'oggetto Map.
+
+ +

Valore ritornato

+ +

true se un elemento con la chiave specificata esisteva nell'oggetto Map ed è stato ora rimosso, o false se non esisteva alcun elemento con la chiave specificata.

+ +

Esempi

+ +

Usare delete()

+ +
var myMap = new Map();
+myMap.set('bar', 'foo');
+
+myMap.delete('bar'); // Ritorna true. Rimosso con successo.
+myMap.has('bar');    // Ritorna false. L'elemento "bar" non è più presente.
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ES2015')}}Initial definition.
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.Map.delete")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/map/foreach/index.html b/files/it/web/javascript/reference/global_objects/map/foreach/index.html new file mode 100644 index 0000000000..ab1c69a310 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/map/foreach/index.html @@ -0,0 +1,88 @@ +--- +title: Map.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Map/forEach +tags: + - ECMAScript 2015 + - JavaScript + - Map + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Map/forEach +--- +
{{JSRef}}
+ +

Il metodo forEach() esegue una funzione fornita come argomento una volta per ogni coppia key/value nell'oggetto Map, secondo l'ordine dell'inseriemento dei valori.

+ +

Sintassi

+ +
myMap.forEach(callback[, thisArg])
+ +

Parametri

+ +
+
callback
+
Funzione da eseguire per ogni elemento.
+
thisArg
+
Valore da usare come this quando si esegue callback.
+
+ +

Descrizione

+ +

Il metodo forEach esegue il callback passato come parametro una volta per ogni key della map esistente. Non è invocato per key che sono state cancellate. Comunque, è invocato per valori che sono presenti ma hanno valore undefined.

+ +

callback è invocato con tre argomenti:

+ + + +

Se il parametro thisArg è fornito al forEach, sarà passato al callback quando viene invocato, per essere usato come suo valore this.  In caso contrario, sarà passato il valore undefined per essere usato come valore this. Il valore this visibile definitivamente dal callbackè determinato secondo le normali regole per determinare il this visibile da una funzione.

+ +

Il range di elementi processati da forEach è determinato anteriormente alla prima invocazione del callback. Gli elementi che sono aggiunti all'oggetto Map dopo che la chiamata a forEach inizi non saranno visitati dal callback. Se eleemnti esistenti dell'oggetto Map vengono cambiati, o cancellati, il loro valore passato al callback sarà il valore nel momento in cui il forEach li visita; elementi che vengono cancellati non sono visitati.

+ +

forEach esegue la funzione callback una volta per ogni elemento nell'oggetto Map; non restituisce alcun valore.

+ +

Esempi

+ +

Stampare il contenuto di un oggetto Map

+ +

Il seguente codice stampa nella console una riga per ogni elemento in un oggetto Map:

+ +
function logMapElements(value, key, map) {
+    console.log("m[" + key + "] = " + value);
+}
+Map([["foo", 3], ["bar", {}], ["baz", undefined]]).forEach(logMapElements);
+// logs:
+// "m[foo] = 3"
+// "m[bar] = [object Object]"
+// "m[baz] = undefined"
+
+ +

Specifiche

+ + + + + + + + + + + + + + +
SpecificationStatoCommento
{{SpecName('ES6', '#sec-map.prototype.foreach', 'Map.prototype.forEach')}}{{Spec2('ES6')}}Definizione iniziale.
+ +

Compatibilità dei browser

+ +

{{Compat("javascript.builtins.Map.forEach")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/map/index.html b/files/it/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..58ee676d23 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,439 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +tags: + - ECMAScript6 + - Experimental + - JavaScript + - Map + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +
{{JSRef}}
+ +

The Map object is a simple key/value map. Any value (both objects and {{Glossary("Primitive", "primitive values")}}) may be used as either a key or a value.

+ +

Syntax

+ +
new Map([iterable])
+
+ +

Parameters

+ +
+
iterable
+
Iterable is an Array or other iterable object whose elements are key-value pairs (2-element Arrays). Each key-value pair is added to the new Map. null is treated as undefined.
+
+ +

Description

+ +

A Map object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of [key, value] for each iteration.

+ +

Key equality

+ +

Key equality is based on the "same-value" algorithm: NaN is considered the same as NaN (even though NaN !== NaN) and all other values are considered equal according to the semantics of the === operator. In earlier versions of the ECMAScript 6 draft -0 and +0 were considered distinct (even though -0 === +0), this has been changed in later versions and has been adapted in Gecko 29 {{geckoRelease("29")}} ({{bug("952870")}}) and a recent nightly Chrome.

+ +

Objects and maps compared

+ +

{{jsxref("Object", "Objects")}} are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this (and because there were no built-in alternatives), Objects have been used as Maps historically; however, there are important differences between Objects and Maps that make using a Map better:

+ + + +

This does not mean you should use Maps everywhere, objects still are used in most cases. Map instances are only useful for collections, and you should consider adapting your code where you have previously used objects for such. Objects shall be used as records, with fields and methods.
+ If you're still not sure which one to use, ask yourself the following questions:

+ + + +

Those all are signs that you want a Map for a collection. If in contrast you have a fixed amount of keys, operate on them individually, and distinguish between their usage, then you want an object.

+ +

Properties

+ +
+
Map.length
+
The value of the length property is 0.
+
{{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

+ +

All Map instances inherit from {{jsxref("Map.prototype")}}.

+ +

Properties

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}

+ +

Methods

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}

+ +

Examples

+ +

Using the Map object

+ +
var myMap = new Map();
+
+var keyString = "a string",
+    keyObj = {},
+    keyFunc = function () {};
+
+// setting the 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
+
+// getting the 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'"
+                         // because keyString === 'a string'
+myMap.get({});           // undefined, because keyObj !== {}
+myMap.get(function() {}) // undefined, because keyFunc !== function () {}
+
+ +

Using NaN as Map keys

+ +

NaN can also be used as a key. Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works, because NaNs are indistinguishable from each other:

+ +
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"
+
+ +

Iterating Maps with for..of

+ +

Maps can be iterated using a for..of loop:

+ +
var myMap = new Map();
+myMap.set(0, "zero");
+myMap.set(1, "one");
+for (var [key, value] of myMap) {
+  console.log(key + " = " + value);
+}
+// Will show 2 logs; first with "0 = zero" and second with "1 = one"
+
+for (var key of myMap.keys()) {
+  console.log(key);
+}
+// Will show 2 logs; first with "0" and second with "1"
+
+for (var value of myMap.values()) {
+  console.log(value);
+}
+// Will show 2 logs; first with "zero" and second with "one"
+
+for (var [key, value] of myMap.entries()) {
+  console.log(key + " = " + value);
+}
+// Will show 2 logs; first with "0 = zero" and second with "1 = one"
+
+ +

Iterating Maps with forEach()

+ +

Maps can be iterated using the forEach() method:

+ +
myMap.forEach(function(value, key) {
+  console.log(key + " = " + value);
+}, myMap)
+// Will show 2 logs; first with "0 = zero" and second with "1 = one"
+
+ +

Relation with Array objects

+ +
var kvArray = [["key1", "value1"], ["key2", "value2"]];
+
+// Use the regular Map constructor to transform a 2D key-value Array into a map
+var myMap = new Map(kvArray);
+
+myMap.get("key1"); // returns "value1"
+
+// Use the spread operator to transform a map into a 2D key-value Array.
+console.log(uneval([...myMap])); // Will show you exactly the same Array as kvArray
+
+// Or use the spread operator on the keys or values iterator to get
+// an array of only the keys or values
+console.log(uneval([...myMap.keys()])); // Will show ["key1", "key2"]
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-map-objects', 'Map')}}{{Spec2('ES6')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support +

{{ CompatChrome(38) }} [1]

+
{{ CompatGeckoDesktop("13") }}11257.1
Constructor argument: new Map(iterable){{ CompatChrome(38) }}{{ CompatGeckoDesktop("13") }}{{CompatNo}}25{{CompatNo}}
iterable{{ CompatChrome(38) }}{{ CompatGeckoDesktop("17") }}{{CompatNo}}257.1
Map.clear(){{ CompatChrome(31) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("19")}}11257.1
Map.keys(), Map.values(), Map.entries(){{ CompatChrome(37) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("20")}}{{CompatNo}}257.1
Map.forEach(){{ CompatChrome(36) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("25")}}11257.1
Key equality for -0 and 0{{ CompatChrome(34) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoDesktop("29")}}{{CompatNo}}25{{CompatNo}}
Constructor argument: new Map(null){{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatGeckoDesktop("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{ CompatGeckoDesktop("42") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{ CompatChrome(38) }} [1]{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}8
Constructor argument: new Map(iterable){{CompatNo}}{{ CompatChrome(38) }}{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
iterable{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("17") }}{{CompatNo}}{{CompatNo}}8
Map.clear(){{CompatNo}}{{ CompatChrome(31) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("19")}}{{CompatNo}}{{CompatNo}}8
Map.keys(), Map.values(), Map.entries(){{CompatNo}}{{ CompatChrome(37) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("20")}}{{CompatNo}}{{CompatNo}}8
Map.forEach(){{CompatNo}}{{ CompatChrome(36) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
Key equality for -0 and 0{{CompatNo}}{{ CompatChrome(34) }}
+ {{ CompatChrome(38) }}
{{CompatGeckoMobile("29")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Constructor argument: new Map(null){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("42")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Starting with Chrome 31, the feature was available behind a preference. In chrome://flags, activate the entry “Enable Experimental JavaScript”.

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/abs/index.html b/files/it/web/javascript/reference/global_objects/math/abs/index.html new file mode 100644 index 0000000000..6dcf7a7dd6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/abs/index.html @@ -0,0 +1,95 @@ +--- +title: Math.abs() +slug: Web/JavaScript/Reference/Global_Objects/Math/abs +translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs +--- +
{{JSRef}}
+ +

La funzione Math.abs() ritorna il valore assoluto di un numero, ovvero

+ +

Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ -x & \text{if} \quad x < 0 \end{cases}

+ +

Sintassi

+ +
Math.abs(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

Il valore assoluto del numero passato come parametro.

+ +

Descrizione

+ +

Siccome abs() è un metodo statico di Math, viene sempre utilizzato come Math.abs() piuttosto che come metodo di un oggetto Math creato in precedenza (Math non è un costruttore).

+ +

Esempi

+ +

Comportamento di Math.abs()

+ +

Passando un oggetto vuoto, un array con più di un elemento, una stringa non numerica o una variabile {{jsxref("undefined")}}/empty il valore di ritorno sarà {{jsxref("NaN")}}. Passando {{jsxref("null")}}, una stringa vuota o un array vuoto, il valore di ritorno sarà 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
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i Browser

+ + + +

{{Compat("javascript.builtins.Math.abs")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/acos/index.html b/files/it/web/javascript/reference/global_objects/math/acos/index.html new file mode 100644 index 0000000000..b872e04ab2 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/acos/index.html @@ -0,0 +1,94 @@ +--- +title: Math.acos() +slug: Web/JavaScript/Reference/Global_Objects/Math/acos +translation_of: Web/JavaScript/Reference/Global_Objects/Math/acos +--- +
{{JSRef}}
+ +

La funzione Math.acos() ritorna l'arcocoseno (in radianti) di un numero, ovvero

+ +

x[-1;1],Math.acos(x)=arccos(x)= the unique y[0;π]such thatcos(y)=x\forall x \in [{-1};1],\;\mathtt{\operatorname{Math.acos}(x)} = \arccos(x) = \text{ the unique } \; y \in [0; \pi] \, \text{such that} \; \cos(y) = x

+ +

Sintassi

+ +
Math.acos(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

L'arcocoseno (in radianti) del numero passato come parametro se quest'ultimo si trova tra i valori -1 e 1; altrimenti ritorna {{jsxref("NaN")}}.

+ +

Descrizione

+ +

Il metodo Math.acos() ritorna un valore numerico compreso tra 0 and π radianti per x compreso tra -1 e 1. Se il valore di x si trova al di fuori di questo range il metodo ritorna {{jsxref("NaN")}}.

+ +

Siccome acos() è un metodo statico di Math, viene sempre usato come Math.acos() piuttosto che come metodo di un oggetto Math creato in precedenza (Math non è un costruttore).

+ +

Esempi

+ +

Math.acos()

+ +
Math.acos(-2);  // NaN
+Math.acos(-1);  // 3.141592653589793
+Math.acos(0);   // 1.5707963267948966
+Math.acos(0.5); // 1.0471975511965979
+Math.acos(1);   // 0
+Math.acos(2);   // NaN
+
+ +

Per valori inferiori a -1 o maggiori di 1, Math.acos() ritorna {{jsxref("NaN")}}.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.2', 'Math.acos')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.acos', 'Math.acos')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.acos', 'Math.acos')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità dei Browser

+ + + +

{{Compat("javascript.builtins.Math.acos")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/atan/index.html b/files/it/web/javascript/reference/global_objects/math/atan/index.html new file mode 100644 index 0000000000..9be8920214 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/atan/index.html @@ -0,0 +1,100 @@ +--- +title: Math.atan() +slug: Web/JavaScript/Reference/Global_Objects/Math/atan +translation_of: Web/JavaScript/Reference/Global_Objects/Math/atan +--- +
{{JSRef}}
+ +

La funzione Math.atan() restituisce l'arcotangente (in radianti) di un numero, definita come

+ +

Math.atan(x)=arctan(x)= l'unica y[-π2;π2]tale chetan(y)=x\mathtt{\operatorname{Math.atan}(x)} = \arctan(x) = \text{ the unique } \; y \in \left[-\frac{\pi}{2}; \frac{\pi}{2}\right] \, \text{such that} \; \tan(y) = x

+ +

Sintassi

+ +
Math.atan(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

L'arcotangente (in radianti) del numero dato x.

+ +

Descrizione

+ +

Il metodo Math.atan() ritorna un valore numerico compreso tra -π2-\frac{\pi}{2} e π2\frac{\pi}{2} radianti.

+ +

Poiché atan() è un membro statico di Math, è da usarsi sempre nella forma Math.atan(), piuttosto che come un metodo di un oggetto Math creato (Math non è il costruttore di una classe).

+ +

Esempî

+ +

Using Math.atan()

+ +
Math.atan(1);   // 0.7853981633974483
+Math.atan(0);   // 0
+Math.atan(-0);  // -0
+
+Math.atan(Infinity);   //  1.5707963267948966
+Math.atan(-Infinity);  // -1.5707963267948966
+
+/*
+L'angolo che la retta su cui giace il segmento [(0,0);(x,y)]
+forma con l'asse x di un sistema a coordinate cartesiane
+*/
+Math.atan(y / x);
+
+ +

Note that you may want to avoid using ±Infinity for stylistic reasons. In this case, {{jsxref("Math.atan2()")}} with 0 as the second argument may be a better solution.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatusCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.4', 'Math.atan')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.atan', 'Math.atan')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.atan', 'Math.atan')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.Math.atan")}}

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/atan2/index.html b/files/it/web/javascript/reference/global_objects/math/atan2/index.html new file mode 100644 index 0000000000..842106f7a1 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/atan2/index.html @@ -0,0 +1,155 @@ +--- +title: Math.atan2() +slug: Web/JavaScript/Reference/Global_Objects/Math/atan2 +tags: + - Arcotangente + - JavaScript + - Math + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/atan2 +--- +
{{JSRef}}
+ +

La funzione Math.atan2() restituisce l'arcotangente del quoziente dei suoi argomenti.

+ +

Sintassi

+ +
Math.atan2(y, x)
+ +

Parametri

+ +
+
y
+
Primo numero.
+
x
+
Secondo numero.
+
+ +

Valore restituito

+ +

L'arcotangente del quoziente degli argomenti forniti alla funzione, espresso in radianti e compreso tra -π e π.

+ +

Descrizione

+ +

Il metodo Math.atan2() restituisce un valore compreso tra -π e π che reppresenta l'angolo teta di un punto (x, y). Questo angolo è orientato in senso antiorario, misurato in radianti e compreso tra l'asse positivo delle ascisse, ed il punto (x, y). È importante ricordare che il primo argomento da fornire alla funzione è l'ordinata del punto ed il secondo la sua ascissa.

+ +

A simple diagram showing the angle returned by atan2(y, x)

+ +

A Math.atan2() vengono passate x ed y separatamente, mentre a Math.atan() deve essere passato il loro quoziente.

+ +

Poichè atan2() è un metodo statico di Math esso viene sempre utilizzato nella forma Math.atan2(), invece che come metodo di un oggetto Math che hai personalmente creato (Math non è un costruttore).

+ +

Examples

+ +

Using Math.atan2()

+ +
Math.atan2(90, 15); // 1.4056476493802699
+Math.atan2(15, 90); // 0.16514867741462683
+
+Math.atan2(±0, -0);               // ±PI.
+Math.atan2(±0, +0);               // ±0.
+Math.atan2(±0, -x);               // ±PI con x > 0.
+Math.atan2(±0, x);                // ±0 con x > 0.
+Math.atan2(-y, ±0);               // -PI/2 con y > 0.
+Math.atan2(y, ±0);                // PI/2 con y > 0.
+Math.atan2(±y, -Infinity);        // ±PI con y finito e y > 0.
+Math.atan2(±y, +Infinity);        // ±0 con y finito e y > 0.
+Math.atan2(±Infinity, x);         // ±PI/2 con x finito.
+Math.atan2(±Infinity, -Infinity); // ±3*PI/4.
+Math.atan2(±Infinity, +Infinity); // ±PI/4.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.5', 'Math.atan2')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.atan2', 'Math.atan2')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.atan2', 'Math.atan2')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/ceil/index.html b/files/it/web/javascript/reference/global_objects/math/ceil/index.html new file mode 100644 index 0000000000..c8cdcb96dd --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,161 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Reference/Global_Objects/Math/ceil +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +
{{JSRef}}
+ +

La funzione Math.ceil() ritorna il più piccolo intero più grande di o uguale a un dato numero.

+ +

Sintassi

+ +
Math.ceil(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

Il più piccolo intero più grande di o uguale al dato numero.

+ +

Descrizione

+ +

Visto che ceil() è un metodo statico di Math, va usato sempre come Math.ceil(), piuttosto che come metodo di un oggetto Math creato (Math non è un costruttore).

+ +

Esempi

+ +

Usare Math.ceil()

+ +

L'esempio seguente mostra un uso di Math.ceil().

+ +
Math.ceil(.95);    // 1
+Math.ceil(4);      // 4
+Math.ceil(7.004);  // 8
+Math.ceil(-0.95);  // -0
+Math.ceil(-4);     // -4
+Math.ceil(-7.004); // -7
+
+ +

Arrotondamento decimale

+ +
// Closure
+(function() {
+  /**
+   * Decimal adjustment of a number.
+   *
+   * @param {String}  type  The type of adjustment.
+   * @param {Number}  value The number.
+   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
+   * @returns {Number} The adjusted value.
+   */
+  function decimalAdjust(type, value, exp) {
+    // If the exp is undefined or zero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // If the value is not a number or the exp is not an integer...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità dei browser

+ + + +

{{Compat("javascript.builtins.Math.ceil")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/e/index.html b/files/it/web/javascript/reference/global_objects/math/e/index.html new file mode 100644 index 0000000000..859d16145b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/e/index.html @@ -0,0 +1,79 @@ +--- +title: Math.E +slug: Web/JavaScript/Reference/Global_Objects/Math/E +translation_of: Web/JavaScript/Reference/Global_Objects/Math/E +--- +
{{JSRef}}
+ +

La costante Math.E rappresenta la base del logaritmo naturale, e, equivale approssimativamente a 2.718.

+ +

Math.E=e2.718\mathtt{\mi{Math.E}} = e \approx 2.718

+ +
{{EmbedInteractiveExample("pages/js/math-e.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrizione

+ +

Poiché E è una proprietà statica di Math, lo si usa sempre come Math.E, piuttosto che come un metodo di un Oggetto Math appositamente creato (Math non ha un costruttore).

+ +

Esempi

+ +

Uso di Math.E

+ +

Il codice seguente restitusice e:

+ +
function getNapier() {
+  return Math.E;
+}
+
+getNapier(); // 2.718281828459045
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.1', 'Math.E')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.e', 'Math.E')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.e', 'Math.E')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ + + +

{{Compat("javascript.builtins.Math.E")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/floor/index.html b/files/it/web/javascript/reference/global_objects/math/floor/index.html new file mode 100644 index 0000000000..3f7f6c7851 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/floor/index.html @@ -0,0 +1,158 @@ +--- +title: Math.floor() +slug: Web/JavaScript/Reference/Global_Objects/Math/floor +translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor +--- +
{{JSRef}}
+ +

La funzione Math.floor() restituisce il numero intero, arrotondato per difetto, del numero passato come parametro.

+ +

Sintassi

+ +
Math.floor(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

Un numero intero rappresentante l'arrotondamento per difetto del numero passato come parametro.

+ +

Descrizione

+ +

Siccome floor() è un metodo statico di Math, viene sempre usato come Math.floor() piuttosto che come metodo di un oggetto Math creato in precedenza (Math non è un costruttore).

+ +

Esempi

+ +

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
+
+ +

Arrotondamento decimale

+ +
// Closure
+(function() {
+  /**
+   * Decimal adjustment of a number.
+   *
+   * @param {String}  type  The type of adjustment.
+   * @param {Number}  value The number.
+   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
+   * @returns {Number} The adjusted value.
+   */
+  function decimalAdjust(type, value, exp) {
+    // If the exp is undefined or zero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // If the value is not a number or the exp is not an integer...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità dei Browser

+ + + +

{{Compat("javascript.builtins.Math.floor")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/index.html b/files/it/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..69cd2ec012 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,208 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +
{{JSRef}}
+ +

Math è un oggetto precostruito che possiede proprietà e metodi per restituire i risultati di costanti e funzioni matematiche. Math non è una funzione.

+ +

Descrizione

+ +

Diversamente dagli altri oggetti globali, Math non è un costruttore. Tutte le proprietà e i metodi di Math sono statici. Per riferirsi alla costante Pi si usa  Math.PI e per chiamare la funzione Seno si usa Math.sin(x) , dove x è l'argomento del metodo. Le costanti sono definite con la piena precisione dei numeri reali in JavaScript.

+ +

Proprietà

+ +
+
{{jsxref("Math.E")}}
+
Costante di Eulero e base dei logaritmi naturali, approssimativamente 2.718.
+
{{jsxref("Math.LN2")}}
+
Logaritmo naturale di 2, approssimativamente 0.693.
+
{{jsxref("Math.LN10")}}
+
Logaritmo naturale di 10, approssimativamente 0.693.
+
{{jsxref("Math.LOG2E")}}
+
Logaritmo a base 2 di E, approssimativamente 1.443.
+
{{jsxref("Math.LOG10E")}}
+
Logaritmo a base 10 di E, approssimativamente 1.443.
+
{{jsxref("Math.PI")}}
+
Rapporto tra la circonferenza di un cerchio ed il suo diametro, approssimativamente 3.14159.
+
{{jsxref("Math.SQRT1_2")}}
+
Radice quadrata di 1/2  ; equivale a 1 fratto la radice quadrata di 2, approsimativamente  0.707.
+
{{jsxref("Math.SQRT2")}}
+
Radice quadrata di 2, approssimativamente 1.414.
+
+ +

Metodi

+ +
+

Ricorda che le funzioni trigonometriche (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) si aspettano e restituiscono gli angoli in radianti. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

+
+ +
+

Ricorda che la precisione di molte delle funzioni matematiche è dipendente dall'sistema di implementazione. questo significa che browser differenti possono dare risultati diversi, e anche lo stessomotore JS su un differente sistema operativo o architettura può dare risultati discordi.

+
+ +
+
{{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 of 1 + x (loge, also ln) of a number.
+
{{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 integral part of the number x, removing any fractional digits.
+
+ +

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

+ +
{{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/it/web/javascript/reference/global_objects/math/max/index.html b/files/it/web/javascript/reference/global_objects/math/max/index.html new file mode 100644 index 0000000000..1c7f425fd0 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/max/index.html @@ -0,0 +1,145 @@ +--- +title: Math.max() +slug: Web/JavaScript/Reference/Global_Objects/Math/max +tags: + - JavaScript + - Math + - Referenza + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/max +--- +
{{JSRef}}
+ +

La funzione Math.max() restituisce il massimo tra zero o più numeri.

+ +

Sintassi

+ +
Math.max([valore1[, valore2[, ...]]])
+ +

Parametri

+ +
+
valore1, valore2, ...
+
Numeri.
+
+ +

Descrizione

+ +

Dato che max() è un metodo statico di Math, viene solitamente usato tramite Math.max(), piuttosto che come metodo di un oggetto di tipo Math (Math non è un construttore).

+ +

Se non vengono passati parametri, il risultato è -{{jsxref("Infinity")}}.

+ +

Se anche solo uno dei parametri non può essere convertito a numero, il risultato è {{jsxref("NaN")}}.

+ +

Esempi

+ +

Usando Math.max()

+ +
Math.max(10, 20);   //  20
+Math.max(-10, -20); // -10
+Math.max(-10, 20);  //  20
+
+ +

La seguente funzione usa il metodo {{jsxref("Function.prototype.apply()")}} per trovare l'elemento massimo in un array di numeri. 
+ getMaxOfArray([1, 2, 3]) è equivalente a Math.max(1, 2, 3) ma può essere usata con array di qualunque dimensione creati programmaticamente.

+ +
function getMaxOfArray(numArray) {
+  return Math.max.apply(null, numArray);
+}
+
+ +

Con il nuovo {{jsxref("Operators/Spread_operator", "spread operator")}}, ottenere l'elemento massimo di un array è ancora più semplice.

+ +
var arr = [1, 2, 3];
+var max = Math.max(...arr);
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificheStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementata in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.max', 'Math.max')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedi inoltre

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/min/index.html b/files/it/web/javascript/reference/global_objects/math/min/index.html new file mode 100644 index 0000000000..562292e15b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/min/index.html @@ -0,0 +1,160 @@ +--- +title: Math.min() +slug: Web/JavaScript/Reference/Global_Objects/Math/min +tags: + - JavaScript + - Matemática + - Math + - Minimo + - Più grande + - Più piccolo + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Math/min +--- +

 

+ +
{{JSRef}}
+ +

La funzione  Math.min() ritorna il più piccolo tra zero o più numeri.

+ +

Sintassi

+ +
Math.min([value1[, value2[, ...]]])
+ +

Parametri

+ +
+
value1, value2, ...
+
numeri.
+
+ +

Valori di Ritorno

+ +

Il più piccolo dei valori dati in input. Se uno degli argomenti non può essere convertito in numero, viene ritornato {{jsxref("NaN")}}.

+ +

Descrizione

+ +

Siccome min() è un metodo static di Math , lo si può sempre usare come Math.min(), piuttosto che come un metodo di un oggetto istanza di Math da te creato (Math non possiede costruttori).

+ +

Se non sono dati argomenti allora il metodo restituirà {{jsxref("Infinity")}}.

+ +

Se anche uno degli aromenti non può essere convertito in un numero, il risultato sarà {{jsxref("NaN")}}.

+ +

Esempi

+ +

Usando Math.min()

+ +

L'sempio di seguito assegna a z il valore minore tra  x e y:

+ +
var x = 10, y = -20;
+var z = Math.min(x, y);
+
+ +

Ritagliare un valore con Math.min()

+ +

Math.min() è spesso usato per limitare un valore in modo che sia sempre minore o uguale a un certo valore limite.
+ Ad esempio il seguente codice

+ +
var x = f(foo);
+
+if (x > boundary) {
+  x = boundary;
+}
+
+ +

può essere scritto come

+ +
var x = Math.min(f(foo), boundary);
+
+ +

{{jsxref("Math.max()")}} può essere similmente utilizzato per limitare il valore massimo.

+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementato in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.12', 'Math.min')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.min', 'Math.min')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.min', 'Math.min')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ +
{{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}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/pow/index.html b/files/it/web/javascript/reference/global_objects/math/pow/index.html new file mode 100644 index 0000000000..5db4139f6a --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/pow/index.html @@ -0,0 +1,151 @@ +--- +title: Math.pow() +slug: Web/JavaScript/Reference/Global_Objects/Math/pow +translation_of: Web/JavaScript/Reference/Global_Objects/Math/pow +--- +
{{JSRef}}
+ +

La funzione Math.pow() restituisce la potenza della base che si desidera moltiplicare per se stessa a seconda del valore dell'esponenete, cioè baseesponente.

+ +

Sintassi

+ +
Math.pow(base, esponente)
+ +

Parametri

+ +
+
base
+
La basee del numero.
+
esponente
+
L'esponente usato per elevare la base.
+
+ +

Valore di Ritorno

+ +

Un numero che rappresenta la base elevata alla potenza dell'esponente.

+ +

Descrizione

+ +

Siccome pow()  è un metodo static di Math, lo usi sempre nella forma Math.pow(), piuttosto che come un metodo di un oggetto Math da te creato (Math non ha costruttori).

+ +

Esempi

+ +

Usando Math.pow()

+ +
// semplice
+Math.pow(7, 2);    // 49
+Math.pow(7, 3);    // 343
+Math.pow(2, 10);   // 1024
+// esponenti fratti
+Math.pow(4, 0.5);  // 2 (radice quadrata di 4)
+Math.pow(8, 1/3);  // 2 (radice cubica di 8)
+Math.pow(2, 0.5);  // 1.4142135623730951 (radice quadrata di 2)
+Math.pow(2, 1/3);  // 1.2599210498948732 (radice cubica di 2)
+// esponenti negativi
+Math.pow(7, -2);   // 0.02040816326530612 (1/49)
+Math.pow(8, -1/3); // 0.5
+// basi negative
+Math.pow(-7, 2);   // 49 (i quadrati son sempre positivi)
+Math.pow(-7, 3);   // -343 (i cubi possono essere negativi)
+Math.pow(-7, 0.5); // NaN (i numeri negativi non hanno una quadrata reale)
+// Siccome le radici "pari" e quelle "dispari" sono vicine tra loro,
+// e i limiti della precisione numerica per i valori di tipo float,
+// le basi negative con esponenti fratti ritornano sempre NaN
+Math.pow(-7, 1/3); // NaN
+
+ +

Specifiche Tecniche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioneStatusCommento
{{SpecName('ES1')}}{{Spec2('ES1')}} +

Definizione iniziale. Implementata in  JavaScript 1.0.

+
{{SpecName('ES5.1', '#sec-15.8.2.13', 'Math.pow')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.pow', 'Math.pow')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.pow', 'Math.pow')}}{{Spec2('ESDraft')}} 
+ +

Compatiblità Browser 

+ +
{{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}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/random/index.html b/files/it/web/javascript/reference/global_objects/math/random/index.html new file mode 100644 index 0000000000..3fcd849257 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/random/index.html @@ -0,0 +1,107 @@ +--- +title: Math.random() +slug: Web/JavaScript/Reference/Global_Objects/Math/random +translation_of: Web/JavaScript/Reference/Global_Objects/Math/random +--- +
{{JSRef}}
+ +
La funzione Math.random()  ritorna un numero pseudo-casuale in virgola mobile compreso tra 0 e 1, con 0 incluso e 1 escluso (quindi nell'intervallo [0, 1)), scalabile al range desiderato. L'implementazione seleziona un numero (seme) iniziale utile all'algoritmo di generazione per restituire numeri randomici, il quale non può essere scelto o resettato dall'utente.
+ +
 
+ +
+

Math.random() non permette la generazione crittograficamente sicura dei numeri casuali, di conseguenza è altamente sconsigliato il suo impiego nell'ambito della sicurezza. Piuttosto sarebbe più corretto utilizzare la Web Crypto API instead, e più precisamente il metodo {{domxref("RandomSource.getRandomValues()", "window.crypto.getRandomValues()")}}.

+
+ +

Sintassi

+ +
Math.random()
+ +

Valore di ritorno

+ +

Un numero pseudo casuale in virgola mobile compreso tra 0 (incluso) e 1 (escluso).

+ +

Esempi

+ +

Bisogna notare che dal momento che i numeri in virgola mobile di JavaScript seguono lo standard IEEE 754 che arrotonda i numeri al numero pari più vicino, i range mostrati per la funzione sottostante non sono esatti (escludendo quello per Math.random()). Se si scelgono margini molto elevati (dell'ordine di 253  o più) è possibile, in casi estremamente rari, calcolare il limite superiore solitamente escluso.

+ +

Ottenere un numero tra [0, 1)

+ +
function getRandom() {
+  return Math.random();
+}
+
+ +

Ottenere un numero random tra due valori

+ +

Questo esempio restituisce un numero random tra due valori specificati. Il valore non è minore di (e può essere uguale a) min, nè maggiore (e nè uguale) a max. 

+ +
function getRandomArbitrary(min, max) {
+  return Math.random() * (max - min) + min;
+}
+
+ +

Ottenere un intero random tra due valori

+ +

Questo esempio restituisce un intero random tra due valori specificati. Il valore non è minore di min (oppure l'intero più grande di min se quest'ultimo non è un intero), nè maggiore (nè uguale) a max. 

+ +
function getRandomInt(min, max) {
+  min = Math.ceil(min);
+  max = Math.floor(max);
+  return Math.floor(Math.random() * (max - min)) + min; //Il max è escluso e il min è incluso
+}
+
+ +
+

Si potrebbe utilizzare l'arrotondamento per ottenere questo, tuttavia così facendo i numeri casuali seguirebbero una distribuzione non uniforme, magari non accettabile.

+
+ +

Ottenere un intero random tra due valori con estremi inclusi

+ +

Le funzioni viste finora escludono sempre l'estremo superiore del range scelto. La funzione getRandomIntInclusive() descritta sotto permette di ottenere questo.

+ +
function getRandomIntInclusive(min, max) {
+  min = Math.ceil(min);
+  max = Math.floor(max);
+  return Math.floor(Math.random() * (max - min + 1)) + min; //Il max è incluso e il min è incluso
+}
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. JS 1.0 (solo per UNIX) / JS 1.1. (tutte le piattaforme)
{{SpecName('ES5.1', '#sec-15.8.2.14', 'Math.random')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.random', 'Math.random')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.random', 'Math.random')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ + + +

{{Compat("javascript.builtins.Math.random")}}

+ +

 

diff --git a/files/it/web/javascript/reference/global_objects/math/round/index.html b/files/it/web/javascript/reference/global_objects/math/round/index.html new file mode 100644 index 0000000000..4b20fb4a42 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/round/index.html @@ -0,0 +1,100 @@ +--- +title: Math.round() +slug: Web/JavaScript/Reference/Global_Objects/Math/round +translation_of: Web/JavaScript/Reference/Global_Objects/Math/round +--- +
{{JSRef}}
+ +

La funzione Math.round() restituisce il valore di un numero approssimato all'intero ad esso più vicino.

+ +
{{EmbedInteractiveExample("pages/js/math-round.html")}}
+ + + +

Sintassi

+ +
Math.round(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore restituito

+ +

Il valore del numero dato approssimato all'intero più vicino.

+ +

Descrizione

+ +

Se la parte frazionale del numero è maggiore di 0.5, l'argomento (x) è approssimato all'intero successivo con il valore assoluto più elevato. Se è inferiore di 0.5, l'argomento è approssimato all'intero con il valore assoluto più basso.  Se la parte frazionale è esattamente 0.5, l'argomento è approssimato all'intero successivo nella direzione di +∞.  Si noti che questo è diverso da quanto accade nelle funzioni round() di molti altri linguaggi, che spesso invece approssimano questo caso all'intero successivo più lontano da zero, (dando un risultato diverso nel caso dei numeri negativi con una parte frazionale di esattamente 0.5).

+ +

Poiché round() è un metodo statico di Math, lo si usa sempre come Math.round(), piuttosto che come un metodo di un Oggetto Math appositamente creato (Math non ha un costruttore).

+ +

Esempi

+ +
Math.round( 20.49); //  20
+Math.round( 20.5 ); //  21
+Math.round( 42   ); //  42
+Math.round(-20.5 ); // -20
+Math.round(-20.51); // -21
+
+ +

 

+ +

Specifications

+ +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.15', 'Math.round')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.round', 'Math.round')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.round', 'Math.round')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Math.round")}}

+ +

 

+ +

See also

+ +

 

+ + diff --git a/files/it/web/javascript/reference/global_objects/math/sqrt/index.html b/files/it/web/javascript/reference/global_objects/math/sqrt/index.html new file mode 100644 index 0000000000..6daf577e02 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/math/sqrt/index.html @@ -0,0 +1,136 @@ +--- +title: Math.sqrt() +slug: Web/JavaScript/Reference/Global_Objects/Math/sqrt +translation_of: Web/JavaScript/Reference/Global_Objects/Math/sqrt +--- +
{{JSRef}}
+ +

La funzione Math.sqrt() ritorna la radice quadrata di un numero, cioè :

+ +

x0,Math.sqrt(x)=x=the uniquey0such thaty2=x\forall x \geq 0, \mathtt{Math.sqrt(x)} = \sqrt{x} = \text{l'unico} \; y \geq 0 \; \text{tale che} \; y^2 = x

+ +

Sintassi

+ +
Math.sqrt(x)
+ +

Parametri

+ +
+
x
+
Un numero.
+
+ +

Valore di ritorno

+ +

La radice quadrata di un dato numero. Se il numero è negativo viene ritornato {{jsxref("NaN")}}.

+ +

Descrizione

+ +

Se il segno di x è negativo, Math.sqrt() ritorna {{jsxref("NaN")}}.

+ +

Siccome sqrt() è un metodo static di Math, puoi usarlo sempre come Math.sqrt(), piutttosto che come un metodo di un oggetto di tipo Math creato da te (Math non è un costruttore).

+ +

Esempio

+ +

Uso di Math.sqrt()

+ +
Math.sqrt(9); // 3
+Math.sqrt(2); // 1.414213562373095
+
+Math.sqrt(1);  // 1
+Math.sqrt(0);  // 0
+Math.sqrt(-1); // NaN
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale. Implementato per 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')}} 
+ +

Compatibilità browser

+ +
{{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}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/nan/index.html b/files/it/web/javascript/reference/global_objects/nan/index.html new file mode 100644 index 0000000000..992f063e9d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/nan/index.html @@ -0,0 +1,79 @@ +--- +title: NaN +slug: Web/JavaScript/Reference/Global_Objects/NaN +translation_of: Web/JavaScript/Reference/Global_Objects/NaN +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La proprietà globale NaN è un valore che rappresenta un non numero (Not-a-Number).

+ +

{{js_property_attributes(0,0,0)}}

+ +

Sintassi

+ +
NaN
+ +

Descrizione

+ +

Nan è una proprietà del global object e indica il fatto che un certo valore non è un numero legale/valido.

+ +

Il valore iniziale di Nan è Not-A-Number — lo stesso valore che si può riscontrare accedendo a Number.NaN. Nei browser moderni NaN è una proprietà non configurabile e non scrivibile (read-only).

+ +

NaN è restituito principalmente come valore di fallimento dalle funzioni "matematiche" come Math.sqrt(-1) oppure quando si prova ad eseguire il parseInt di una stringa che non contiene cifre numeriche come parseInt("blabla")

+ +

Testare il valore NaN

+ +

Gli operatori di uguaglianza (== o ===) non possono essere usati per verificare il valore di NaN. Deve essere invece utilizzato il metodo IsNaN() presente sia nell'oggetto globale {{jsxref("Global_Objects/isNaN", "isNaN()")}} che nell'oggetto Number {{jsxref("Number.isNaN()")}}.  

+ +
NaN === NaN;        // false
+Number.NaN === NaN; // false
+isNaN(NaN);         // true
+isNaN(Number.NaN);  // true
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition. Implemented in 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')}} 
+ +

Compatibilità

+ + + +

{{Compat("javascript.builtins.NaN")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/null/index.html b/files/it/web/javascript/reference/global_objects/null/index.html new file mode 100644 index 0000000000..80ee3de685 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/null/index.html @@ -0,0 +1,89 @@ +--- +title: 'null' +slug: Web/JavaScript/Reference/Global_Objects/null +translation_of: Web/JavaScript/Reference/Global_Objects/null +--- +
{{jsSidebar("Objects")}}
+ +

Il valore null rappresenta l'assenza intenzionale di qualsiasi valore dell'oggetto. È una delle {{Glossary("Primitive", "primitive values")}} di JavaScript.

+ +
{{EmbedInteractiveExample("pages/js/globalprops-null.html")}}
+ + + +

Sintassi

+ +
null
+ +

Descrizione

+ +

Il valore null è scritto con un letterale: null. null non è un identificatore per una proprietà dell'oggetto globale, come {{jsxref("Global_Objects/undefined","undefined")}} può essere. Invece, null esprime una mancanza di identificazione, indicando che una variabile punta a nessun oggetto. Nelle API, null viene spesso recuperato in un punto in cui è possibile prevedere un oggetto ma nessun oggetto è rilevante.

+ +
// foo non esiste Non è definito e non è mai stato inizializzato:
+foo;
+"ReferenceError: foo is not defined"
+
+// foo è noto per esistere ora ma non ha alcun tipo o valore:
+var foo = null;
+foo;
+"null"
+
+ +

Differenze tra nullundefined

+ +

Durante il controllo per nullundefined, attenti alle differenze tra gli operatori equality (==) e identity (===), come il primo esegue la conversione del tipo.

+ +
typeof null          // "object" (non "null" per motivi legacy)
+typeof undefined     // "undefined"
+null === undefined   // false
+null  == undefined   // true
+null === null        // true
+null == null         // true
+!null                // true
+isNaN(1 + null)      // false
+isNaN(1 + undefined) // true
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-4.3.11', 'null value')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-null-value', 'null value')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-null-value', 'null value')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.null")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/number/index.html b/files/it/web/javascript/reference/global_objects/number/index.html new file mode 100644 index 0000000000..39c8eb37d2 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/number/index.html @@ -0,0 +1,188 @@ +--- +title: Number +slug: Web/JavaScript/Reference/Global_Objects/Number +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +
    +
  1. {{JSRef}}
  2. +
+ +
Number is a primitive wrapper object used to represent and manipulate numbers like 37 or -9.25.
+ +
+ +
+ +

The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function.

+ +

The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to what it can store. A Number only keeps about 17 decimal places of precision; arithmetic is subject to rounding. The largest value a Number can hold is about 1.8×10308. Numbers beyond that are replaced with the special Number constant {{jsxref("Infinity")}}.

+ +

A number literal like 37 in JavaScript code is a floating-point value, not an integer. There is no separate integer type in common everyday use. (JavaScript now has a {{jsxref("BigInt")}} type, but it was not designed to replace Number for everyday uses. 37 is still a Number, not a BigInt.)

+ +
+
+ +

Description

+ +

When used as a function, Number(value) converts a string or other value to the Number type. If the value can't be converted, it returns {{jsxref("NaN")}}.

+ +

Literal syntax

+ +
123    // one-hundred twenty-three
+123.0  // same
+123 === 123.0  // true
+ +

Function syntax

+ +
Number('123')  // returns the number 123
+Number('123') === 123  // true
+
+Number("unicorn")  // NaN
+Number(undefined)  // NaN
+
+ +

Constructor

+ +
+
Number()
+
Creates a new Number value.
+
+ +

Static properties

+ +
+
{{jsxref("Number.EPSILON")}}
+
The smallest interval between two representable numbers.
+
{{jsxref("Number.MAX_SAFE_INTEGER")}}
+
The maximum safe integer in JavaScript (253 - 1).
+
{{jsxref("Number.MAX_VALUE")}}
+
The largest positive representable number.
+
{{jsxref("Number.MIN_SAFE_INTEGER")}}
+
The minimum safe integer in JavaScript (-(253 - 1)).
+
{{jsxref("Number.MIN_VALUE")}}
+
The smallest positive representable number—that is, the positive number closest to zero (without actually being zero).
+
{{jsxref("Number.NaN")}}
+
Special "Not a Number" value.
+
{{jsxref("Number.NEGATIVE_INFINITY")}}
+
Special value representing negative infinity. Returned on overflow.
+
{{jsxref("Number.POSITIVE_INFINITY")}}
+
Special value representing infinity. Returned on overflow.
+
{{jsxref("Number.prototype")}}
+
Allows the addition of properties to the Number object.
+
+ +

Static methods

+ +
+
{{jsxref("Number.isNaN()")}}
+
Determine whether the passed value is NaN.
+
{{jsxref("Number.isFinite()")}}
+
Determine whether the passed value is a finite number.
+
{{jsxref("Number.isInteger()")}}
+
Determine whether the passed value is an integer.
+
{{jsxref("Number.isSafeInteger()")}}
+
Determine whether the passed value is a safe integer (number between -(253 - 1) and 253 - 1).
+
{{jsxref("Number.parseFloat()", "Number.parseFloat(string)")}}
+
This is the same as the global {{jsxref("parseFloat", "parseFloat()")}} function.
+
{{jsxref("Number.parseInt()", "Number.parseInt(string, [radix])")}}
+
This is the same as the global {{jsxref("parseInt", "parseInt()")}} function.
+
+ +

Instance methods

+ +
+
{{jsxref("Number.prototype.toExponential()" ,"Number.prototype.toExponential(fractionDigits)")}}
+
Returns a string representing the number in exponential notation.
+
{{jsxref("Number.prototype.toFixed()", "Number.prototype.toFixed(digits)")}}
+
Returns a string representing the number in fixed-point notation.
+
{{jsxref("Number.prototype.toLocaleString()", "Number.prototype.toLocaleString([locales [, options]])")}}
+
Returns a string with a language sensitive representation of this number. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.
+
{{jsxref("Number.prototype.toPrecision()", "Number.prototype.toPrecision(precision)")}}
+
Returns a string representing the number to a specified precision in fixed-point or exponential notation.
+
{{jsxref("Number.prototype.toString()", "Number.prototype.toString([radix])")}}
+
Returns a string representing the specified object in the specified radix ("base"). Overrides the {{jsxref("Object.prototype.toString()")}} method.
+
{{jsxref("Number.prototype.valueOf()")}}
+
Returns the primitive value of the specified object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.
+
+ +

Examples

+ +

Using the Number object to assign values to numeric variables

+ +

The following example uses the Number object's properties to assign values to several numeric variables:

+ +
const biggestNum     = Number.MAX_VALUE
+const smallestNum    = Number.MIN_VALUE
+const infiniteNum    = Number.POSITIVE_INFINITY
+const negInfiniteNum = Number.NEGATIVE_INFINITY
+const notANum        = Number.NaN
+
+ +

Integer range for Number

+ +

The following example shows the minimum and maximum integer values that can be represented as Number object. (More details on this are described in the ECMAScript standard, chapter 6.1.6 The Number Type.)

+ +
const biggestInt  = Number.MAX_SAFE_INTEGER  //  (253 - 1) =>  9007199254740991
+const smallestInt = Number.MIN_SAFE_INTEGER  // -(253 - 1) => -9007199254740991
+ +

When parsing data that has been serialized to JSON, integer values falling outside of this range can be expected to become corrupted when JSON parser coerces them to Number type.

+ +

A possible workaround is to use {{jsxref("String")}} instead.

+ +

Larger numbers can be represented using the {{jsxref("BigInt")}} type.

+ +

Using Number to convert a Date object

+ +

The following example converts the {{jsxref("Date")}} object to a numerical value using Number as a function:

+ +
let d = new Date('December 17, 1995 03:24:00')
+console.log(Number(d))
+
+ +

This logs 819199440000.

+ +

Convert numeric strings and null to numbers

+ +
Number('123')     // 123
+Number('123') === 123 /// true
+Number('12.3')    // 12.3
+Number('12.00')   // 12
+Number('123e-1')  // 12.3
+Number('')        // 0
+Number(null)      // 0
+Number('0x11')    // 17
+Number('0b11')    // 3
+Number('0o11')    // 9
+Number('foo')     // NaN
+Number('100a')    // NaN
+Number('-Infinity') //-Infinity
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-number-objects', 'Number')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Number")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/assign/index.html b/files/it/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..6280745df2 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,268 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Reference/Global_Objects/Object/assign +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +
{{JSRef}}
+ +

Sommario

+ +

La funzione Object.assign() copia tutte le proprietà enumerabili da uno o più oggetti di origine in un oggetto di destinazione. Restituisce l'oggetto di destinazione.

+ +

Sintassi

+ +
Object.assign(target, ...sources)
+ +

Parametri

+ +
+
target
+
L'oggetto di destinazione.
+
sources
+
Gli oggetti di origine.
+
+ +

Descrizione

+ +

La funzione Object.assign() copia soltanto le proprietà enumerabili appartenenti agli oggetti di origine (non quelle che fanno parte della loro catena dei prototipi) in un oggetto di destinazione. Utilizza [[Get]] sugli oggetti di origine e [[Put]] su quello di destinazione, quindi invoca getter e setter, quando presenti. Quindi assegna le proprietà, piuttosto che limitarsi a copiarle o a definirne di nuove. Ciò lo rende inadatto per aggiungere nuove proprietà in un prototipo se le proprietà vengono copiate da un oggetto contenente getter o setter. Per copiare le proprietà, incluso il fatto di essere enumerabili o no, in un prototipo, bisognerebbe usare {{jsxref("Object.defineProperty()")}}.

+ +

Vengono copiate sia le proprietà aventi come nomi delle {{jsxref("String", "stringhe")}} che dei {{jsxref("Symbol", "simboli")}}.

+ +

In caso di errore, per esempio se una proprietà non è sovrascrivibile, viene generato un {{jsxref("TypeError")}}, e l'oggetto di destinazione rimane invariato.

+ +

Notare che Object.assign() non genera un errore se uno dei valori di origine è {{jsxref("null")}} o {{jsxref("undefined")}}.

+ +

Esempi

+ +

Clonare un oggetto

+ +

Si potrebbe pensare di clonare un oggetto semplicemente assegnandolo ad un altra variabile:

+ +
var obj = { a: 1 };
+var copia = obj;
+console.log(obj, copia); // { a: 1 }, { a: 1 }
+obj.a = 2;
+console.log(obj, copia); // { a: 2 }, { a: 2 }
+                         // Ma copia.a non valeva 1?
+ +

Utilizzando Object.assign() il problema non si verifica:

+ +
var obj = { a: 1 };
+var copia = Object.assign({}, obj);
+console.log(obj, copia); // { a: 1 }, { a: 1 }
+obj.a = 2;
+console.log(obj, copia); // { a: 2 }, { a: 1 }
+
+ +

Unire più oggetti

+ +
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 }, le proprietà vengono aggiunte all'oggetto di destinazione
+
+ +

Copiare proprietà aventi come indici dei simboli

+ +
var o1 = { a: 1 };
+var o2 = { [Symbol("foo")]: 2 };
+
+var obj = Object.assign({}, o1, o2);
+console.log(obj); // { a: 1, Symbol(foo): 2 }
+
+ +

Le proprietà ereditate o non-enumerabili non vengono copiate

+ +
var obj = Object.create({ foo: 1 }, { // foo è una proprietà ereditata
+  bar: {
+    value: 2  // bar è una proprietà non-enumerabile
+  },
+  baz: {
+    value: 3,
+    enumerable: true  // baz è una proprietà enumerabile
+  }
+});
+
+var copia = Object.assign({}, obj);
+console.log(copia); // { baz: 3 }
+
+ +

I valori primitivi vengono trasformati in oggetti

+ +
var v1 = '123';
+var v2 = true;
+var v3 = 10;
+var v4 = Symbol("foo");
+
+var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
+// I valori primitivi vengono trasformati in oggetti, null e undefined ignorati.
+// Notare che solo le stringhe hanno proprietà enumerabili
+console.log(obj); // { "0": "1", "1": "2", "2": "3" }
+
+ +

Se viene generata un eccezione, la funzione si ferma

+ +
var destinazione = Object.defineProperty({}, 'foo', {
+  value: 1,
+  writeable: false
+}); // destinazione.foo non può essere modificata
+
+Object.assign(destinazione, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
+// TypeError: "foo" is read-only
+// L'eccezione viene generata quando si modifica destinazione.foo
+
+console.log(destinazione.bar);  // 2, Il primo oggetto viene copiato correttamente
+console.log(destinazione.foo2); // 3, La prima proprietà del secondo oggetto viene copiata correttamente
+console.log(destinazione.foo);  // 1, L'eccezione viene generata qui
+console.log(destinazione.foo3); // undefined, la funzione ha già finto di copiare
+console.log(destinazione.baz);  // undefined, la funzione ha già finto di copiare
+
+ +

Copiare i getter

+ +
var obj = {
+  foo: 1,
+  get bar() {
+    return 2;
+  }
+};
+
+var copia = Object.assign({}, obj);
+console.log(copia);
+// { foo: 1, bar: 2 }, non viene copiato il getter obj.bar, ma il suo valore
+
+// Questa funzione copia mantenendo getter e setter
+function myAssign(target, ...sources) {
+  sources.forEach(source => {
+    Object.defineProperties(target, Object.keys(source).reduce((descriptors, key) => {
+      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
+      return descriptors;
+    }, {}));
+  });
+  return target;
+}
+
+var copia = myAssign({}, obj);
+console.log(copia);
+// { foo:1, get bar() { return 2 } }
+
+ +

Polyfill

+ +

Questo polyfill non supporta i simboli (che comunque non sono supportati da ECMAScript 5):

+ +
if (!Object.assign) {
+  Object.defineProperty(Object, 'assign', {
+    enumerable: false,
+    configurable: true,
+    writable: true,
+    value: function(target, firstSource) {
+      'use strict';
+      if (target === undefined || target === null) {
+        throw new TypeError('Cannot convert first argument to object');
+      }
+
+      var to = Object(target);
+      for (var i = 1; i < arguments.length; i++) {
+        var nextSource = arguments[i];
+        if (nextSource === undefined || nextSource === null) {
+          continue;
+        }
+        nextSource = Object(nextSource);
+
+        var keysArray = Object.keys(Object(nextSource));
+        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
+          var nextKey = keysArray[nextIndex];
+          var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
+          if (desc !== undefined && desc.enumerable) {
+            to[nextKey] = nextSource[nextKey];
+          }
+        }
+      }
+      return to;
+    }
+  });
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + +
SpecificaStatoCommenti
{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}{{Spec2('ES2015')}}Definizione iniziale.
+ +

Compatibilità con i browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{CompatChrome("45")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("34")}}{{CompatNo}}{{CompatOpera("32")}}{{CompatSafari("9")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{CompatNo}}{{CompatChrome("45")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("34")}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/create/index.html b/files/it/web/javascript/reference/global_objects/object/create/index.html new file mode 100644 index 0000000000..d2b020b955 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/create/index.html @@ -0,0 +1,234 @@ +--- +title: Object.create() +slug: Web/JavaScript/Reference/Global_Objects/Object/create +tags: + - Creazione + - Oggetto + - Prototipo + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/create +--- +
+ {{JSRef("Global_Objects", "Object")}}
+

Sommario

+

Il metodo Object.create() crea un nuovo oggetto a partire dall'oggetto prototipo e dalle proprietà specificati.

+

Sintassi

+
Object.create(proto[, propertiesObject])
+

Parametri

+
+
+ proto
+
+ L'oggetto che farà da prototipo per il nuovo oggetto creato.
+
+ propertiesObject
+
+ Opzionale. Se specificato e non {{jsxref("Global_Objects/undefined", "undefined")}}, un oggetto le cui proprie proprietà enumerabili (ovvero, quelle proprietà definite esclusivamente su di sé e non quelle enumerabili presenti nella sua catena dei prototipi) specificano descrittori di proprietà da aggiungere all'oggetto appena creato, con i corrispondenti nomi di proprietà. Queste proprietà corrispondono al secondo argomento di {{jsxref("Object.defineProperties()")}}.
+
+

Throws

+

Lancia un'eccezione di tipo {{jsxref("Global_Objects/TypeError", "TypeError")}} se il parametro  proto non è {{jsxref("Global_Objects/null", "null")}} oppure un oggetto.

+

Esempi

+

Esempio: ereditarietà classica con Object.create

+

Sotto, trovi un esempio di come implementare un'ereditarietà classica usando Object.create. Si tratta di un'ereditarietà singola, l'unica supportata da Javascript.

+
// Shape - superclass
+function Shape() {
+  this.x = 0;
+  this.y = 0;
+}
+
+// superclass method
+Shape.prototype.move = function(x, y) {
+  this.x += x;
+  this.y += y;
+  console.info('Shape moved.');
+};
+
+// Rectangle - subclass
+function Rectangle() {
+  Shape.call(this); // call super constructor.
+}
+
+// subclass extends superclass
+Rectangle.prototype = Object.create(Shape.prototype);
+Rectangle.prototype.constructor = Rectangle;
+
+var rect = new Rectangle();
+
+console.log("Is rect an instance of Rectangle? " + (rect instanceof Rectangle)); // true
+console.log("Is rect an instance of Shape? " + (rect instanceof Shape)); // true
+
+rect.move(1, 1); // Outputs, 'Shape moved.'
+
+

Se desideri ereditare proprietà e metodi da oggetti multipli, puoi utilizzare dei mixins.

+
function MyClass() {
+  SuperClass.call(this);
+  OtherSuperClass.call(this);
+}
+
+MyClass.prototype = Object.create(SuperClass.prototype); // inherit
+mixin(MyClass.prototype, OtherSuperClass.prototype); // mixin
+
+MyClass.prototype.myMethod = function() {
+  // do a thing
+};
+
+

La funzione mixin copia le funzioni dell'oggetto prototype della superclasse nell'oggetto prototype della sottoclasse; la funzione mixin deve essere implementata dall'utente. Un esempio di funzione simil mixin potrebbe essere jQuery.extend.

+

Esempio: Usare l'argomento propertiesObject con Object.create

+
var o;
+
+// create an object with null as prototype
+o = Object.create(null);
+
+
+o = {};
+// is equivalent to:
+o = Object.create(Object.prototype);
+
+
+// Example where we create an object with a couple of sample properties.
+// (Note that the second parameter maps keys to *property descriptors*.)
+o = Object.create(Object.prototype, {
+  // foo is a regular 'value property'
+  foo: { writable: true, configurable: true, value: 'hello' },
+  // bar is a getter-and-setter (accessor) property
+  bar: {
+    configurable: false,
+    get: function() { return 10; },
+    set: function(value) { console.log('Setting `o.bar` to', value); }
+  }
+});
+
+
+function Constructor() {}
+o = new Constructor();
+// is equivalent to:
+o = Object.create(Constructor.prototype);
+// Of course, if there is actual initialization code in the
+// Constructor function, the Object.create cannot reflect it
+
+
+// create a new object whose prototype is a new, empty object
+// and a adding single property 'p', with value 42
+o = Object.create({}, { p: { value: 42 } });
+
+// by default properties ARE NOT writable, enumerable or configurable:
+o.p = 24;
+o.p;
+// 42
+
+o.q = 12;
+for (var prop in o) {
+  console.log(prop);
+}
+// 'q'
+
+delete o.p;
+// false
+
+// to specify an ES3 property
+o2 = Object.create({}, {
+  p: {
+    value: 42,
+    writable: true,
+    enumerable: true,
+    configurable: true
+  }
+});
+
+

Polyfill

+

Questo polyfill implementa il caso di utilizzo principale, ovvero creare un nuovo oggetto specificando un oggetto prototipo, ma non prende in considerazione il secondo argomento dell'API orginale.

+
if (typeof Object.create != 'function') {
+  Object.create = (function() {
+    var Object = function() {};
+    return function (prototype) {
+      if (arguments.length > 1) {
+        throw Error('Second argument not supported');
+      }
+      if (typeof prototype != 'object') {
+        throw TypeError('Argument must be an object');
+      }
+      Object.prototype = prototype;
+      var result = new Object();
+      Object.prototype = null;
+      return result;
+    };
+  })();
+}
+
+

Specifiche

+ + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.2.3.5', 'Object.create')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.create', 'Object.create')}}{{Spec2('ES6')}} 
+

Compatibilità browser

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
CaratteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto base{{CompatChrome("5")}}{{CompatGeckoDesktop("2")}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5")}}
+
+
+ + + + + + + + + + + + + + + + + + + + + +
CaratteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}{{CompatVersionUnknown}}{{CompatOperaMobile("11.50")}}{{CompatVersionUnknown}}
+
+

Basato sulla tabella di compatibilità di Kangax.

+

Vedi anche

+ diff --git a/files/it/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/it/web/javascript/reference/global_objects/object/defineproperties/index.html new file mode 100644 index 0000000000..c905420eb2 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/defineproperties/index.html @@ -0,0 +1,224 @@ +--- +title: Object.defineProperties() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +--- +
{{JSRef}}
+ +

Il metodo Object.defineProperties() definisce nuove proprietà o modifica le proprietà esistenti, direttamente sull'oggetto di ritorno.

+ +

Sintassi

+ +
Object.defineProperties(obj, props)
+ +

Parametri

+ +
+
obj
+
L'oggetto su cui definire le nuove proprietà o modificare le esistenti proprietà.
+
props
+
Un oggetto che contiene le proprietà enumerabili. Per ogni proprietà troviamo dei descrittori della proprietà stessa, che ne impostano il comportamento. Suddividiamo i descrittori in due tipologie: il data descriptors e i descrittorei che ne regolano gli accessi (guarda {{jsxref("Object.defineProperty()")}} per maggiori dettagli). I descrittori hanno le seguenti c:
+
+
+
configurable
+
true se e solo se la proprietà individuata dal descrittore può essere cambiata e se la proprietà può essere cancellata dal presente oggetto.
+ Defaults a false.
+
enumerable
+
true se e solo se la proprietà è visualizzabile durante una enumerazione delle proprietà del presente oggetto (es. for-in)
+ Defaults a false.
+
+ +
+
value
+
Il valore associato con la proprietà che si sta definendo. Può essere un qualsiasi valore valido di Javascript (number, object, function, ecc...)
+ Defaults a {{jsxref("undefined")}}.
+
writable
+
true se e solo se il valore associato per la proprietà può essere cambiato con un {{jsxref("Operators/Assignment_Operators", "operatore di assegnazione", "", 1)}}.
+ Defaults to false.
+
+ +
+
get
+
Una funzione che serve da getter (prelevare il dato) per la proprietà, o {{jsxref("undefined")}} se non è presente un getter. Il valore di ritorno della funzione verrà usato come valore della proprietà
+ Defaults a {{jsxref("undefined")}}.
+
set
+
Una funzione che serve da setter (impostare il dato) per la proprietà {{jsxref("undefined")}} se non è presente il setter. La funzione riceverà un solo argomento che verrà assegnato come valore della proprietà.
+ Defaults a {{jsxref("undefined")}}.
+
+
+
+ +

Valore di ritorno

+ +

L'oggetto che è stato passato alla funzione.

+ +

Descrizione

+ +

Object.defineProperties, in sostanza, definisce tutte le proprietà di un oggetto, corrispondenti alle proprietà "own" proprie di un oggetto obj.

+ +

Esempio

+ +
var obj = {};
+Object.defineProperties(obj, {
+  'property1': {
+    value: true,
+    writable: true
+  },
+  'property2': {
+    value: 'Hello',
+    writable: false
+  }
+  // etc. etc.
+});
+
+ +

Polyfill

+ +

Assumendo di eseguire un ambiente precedente con tutti i nomi e le proprietà che fanno riferimento ai valori iniziali, Object.defineProperties è quasi completamente equivalente (nota il commento in isCallable) al seguente reimplementazione 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;
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
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')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2")}}{{CompatChrome("5")}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/freeze/index.html b/files/it/web/javascript/reference/global_objects/object/freeze/index.html new file mode 100644 index 0000000000..26201fdb0c --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/freeze/index.html @@ -0,0 +1,210 @@ +--- +title: Object.freeze() +slug: Web/JavaScript/Reference/Global_Objects/Object/freeze +translation_of: Web/JavaScript/Reference/Global_Objects/Object/freeze +--- +
{{JSRef}}
+ +

Il metodo Object.freeze() congela un oggetto: ne previene l'aggiunta, la modifica e la rimozione di proprietà, inclusa la loro enumerabilità, configurabilità e accessibilità. In sostanza, l'oggetto è reso effettivamente immutabile. Il metodo restituisce lo stesso oggetto che è stato passato alla funzione. 

+ +

Sintassi

+ +
Object.freeze(obj)
+ +

Parametri

+ +
+
obj
+
L'oggetto da congelare.
+
+ +

Valore di ritorno

+ +

L'oggetto passato alla funzione.

+ +

Descrizione

+ +

Nulla può essere aggiunto o rimosso dall'insieme delle proprietà di un oggetto congelato. Qualsiasi tentativo di fare ciò fallirebbe, o silenziosamente o attraverso il ritorno di un errore {{jsxref("TypeError")}} (più frequentemente, ma non necessariamente, quest'ultimo scenario accadrebbe in {{jsxref("Strict_mode", "strict mode", "", 1)}}).

+ +

I valori delle proprietà non possono essere cambiati, anche quando si tratta di setters e getters. Da notare che se un oggetto costituisce il valore di una proprietà, esso può essere ancora modificato senza problemi, a meno che anch'esso non sia stato congelato.

+ +

Esempi

+ +
var obj = {
+  prop: function() {},
+  foo: 'bar'
+};
+
+// Nuove proprietà possono essere aggiunte, proprietà già esistenti possono
+// essere modificate o rimosse
+obj.foo = 'baz';
+obj.lumpy = 'woof';
+delete obj.prop;
+
+
+// Sia l'oggetto che viene passato che quello restituito verranno congelati.
+// No serve salvare l'oggetto restituito per congelare l'originale
+var o = Object.freeze(obj);
+
+o === obj; // true
+Object.isFrozen(obj); // === true
+
+// Adesso qualsiasi cambiamento fallirà
+obj.foo = 'quux'; // silenziosamente, non succede niente
+obj.quaxxor = 'the friendly duck'; // silenziosamente, non aggiungerà alcuna proprietò
+
+
+// ...e nella modalità strict questi tentativi di modifica faranno lanciare TypeErrors
+function fail(){
+  'use strict';
+  obj.foo = 'sparky'; // throws a TypeError
+  delete obj.quaxxor; // throws a TypeError
+  obj.sparky = 'arf'; // throws a TypeError
+}
+
+fail();
+
+
+// Tentare di cambiare attraverso Object.defineProperty farà anche lanciare un TypeError
+Object.defineProperty(obj, 'ohai', { value: 17 }); // throws a TypeError
+Object.defineProperty(obj, 'foo', { value: 'eit' }); // throws a TypeError
+
+ +

Il seguente esempio mostra come oggetti che sono valori di proprietà possono essere mutati(il congelamento si ferma ad un solo livello di profondità).

+ +
obj1 = {
+  internal: {}
+};
+
+Object.freeze(obj1);
+obj1.internal.a = 'aValue';
+
+obj1.internal.a // 'aValue'
+
+
+// Per fare un oggetto totalmente non modificabile, congela ciascun oggetto in obj.
+// Per farlo noi usiamo questa funzione.
+function deepFreeze(obj) {
+
+  // Prende tutti i nomi delle proprietà definite in obj
+  var propNames = Object.getOwnPropertyNames(obj);
+
+  // Congela tutte le proprietà prima di congelare obj
+  propNames.forEach(function(name) {
+    var prop = obj[name];
+
+    // Congela prop se esso è un oggetto
+    if (typeof prop == 'object' && prop !== null)
+      deepFreeze(prop);
+  });
+
+  // Congela se stesso (niente operazione se esso è già congelato)
+  return Object.freeze(obj);
+}
+
+obj2 = {
+  internal: {}
+};
+
+deepFreeze(obj2);
+obj2.internal.a = 'anotherValue';
+obj2.internal.a; // undefined
+
+ +

Note

+ +

In ES5, se l'argomento di questo metodo non è un oggetto, allora verrà ritornato un errore {{jsxref("TypeError")}}. In ES2015, un argomento che non è un oggetto verrà trattato come se fosse un normale oggetto già congelato, e verrà perciò semplicemente ritornato.

+ +
> Object.freeze(1)
+TypeError: 1 is not an object // ES5 code
+
+> Object.freeze(1)
+1                             // ES2015 code
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.2.3.9', 'Object.freeze')}}{{Spec2('ES5.1')}}Commento iniziale. Implementato in JavaScript 1.8.5.
{{SpecName('ES2015', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ESDraft')}}
+ +

Compatibilità con i browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Funzionalità di base{{CompatGeckoDesktop("2")}}{{CompatChrome("6")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Funzionalità di base{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/it/web/javascript/reference/global_objects/object/getprototypeof/index.html new file mode 100644 index 0000000000..dd72c6cdf3 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/getprototypeof/index.html @@ -0,0 +1,130 @@ +--- +title: Object.getPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +tags: + - ECMAScript5 + - ECMAScript6 + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +--- +
{{JSRef}}
+ +

Il metodo Object.getPrototypeOf() restituisce il prototipo (ovvero il valore della proprietà interna [[Prototype]]) dell'oggetto specificato.

+ +

Sintassi

+ +
Object.getPrototypeOf(obj)
+ +

Parametri

+ +
+
obj
+
L'oggetto di cui si vuole ottenere il prototipo.
+
+ +

Esempi

+ +
var proto = {};
+var obj = Object.create(proto);
+Object.getPrototypeOf(obj) === proto; // true
+
+ +

Note

+ +

Se il parametro obj non è un oggetto, nello standard ES5 il metodo innescherà un'eccezione {{jsxref("TypeError")}}, mentre nello standard ES6 il parametro sarà assegnato forzatamente ad un {{jsxref("Object")}}.

+ +
Object.getPrototypeOf("foo");
+// TypeError: "foo" is not an object (ES5 code)
+Object.getPrototypeOf("foo");
+// String.prototype                  (ES6 code)
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}Prima definizione.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
+ +

Compatibilità fra i Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Note specifiche su Opera

+ +

Anche se le vecchie versioni di Opera non supportano ancora il metodo Object.getPrototypeOf(), comunque dalla versione 10.50 è stata implementata la proprietà non standard {{jsxref("Object.proto", "__proto__")}}.

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/it/web/javascript/reference/global_objects/object/hasownproperty/index.html new file mode 100644 index 0000000000..7287ed1e18 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/hasownproperty/index.html @@ -0,0 +1,164 @@ +--- +title: Object.prototype.hasOwnProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +tags: + - JavaScript + - Object + - Prototype + - hasOwnProperty + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +--- +
{{JSRef}}
+ +

Il metodo hasOwnProperty() restituisce un valore booleano che indica se l'oggetto ha la proprietà specificata come propria proprietà (invece di ereditarla).

+ +
{{EmbedInteractiveExample("pages/js/object-prototype-hasownproperty.html")}}
+ + + +

Sintassi

+ +
obj.hasOwnProperty(prop)
+ +

Parametri

+ +
+
prop
+
Il nome della {{jsxref("String")}} o il {{Glossary("Symbol")}} della proprietà da testare.
+
+ +

Valore di ritorno

+ +

Un {{jsxref("Boolean")}} che indica se l'oggetto ha o meno la proprietà specificata come proprietà propria.

+ +

Descrizione

+ +

Tutti i discendenti di {{jsxref("Object")}} ereditano il metodo hasOwnProperty. Questo metodo può essere utilizzato per determinare se un oggetto ha la proprietà specificata come proprietà diretta di tale oggetto; a differenza dell'operatore {{jsxref("Operators/in", "in")}}, questo metodo non controlla una proprietà nella catena di prototipi dell'oggetto.

+ +

Note

+ +

hasOwnProperty restituisce true anche se il valore della proprietà è nullundefined.

+ +
o = new Object();
+o.propOne = null;
+o.hasOwnProperty('propOne');   // ritorna true
+o.propTwo = undefined;
+o.hasOwnProperty('propTwo');   // ritorna true
+
+ +

Esempi

+ +

Usare hasOwnProperty per verificare l'esistenza di una proprietà

+ +

L'esempio seguente determina se l'oggetto o contiene una proprietà denominata prop:

+ +
o = new Object();
+o.hasOwnProperty('prop');   // ritorna false
+o.prop = 'exists';
+o.hasOwnProperty('prop');   // ritorna true
+
+ +

Dirette vs. proprietà ereditate

+ +

Il seguente esempio distingue tra proprietà dirette e proprietà ereditate attraverso la catena del prototipo:

+ +
o = new Object();
+o.prop = 'exists';
+o.hasOwnProperty('prop');             // ritorna true
+o.hasOwnProperty('toString');         // ritorna false
+o.hasOwnProperty('hasOwnProperty');   // ritorna false
+
+ +

Iterare sulle proprietà di un oggetto

+ +

L'esempio seguente mostra come eseguire iterazioni sulle proprietà di un oggetto senza eseguire l'esecuzione su proprietà ereditate. Si noti che il ciclo {{jsxref("Statements/for...in", "for...in")}} sta già solo iterando gli oggetti enumerabili, quindi non si dovrebbe assumere in base alla mancanza di proprietà non enumerabili mostrate nel ciclo che hasOwnProperty è strettamente limitato agli elementi enumerabili (come con {{jsxref("Object.getOwnPropertyNames()")}}).

+ +
var buz = {
+  fog: 'stack'
+};
+
+for (var name in buz) {
+  if (buz.hasOwnProperty(name)) {
+    console.log('this is fog (' +
+      name + ') for sure. Value: ' + buz[name]);
+  }
+  else {
+    console.log(name); // toString o qualcos'altro
+  }
+}
+
+ +

Usare hasOwnProperty come nome di una proprietà

+ +

JavaScript non protegge il nome della proprietà hasOwnProperty; quindi, se esiste la possibilità che un oggetto possa avere una proprietà con questo nome, è necessario utilizzare un hasOwnProperty esterno per ottenere risultati corretti:

+ +
var foo = {
+  hasOwnProperty: function() {
+    return false;
+  },
+  bar: 'Here be dragons'
+};
+
+foo.hasOwnProperty('bar'); // restituisce sempre false
+
+// Usare hasOwnProperty di un altro oggetto
+// e chiamarlo con 'this' impostato su foo
+({}).hasOwnProperty.call(foo, 'bar'); // true
+
+// È anche possibile utilizzare la proprietà hasOwnProperty
+// dal prototipo Object per questo scopo
+Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
+
+ +

Nota che nell'ultimo caso non ci sono oggetti appena creati.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ESDraft', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale Implementato in JavaScript 1.5.
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.Object.hasOwnProperty")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/index.html b/files/it/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..8c567d9ea2 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,224 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - NeedsBrowserCompatibility + - NeedsMobileBrowserCompatibility + - Object + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef("Global_Objects", "Object")}}
+ +

Sommari

+ +

Il costruttore Object crea un oggetto.

+ +

Sintassi

+ +
// Letterale
+{ [ coppiaNomeValore1 [, coppiaNomeValore2 [, ...coppiaNomeValoreN] ] ] }
+
+// Richiamato come una classe
+new Object( [ value ] )
+ +

Parametri

+ +
+
coppiaNomeValore1, coppiaNomeValore2, ... coppiaNomeValoreN
+
Coppie formate da un nome (una stringa) e un valore (di qualsiasi tipo), dove il nome è separato dal valore con i due punti.
+
+
{
+    "nome1": "valore1",
+    nome2: "valore2" // Gli apici nel nome sono opzionali
+};
+
+
+
+ +
+
value
+
Qualsiasi valore.
+
+ +

Descrizione

+ +

Il costruttore Object crea un oggetto avente il valore dato. Se il valore è {{jsxref("Global_Objects/null", "null")}} o {{jsxref("Global_Objects/undefined", "undefined")}}, verrà creato un oggetto vuoto; altrimenti un oggetto del tipo corrispondente al valore dato. Se il valore è già un oggetto, verra restituito senza alcuna modifica.

+ +

Quando richiamato come normale funzione, il comportamento di Object() è identico a new Object().

+ +

Proprietà del costruttore Object

+ +
+
Object.length
+
Ha valore pari a 1.
+
{{jsxref("Object.prototype")}}
+
Permette di aggiungere altre proprietà ad ogni oggetto di tipo Object.
+
+ +

{{ jsOverrides("Function", "Properties", "prototype") }}

+ +

Metodi del costruttore Object

+ +
+
{{jsxref("Object.assign()")}} {{experimental_inline}}
+
Crea un nuovo oggetto copiando i valori di tutti le proprietà enumerabili da uno o più oggetti.
+
{{jsxref("Object.create()")}}
+
Crea un nuovo oggetto utilizzando il prototipo e le proprietà specificate.
+
{{jsxref("Object.defineProperty()")}}
+
Aggiunge una proprietà descritta dall'oggetto specificato.
+
{{jsxref("Object.defineProperties()")}}
+
Aggiunge più proprietà descritte dall'oggetto specificato.
+
{{jsxref("Object.freeze()")}}
+
Congela un oggetto: le sue proprietà non possono più essere cancellate o modificate.
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
Restituisce un oggetto che descriva la proprietà specificata.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
Restituisce un array contenente i nomi di tutte le proprietà (enumerabili e non-enumerabili) dell'oggetto specificato.
+
{{jsxref("Object.getPrototypeOf()")}}
+
Restituisce il prototipo dell'oggetto specificato.
+
{{jsxref("Object.is()")}} {{ experimental_inline() }}
+
Determina se due valori sono o no uguali (quindi lo stesso oggetto).
+
{{jsxref("Object.isExtensible()")}}
+
Determina se è permesso estendere un oggetto.
+
{{jsxref("Object.isFrozen()")}}
+
Determina se un oggetto è stato congelato.
+
{{jsxref("Object.isSealed()")}}
+
Determina se un oggetto è stato sigillato.
+
{{jsxref("Object.keys()")}}
+
Restituisce un array contenente i nomi di tutte le proprietà enumerabili dell'oggetto.
+
{{jsxref("Object.observe()")}} {{experimental_inline}}
+
Osserva i cambiamenti di un oggetto in modo asincrono.
+
{{jsxref("Object.preventExtensions()")}}
+
Impedisce ad un oggetto di essere esteso.
+
{{jsxref("Object.seal()")}}
+
Impedisce di eliminare le proprietà di un oggetto.
+
{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}
+
+

Imposta i prototipo (quindi la proprietà intena ​[[Prototype]]) di un oggetto.

+
+
+ +

{{jsOverrides("Function", "Methods", "create", "defineProperty", "defineProperties", "getOwnPropertyDescriptor", "getPrototypeOf")}}

+ +

Instanze di Object e l'oggetto prototipo Object

+ +

In JavaScript, tutti gli oggetti sono discendenti di Object; tutti gli oggetti ereditano metodi e proprietà di {{jsxref("Object.prototype")}}, anche se queste possono essere sovrascritte. Per esempio, i prototpipi degli altri costruttori sovrascrivono la proprietà constructor e forniscono un loro metodo toString(). I cambiamenti al prototipo di Object venogno estesi a tutti gli oggetti, eccetto quelli che sovrascrivono le proprietà e i metodi cambiati.

+ +

Poprietà

+ +

{{page('/it/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}

+ +

Metodi

+ +

{{page('/it/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}

+ +

Esempi

+ +

Usare Object con i valori null e undefined

+ +

Questi esempi restituiscono tutti lo stesso oggetto:

+ +
var o = {};
+ +
var o = new Object();
+
+ +
var o = new Object(undefined);
+
+ +
var o = new Object(null);
+
+ +

Usare Object per creare oggetti Boolean

+ +

I seguenti esempi assegnano alla variabile o un oggetto {{jsxref("Global_Objects/Boolean", "Boolean")}}:

+ +
var o = new Object(true);
+// Equivalente a new Boolean(true)
+ +
var o = new Object(Boolean());
+// Equivalente a new Boolean(false)
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition. Implemented in JavaScript 1.0StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

 

diff --git a/files/it/web/javascript/reference/global_objects/object/is/index.html b/files/it/web/javascript/reference/global_objects/object/is/index.html new file mode 100644 index 0000000000..ffb979fcb5 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/is/index.html @@ -0,0 +1,130 @@ +--- +title: Object.is() +slug: Web/JavaScript/Reference/Global_Objects/Object/is +tags: + - Comparazione + - Condizionale + - Condizione + - ECMAScript 2015 + - Equalità + - Italiano + - JavaScript + - Oggetto + - Uguaglianza + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/is +--- +
{{JSRef}}
+ +

Il metodo Object.is() determina se i due parametri di input hanno lo stesso valore.

+ +

Sintassi

+ +
Object.is(value1, value2);
+ +

Parametri

+ +
+
value1
+
Il primo valore da comparare.
+
value2
+
Il secondo valore da comparare.
+
+ +

Return value

+ +

A {{jsxref("Boolean")}} indicating whether or not the two arguments are the same value.

+ +

Descrizione

+ +

Object.is() determina se due valori sono uguali. Due valori sono uguali se sono :

+ + + +

Questo non è la stessa uguaglianza dell'operatore {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}. L'operatore {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} applica varie conversioni ad entrambi (se non sono dello stesso tipo) prima di testare l'uguaglianza (ad esempio, "" == false risultando true), ma Object.is non converte i loro valori.

+ +

Inoltre questo non è la stessa uguaglianza dell'operatore {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}. L'operatore {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}} (ed anche l'operatore {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}) trattano i numeri -0 e +0 come uguali e trattano {{jsxref("Number.NaN")}} differentemente da {{jsxref("NaN")}}.

+ +

Esempi

+ +
Object.is('foo', 'foo');     // true
+Object.is(window, window);   // true
+
+Object.is('foo', 'bar');     // false
+Object.is([], []);           // false
+
+var test = { a: 1 };
+Object.is(test, test);       // true
+
+Object.is(null, null);       // true
+
+// Casi speciali
+Object.is(0, -0);            // false
+Object.is(-0, -0);           // true
+Object.is(NaN, 0/0);         // true
+
+ +

Polyfill

+ +
if (!Object.is) {
+  Object.is = function(x, y) {
+    // Algoritmo SameValue
+    if (x === y) { // Steps 1-5, 7-10
+      // Steps 6.b-6.e: +0 != -0
+      return x !== 0 || 1 / x === 1 / y;
+    } else {
+     // Step 6.a: NaN == NaN
+     return x !== x && y !== y;
+    }
+  };
+}
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-object.is', 'Object.is')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-object.is', 'Object.is')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità coi browser

+ +
+ + +

{{Compat("javascript.builtins.Object.is")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/isfrozen/index.html b/files/it/web/javascript/reference/global_objects/object/isfrozen/index.html new file mode 100644 index 0000000000..b1220f1ae5 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/isfrozen/index.html @@ -0,0 +1,184 @@ +--- +title: Object.isFrozen() +slug: Web/JavaScript/Reference/Global_Objects/Object/isFrozen +tags: + - ECMAScript 5 + - Function + - Italian + - Italiano + - JavaScript + - JavaScript 1.8.5 + - Method + - Object + - Oggetto + - funzione + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isFrozen +--- +
{{JSRef}}
+ +

Il metodo Object.isFrozen() determina se un oggetto è {{jsxref("Object.freeze()", "congelato", "", 1)}}.

+ +
{{EmbedInteractiveExample("pages/js/object-isfrozen.html")}}
+ + + +

Syntax

+ +
Object.isFrozen(obj)
+ +

Parametri

+ +
+
obj
+
L'oggetto da controllare.
+
+ +

Valori di ritorno

+ +

Un {{jsxref("Boolean")}} che indica se l'oggetto è congelato oppure no.

+ +

Description

+ +

Un oggetto è congelato solo e soltanto se non è {{jsxref("Object.isExtensible()", "estensibile", "", 1)}}, tutte le sue proprietà sono non-configurabili, e tutte le sue proprietà "data" (che non sono proprietà "accessor", quindi non hanno componenti getter o setters) non sono sovrascrivibili.

+ +

Esempi

+ +
// Un nuovo oggetto è estensibile, quindi non è congelato.
+Object.isFrozen({}); // === false
+
+// Un oggetto vuoto che non è estensibile
+// è vacuamente congelato.
+var vacuouslyFrozen = Object.preventExtensions({});
+Object.isFrozen(vacuouslyFrozen); // === true
+
+// Un nuovo oggetto con una sola proprietà è estensibile,
+// quindi non è congelato.
+var oneProp = { p: 42 };
+Object.isFrozen(oneProp); // === false
+
+// Prevenire le estensioni dell'oggetto, comunque non
+// lo rende congelato, perché la proprietà è comunque
+// configurabile(e sovrascrivibile).
+Object.preventExtensions(oneProp);
+Object.isFrozen(oneProp); // === false
+
+// ...ma poi cancellare quella proprietà, rende l'oggetto
+// vacuamente congelato.
+delete oneProp.p;
+Object.isFrozen(oneProp); // === true
+
+// Un oggetto non-estensibile con una proprietà non-sovrascrivibile,
+// ma comunque configurabile, non è congelato.
+var nonWritable = { e: 'plep' };
+Object.preventExtensions(nonWritable);
+Object.defineProperty(nonWritable, 'e', {
+  writable: false
+}); // rende non-sovrascrivibile
+Object.isFrozen(nonWritable); // === false
+
+// Cambiare quella proprietà in non-configurabile
+// rende l'oggetto congelato.
+Object.defineProperty(nonWritable, 'e', {
+  configurable: false
+}); // rende non-configurabile
+Object.isFrozen(nonWritable); // === true
+
+// Un oggetto non-estensibile con una proprietà non-configurabile
+// ma comunque sovrascribile, non è congelato.
+var nonConfigurable = { release: 'the kraken!' };
+Object.preventExtensions(nonConfigurable);
+Object.defineProperty(nonConfigurable, 'release', {
+  configurable: false
+});
+Object.isFrozen(nonConfigurable); // === false
+
+// Cambiare quella proprietà in non-sovrascribile,
+// allora rende l'oggetto congelato.
+Object.defineProperty(nonConfigurable, 'release', {
+  writable: false
+});
+Object.isFrozen(nonConfigurable); // === true
+
+// Un oggetto non-estensibile con una configurabile
+// proprietà "accessor", non è congelato.
+var accessor = { get food() { return 'yum'; } };
+Object.preventExtensions(accessor);
+Object.isFrozen(accessor); // === false
+
+// ...ma poi rendere quella proprietà non-configurabile
+// congela l'oggetto.
+Object.defineProperty(accessor, 'food', {
+  configurable: false
+});
+Object.isFrozen(accessor); // === true
+
+// Ma il metodo più veloce per congelare un oggetto,
+// è utilizzare il metodo Object.freeze su di esso.
+var frozen = { 1: 81 };
+Object.isFrozen(frozen); // === false
+Object.freeze(frozen);
+Object.isFrozen(frozen); // === true
+
+// Per definizione, un oggetto congelato non è estensibile.
+Object.isExtensible(frozen); // === false
+
+// E sempre per definizione, un oggetto congelato è anche sigillato.
+Object.isSealed(frozen); // === true
+
+ +

Note

+ +

In ES5, se l'argomento di questo metodo non è un'oggetto, allora verrà generato un {{jsxref("TypeError")}}. In ES2015, un argomento che non è un oggetto verrà trattato come se fosse un normale oggetto già congelato, e perciò verrà semplicemente ritornato true.

+ +
Object.isFrozen(1);
+// TypeError: 1 non è un oggetto (codice in ES5)
+
+Object.isFrozen(1);
+// true                          (codice in ES2015)
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.12', 'Object.isFrozen')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.isfrozen', 'Object.isFrozen')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.isfrozen', 'Object.isFrozen')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Object.isFrozen")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/issealed/index.html b/files/it/web/javascript/reference/global_objects/object/issealed/index.html new file mode 100644 index 0000000000..d3bdf1b76b --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/issealed/index.html @@ -0,0 +1,146 @@ +--- +title: Object.isSealed() +slug: Web/JavaScript/Reference/Global_Objects/Object/isSealed +tags: + - ECMAScript 5 + - Function + - Italian + - Italiano + - JavaScript + - JavaScript 1.8.5 + - Method + - Object + - Oggetto + - funzione + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/isSealed +--- +
{{JSRef}}
+ +

Il metodo Object.isSealed() determina se un oggetto è sigillato.

+ +
{{EmbedInteractiveExample("pages/js/object-issealed.html")}}
+ + + +

Syntax

+ +
Object.isSealed(obj)
+ +

Parametri

+ +
+
obj
+
L'oggetto da controllare.
+
+ +

Valore di ritorno

+ +

Un {{jsxref("Boolean")}} che indica se l'oggetto è congelato oppure no.

+ +

Descrizione

+ +

Ritorna true se l'oggetto è sigillato, altrimenti false. Un oggetto  è sigillato se non è {{jsxref("Object.isExtensible", "estensibile", "", 1)}} e se tutte le sue proprietà sono non-configurabili e non possono essere rimosse (ma non necessariamente non-sovrascrivibili).

+ +

Esempi

+ +
// Gli oggetti non sono sigillati di default.
+var empty = {};
+Object.isSealed(empty); // === false
+
+// Se rendi un oggetto vuoto non-estensibile,
+// è vacuamente sigillato.
+Object.preventExtensions(empty);
+Object.isSealed(empty); // === true
+
+// Lo stesso non si verifica con un oggetto non vuoto,
+// a meno che le sue proprietà non sono tutte non-configurabili.
+var hasProp = { fee: 'fie foe fum' };
+Object.preventExtensions(hasProp);
+Object.isSealed(hasProp); // === false
+
+// Ma rendere tutte le sue proprietà non-configurabili
+// rende l'oggetto effettivamente sigillato.
+Object.defineProperty(hasProp, 'fee', {
+  configurable: false
+});
+Object.isSealed(hasProp); // === true
+
+// Il metodo più veloce per sigillare un oggetto, ovviamente,
+// è il metodo Object.seal.
+var sealed = {};
+Object.seal(sealed);
+Object.isSealed(sealed); // === true
+
+// Un oggetto sigillato è, per definizione, non-estensibile.
+Object.isExtensible(sealed); // === false
+
+// Un oggetto sigillato può anche essere congelato,
+// ma non è necessario.
+Object.isFrozen(sealed); // === true
+// (tutte le proprietà sono anche non-sovrascrivibili)
+
+var s2 = Object.seal({ p: 3 });
+Object.isFrozen(s2); // === false
+// ('p' è comunque sovrascrivibile)
+
+var s3 = Object.seal({ get p() { return 0; } });
+Object.isFrozen(s3); // === true
+// (per le proprietà "accessor", è importante solo la configurabilità della proprietà)
+
+ +

Note

+ +

In ES5, se l'argomento di questo metodo non è un'oggetto, allora verrà generato un {{jsxref("TypeError")}}. In ES2015, un argomento che non è un oggetto verrà trattato come se fosse un normale oggetto già sigillato, e perciò verrà semplicemente ritornato true.

+ +
Object.isSealed(1);
+// TypeError: 1 non è un oggetto (codice in ES5)
+
+Object.isSealed(1);
+// true                          (codice in ES2015)
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.11', 'Object.isSealed')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.issealed', 'Object.isSealed')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.issealed', 'Object.isSealed')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Object.isSealed")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/keys/index.html b/files/it/web/javascript/reference/global_objects/object/keys/index.html new file mode 100644 index 0000000000..ed748c0fad --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/keys/index.html @@ -0,0 +1,167 @@ +--- +title: Object.keys() +slug: Web/JavaScript/Reference/Global_Objects/Object/keys +tags: + - ECMAScript5 + - JavaScript + - JavaScript 1.8.5 + - Metodi + - Oggetti +translation_of: Web/JavaScript/Reference/Global_Objects/Object/keys +--- +
+ {{JSRef("Global_Objects", "Object")}}
+

Sommario

+

Il metodo Object.keys() restituisce un array contenente le proprietà enumerabili di un dato oggetto, nel medesimo ordine fornito da un ciclo for...in  (la differenza è che un ciclo for-in enumera anche le proprietà nella catena di prototipi).

+

Sintassi

+
Object.keys(obj)
+

Parametri

+
+
+ obj
+
+ L'oggetto del quale si devono restituire le proprietà enumerabili.
+
+

Descrizione

+

Object.keys restituisce un array i quali elementi sono stringhe corrispondenti alle proprietà enumerabili trovate direttamente in obj. L'ordine delle proprietà è lo stesso di quello dato ciclando manualmente sulle proprietà dell'oggetto.

+

Esempi

+
var arr = ["a", "b", "c"];
+alert(Object.keys(arr)); // chiama alert con argomento "0,1,2"
+
+// array like object
+var obj = { 0 : "a", 1 : "b", 2 : "c"};
+alert(Object.keys(obj)); // chiama alert con argomento "0,1,2"
+
+// array like object with random key ordering
+var an_obj = { 100: "a", 2: "b", 7: "c"};
+alert(Object.keys(an_obj)); // chiama alert con argomento "2, 7, 100"
+
+// getFoo is property which isn't enumerable
+var my_obj = Object.create({}, { getFoo : { value : function () { return this.foo } } });
+my_obj.foo = 1;
+
+alert(Object.keys(my_obj)); // chiama alert con foo come unico argomento
+
+

Per ottenere tutte le proprietà, anche quelle non enumerabili, si veda {{jsxref("Object.getOwnPropertyNames")}}.

+

Polyfill

+

Per aggiungere un supporto equivalente a Object.keys, in ambienti datati che non lo supportino nativamente, si copi il seguente frammento di codice:

+
// Da https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
+if (!Object.keys) {
+  Object.keys = (function () {
+    'use strict';
+    var hasOwnProperty = Object.prototype.hasOwnProperty,
+        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
+        dontEnums = [
+          'toString',
+          'toLocaleString',
+          'valueOf',
+          'hasOwnProperty',
+          'isPrototypeOf',
+          'propertyIsEnumerable',
+          'constructor'
+        ],
+        dontEnumsLength = dontEnums.length;
+
+    return function (obj) {
+      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
+        throw new TypeError('Object.keys called on non-object');
+      }
+
+      var result = [], prop, i;
+
+      for (prop in obj) {
+        if (hasOwnProperty.call(obj, prop)) {
+          result.push(prop);
+        }
+      }
+
+      if (hasDontEnumBug) {
+        for (i = 0; i < dontEnumsLength; i++) {
+          if (hasOwnProperty.call(obj, dontEnums[i])) {
+            result.push(dontEnums[i]);
+          }
+        }
+      }
+      return result;
+    };
+  }());
+}
+
+

Si noti che il codice sopra include chiavi non-enumerabili in IE7 (e forse IE8), nel caso in cui si passi un oggetto proveniente da un'altra finestra.

+

Per un semplice polyfill, si veda Javascript - Object.keys Browser Compatibility.

+

Specifiche

+ + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}{{Spec2('ES5.1')}}Definizione iniziale.
+ implementato in in JavaScript 1.8.5
{{SpecName('ES6', '#sec-object.keys', 'Object.keys')}}{{Spec2('ES6')}} 
+

Compatibilità dei browser

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Supporto base4 (2.0)59125
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Supporto base{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+

Basato su Kangax's compat table.

+

Vedere anche

+ diff --git a/files/it/web/javascript/reference/global_objects/object/observe/index.html b/files/it/web/javascript/reference/global_objects/object/observe/index.html new file mode 100644 index 0000000000..4307b4e75f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/observe/index.html @@ -0,0 +1,189 @@ +--- +title: Object.observe() +slug: Web/JavaScript/Reference/Global_Objects/Object/observe +translation_of: Archive/Web/JavaScript/Object.observe +--- +
{{JSRef}} {{obsolete_header}}
+ +

Sommario

+ +

Il metodo Object.observe() è usato per l'osservazione asincrona dei cambiamenti di un oggetto. Esso fornisce uno stream dei cambiamenti nell'ordine in cui si verificano.

+ +

Sintassi

+ +
Object.observe(obj, callback[, acceptList])
+ +

Parametri

+ +
+
obj
+
L'oggetto che verrà osservato.
+
callback
+
La funzione richiamata ogni volta che si verificano delle modifiche, con i seguenti argomenti: +
+
changes
+
Un array di oggetti di oggetti che rappresentano una modifica. Le properties di questi oggetti sono: +
    +
  • name: Il nome della property che è stata modificata.
  • +
  • object: L'oggetto modificato dopo che la modifica è avvenuta.
  • +
  • type: Una stringa che indica il tipo di modifica in atto. Può essere valorizzata con "add", "update" o "delete".
  • +
  • oldValue: Solo per i tipi "update" e "delete". Indica il valore prima della modifica.
  • +
+
+
+
+
acceptList
+
La lista dei tipi di modifiche che possono essere osservate su un dato oggetto per un dato callback. Se omesso, sarà usato l'array ["add", "update", "delete", "reconfigure", "setPrototype", "preventExtensions"].
+
+ +

Descrizione

+ +

La funzione callback è chiamata ogni volta che una modifica viene fatta sull'obj. Ad essa viene passata un'array di tutte le modifiche, nell'ordine in cui si verificano.

+ +

Esempi

+ +

Esempio: Log di tutti e sei differenti tipi

+ +
var obj = {
+  foo: 0,
+  bar: 1
+};
+
+Object.observe(obj, function(changes) {
+  console.log(changes);
+});
+
+obj.baz = 2;
+// [{name: 'baz', object: <obj>, type: 'add'}]
+
+obj.foo = 'hello';
+// [{name: 'foo', object: <obj>, type: 'update', oldValue: 0}]
+
+delete obj.baz;
+// [{name: 'baz', object: <obj>, type: 'delete', oldValue: 2}]
+
+Object.defineProperty(obj, 'foo', {writable: false});
+// [{name: 'foo', object: <obj>, type: 'reconfigure'}]
+
+Object.setPrototypeOf(obj, {});
+// [{name: '__proto__', object: <obj>, type: 'setPrototype', oldValue: <prototype>}]
+
+Object.seal(obj);
+// [
+//   {name: 'foo', object: <obj>, type: 'reconfigure'},
+//   {name: 'bar', object: <obj>, type: 'reconfigure'},
+//   {object: <obj>, type: 'preventExtensions'}
+// ]
+
+ +

Esempio: Data Binding

+ +
// A user model
+var user = {
+  id: 0,
+  name: 'Brendan Eich',
+  title: 'Mr.'
+};
+
+// Create a greeting for the user
+function updateGreeting() {
+  user.greeting = 'Hello, ' + user.title + ' ' + user.name + '!';
+}
+updateGreeting();
+
+Object.observe(user, function(changes) {
+  changes.forEach(function(change) {
+    // Any time name or title change, update the greeting
+    if (change.name === 'name' || change.name === 'title') {
+      updateGreeting();
+    }
+  });
+});
+
+ +

Esempio: Tipo di modifica personalizzata

+ +
// A point on a 2D plane
+var point = {x: 0, y: 0, distance: 0};
+
+function setPosition(pt, x, y) {
+  // Performing a custom change
+  Object.getNotifier(pt).performChange('reposition', function() {
+    var oldDistance = pt.distance;
+    pt.x = x;
+    pt.y = y;
+    pt.distance = Math.sqrt(x * x + y * y);
+    return {oldDistance: oldDistance};
+  });
+}
+
+Object.observe(point, function(changes) {
+  console.log('Distance change: ' + (point.distance - changes[0].oldDistance));
+}, ['reposition']);
+
+setPosition(point, 3, 4);
+// Distance change: 5
+
+ +

Specifiche

+ +

Argomentazione proposta per ECMAScript 7.

+ +

Compatibilita browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaratteristicaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto base{{CompatChrome("36")}}{{CompatNo}}{{CompatNo}}{{CompatOpera("23")}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatNo}}{{CompatChrome("36")}}{{CompatNo}}{{CompatNo}}{{CompatOpera("23")}}{{CompatNo}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/prototype/index.html b/files/it/web/javascript/reference/global_objects/object/prototype/index.html new file mode 100644 index 0000000000..ea834e65de --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/prototype/index.html @@ -0,0 +1,214 @@ +--- +title: Object.prototype +slug: Web/JavaScript/Reference/Global_Objects/Object/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef("Global_Objects", "Object")}}
+ +

Sommario

+ +

La proprietà Object.prototype rappresenta l'oggetto prototipo di {{jsxref("Global_Objects/Object", "Object")}}.

+ +

{{js_property_attributes(0, 0, 0)}}

+ +

Descrizione

+ +

In JavaScript, tutti gli oggetti sono discendenti di {{jsxref("Global_Objects/Object", "Object")}}; tutti gli oggetti ereditano metodi e proprietà di Object.prototype (tranne nel caso l'oggetto abbia il prototipo uguale a {{jsxref("Global_Objects/null", "null")}}, quindi creati con il metodo {{jsxref("Object.create", "Object.create(null)")}}), anche se questi possono essere sovrascritti. Per esempio, i prototipi degli altri costruttori sovrascrivono la proprietà constructor e forniscono un loro metodo {{jsxref("Object.prototype.toString", "toString()")}}. I cambiamenti al prototipo di Object vengono estesi a tutti gli oggetti, eccetto quelli che sovrascrivono le proprietà e i metodi cambiati.

+ +

Proprietà

+ +
+
{{jsxref("Object.prototype.constructor")}}
+
Specifica la funzione che ha creato l'oggetto a partire dal prototipo.
+
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
+
È un riferimento all'oggetto usato come prototipo quando l'oggetto è stato istanziato.
+
{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}
+
Permette di definire una funzione che venga chiamata quando viene chiamato un metodo non definito.
+
{{jsxref("Object.prototype.__count__")}} {{obsolete_inline}}
+
Rappresenta il numero di proprietà persenti in un oggetto, ma è stato rimosso.
+
{{jsxref("Object.prototype.__parent__")}} {{obsolete_inline}}
+
Rappresenta il contesto di un oggetto, ma è stato rimosso.
+
+ +

Metodi

+ +
+
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associa una funzione a una proprietà di un oggetto. Quando si tenta di leggere il valore di tale proprietà, viene eseguita la funzione e restituito il valore che restituisce.
+
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associa una funzione a una proprietà di un oggetto. Quando si tenta di cambiare il valore di tale proprietà, viene eseguita la funzione.
+
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Restituisce la funzione definita tramite {{jsxref("Object.prototype.defineGetter", "__defineGetter__()")}}.
+
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Restituisce la funzione definita tramite {{jsxref("Object.prototype.defineSetter", "__defineSetter__()")}}.
+
{{jsxref("Object.prototype.hasOwnProperty()")}}
+
Determina se l'oggetto contiene direttamente una proprietà (non ereditata tramite il prototipo).
+
{{jsxref("Object.prototype.isPrototypeOf()")}}
+
Determina se un oggetto fa parte della catena dei prototipi dell'oggetto sul quale è richiamato questo metodo.
+
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
+
Determina se l'attributo DontEnum di ECMAScript interno è presente.
+
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
+
Restituisce una stringa contenente il codice sorgente di un oggetto rappresentante l'oggetto sul quale questo metodo viene richiamato; puoi usare questo valore per creare un nuovo oggetto.
+
{{jsxref("Object.prototype.toLocaleString()")}}
+
Richiama {{jsxref("Object.prototype.toString", "toString()")}}.
+
{{jsxref("Object.prototype.toString()")}}
+
Restituisce la rappresentazione dell'oggetto sotto forma di stringa.
+
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
+
Termina di osservare i cambiamenti di una proprietà dell'oggetto.
+
{{jsxref("Object.prototype.valueOf()")}}
+
Ritorna il valore primitivo dell'oggetto.
+
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
+
Inizia a osservare i cambiamenti di una proprietà di un oggetto.
+
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
+
Esegue una stringa di codice JavaScript nel contesto dell'oggetto, ma è stato rimosso.
+
+ +

Esempi

+ +

Siccome in JavaScript gli oggetti non sono sub-classabili in modo "standard", il prototipo è una soluzione utile per creare un oggetto che funzioni da "classe di base" che contenga dei metodi comuni a più oggetti. Per esempio:

+ +
var Persona = function() {
+  this.saParlare = true;
+};
+
+Persona.prototype.saluta = function() {
+  if (this.saParlare) {
+    console.log('Ciao, mi chiamo ' + this.nome);
+  }
+};
+
+var Dipendente = function(nome, titolo) {
+  Persona.call(this);
+  this.nome = nome;
+  this.titolo = titolo;
+};
+
+Dipendente.prototype = Object.create(Persona.prototype);
+Dipendente.prototype.constructor = Dipendente;
+
+Dipendente.prototype.saluta = function() {
+  if (this.saParlare) {
+    console.log('Ciao mi chiamo ' + this.nome + ' e lavoro come ' + this.titolo);
+  }
+};
+
+var Cliente = function(nome) {
+  Persona.call(this);
+  this.nome = nome;
+};
+
+Cliente.prototype = Object.create(Persona.prototype);
+Cliente.prototype.constructor = Cliente;
+
+var Mimo = function(nome) {
+  Persona.call(this);
+  this.nome = nome;
+  this.saParlare = false;
+};
+
+Mimo.prototype = Object.create(Persona.prototype);
+Mimo.prototype.constructor = Mimo;
+
+var bob = new Dipendente('Bob', 'Architetto');
+var joe = new Cliente('Joe');
+var rg = new Dipendente('Red Green', 'Tuttofare');
+var mike = new Cliente('Mike');
+var mime = new Mimo('Mimo');
+bob.saluta();
+joe.saluta();
+rg.saluta();
+mike.saluta();
+mime.saluta();
+
+ +

Stamperà:

+ +
Ciao, mi chiamo Bob e lavoro come Architetto
+Ciao, mi chiamo Joe
+Ciao, mi chiamo Red Green, e lavoro come Tuttofare
+Ciao, mi chiamo Mike
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition. Implemented in JavaScript 1.0.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/seal/index.html b/files/it/web/javascript/reference/global_objects/object/seal/index.html new file mode 100644 index 0000000000..4d301b568c --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/seal/index.html @@ -0,0 +1,157 @@ +--- +title: Object.seal() +slug: Web/JavaScript/Reference/Global_Objects/Object/seal +tags: + - ECMAScript 5 + - Italian + - Italiano + - JavaScript + - JavaScript 1.8.5 + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/seal +--- +
{{JSRef}}
+ +

Il metodo Object.seal() "sigilla" un oggetto, e ciò rende impossibile l'aggiunta di nuove proprietà e rende tutte le proprietà esistenti non-configurabili. I valori delle proprietà presenti possono comunque essere cambiati, finché sono sovrascrivibili.

+ +
{{EmbedInteractiveExample("pages/js/object-prototype-seal.html")}}
+ + + +

Sintassi

+ +
Object.seal(obj)
+ +

Parametri

+ +
+
obj
+
L'oggetto da sigillare.
+
+ +

Valore di ritorno

+ +

L'oggetto sigillato.

+ +

Descrizione

+ +

Di default, gli oggetti sono {{jsxref("Object.isExtensible()", "estensibili", "", 1)}} (possono essergli aggiunte nuove proprietà). Sigillare un oggetto rende impossibile l'aggiunta di nuove proprietà e rende tutte le proprietà esistenti non-configurabili. Questo rende le proprietà dell'oggetto statiche ed immutabili. Rendere tutte le proprietà non-configurabili, inoltre, rende impossibile la conversione da proprietà "data" a proprietà "accessor" e viceversa, ma non rende impossibile la modifica dei valori delle proprietà "data". Qualsiasi tentativo di aggiungere o rimuovere proprietà ad un oggetto sigillato, o convertire una proprietà "data" in una proprietà "accessor" o viceversa, fallirebbe, o in modo silenzioso o  attraverso il ritorno di un {{jsxref("TypeError")}} (più frequentemente, ma non necessariamente, quest'ultimo scenario accadrebbe in {{jsxref("Strict_mode", "strict mode", "", 1)}}).

+ +

Le catene di prototipi non vengono sigillate. Invece, la proprietà {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} viene sigillata.

+ +

Ritorna l'oggetto passato ma sigillato.

+ +

Examples

+ +
var obj = {
+  prop: function() {},
+  foo: 'bar'
+};
+
+// Nuove proprietà potrebbero essere aggiunte, proprietà esistenti
+// potrebbero essere modificate o rimosse.
+obj.foo = 'baz';
+obj.lumpy = 'woof';
+delete obj.prop;
+
+var o = Object.seal(obj);
+
+o === obj; // true
+Object.isSealed(obj); // === true
+
+// Cambiare proprietà su un oggetto sigillato
+// è ancora possibile.
+obj.foo = 'quux';
+
+// Ma non puoi convertire proprietà "data" in proprietà "accessor"
+// o viceversa.
+Object.defineProperty(obj, 'foo', {
+  get: function() { return 'g'; }
+}); // genera un TypeError
+
+// Ora, qualunque cambiamento, eccetto i valori delle proprietà,
+// fallirà.
+obj.quaxxor = 'the friendly duck';
+// silenziosamente non aggiunge la proprietà, per cui non genera errori od eccezioni
+delete obj.foo;
+// silenziosamente non rimuove la proprietà, per cui non genera errori od eccezioni
+
+// ...ed in strict mode, aggiungere o rimuovere proprietà
+// genererà TypeErrors.
+function fail() {
+  'use strict';
+  delete obj.foo; // genera un TypeError
+  obj.sparky = 'arf'; // genera un TypeError
+}
+fail();
+
+// Anche aggiungere proprietà tramite
+// Object.defineProperty genererà l'errore.
+Object.defineProperty(obj, 'ohai', {
+  value: 17
+}); // genera un TypeError
+Object.defineProperty(obj, 'foo', {
+  value: 'eit'
+}); // modifica il valore di una proprietà esistente
+
+ +

Note

+ +

In ES5, se l'argomento di questo metodo non è un'oggetto, allora verrà generato un {{jsxref("TypeError")}}. In ES2015, un argomento che non è un oggetto verrà trattato come se fosse un normale oggetto già sigillato, e verrà perciò semplicemente ritornato.

+ +
Object.seal(1);
+// TypeError: 1 non è un oggetto (codice in ES5)
+
+Object.seal(1);
+// 1                             (codice in ES2015)
+
+ +

Differenza con Object.freeze()

+ +

Le proprietà esistenti in oggetti congelati con Object.freeze() sono rese immutabili. Gli oggetti sigillati con Object.seal() possono ricevere modifiche alle proprietà esistenti.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.8', 'Object.seal')}}{{Spec2('ES5.1')}}Definizione iniziale. Implementato in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.seal', 'Object.seal')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-object.seal', 'Object.seal')}}{{Spec2('ESDraft')}}
+ +

Compatibilità con i browser

+ +
+ + +

{{Compat("javascript.builtins.Object.seal")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/object/tostring/index.html b/files/it/web/javascript/reference/global_objects/object/tostring/index.html new file mode 100644 index 0000000000..5a77ea1a3e --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/object/tostring/index.html @@ -0,0 +1,170 @@ +--- +title: Object.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Object/toString +tags: + - JavaScript + - Method + - Object + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString +--- +
{{JSRef("Global_Objects", "Object")}}
+ +

Sommario

+ +

Il metodo toString() restituisce una stringa a che rappresenta l'oggetto.

+
{{EmbedInteractiveExample("pages/js/object-prototype-tostring.html")}}
+ + +

Sintassi

+ +
obj.toString()
+ +

Descrizione

+ +

Ogni oggetto ha un metodo toString() che è automaticamente chiamato quando l'oggetto deve essere rappresentato come valore testuale o quando l'oggetto è referenziato in un contesto in cui viene attesa una stringa. Di default, il metodo toString() è ereditato da ogni oggetto che discende da Object. Se il metodo non è sovrascritto in un oggetto personalizzato, toString() restituisce "[object type]", dove type è il tipo di oggetto. Il codice di seguito lo illustra:

+ +
var o = new Object();
+o.toString();           // returns [object Object]
+
+ +
+

Nota: A partire da JavaScript 1.8.5 toString() richiamato su {{jsxref("Global_Objects/null", "null")}} restituisce [object Null], e {{jsxref("Global_Objects/undefined", "undefined")}} restituisce [object Undefined], come definito nella versione 5 di ECMAScript e nei succcessivi Errata. Vedi {{anch("Example:_Using_toString_to_detect_object_type", "Using toString to detect object type")}}.

+
+ +

Esempi

+ +

Esempio: Sovrascrittura del metodo di default toString 

+ +

Puoi creare una funzione che deve essere richiamata al posto del default metodo toString(). Il metodo toString() non prende argomenti e deve restituire una stringa. Esso può assumere qualunque valore tu voglia, ma sarà molto utile se comunichi informazioni sull'oggetto.

+ +

Il codice seguente definisce l'oggetto Dog e crea theDog, ovvero un oggetto di tipo 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');
+
+ +

Richiamando il metodo toString() su questo oggetto personalizzato, esso restituisce il valore di default ereditato da {{jsxref("Global_Objects/Object", "Object")}}:

+ +
theDog.toString(); // returns [object Object]
+
+ +

Il codice seguente crea e assegna il metodo dogToString() per sovrascrivere il metodo di default toString(). Questa funzione genera una stringa contenente i valori name, breed, color e sex dell'oggetto, nella forma di "property = value;".

+ +
Dog.prototype.toString = function dogToString() {
+  var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed;
+  return ret;
+}
+
+ +

Col precedente codice, la funzione dogToString() è richiamata automaticamente da JavaScript ogni volta che l'oggetto theDog è usato in un contesto string, e restituisce la seguente stringa:

+ +
Dog Gabby is a female chocolate Lab
+
+ +

Esempio: Uso di toString() per individuare l'oggetto class

+ +

toString() può essere usato con ogni oggetto e permette di ottenere il suo class. Per usare Object.prototype.toString() con ogni oggetto, c'è bisogno di richiamare {{jsxref("Function.prototype.call()")}} o {{jsxref("Function.prototype.apply()")}} su di esso, passando l'oggetto che si cerca di ispezionare come primo parametro chiamato 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]
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificheStatoCommento
ECMAScript 1 Edizione.StandardDefinizione iniziale. Implementato in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.4.2', 'Object.prototype.toString')}}{{Spec2('ES5.1')}}Richiamato su {{jsxref("Global_Objects/null", "null")}} restituisce [object Null], e {{jsxref("Global_Objects/undefined", "undefined")}} restituisce [object Undefined]
{{SpecName('ES6', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}{{Spec2('ES6')}}
+ +

Compatibilità browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaratteristicheChromeFirefox (Gecko)Internet ExplorerOperaSafari
Support Base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Support Base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/parsefloat/index.html b/files/it/web/javascript/reference/global_objects/parsefloat/index.html new file mode 100644 index 0000000000..f587064676 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/parsefloat/index.html @@ -0,0 +1,139 @@ +--- +title: parseFloat() +slug: Web/JavaScript/Reference/Global_Objects/parseFloat +translation_of: Web/JavaScript/Reference/Global_Objects/parseFloat +--- +
+
+
+ {{jsSidebar("Objects")}}
+
+
+

Sommario

+

La funzione parseFloat()  riceve una stringa come argomento e ritorna un numero in virgola mobile.

+

Sintassi

+
parseFloat(string)
+

Parametri

+
+
+ string
+
+ Una stringa che rapprestena il valore da analizzare.
+
+

Descrizione

+

parseFloat è una funzione primo livello ( globale ) e non è associata con nessun oggetto.

+

parseFloat analizza il parametro rappresentato da una stringa e ritorna un numero in virgola mobile. Se rileva un carattere diverso da segni ( + o - ), numeri ( 0 - 9 ), punto di separazione decimale o un esponente, la funzione ritorna il valore fino a quel punto ignorando il carattere rilevato e tutti quelli successvi. Gli spazi bianchi, iniziali e finali, sono consentiti.

+

Se il primo carattere dell'argomento non può essere analizzato, parseFloat ritorna NaN.

+

Per questioni aritmetiche, il valore NaN non è di tipo numerico. Per determinare se il risultato di ParseFloat è  NaN occorre chiamare la funzione {{jsxref("Global_Objects/isNaN", "isNaN")}}. Se NaN viene utilizzato per un operazione aritmetica, la stessa risulterà NaN.

+

parseFloat può analizzare e ritornare il valore Infinity. La funzione {{jsxref("Global_Objects/isNaN", "isNaN")}} consente di determinare se il risultato è un numero finito  (not Infinity-Infinity, o NaN).

+

Esempi

+

Esempio: parseFloat ritorna un numero

+

Tutti gli esempi seguenti ritornano 3.14

+
parseFloat("3.14");
+parseFloat("314e-2");
+parseFloat("0.0314E+2");
+parseFloat("3.14altri caratteri non numerici");
+
+

Esempio: parseFloat ritorna NaN

+

L'esempio seguente ritorna il valore NaN

+
parseFloat("FF2");
+
+

Una funzione di analisi più approfondita.

+

Talvolta può essere necessario un maggior controllo sulla funzione di parse, le regular expression possono aiutare :

+
var filterFloat = function (value) {
+    if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
+      .test(value))
+      return Number(value);
+  return NaN;
+}
+
+console.log(filterFloat('421'));               // 421
+console.log(filterFloat('-421'));              // -421
+console.log(filterFloat('+421'));              // 421
+console.log(filterFloat('Infinity'));          // Infinito
+console.log(filterFloat('1.61803398875'));     // 1.61803398875
+console.log(filterFloat('421e+0'));            // NaN
+console.log(filterFloat('421hop'));            // NaN
+console.log(filterFloat('hop1.61803398875'));  // NaN
+
+

Nota: questo codice è a scopo esplicativo. La funzione non accetta numeri validi come 1. o .5+

+

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
ECMAScript 1a Edizione.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.2.3', 'parseFloat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-parsefloat-string', 'parseFloat')}}{{Spec2('ES6')}} 
+

Compatibilità Browser

+

{{ 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() }}
+
+

Leggi anche:

+ diff --git a/files/it/web/javascript/reference/global_objects/parseint/index.html b/files/it/web/javascript/reference/global_objects/parseint/index.html new file mode 100644 index 0000000000..c6300b4b3e --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/parseint/index.html @@ -0,0 +1,190 @@ +--- +title: parseInt() +slug: Web/JavaScript/Reference/Global_Objects/parseInt +translation_of: Web/JavaScript/Reference/Global_Objects/parseInt +--- +
{{jsSidebar("Objects")}}
+ +

La funzione parseInt() analizza un argomento stringa e restituisce un numero intero della radice specificata (la base nei sistemi numerici matematici).

+ +
{{EmbedInteractiveExample("pages/js/globalprops-parseint.html")}}
+ + + +

Sintassi

+ +
parseInt(string, radix);
+ +

Parametri

+ +
+
string
+
Il valore da analizzare. Se l'argomento string non è una stringa, viene convertito in una stringa (utilizzando l'operazione astratta ToString). Gli spazi bianchi iniziali nell'argomento stringa vengono ignorati.
+
radix
+
Un numero intero compreso tra 2 e 36 che rappresenta la radice (la base nei sistemi numerici matematici) della stringa sopra menzionata.
+
+ +

Valore di ritorno

+ +

Un numero intero analizzato dalla stringa specificata. Se il primo carattere non può essere convertito in un numero, viene restituito {{jsxref("NaN")}}.

+ +

Descrizione

+ +

La funzione parseInt converte il suo primo argomento in una stringa, lo analizza e restituisce un numero intero o NaN. Se non è NaN, il valore restituito sarà l'intero che è il primo argomento preso come numero nella radice specificata (base). Ad esempio, una radice di 10 indica la conversione da un numero decimale, 8 ottali, 16 esadecimali e così via. Per le radici sopra 10, le lettere dell'alfabeto indicano numeri maggiori di 9. Ad esempio, per i numeri esadecimali (base 16), vengono utilizzate le lettere da A a F.

+ +

Se parseInt incontra un carattere che non è un numero nella radice specificata, lo ignora e tutti i caratteri successivi e restituisce il valore intero analizzato fino a quel punto. parseInt tronca i numeri ai valori interi. Sono ammessi spazi iniziali e finali.

+ +

Poiché alcuni numeri includono il carattere e nella loro rappresentazione di stringa (ad esempio 6.022e23), l'uso di parseInt per troncare valori numerici produrrà risultati imprevisti se utilizzato su numeri molto grandi o molto piccoli. parseInt non dovrebbe essere usato come sostituto di {{jsxref("Math.floor()")}}.

+ +

Se radix è undefined o 0 (o assente), JavaScript assume quanto segue:

+ + + +

Se il primo carattere non può essere convertito in un numero, parseInt restituisce NaN.

+ +

Per scopi aritmetici, il valore NaN vnon è un numero in nessuna radice. È possibile chiamare la funzione {{jsxref("isNaN")}} per determinare se il risultato di parseInt è NaN. Se NaN viene passato alle operazioni aritmetiche, i risultati dell'operazione saranno anche NaN.

+ +

Per convertire il numero nella sua stringa letterale in una particolare radix, usa intValue.toString(radix).

+ +

Esempi

+ +

Usare parseInt

+ +

Tutti gli esempi seguenti restituiscono 15:

+ +
parseInt('0xF', 16);
+parseInt('F', 16);
+parseInt('17', 8);
+parseInt(021, 8);
+parseInt('015', 10);   // parseInt(015, 10); ritornerà 15
+parseInt(15.99, 10);
+parseInt('15,123', 10);
+parseInt('FXX123', 16);
+parseInt('1111', 2);
+parseInt('15 * 3', 10);
+parseInt('15e2', 10);
+parseInt('15px', 10);
+parseInt('12', 13);
+
+ +

I seguenti esempi restituiscono tutti NaN:

+ +
parseInt('Hello', 8); // Non è un numero
+parseInt('546', 2);   // Le cifre non sono valide per le rappresentazioni binarie
+
+ +

Tutti gli esempi seguenti restituiscono -15:

+ +
parseInt('-F', 16);
+parseInt('-0F', 16);
+parseInt('-0XF', 16);
+parseInt(-15.1, 10);
+parseInt('-17', 8);
+parseInt('-15', 10);
+parseInt('-1111', 2);
+parseInt('-15e1', 10);
+parseInt('-12', 13);
+
+ +

Tutti gli esempi seguenti restituiscono 4:

+ +
parseInt(4.7, 10);
+parseInt(4.7 * 1e22, 10); // Il numero molto grande diventa 4
+parseInt(0.00000000000434, 10); // Il numero molto piccolo diventa 4
+
+ +

L'esempio seguente restituisce 224:

+ +
parseInt('0e0', 16);
+
+ +

Interpretazioni ottali senza radix

+ +

Sebbene scoraggiato da ECMAScript 3 e proibito da ECMAScript 5, molte implementazioni interpretano una stringa numerica che inizia con uno 0 iniziale come ottale. Il seguente potrebbe avere un risultato ottale o potrebbe avere un risultato decimale. Specifica sempre una radice per evitare questo comportamento inaffidabile.

+ +
parseInt('0e0'); // 0
+parseInt('08'); // 0, '8' non è una cifra ottale.
+
+ +

ECMAScript 5 rimuove l'interpretazione ottale

+ +

La specifica ECMAScript 5 della funzione parseInt non consente più alle implementazioni di trattare le stringhe che iniziano con un carattere 0 come valori ottali. ECMAScript 5 afferma:

+ +

La funzione parseInt produce un valore intero dettato dall'interpretazione del contenuto dell'argomento stringa in base alla radice specificata. Lo spazio bianco principale nella stringa viene ignorato. Se radix non è definito o 0, si presume che sia 10 tranne quando il numero inizia con le coppie di caratteri 0x0X, nel qual caso si assume una radice di 16.

+ +

Ciò differisce da ECMAScript 3, che scoraggiava, ma consentiva l'interpretazione ottale.

+ +

Molte implementazioni non hanno adottato questo comportamento a partire dal 2013 e, poiché i browser più vecchi devono essere supportati, specificare sempre una radice.

+ +

Una funzione di analisi più rigorosa

+ +

A volte è utile avere un modo più rigoroso di analizzare i valori int. Le espressioni regolari possono aiutare:

+ +
var filterInt = function(value) {
+  if (/^(-|\+)?(\d+|Infinity)$/.test(value))
+    return Number(value);
+  return NaN;
+}
+
+console.log(filterInt('421'));               // 421
+console.log(filterInt('-421'));              // -421
+console.log(filterInt('+421'));              // 421
+console.log(filterInt('Infinity'));          // Infinity
+console.log(filterInt('421e+0'));            // NaN
+console.log(filterInt('421hop'));            // NaN
+console.log(filterInt('hop1.61803398875'));  // NaN
+console.log(filterInt('1.61803398875'));     // NaN
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{SpecName('ES5.1', '#sec-15.1.2.2', 'parseInt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-parseint-string-radix', 'parseInt')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-parseint-string-radix', 'parseInt')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.parseInt")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/promise/all/index.html b/files/it/web/javascript/reference/global_objects/promise/all/index.html new file mode 100644 index 0000000000..4d1c9a970c --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/promise/all/index.html @@ -0,0 +1,110 @@ +--- +title: Promise.all() +slug: Web/JavaScript/Reference/Global_Objects/Promise/all +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all +--- +
{{JSRef}}
+ +

Il metodo Promise.all(iterable) restituisce una singola promise che viene risolta quando tutte le promise nell'iterable passate come parametro vengono risolte. Scatena una reject contenente la ragione della prima promise che viene respinta.

+ +

Sintassi

+ +
Promise.all(iterable);
+ +

Parameteri

+ +
+
iterable
+
Un oggetto iterabile, come un {{jsxref("Array")}}. See iterable.
+
+ +

Valore di ritorno

+ +

Un {{jsxref("Promise")}} che viene risolto quando tutti i promise nell'iterable passato come parametro vengono risolti, o scatena una reject contenente la ragione del primo promise che viene rigettato

+ +

Descrizione

+ +

Il metodo Promise.all ritorna un array di valori ritornati dai promise nell oggetto iterable che ha ricevuto. L'array dei valori ritornati mantiene lo stesso ordine dell'oggetto iterable originario e non l'ordine di risoluzione dei promise. Se uno dei valori dell'oggetto iterabile passato come parametro non un promise viene automaticamente convertito con {{jsxref("Promise.resolve")}}. 

+ +

Se uno qualsiasi dei promise passati viene rigettato, il metodo all Promise viene rigettato automaticamente con il valore del promise rigettato, scartando tutti i promise indipendentemente dal fatto che gli altri siano stati risolti o meno. Se viene passato un un array vuoto, allora questo metodo ritorna immediatamente.

+ +

Esempi

+ +

Usare Promise.all

+ +

Il metodo Promise.all aspetta la risoluzione di tutti i promise  (od il primo che viene rigettato).

+ +
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 comportamento fail-fast

+ +

Il metodo Promise.all viene rigettato se uno degli elementi viene rigettato e Promise.all viene rigettato immediatamente. In caso quattro promise vengono risolti dopo un  timeout, e uno viene rigettato immediatamente: allora Promise.all viene rigettato immediamente.

+ +
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(value => {
+  console.log(value);
+}, reason => {
+  console.log(reason)
+});
+
+//From console:
+//"reject"
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificheStatusCommenti
{{SpecName('ES6', '#sec-promise.all', 'Promise.all')}}{{Spec2('ES6')}}Definizione iniziale nello standard ECMA.
{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}{{Spec2('ESDraft')}} 
+ +

Compatibilitá dei browser

+ + + +

{{Compat}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/promise/catch/index.html b/files/it/web/javascript/reference/global_objects/promise/catch/index.html new file mode 100644 index 0000000000..0b9b906153 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/promise/catch/index.html @@ -0,0 +1,124 @@ +--- +title: Promise.prototype.catch() +slug: Web/JavaScript/Reference/Global_Objects/Promise/catch +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch +--- +
{{JSRef}}
+ +

Il metodo catch() restituisce una Promise e si occusa esclusivamente nei casi respinti. Si comporta come una chiamata {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}}.

+ +

 

+ +

Sintassi

+ +
p.catch(onRejected);
+
+p.catch(function(reason) {
+   // rejection
+});
+
+ +

Parametri

+ +
+
onRejected
+
Una {{jsxref("Function")}} chiamata quando la Promise viene respinta. Questa funzione richiede un parametro, la motivazione della respinta.
+
+ +

Descrizione

+ +

Il metodo catch può essere utile per gestire errori nella composizione delle promise.

+ +

Esempi

+ +

Uso del metodo 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!"
+});
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support32{{CompatGeckoDesktop(29.0)}} [1]{{CompatNo}}197.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoMobile(29.0)}} [1]{{CompatNo}}{{CompatNo}}832
+
+ +

[1] Gecko 24 has an experimental implementation of Promise, under the initial name of Future. It got renamed to its final name in Gecko 25, but disabled by default behind the flag dom.promise.enabled. Bug 918806 enabled Promises by default in Gecko 29.

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/promise/index.html b/files/it/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..d2f579bc51 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,248 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +tags: + - ECMAScript 2015 + - JavaScript + - Promise + - async +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +
{{JSRef}}
+ +

Gli oggetti Promise sono usati per computazioni in differita e asincrone. Una Promise rappresenta un'operazione che non è ancora completata, ma lo sarà in futuro.

+ +

Sintassi

+ +
new Promise(function(resolve, reject) { ... });
+ +

Parametri

+ +
+
executor
+
+

Una funzione che ha due argomenti: resolve e reject.  Tale funzione viene chiamata immediatamente dall'implementazione della Promise, passando i due argomenti resolve e reject, che sono due funzioni. Le due funzioni resolve e reject, quando chiamate, risolvono o rigettano la promise. L'esecutore inizia del lavoro (solitamente asincrono), e, una volta completato, chiama resolve per risolvere la promise, o reject se c'è stato qualche errore. Se un errore viene sollevato nella funzione di esecuzione (executor) la promise viene rigettata.

+
+
+ +

Descrizione

+ +

Una Promise rappresenta un proxy per un valore non necessariamente noto quando la promise è stata creata.  Consente di associare degli handlers con il successo o il fallimento di un'azione asincrona  (e il "valore" in caso di successo, o la motivazione in caso di fallimento). Questo in pratica consente di utilizzare dei metodi asincroni di fatto come se fossero sincroni: la funzione che compie del lavoro asincrono non ritorna il valore di completamento ma ritorna una promise, tramite la quale si potrà ottenere il valore di completamento una volta che la promise sarà terminata.

+ +

Una Promise può presentarsi in uno dei seguenti stati:

+ + + +

Una promise in pending può evolvere sia in fulfilled con un valore, sia in rejected con una motivazione (errore). Quando accade una di queste situazioni, vengono chiamati gli handler associati che sono stati accodati dal metodo then della promise. (Se la promise è già stata soddisfatta o respinta quando viene agganciato l'handler, quest'ultimo verrà chiamato immediatamente, quindi non è necessario che gli handler vengano agganciati prima del completamento dell'operazione asincrona).

+ +

Poichè i metodi {{jsxref("Promise.then", "Promise.prototype.then")}} e {{jsxref("Promise.catch", "Promise.prototype.catch")}} restituiscono delle promise, è possibile concatenarli tramite l'operazione di composition.

+ +

+ +
+

Da non confondere con: molti altri linguaggi hanno meccanismi simili per la lazy evaluation ed il calcolo differito, che a loro volta vengono chiamati "promise" (es. Schemes). Le Promise in Javascript rappresentano un processo che è gia accaduto, che può essere concatenato con delle funzioni di callback. Se stai cercando di eseguire una lazy evaluation (valutazione non immediata) di un'espressione, considera l'utilizzo delle arrow function senza argomenti: f = () => expression per creare un'espressione non valutata immediatamente (lazy-evaluated) ed usare f() per valutarla.

+
+ +
+

Nota: Si dice che una promise è "ferma" (settled) se è soddisfatta o respinta, ma non in pending. Si può parlare anche di promessa "risolta" (resolved) quando la promise è ferma o è bloccata in una catena di promise. States and fates di Domenic Denicola contiene maggiori dettagli sulla terminologia riguardo le promise.

+
+ +

Proprietà

+ +
+
Promise.length
+
La proprietà length (lunghezza) ha come valore 1 (numero di argomenti del costruttore).
+
{{jsxref("Promise.prototype")}}
+
Rappresenta il prototype per il costruttore della Promise.
+
+ +

Metodi

+ +
+
{{jsxref("Promise.all", "Promise.all(iterable)")}}
+
Ritorna una promise che si risolve quando tutte le promises dell'argomento iterabile sono state risolte. Oppure, viene rigettato appena una promise dell'argomento di tipo Iterable viene rigettato. Se tutto va a buon fine, la promise viene completata con un array contenente i valori di completamento di ciascuna promise dell'iterable, nello stesso ordine di quello dell'iterable. In caso fallisca (cioè appena una prima promise dell'iterable fallisce), Promise.all viene rigettato con la ragione (errore) della prima promise che ha fallito. Questo è utile per aggregare insieme il risultato di più promises.
+
{{jsxref("Promise.race", "Promise.race(iterable)")}}
+
Restituisce una promise che si risolve o respinge, non appena una delle promises dell'iterable si risolve o respinge, con il valore o la motivazione da quella promise.
+
+ +
+
{{jsxref("Promise.reject", "Promise.reject(reason)")}}
+
Restituisce un oggetto Promise che è respinta con la data motivazione.
+
+ +
+
{{jsxref("Promise.resolve", "Promise.resolve(value)")}}
+
Restituise un oggetto Promise che è risolto con il valore dato. Se il valore é un thenable (es. ha un metodo then), la promise restituita "seguirà" quel thenable, usando il suo stato; altirmenti la promise restituita sarà soddisfatta con il valore. Generalmente, se non sei sicuro che un valore sia di tipo Promise usa {{jsxref("Promise.resolve", "Promise.resolve(value)")}} e lavora con il valore restituito dalla promise.
+
+ +

Promise prototype

+ +

Proprietà

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}

+ +

Metodi

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}

+ +

Creazione di una Promise

+ +

Un oggetto di tipo Promise, viene creato con la keyowrd new ed il suo costruttore. Questo costruttore accetta come argomento una funzione, chiamata "funzione esecutore (executor function)". Questa funzione accetta altre due funzioni come parametri. La prima (resolve) viene eseguita in modo asincrono quando l'operazione viene eseguita con successo e restituisce il risultato dell'operazione come valore. La seconda (reject) viene eseguita nel caso in cui l'operazione fallisca e restituisce il motivo per cui l'operazione non è stata eseguita: generalmente un oggetto di tipo Error

+ +
const myFirstPromise = new Promise((resolve, reject) => {
+  // esegue qualcosa di asincrono che eventualmente chiama:
+  //
+     resolve(someValue); // fulfilled
+  // oppure
+     reject("motivo del fallimento"); // rejected
+});
+ +

Per creare una funzione con il comportamento di Promise, semplicemente restituisci una promise

+ +
function myAsyncFunction(url) {
+  return new Promise((resolve, reject) => {
+    const xhr = new XMLHttpRequest();
+    xhr.open("GET", url);
+    xhr.onload = () => resolve(xhr.responseText);
+    xhr.onerror = () => reject(xhr.statusText);
+    xhr.send();
+  });
+}
+ +

Esempi

+ +

Esempio semplice

+ +
let myFirstPromise = new Promise((resolve, reject) => {
+  // Chiamiamo resolve(...) quando viene eseguito correttamente, e reject(...) quando fallisce.
+  // In questo esempio viene utilizzato setTimeout(...) per simulare un'operazione asincrona.
+  // Nella realtà probabilmente utilizzerai qualcosa del tipo XHR o HTML5 API.
+  setTimeout(function(){
+    resolve("Success!"); // È andato tutto perfettamente!
+  }, 250);
+});
+
+myFirstPromise.then((successMessage) => {
+  // successMessage viene passato alla funzione resolve(...) .
+  // Non deve essere necessariamente una stringa, ma nel caso sia solo un messaggio probabilmemte lo sarà.
+  console.log("Yay! " + successMessage);
+});
+ +

Esempio avanzato

+ +
<button id="btn">Make a promise!</button>
+<div id="log"></div>
+ +

Questo piccolo esempio mostra il meccanismo delle Promise. Il metodo testPromise() viene richiamato ogni volta che il {{HTMLElement("button")}} viene cliccato. Crea una promise che viene risolta correttamente (fulfilled), utilizzando {{domxref("window.setTimeout()")}} che incrementa il contatore ogni 1-3 secondi (random). Il costruttore Promise viene utilizzato per creare la promise.

+ +

La risoluzione della promise viene semplicemente loggata tramite una funzione di callback fulfill {{jsxref("Promise.prototype.then()","p1.then()")}}. Una serie di log mostrano che il comportamento sincrono del metodo è disaccoppiato rispetto all'esecuzione asincrona della promise.

+ +
'use strict';
+var promiseCount = 0;
+
+function testPromise() {
+    let thisPromiseCount = ++promiseCount;
+
+    let log = document.getElementById('log');
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Started (<small>Sync code started</small>)<br/>');
+
+    // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s)
+    let p1 = new Promise(
+        // The resolver function is called with the ability to resolve or
+        // reject the promise
+       (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 with the then() call,
+    // and what to do when the promise is rejected with the catch() call
+    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
+       (reason) => {
+            console.log('Handle rejected promise ('+reason+') here.');
+        });
+
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Promise made (<small>Sync code terminated</small>)<br/>');
+}
+
+
+
+if ("Promise" in window) {
+  let btn = document.getElementById("btn");
+  btn.addEventListener("click",testPromise);
+} else {
+  log = document.getElementById('log');
+  log.innerHTML = "Live example not available as your browser doesn't support the <code>Promise<code> interface.";
+}
+ +

In questo esempio si comincia cliccando il bottone. Per testare necessiti di un browser che supporta le Promise. Cliccando il bottone diverse volte in un lasso di tempo breve vedrai che le funzioni verranno risolte una dopo l'altra.

+ +

Caricare un'immagine con XHR

+ +

Un'altro semplice esempio che utilizza le Promise e XMLHttpRequest mostra come caricare un'immagine è disponibile sul repository di MDN su Github. Puoi inoltre vederla in azione. Ogni azione è commentata e puoi seguire passo-passo come viene creata la Promise e gestita tramite XHR.

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES2015', '#sec-promise-objects', 'Promise')}}{{Spec2('ES2015')}} +

Prima definizione in uno standard ECMA.

+
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}} +

 

+
+ +

Supporto dei browser

+ +

{{Compat("javascript.builtins.Promise")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/proxy/handler/apply/index.html b/files/it/web/javascript/reference/global_objects/proxy/handler/apply/index.html new file mode 100644 index 0000000000..f803b41255 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/proxy/handler/apply/index.html @@ -0,0 +1,119 @@ +--- +title: handler.apply() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply +tags: + - ECMAScript 2015 + - JavaScript + - Proxy + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/apply +--- +
{{JSRef}}
+ +

Il metodo handler.apply() costituisce una trap per una chiamata a funzione.

+ +
{{EmbedInteractiveExample("pages/js/proxyhandler-apply.html", "taller")}}
+ + + +

Sintassi

+ +
var p = new Proxy(target, {
+  apply: function(target, thisArg, argumentsList) {
+  }
+});
+
+ +

Parametri

+ +

I seguenti parametri vengono passati al metodo apply. this è legato all'handler.

+ +
+
target
+
L'oggetto target.
+
thisArg
+
Il valore di this relativo alla chiamata.
+
argumentsList
+
La lista degli argomenti della chiamata.
+
+ +

Valore di ritorno

+ +

Il metodo apply può restituire qualsiasi valore.

+ +

Descrizione

+ +

Il metodo handler.apply è una trap per le chiamate a funzione.

+ +

Operazioni intercettate

+ +

Questa trap può intercettare le seguenti operazioni:

+ + + +

Invarianti

+ +

Se le seguenti invarianti non sono rispettate il proxy emetterà un TypeError:

+ + + +

Esempi

+ +

Il codice seguente intercetta una chiamata a funzione.

+ +
var p = new Proxy(function() {}, {
+  apply: function(target, thisArg, argumentsList) {
+    console.log('chiamato con: ' + argumentsList.join(', '));
+    return argumentsList[0] + argumentsList[1] + argumentsList[2];
+  }
+});
+
+console.log(p(1, 2, 3)); // "chiamato con: 1, 2, 3"
+                         // 6
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist', '[[Call]]')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +
+ + +

{{Compat("javascript.builtins.Proxy.handler.apply")}}

+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/proxy/handler/index.html b/files/it/web/javascript/reference/global_objects/proxy/handler/index.html new file mode 100644 index 0000000000..042e9b50b1 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/proxy/handler/index.html @@ -0,0 +1,83 @@ +--- +title: Proxy handler +slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler +tags: + - ECMAScript 2015 + - JavaScript + - NeedsTranslation + - Proxy + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy +--- +
{{JSRef}}
+ +

The proxy's handler object is a placeholder object which contains traps for {{jsxref("Proxy", "proxies", "", 1)}}.

+ +

Methods

+ +

All traps are optional. If a trap has not been defined, the default behavior is to forward the operation to the target.

+ +
+
{{jsxref("Global_Objects/Proxy/handler/getPrototypeOf", "handler.getPrototypeOf()")}}
+
A trap for {{jsxref("Object.getPrototypeOf")}}.
+
{{jsxref("Global_Objects/Proxy/handler/setPrototypeOf", "handler.setPrototypeOf()")}}
+
A trap for {{jsxref("Object.setPrototypeOf")}}.
+
{{jsxref("Global_Objects/Proxy/handler/isExtensible", "handler.isExtensible()")}}
+
A trap for {{jsxref("Object.isExtensible")}}.
+
{{jsxref("Global_Objects/Proxy/handler/preventExtensions", "handler.preventExtensions()")}}
+
A trap for {{jsxref("Object.preventExtensions")}}.
+
{{jsxref("Global_Objects/Proxy/handler/getOwnPropertyDescriptor", "handler.getOwnPropertyDescriptor()")}}
+
A trap for {{jsxref("Object.getOwnPropertyDescriptor")}}.
+
{{jsxref("Global_Objects/Proxy/handler/defineProperty", "handler.defineProperty()")}}
+
A trap for {{jsxref("Object.defineProperty")}}.
+
{{jsxref("Global_Objects/Proxy/handler/has", "handler.has()")}}
+
A trap for the {{jsxref("Operators/in", "in")}} operator.
+
{{jsxref("Global_Objects/Proxy/handler/get", "handler.get()")}}
+
A trap for getting property values.
+
{{jsxref("Global_Objects/Proxy/handler/set", "handler.set()")}}
+
A trap for setting property values.
+
{{jsxref("Global_Objects/Proxy/handler/deleteProperty", "handler.deleteProperty()")}}
+
A trap for the {{jsxref("Operators/delete", "delete")}} operator.
+
{{jsxref("Global_Objects/Proxy/handler/ownKeys", "handler.ownKeys()")}}
+
A trap for {{jsxref("Object.getOwnPropertyNames")}} and {{jsxref("Object.getOwnPropertySymbols")}}.
+
{{jsxref("Global_Objects/Proxy/handler/apply", "handler.apply()")}}
+
A trap for a function call.
+
{{jsxref("Global_Objects/Proxy/handler/construct", "handler.construct()")}}
+
A trap for the {{jsxref("Operators/new", "new")}} operator.
+
+ +

Some non-standard traps are obsolete and have been removed.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-object-internal-methods-and-internal-slots', 'Proxy Object Internal Methods and Internal Slots')}}{{Spec2('ESDraft')}}The enumerate handler has been removed.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Proxy.handler")}}

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/proxy/index.html b/files/it/web/javascript/reference/global_objects/proxy/index.html new file mode 100644 index 0000000000..fa35ff1d43 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/proxy/index.html @@ -0,0 +1,396 @@ +--- +title: Proxy +slug: Web/JavaScript/Reference/Global_Objects/Proxy +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy +--- +
+
{{JSRef}}
+ +
L'oggetto Proxy è utilizzato per definire comportamenti personalizzati per operazioni fondamentali (per esempio: ricerca delle proprietà, assegnazione, enumerazione, invocazione delle funzioni, ecc.).
+
+ +

Terminologia

+ +
+
handler
+
Oggetto placeholder, il quale contiene le trappole.
+
traps
+
I metodi che forniscono l'accesso alle proprietà. Questo è analogo al concetto di trappola nei sistemi operativi.
+
target
+
Oggetti, che i proxy virtualizzano (sostituiscono). Viene spesso utilizzato come back-end di archiviazione per il proxy. Le invarianti, riguardanti oggetti non estensibili o proprietà non configurabili, sono verificate prima di interagire con l'obiettivo.
+
+ +

Sintassi

+ +
var p = new Proxy(target, handler);
+
+ +

Parametri

+ +
+
target
+
Un oggetto target che il Proxy ingloberà. Può essere un qualsiasi tipo di oggetto, array nativi inclusi, funzioni o anche altri Proxy.
+
handler
+
Un oggetto le cui proprietà sono funzioni che definiscono i comportamenti del proxy quando un'operazione viene effettuata su di esso.
+
+ +

Metodi

+ +
+
{{jsxref("Proxy.revocable()")}}
+
Crea un oggetto Proxy revocabile.
+
+ +

Metodi dell'handler object

+ +

L'oggetto handler è un oggetto placeholder, il quale contiene le trappole per il Proxy.

+ +

Esempi

+ +

Esempio base

+ +

In questo esempio base il numero 37 viene restituito come valore di default quando l'oggetto non contiene la proprietà richiesta. Viene utilizzato il get handler.

+ +
var handler = {
+    get: function(target, name) {
+        return name in target ?
+            target[name] :
+            37;
+    }
+};
+
+var p = new Proxy({}, handler);
+p.a = 1;
+p.b = undefined;
+
+console.log(p.a, p.b); // 1, undefined
+console.log('c' in p, p.c); // false, 37
+
+ +

No-op forwarding proxy

+ +

In questo esempio viene utilizzato un semplice oggetto Javascript come target, al quale il proxy inoltrerà tutte le operazioni che sono state applicate su di esso. 

+ +
var target = {};
+var p = new Proxy(target, {});
+
+p.a = 37; // operazione inoltrata al target
+
+console.log(target.a); // 37. Operazione inoltrata con successo
+
+ +

Validation

+ +

Con un proxy, puoi facilmente validare il valore passato per un oggetto. In questo esempio viene utilizzato il  set handler.

+ +
let validator = {
+  set: function(obj, prop, value) {
+    if (prop === 'age') {
+      if (!Number.isInteger(value)) {
+        throw new TypeError('L\'età non è un numero intero');
+      }
+      if (value > 200) {
+        throw new RangeError('L\'età sembra non essere valida');
+      }
+    }
+
+    // Il comportamento di default da adoperare per memorizzare il valore
+    obj[prop] = value;
+
+    return true;
+  }
+};
+
+let person = new Proxy({}, validator);
+
+person.age = 100;
+console.log(person.age); // 100
+person.age = 'young'; // Lancia una eccezione
+person.age = 300; // Lancia una eccezione
+ +

Extending constructor

+ +

Una funzione proxy può facilmente estendere un costruttore con un nuovo costruttore. Questo esempio usa gli handler: construct e apply .

+ +
function extend(sup, base) {
+  var descriptor = Object.getOwnPropertyDescriptor(
+    base.prototype, 'constructor'
+  );
+  base.prototype = Object.create(sup.prototype);
+  var handler = {
+    construct: function(target, args) {
+      var obj = Object.create(base.prototype);
+      this.apply(target, obj, args);
+      return obj;
+    },
+    apply: function(target, that, args) {
+      sup.apply(that, args);
+      base.apply(that, args);
+    }
+  };
+  var proxy = new Proxy(base, handler);
+  descriptor.value = proxy;
+  Object.defineProperty(base.prototype, 'constructor', descriptor);
+  return proxy;
+}
+
+var Person = function(name) {
+  this.name = name;
+};
+
+var Boy = extend(Person, function(name, age) {
+  this.age = age;
+});
+
+Boy.prototype.sex = 'M';
+
+var Peter = new Boy('Peter', 13);
+console.log(Peter.sex);  // "M"
+console.log(Peter.name); // "Peter"
+console.log(Peter.age);  // 13
+ +

Manipulating DOM nodes

+ +

Alcune volte vorresti attivare o disattivare un attributo o una classe di due elementi differenti. Qui è mostrato come è possibile farlo utilizzando il set handler.

+ +
let view = new Proxy({
+  selected: null
+},
+{
+  set: function(obj, prop, newval) {
+    let oldval = obj[prop];
+
+    if (prop === 'selected') {
+      if (oldval) {
+        oldval.setAttribute('aria-selected', 'false');
+      }
+      if (newval) {
+        newval.setAttribute('aria-selected', 'true');
+      }
+    }
+
+    // Il comportamento di default da adoperare per memorizzare il valore
+    obj[prop] = newval;
+
+    // Indicate success
+    return true;
+  }
+});
+
+let i1 = view.selected = document.getElementById('item-1');
+console.log(i1.getAttribute('aria-selected')); // 'true'
+
+let i2 = view.selected = document.getElementById('item-2');
+console.log(i1.getAttribute('aria-selected')); // 'false'
+console.log(i2.getAttribute('aria-selected')); // 'true'
+ +

Value correction and an extra property

+ +

L'oggetto products  del proxy valuta il valore passato e lo converte in un array se è necessario. L'oggetto supporta anche una proprietà extra chiamata latestBrowser, uttilizzabile sia come getter che come setter.

+ +
let products = new Proxy({
+  browsers: ['Internet Explorer', 'Netscape']
+},
+{
+  get: function(obj, prop) {
+    // An extra property
+    if (prop === 'latestBrowser') {
+      return obj.browsers[obj.browsers.length - 1];
+    }
+
+    // Il comportamento di default per restituire il valore
+    return obj[prop];
+  },
+  set: function(obj, prop, value) {
+    // An extra property
+    if (prop === 'latestBrowser') {
+      obj.browsers.push(value);
+      return true;
+    }
+
+    // Converte il valore se non è un array
+    if (typeof value === 'string') {
+      value = [value];
+    }
+
+    // Il comportamento di default per memorizzare il valore
+    obj[prop] = value;
+
+    // Indicate success
+    return true;
+  }
+});
+
+console.log(products.browsers); // ['Internet Explorer', 'Netscape']
+products.browsers = 'Firefox'; // passa una stringa (per sbaglio)
+console.log(products.browsers); // ['Firefox'] <- nessun problema, il valore passato è un array
+
+products.latestBrowser = 'Chrome';
+console.log(products.browsers); // ['Firefox', 'Chrome']
+console.log(products.latestBrowser); // 'Chrome'
+ +

Trovare un oggetto in un array dalla sua proprietà

+ +

Questo proxy estende un array con alcune caratteristiche utiliti. Come puoi notare, puoi facilmente definire nuove proprietà senza utilizzare Object.defineProperties. Questo esempio può essere adattato per trovare una riga di una tabella partendo dalla sua cella. In questo caso il target sarà table.rows.

+ +
let products = new Proxy([
+  { name: 'Firefox', type: 'browser' },
+  { name: 'SeaMonkey', type: 'browser' },
+  { name: 'Thunderbird', type: 'mailer' }
+],
+{
+  get: function(obj, prop) {
+    // Il comportamento di default per ritornare un valore; prop è di solito un numero intero
+    if (prop in obj) {
+      return obj[prop];
+    }
+
+    // Ottieni il numero di prodotti; un alias di products.length
+    if (prop === 'number') {
+      return obj.length;
+    }
+
+    let result, types = {};
+
+    for (let product of obj) {
+      if (product.name === prop) {
+        result = product;
+      }
+      if (types[product.type]) {
+        types[product.type].push(product);
+      } else {
+        types[product.type] = [product];
+      }
+    }
+
+    // Ottieni un prodotto dal campo name
+    if (result) {
+      return result;
+    }
+
+    // Ottieni un prodotto dal campo type
+    if (prop in types) {
+      return types[prop];
+    }
+
+    // Ottieni i tipi di prodotto
+    if (prop === 'types') {
+      return Object.keys(types);
+    }
+
+    return undefined;
+  }
+});
+
+console.log(products[0]); // { name: 'Firefox', type: 'browser' }
+console.log(products['Firefox']); // { name: 'Firefox', type: 'browser' }
+console.log(products['Chrome']); // undefined
+console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }]
+console.log(products.types); // ['browser', 'mailer']
+console.log(products.number); // 3
+
+ +

Una lista completa di traps

+ +

Adesso, per creare una lista di trappole, per scopi didattici, proveremo a proxare un oggetto non nativo che è particolarmente adatto a questo tipo di operazioni: l' oggetto globale docCookies creato da the "little framework" published on the document.cookie page.

+ +
/*
+  var docCookies = ... get the "docCookies" object here:
+  https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support
+*/
+
+var docCookies = new Proxy(docCookies, {
+  get: function (oTarget, sKey) {
+    return oTarget[sKey] || oTarget.getItem(sKey) || undefined;
+  },
+  set: function (oTarget, sKey, vValue) {
+    if (sKey in oTarget) { return false; }
+    return oTarget.setItem(sKey, vValue);
+  },
+  deleteProperty: function (oTarget, sKey) {
+    if (sKey in oTarget) { return false; }
+    return oTarget.removeItem(sKey);
+  },
+  enumerate: function (oTarget, sKey) {
+    return oTarget.keys();
+  },
+  ownKeys: function (oTarget, sKey) {
+    return oTarget.keys();
+  },
+  has: function (oTarget, sKey) {
+    return sKey in oTarget || oTarget.hasItem(sKey);
+  },
+  defineProperty: function (oTarget, sKey, oDesc) {
+    if (oDesc && 'value' in oDesc) { oTarget.setItem(sKey, oDesc.value); }
+    return oTarget;
+  },
+  getOwnPropertyDescriptor: function (oTarget, sKey) {
+    var vValue = oTarget.getItem(sKey);
+    return vValue ? {
+      value: vValue,
+      writable: true,
+      enumerable: true,
+      configurable: false
+    } : undefined;
+  },
+});
+
+/* Test dei cookie */
+
+console.log(docCookies.my_cookie1 = 'First value');
+console.log(docCookies.getItem('my_cookie1'));
+
+docCookies.setItem('my_cookie1', 'Changed value');
+console.log(docCookies.my_cookie1);
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ES2016', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ES2016')}} 
{{SpecName('ES2017', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ES2017')}} 
{{SpecName('ESDraft', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità tra Browser

+ + + +

{{Compat("javascript.builtins.Proxy", 2)}}

+ +

Vedi anche

+ + + +

Nota di licenza

+ +

Alcuni contentui (test, esempi) in questa pagina sono stati copiati o adattatu dall' ECMAScript wiki i quali contenuti sono sotto licenza CC 2.0 BY-NC-SA.

diff --git a/files/it/web/javascript/reference/global_objects/proxy/revocabile/index.html b/files/it/web/javascript/reference/global_objects/proxy/revocabile/index.html new file mode 100644 index 0000000000..bf87d7e3e7 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/proxy/revocabile/index.html @@ -0,0 +1,86 @@ +--- +title: Proxy.revocable() +slug: Web/JavaScript/Reference/Global_Objects/Proxy/revocabile +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/revocable +--- +
{{JSRef}}
+ +

Il metodo Proxy.revocable() è usato per creare un oggetto {{jsxref("Proxy")}} revocabile.

+ +

Sintassi

+ +
Proxy.revocable(target, handler);
+
+ +

Parametri

+ +
{{ Page("it/docs/Web/JavaScript/Reference/Global_Objects/Proxy", "Parametri") }}
+ +

Valore restituito

+ +

Un nuovo oggetto Proxy revocabile.

+ +

Descrizione

+ +

Un Proxy revocabile è un oggetto con le seguenti due proprietà {proxy: proxy, revoke: revoke}.

+ +
+
proxy
+
L'oggetto Proxy creato con new Proxy(target, handler).
+
revoke
+
Una funzione che non richiede argomenti per disattivare il proxy.
+
+ +

Se la funzione revoke() viene invocata, il proxy diventa inutilizzabile: se si tenta di farne uso si otterrà un {{jsxref("TypeError")}}. Una volta che il proxy è revocato rimarrà in questo stato e potrà essere eliminato dal garbage collector. Successive invocazioni di revoke() non avranno effetto.

+ +

Esempi

+ +
var revocable = Proxy.revocable({}, {
+  get: function(target, name) {
+    return "[[" + name + "]]";
+  }
+});
+var proxy = revocable.proxy;
+console.log(proxy.foo); // "[[foo]]"
+
+revocable.revoke();
+
+console.log(proxy.foo); // viene sollevato un TypeError
+proxy.foo = 1           // viene sollevato un TypeError
+delete proxy.foo;       // viene sollevato un TypeError
+typeof proxy            // "object", typeof non innesca nessuna trappola
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy.revocable', 'Proxy Revocation Functions')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-proxy.revocable', 'Proxy Revocation Functions')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità tra Browser

+ + + +

{{Compat("javascript.builtins.Proxy.revocable")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/set/entries/index.html b/files/it/web/javascript/reference/global_objects/set/entries/index.html new file mode 100644 index 0000000000..367507d3d5 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/set/entries/index.html @@ -0,0 +1,113 @@ +--- +title: Set.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Set/entries +translation_of: Web/JavaScript/Reference/Global_Objects/Set/entries +--- +
{{JSRef}}
+ +

Il metodo entries() restituisce un novo oggetto Iterator che contiene un array di [valore, valore] per ciascun elemento nell'oggetto Set, nell'ordine con cui sono stati inseriti. Per gli oggetti di tipo Set non esiste alcuna chiave come per gli oggetti di tipo Map. Comunque, per mantenere le API simili a quelle dell'oggetto Map, per ciascun elemento dell'array viene utilizzato value anche per la chiave, perciò viene restituito un array [valore, valore].

+ +

Sintassi

+ +
mySet.entries()
+ +

Valore restituito

+ +

Un nuovo oggetto Iterator che contiene un array di [valore, valore] per ciascun elemento nell'oggetto Set, nell'ordine con cui sono stati inseriti.

+ +

Esempi

+ +

Uso di entries()

+ +
var mySet = new Set();
+mySet.add("foobar");
+mySet.add(1);
+mySet.add("baz");
+
+var setIter = mySet.entries();
+
+console.log(setIter.next().value); // ["foobar", "foobar"]
+console.log(setIter.next().value); // [1, 1]
+console.log(setIter.next().value); // ["baz", "baz"]
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificheStatoCommenti
{{SpecName('ES6', '#sec-set.prototype.entries', 'Set.prototype.entries')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.entries', 'Set.prototype.entries')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support38{{ CompatGeckoDesktop("24") }}{{CompatNo}}257.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}38{{ CompatGeckoMobile("24") }}{{CompatNo}}{{CompatNo}}8
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/set/index.html b/files/it/web/javascript/reference/global_objects/set/index.html new file mode 100644 index 0000000000..c8de5d83f6 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/set/index.html @@ -0,0 +1,394 @@ +--- +title: Set +slug: Web/JavaScript/Reference/Global_Objects/Set +translation_of: Web/JavaScript/Reference/Global_Objects/Set +--- +
{{JSRef}}
+ +
L'oggetto Set permette di memorizzare valori unici di qualunque tipo, che siano {{Glossary("Primitive", "valori primitivi")}} o riferimenti ad oggetti.
+ +
 
+ +

Sintassi

+ +
new Set([iterabile]);
+ +

Parametri

+ +
+
iterabile
+
Se un oggetto iterabile è passato, tutti i suoi elementi saranno aggiunti al nuovo Set. null viene trattato come undefined.
+
+ +

Descrizione

+ +

Gli oggetti Set sono collezioni di valori, e possibile iterare i valori nel loro ordine di inserimento. Un valore in un Set può occorrere solo una volta; è quindi unico nella collezione.

+ +

Uguaglianza dei valori

+ +

Dato che ogni valore in un Set deve essere unico, dovra essere controllata l'uguaglianza di un nuovo valore con valori già presenti nel Set, questa operazione non è basata sullo stesso algoritmo usato per l'operatore ===. Nello specifico, per i Set, +0 (che è strettamente uguale a -0) e -0 sono valori differenti. Comunque, questo è stato cambiato nell'ultima specifica ECMAScript 6. Partendo da Gecko 29.0 {{geckoRelease("29")}} ({{bug("952870")}}) e da questa recente nightly Chrome issue, +0 e -0 sono trattati come valori identici nell'oggetto Set. Inoltre, NaN e undefined possono essere memorizzati nei Set. NaN è considerato unguale a NaN (anche se NaN !== NaN).

+ +

Proprietà

+ +
+
Set.size
+
Il valore della proprietà size è 0. 
+
{{jsxref("Set.@@species", "get Set[@@species]")}}
+
Il costruttore della funzione che viene usato per creare oggetti derivati.
+
{{jsxref("Set.prototype")}}
+
Rappresenta il prototipo per il costruttore del Set. Consente l'aggiunta di proprietà a tutti gli oggetti Set.
+
+ +

Instanze Set

+ +

Tutte le instanze di Set ereditano da {{jsxref("Set.prototype")}}.

+ +

Proprietà

+ +

{{page('it-IT/Web/JavaScript/Reference/Global_Objects/Set/prototype','Properties')}}

+ +

Methods

+ +

{{page('it-IT/Web/JavaScript/Reference/Global_Objects/Set/prototype','Methods')}}

+ +

Esempi

+ +

Uso dell'oggetto Set

+ +
var mySet = new Set();
+
+mySet.add(1);
+mySet.add(5);
+mySet.add("some text");
+var o = {a: 1, b: 2};
+mySet.add(o);
+
+mySet.has(1); // true
+mySet.has(3); // false, 3 non è stato aggiunto al set
+mySet.has(5);              // true
+mySet.has(Math.sqrt(25));  // true
+mySet.has("Some Text".toLowerCase()); // true
+mySet.has(o); // true
+
+mySet.size; // 4
+
+mySet.delete(5); // rimuove 5 dal set
+mySet.has(5);    // false, 5 è stato rimosso
+
+mySet.size; // 3, abbiamo rimosso 1 valore
+
+ +

Iterando oggetti Set

+ +
// iterando i valori in un set
+// logga gli item in ordine: 1, "testo di esempio"
+for (let item of mySet) console.log(item);
+
+// logga gli item in ordine: 1, "testo di esempio"
+for (let item of mySet.keys()) console.log(item);
+
+// logga gli item in ordine: 1, "testo di esempio"
+for (let item of mySet.values()) console.log(item);
+
+// logga gli item in ordine: 1, "testo di esempio"
+//(chiavi e valori qui sono uguali)
+for (let [key, value] of mySet.entries()) console.log(key);
+
+// converte un set in un Array semplice (con )
+// convert set to plain Array (con Array comprehensions)
+var myArr = [v for (v of mySet)]; // [1, "some text"]
+// Alternativa (con Array.from)
+var myArr = Array.from(mySet); // [1, "some text"]
+
+// Il seguente snippet funzionerà anche in un documento HTML
+mySet.add(document.body);
+mySet.has(document.querySelector("body")); // true
+
+// conversione tra Set e Array
+mySet2 = new Set([1,2,3,4]);
+mySet2.size; // 4
+[...mySet2]; // [1,2,3,4]
+
+// l'itersezione può essere simulata con
+var intersection = new Set([...set1].filter(x => set2.has(x)));
+
+// la differenza può essere simulata con
+var difference = new Set([...set1].filter(x => !set2.has(x)));
+
+// Itera i valori di un set con forEach
+mySet.forEach(function(value) {
+  console.log(value);
+});
+
+// 1
+// 2
+// 3
+// 4
+ +

Relazione con gli oggetti Array

+ +
var myArray = ["value1", "value2", "value3"];
+
+// Uso del costruttore di Set per trasformare un Array in un Set
+var mySet = new Set(myArray);
+
+mySet.has("value1"); // ritorna true
+
+// Usa l'operatore spread per trasformare un Set in un Array
+console.log(uneval([...mySet])); // Mostrerà lo stesso identico Array di myArray
+ +

Specifica

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-set-objects', 'Set')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support +

{{ CompatChrome(38) }} [1]

+
{{ CompatGeckoDesktop("13") }}{{ CompatIE("11") }}257.1
Constructor argument: new Set(iterable){{ CompatChrome(38) }}{{ CompatGeckoDesktop("13") }}{{CompatNo}}25{{CompatNo}}
iterable{{ CompatChrome(38) }}{{ CompatGeckoDesktop("17") }}{{CompatNo}}257.1
Set.clear(){{ CompatChrome(38) }}{{CompatGeckoDesktop("19")}}{{ CompatIE("11") }}257.1
Set.keys(), Set.values(), Set.entries(){{ CompatChrome(38) }}{{CompatGeckoDesktop("24")}}{{CompatNo}}257.1
Set.forEach(){{ CompatChrome(38) }}{{CompatGeckoDesktop("25")}}{{ CompatIE("11") }}257.1
Value equality for -0 and 0{{ CompatChrome(38) }}{{CompatGeckoDesktop("29")}}{{CompatNo}}25{{CompatNo}}
Constructor argument: new Set(null){{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched add() in Constructor{{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Set[@@species]{{CompatUnknown}}{{CompatGeckoDesktop("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Set() without new throws{{CompatUnknown}}{{CompatGeckoDesktop("42")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(38)}} [1]{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}8
Constructor argument: new Set(iterable){{CompatNo}}{{CompatChrome(38)}}{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
iterable{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("17") }}{{CompatNo}}{{CompatNo}}8
Set.clear(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("19")}}{{CompatNo}}{{CompatNo}}8
Set.keys(), Set.values(), Set.entries(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("24")}}{{CompatNo}}{{CompatNo}}8
Set.forEach(){{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
Value equality for -0 and 0{{CompatNo}}{{ CompatChrome(38) }}{{CompatGeckoMobile("29")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Constructor argument: new Set(null){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched add() in Constructor{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Set[@@species]{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Set() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("42")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] La caratteristica è disponibile come opzione da Chrome 31. In chrome://flags, attivare la voce “Enable Experimental JavaScript”.

+ +

Guarda pure

+ + diff --git a/files/it/web/javascript/reference/global_objects/set/values/index.html b/files/it/web/javascript/reference/global_objects/set/values/index.html new file mode 100644 index 0000000000..e662f3d62d --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/set/values/index.html @@ -0,0 +1,114 @@ +--- +title: Set.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Set/values +translation_of: Web/JavaScript/Reference/Global_Objects/Set/values +--- +
{{JSRef}}
+ +

Il metodo values() restituisce un nuovo oggetto di tipo Iterator che contiene tutti i valori presenti nell'oggetto Set, nell'ordine con cui sono stati inseriti.

+ +

Il metodo keys() è un alias per questo metodo (in modo da mantenere api simili all'oggetto {{jsxref("Map")}}); si comporta esattamente allo stesss modo e restiuisce i valori contenuti nell'oggetto Set.

+ +

Sintassi

+ +
mySet.values();
+
+ +

Valore restituito

+ +

Un nuovo oggetto di tipo Iterator che contiene tutti i valori presenti nell'oggetto Set, nell'ordine con cui sono stati inseriti.

+ +

Esempi

+ +

Uso di values()

+ +
var mySet = new Set();
+mySet.add("foo");
+mySet.add("bar");
+mySet.add("baz");
+
+var setIter = mySet.values();
+
+console.log(setIter.next().value); // "foo"
+console.log(setIter.next().value); // "bar"
+console.log(setIter.next().value); // "baz"
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificheStatoCommenti
{{SpecName('ES6', '#sec-set.prototype.values', 'Set.prototype.values')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.values', 'Set.prototype.values')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support38{{CompatGeckoDesktop("24")}}{{CompatNo}}257.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}38{{ CompatGeckoMobile("24") }}{{ CompatNo}}{{ CompatNo}}8
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/charat/index.html b/files/it/web/javascript/reference/global_objects/string/charat/index.html new file mode 100644 index 0000000000..312cfa9713 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/charat/index.html @@ -0,0 +1,247 @@ +--- +title: String.prototype.charAt() +slug: Web/JavaScript/Reference/Global_Objects/String/charAt +translation_of: Web/JavaScript/Reference/Global_Objects/String/charAt +--- +
{{JSRef}}
+ +

Il metodo {{jsxref("String")}} dell'oggetto charAt() restituisce una nuova stringa che consiste nella singola unità di codice UTF-16 situata nell'offset specificato nella stringa.

+ +
{{EmbedInteractiveExample("pages/js/string-charat.html")}}
+ + + +

Sintassi

+ +
carattere = str.charAt(indice)
+ +

Parametri

+ +
+
index
+
Un numero intero compreso tra 0 e 1-meno della lunghezza della stringa. Se non viene fornito alcun indice, il valore predefinito è 0, quindi viene restituito il primo carattere nella stringa.
+
+ +

Valore restituito

+ +

Una stringa che rappresenta il carattere (esattamente un'unità di codice UTF-16) nell'indice specificato; stringa vuota se index non è compreso nell'intervallo

+ +

Descrizione

+ +

I caratteri in una stringa sono indicizzati da sinistra a destra. L'indice del primo carattere è 0 e l'indice dell'ultimo carattere in una stringa chiamata stringName è stringName.length - 1. Se l'indice che fornisci è fuori da questo intervallo, JavaScript restituisce una stringa vuota.

+ +

Se non viene fornito alcun indice per charAt(), il valore predefinito è 0.

+ +

Esempi

+ +

Visualizzazione di caratteri in posizioni diverse in una stringa

+ +

Nell'esempio seguente vengono visualizzati caratteri in posizioni diverse nella stringa "Brave new world":

+ +
var anyString = 'Brave new world';
+console.log("Il carattere nell'indice 0 è '" + anyString.charAt()   + "'");
+// Non è stato fornito alcun indice, usato 0 come predefinito
+
+console.log("The character at index 0   is '" + anyString.charAt(0)   + "'");
+console.log("The character at index 1   is '" + anyString.charAt(1)   + "'");
+console.log("The character at index 2   is '" + anyString.charAt(2)   + "'");
+console.log("The character at index 3   is '" + anyString.charAt(3)   + "'");
+console.log("The character at index 4   is '" + anyString.charAt(4)   + "'");
+console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
+
+ +

Queste righe mostrano quanto segue:

+ +
//Il carattere nell'indice 0   is 'B'
+
+//Il carattere nell'indice 0   is 'B'
+//Il carattere nell'indice 1   is 'r'
+//Il carattere nell'indice 2   is 'a'
+//Il carattere nell'indice 3   is 'v'
+//Il carattere nell'indice 4   is 'e'
+//Il carattere nell'indice 999 is ''
+
+ +

Recupero di caratteri interi

+ +

Quanto segue fornisce un mezzo per garantire che l'attraversamento di un loop string fornisca sempre un intero carattere, anche se la stringa contiene caratteri che non si trovano nel piano multi-lingue di base.

+ +
var str = 'A \uD87E\uDC04 Z'; // Potremmo anche usare direttamente un carattere non-BMP
+for (var i = 0, chr; i < str.length; i++) {
+  if ((chr = getWholeChar(str, i)) === false) {
+    continue;
+  }
+  // Adatta questa linea all'inizio di ogni ciclo, passando l'intera stringa e
+  // l'iterazione corrente e il ritorno di una variabile per rappresentare il
+  // personaggio individuale
+
+  console.log(chr);
+}
+
+function getWholeChar(str, i) {
+  var code = str.charCodeAt(i);
+
+  if (Number.isNaN(code)) {
+    return ''; // Posizione non trovata
+  }
+  if (code < 0xD800 || code > 0xDFFF) {
+    return str.charAt(i);
+  }
+
+  // Alto surrogato (potrebbe cambiare l'ultimo esadecimale a 0xDB7F per trattare un alto privato
+   // si surroga come singoli caratteri)
+  if (0xD800 <= code && code <= 0xDBFF) {
+    if (str.length <= (i + 1)) {
+      throw 'Alto surrogato senza seguire un surrogato basso';
+    }
+    var next = str.charCodeAt(i + 1);
+      if (0xDC00 > next || next > 0xDFFF) {
+        throw 'Alto surrogato senza seguire un surrogato basso';
+      }
+      return str.charAt(i) + str.charAt(i + 1);
+  }
+  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
+  if (i === 0) {
+    throw 'Basso surrogato senza precedente surrogato elevato';
+  }
+  var prev = str.charCodeAt(i - 1);
+
+  // (could change last hex to 0xDB7F to treat high private
+  // surrogates as single characters)
+  if (0xD800 > prev || prev > 0xDBFF) {
+    throw 'Basso surrogato senza precedente surrogato elevato';
+  }
+  // Ora possiamo passare sopra surrogati bassi come secondo componente
+   // in una coppia che abbiamo già elaborato
+  return false;
+}
+
+ +

In un ambiente ECMAScript 2016 che consente l'assegnazione destrutturata, la seguente è un'alternativa più succinta e un po 'più flessibile in quanto incrementa automaticamente una variabile incrementale (se il carattere lo richiede in quanto coppia surrogata).

+ +
var str = 'A\uD87E\uDC04Z'; // Potremmo anche usare direttamente un carattere non-BMP
+for (var i = 0, chr; i < str.length; i++) {
+  [chr, i] = getWholeCharAndI(str, i);
+  // Adatta questa linea all'inizio di ogni ciclo, passando l'intera stringa e
+  // l'iterazione corrente e la restituzione di un array con il singolo carattere
+  // e valore "i" (modificato solo se una coppia surrogata)
+
+  console.log(chr);
+}
+function getWholeCharAndI(str, i) {
+  var code = str.charCodeAt(i);
+  if (Number.isNaN(code)) {
+    return ''; // Posizione non trovata
+  }
+  if (code < 0xD800 || code > 0xDFFF) {
+    return [str.charAt(i), i]; // Carattere normale, mantenendo 'i' lo stesso
+  }
+  // Alto surrogato (potrebbe cambiare l'ultimo esadecimale a 0xDB7F per trattare un alto privato
+  // si surroga come singoli caratteri)
+  if (0xD800 <= code && code <= 0xDBFF) {
+    if (str.length <= (i + 1)) {
+      throw "Alto surrogato senza seguire un surrogato basso";
+    }
+    var next = str.charCodeAt(i + 1);
+      if (0xDC00 > next || next > 0xDFFF) {
+        throw "Alto surrogato senza seguire un surrogato basso";
+      }
+      return [str.charAt (i) + str.charAt (i + 1), i + 1];
+  }
+  // Basso surrogato (0xDC00 <= code && code <= 0xDFFF)
+  if (i === 0) {
+    throw "Basso surrogato senza precedente surrogato elevato";
+  }
+  var prev = str.charCodeAt(i - 1);
+  // (potrebbe cambiare l'ultimo esadecimale in 0xDB7F per trattare i surrogati ad alto livello privato
+  // come singoli caratteri)
+  if (0xD800 > prev || prev > 0xDBFF) {
+    throw "Basso surrogato senza precedente surrogato elevato";
+  }
+  // Restituisce invece il carattere successivo (e incrementa)
+  return [str.charAt(i + 1), i + 1];
+}
+
+ +

Correggere charAt() per supportare caratteri non-Basic-Multilingual-Plane (BMP)

+ +

Mentre l'esempio sopra può essere più frequentemente utile per coloro che desiderano supportare caratteri non BMP (dal momento che non richiede al chiamante di sapere dove potrebbe apparire un personaggio non BMP), nel caso in cui uno lo desideri, nella scelta di un personaggio per indice, per trattare le coppie surrogate all'interno di una stringa come i singoli caratteri che rappresentano, si può usare quanto segue:

+ +
function fixedCharAt(str, idx) {
+  var ret = '';
+  str += '';
+  var end = str.length;
+
+  var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
+  while ((surrogatePairs.exec(str)) != null) {
+    var li = surrogatePairs.lastIndex;
+    if (li - 2 < idx) {
+      idx++;
+    } else {
+      break;
+    }
+  }
+
+  if (idx >= end || idx < 0) {
+    return '';
+  }
+
+  ret += str.charAt(idx);
+
+ if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) {
+    // Vai avanti, poiché uno dei "personaggi" fa parte di una coppia di sostituti
+    ret += str.charAt(idx + 1);
+  }
+  return ret;
+}
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioniStatoCommenti
{{SpecName('ES1')}}{{Spec2('ES1')}}definizione iniziale.
{{SpecName('ES5.1', '#sec-15.5.4.4', 'String.prototype.charAt')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.charat', 'String.prototype.charAt')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.charat', 'String.prototype.charAt')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con il browser

+ + + +

{{Compat("javascript.builtins.String.charAt")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/includes/index.html b/files/it/web/javascript/reference/global_objects/string/includes/index.html new file mode 100644 index 0000000000..44eac8fc22 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/includes/index.html @@ -0,0 +1,188 @@ +--- +title: String.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/String/includes +translation_of: Web/JavaScript/Reference/Global_Objects/String/includes +--- +
{{JSRef}}
+ +
Il metodo includes() verifica se una stringa ne contiene un'altra desiderata, restituendo truefalse in base dell'esito della ricerca.
+ +
 
+ +

Sintassi

+ +
str.includes(searchString[, position])
+ +

Parametri

+ +
+
searchString
+
Una stringa da cercare all'interno di una stringa.
+
position
+
Opzionale. La posizione in questa stringa. La posizione in questa stringa in cui iniziare la ricerca di searchString; il valore predefinito è 0.
+
+ +

Valore di ritorno

+ +

true se la stringa contiene la stringa di ricerca; altrimenti, false.

+ +

Descrizione

+ +

Questo metodo permette di determinare se la stringa includa o no un'altra stringa.

+ +

Sensitività alle maiuscole

+ +

Il metodo includes() è sensibile alle maiuscole. Per esempio, la seguente espressione restituisce false:

+ +
'Blue Whale'.includes('blue'); // returns false
+
+ +

Esempi

+ +

Utilizzando includes()

+ +
var str = 'To be, or not to be, that is the question.';
+
+console.log(str.includes('To be'));       // true
+console.log(str.includes('question'));    // true
+console.log(str.includes('nonexistent')); // false
+console.log(str.includes('To be', 1));    // false
+console.log(str.includes('TO BE'));       // false
+
+ +

Polyfill

+ +

Questo metodo è stato aggiunto alla specifica ECMAScript 2015 e potrebbe essere non disponibile ancora in tutte le implementazioni di JavaScript.

+ +
if (!String.prototype.includes) {
+  String.prototype.includes = function(search, start) {
+    'use strict';
+    if (typeof start !== 'number') {
+      start = 0;
+    }
+
+    if (start + search.length > this.length) {
+      return false;
+    } else {
+      return this.indexOf(search, start) !== -1;
+    }
+  };
+}
+
+/*
+https://github.com/FabioVergani/js-Polyfill_StringIncludes/blob/master/StringIncludes.js
+
+(function(s){'use strict';
+ var o=s.prototype,p='includes';
+ o[p]||(o[p]=function(a,b){//search,start
+  var e=this,i=isNaN(b)?0:b,t=a,l=t.length;
+  return (l<1||((i+l)>e.length))?false:-1!==e.indexOf(t,i);
+ });
+})(String);
+
+*/
+ +

 

+ +

 

+ +

 

+ +

 

+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.includes', 'String.prototype.includes')}}{{Spec2('ES6')}}Definizioni inizili.
{{SpecName('ESDraft', '#sec-string.prototype.includes', 'String.prototype.includes')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser 

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatChrome("41")}}{{CompatGeckoDesktop("40")}}{{CompatNo}}14393+{{CompatNo}}{{CompatSafari("9")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("40")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

String.prototype.contains

+ +

In Firefox 18 - 39, il nome di questo metodo era contains(). E' stato rinominato inincludes() in {{bug(1102219)}} a causa del seguente motivo:

+ +

E' stato riportato che alcuni websites che utilizzano MooTools 1.2 non funzionavano su Firefox 17. Tale versione di MooTools controlla se String.prototype.contains() esiste e, se non esiste,  MooTools aggiunge una propria funzione. Con l'introduzione di questa funzione in Firefox 17, il comportamento di tale controllo è cambiato in un modo che il codice basato su String.prototype.contains()  non funzioni. Come risultato, l'implementazione  è stata disabilitata in Firefox 17 e String.prototype.contains() era disponibile nella versione successiva, in Firefox 18, quando outreach to MooTools stava conducendo al rilascio di MooTools version 1.2.6.

+ +

MooTools 1.3 forza la propria versione di  String.prototype.contains(), così i siti web che si affidano ad essa non vanno in break. Comunque si noti che la signature di  MooTools 1.3 e quella di ECMAScript 2015 per questo metodo differiscono (sul secondo argomento). Più avanti , MooTools 1.5+ ha cambiato la  signature per incontrare lo standard ES2015.

+ +

In Firefox 48, String.prototype.contains() è stato rimosso. Usare String.prototype.includes() solamente.

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/index.html b/files/it/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..713f9a0cb4 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,410 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - NeedsTranslation + - Reference + - String + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

L'oggetto globale "String" è un costruttore per le stringhe o una sequenza alfanumerica di caratteri.

+ +

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)
+ +

Parametri

+ +
+
thing
+
Anything to be converted to a string.
+
+ +

Template literals

+ +

Starting with ECMAScript 2015, string literals can also be so-called Template literals:

+ +
`hello world`
+`hello!
+ world!`
+`hello ${who}`
+escape `<a>${who}</a>`
+ +
+
+ +

Escape notation

+ +

Beside regular, printable characters, special characters can be encoded using escape notation:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CodeOutput
\0the NULL character
\'single quote
\"double quote
\\backslash
\nnuova linea
\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.

+ +

Descrizione

+ +

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. Note that you can not rely on them cross-browser without using the shim that is provided below.

+
+ +

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'));
+
+ +

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.

+ +

The following is a shim to provide support to non-supporting browsers:

+ +
/*globals define*/
+// Assumes all supplied String instance methods already present
+// (one may use shims for these if not available)
+(function() {
+  'use strict';
+
+  var i,
+    // We could also build the array of methods with the following, but the
+    //   getOwnPropertyNames() method is non-shimable:
+    // Object.getOwnPropertyNames(String).filter(function(methodName) {
+    //   return typeof String[methodName] === 'function';
+    // });
+    methods = [
+      'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
+      'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
+      'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
+      'toLocaleUpperCase', 'localeCompare', 'match', 'search',
+      'replace', 'split', 'substr', 'concat', 'slice'
+    ],
+    methodCount = methods.length,
+    assignStringGeneric = function(methodName) {
+      var method = String.prototype[methodName];
+      String[methodName] = function(arg1) {
+        return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
+      };
+    };
+
+  for (i = 0; i < methodCount; i++) {
+    assignStringGeneric(methods[i]);
+  }
+}());
+
+ +

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, as 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('ES6', '#sec-string-objects', 'String')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatVersionUnknown}}{{CompatGeckoDesktop("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/indexof/index.html b/files/it/web/javascript/reference/global_objects/string/indexof/index.html new file mode 100644 index 0000000000..e8653cac62 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/indexof/index.html @@ -0,0 +1,151 @@ +--- +title: String.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/indexOf +translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf +--- +
{{JSRef}}
+ +

Il metodo indexOf() restituisce l'indice all'interno dell'oggetto {{jsxref("String")}} chiamante della prima occorrenza del valore specificato, avviando la ricerca su fromIndex. Restituisce -1 se il valore non viene trovato.

+ +
{{EmbedInteractiveExample("pages/js/string-indexof.html")}}
+ + + +
Note: Per il metodo dell'Array, vedere {{jsxref("Array.prototype.indexOf()")}}.
+ +

Sintassi

+ +
str.indexOf(searchValue[, fromIndex])
+ +

Parametri

+ +
+
searchValue
+
Una stringa che rappresenta il valore da cercare. Se non viene fornita esplicitamente alcuna stringa, searchValue sarà forzato a "undefined" e questo valore verrà cercato nella stringa corrente.
+
fromIndex {{optional_inline}}
+
Un numero intero che rappresenta l'indice al quale avviare la ricerca; il valore predefinito è  0. Per valori fromIndex values inferiori a 0 o maggiori di str.length, la ricerca inizia rispettivamente con 0str.length.
+
+ +

Valore di ritorno

+ +

L'indice della prima occorrenza di searchValue o -1 se non trovato.
+ Una stringa vuota searchValue corrisponderà a qualsiasi indice tra 0 e str.length.

+ +

Descrizione

+ +

I caratteri in una stringa sono indicizzati da sinistra a destra. L'indice del primo carattere è 0 e l'indice dell'ultimo carattere di una stringa chiamata stringName è stringName.length - 1.

+ +
'Blue Whale'.indexOf('Blue');     // ritorna  0
+'Blue Whale'.indexOf('Blute');    // ritorna -1
+'Blue Whale'.indexOf('Whale', 0); // ritorna  5
+'Blue Whale'.indexOf('Whale', 5); // ritorna  5
+'Blue Whale'.indexOf('Whale', 7); // ritorna -1
+'Blue Whale'.indexOf('');         // ritorna  0
+'Blue Whale'.indexOf('', 9);      // ritorna  9
+'Blue Whale'.indexOf('', 10);     // ritorna 10
+'Blue Whale'.indexOf('', 11);     // ritorna 10
+
+ +

Il metodo indexOf() è case sensitive. Ad esempio, la seguente espressione restituisce -1:

+ +
'Blue Whale'.indexOf('blue'); // ritorna -1
+
+ +

Controllo delle occorrenze

+ +

Nota che '0' non valuta true e '-1' non valuta false. Pertanto, quando si verifica se esiste una stringa specifica all'interno di un'altra stringa, il modo corretto per verificare sarebbe:

+ +
'Blue Whale'.indexOf('Blue') !== -1; // true
+'Blue Whale'.indexOf('Bloe') !== -1; // false
+
+ +

Esempi

+ +

Usare indexOf()

+ +

Nell'esempio seguente viene utilizzato indexOf() per individuare i valori nella stringa "Brave new world".

+ +
const str = 'Brave new world';
+
+console.log('L'indice della prima w dall'inizio è ' + str.indexOf('w'));  // logga 8
+console.log('L'indice di "new" dall'inizio è ' + str.indexOf('new'));  // logga 6
+
+ +

indexOf() e il case-sensitivity

+ +

L'esempio seguente definisce due variabili stringa. Le variabili contengono la stessa stringa tranne che la seconda stringa contiene lettere maiuscole. Il primo metodo {{domxref("console.log()")}} mostra 19. Ma poiché il metodo indexOf() è case sensitive, la stringa "cheddar" non si trova in myCapString, quindi il secondo metodo console.log() mostra -1.

+ +
const myString    = 'brie, pepper jack, cheddar';
+const myCapString = 'Brie, Pepper Jack, Cheddar';
+
+console.log('myString.indexOf("cheddar") è ' + myString.indexOf('cheddar'));
+// logs 19
+console.log('myCapString.indexOf("cheddar") è ' + myCapString.indexOf('cheddar'));
+// logs -1
+
+ +

Uso di indexOf() per contare le occorrenze di una lettera in una stringa

+ +

L'esempio seguente imposta count sul numero di occorrenze della lettera e nella stringa str:

+ +
const str = 'Essere o non essere, questa è la domanda.';
+let count = 0;
+let position = str.indexOf('e');
+
+while (position !== -1) {
+  count++;
+  position = str.indexOf('e', position + 1);
+}
+
+console.log(count); // mostra 4
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.builtins.String.indexOf")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/length/index.html b/files/it/web/javascript/reference/global_objects/string/length/index.html new file mode 100644 index 0000000000..e575b777b8 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/length/index.html @@ -0,0 +1,90 @@ +--- +title: string.length +slug: Web/JavaScript/Reference/Global_Objects/String/length +translation_of: Web/JavaScript/Reference/Global_Objects/String/length +--- +
{{JSRef}}
+ +

La proprietà length di un oggetto {{jsxref("String")}} indica la lunghezza di una stringa, in unità di codice UTF-16.

+ +

Sintassi

+ +
str.length
+ +

Descrizione

+ +

Questa proprietà restituisce il numero di unità di codice nella stringa. {{interwiki("wikipedia", "UTF-16")}}, il formato di stringa utilizzato da JavaScript, utilizza una singola unità di codice a 16 bit per rappresentare i caratteri più comuni, ma deve utilizzare due unità di codice per meno comunemente- caratteri usati, quindi è possibile che il valore restituito dalla length “lunghezza“ non corrisponda al numero effettivo di caratteri nella stringa.

+ +

ECMASCript 2016 (ed. 7) ha stabilito una lunghezza massima di 2^53 - 1 elementi. In precedenza, non è stata specificata una lunghezza massima.. 

+ +

Per una stringa vuota, length è 0.

+ +

La proprietà statica String.length restituisce il valore 1.

+ +

Esempi

+ +

Basic usage

+ +
var x = 'Mozilla';
+var empty = '';
+
+console.log('Mozilla is ' + x.length + ' code units long');
+/* "Mozilla è lungo 7 unità di codice" */
+
+console.log('La stringa vuota ha una lunghezza di
+ ' + empty.length);
+/* "La stringa vuota ha una lunghezza di 0" */
+ +

Assegnazione a length

+ +
var myString = "bluebells";
+
+// Il tentativo di assegnare un valore alla proprietà .length di una stringa non ha alcun effetto osservabile.
+myString.length = 4;
+console.log(myString);
+/* "bluebells" */
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioniStatoCommenti
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale Implementato in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibili

+ + + +

{{Compat("javascript.builtins.String.length")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/prototype/index.html b/files/it/web/javascript/reference/global_objects/string/prototype/index.html new file mode 100644 index 0000000000..b13374a9a0 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/prototype/index.html @@ -0,0 +1,178 @@ +--- +title: String.prototype +slug: Web/JavaScript/Reference/Global_Objects/String/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

La proprietà String.prototyperappresenta l'oggetto prototipo {{jsxref("String")}}.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Description

+ +

Tutte le istanze {{jsxref("String")}} ereditano da String.prototype . Le modifiche all'oggetto prototipo String vengono propagate a tutte le istanze {{jsxref("String")}}.

+ +

Properties

+ +
+
String.prototype.constructor
+
Specifica la funzione che crea il prototipo di un oggetto.
+
{{jsxref("String.prototype.length")}}
+
Riflette la lunghezza della stringa.
+
N
+
Utilizzato per accedere al carattere in N posizione in cui N è un numero intero positivo compreso tra 0 e uno inferiore al valore della {{jsxref("String.length", "length")}}. Queste proprietà sono di sola lettura.
+
+ +

Metodi

+ +

Metodi non correlati HTML

+ +
+
{{jsxref("String.prototype.charAt()")}}
+
Restituisce il carattere (esattamente un'unità di codice UTF-16) all'indice specificato
+
{{jsxref("String.prototype.charCodeAt()")}}
+
Restituisce un numero che corrisponde al valore dell'unità di codice UTF-16 nell'indice specificato.
+
{{jsxref("String.prototype.codePointAt()")}}
+
Restituisce un numero intero non negativo Numero che è il valore del punto di codice codificato UTF-16 che inizia con l'indice specificato.
+
{{jsxref("String.prototype.concat()")}}
+
Combina il testo di due stringhe e restituisce una nuova stringa.
+
{{jsxref("String.prototype.includes()")}}
+
Determina se una stringa può essere trovata all'interno di un'altra stringa.
+
{{jsxref("String.prototype.endsWith()")}}
+
Determina se una stringa termina con i caratteri di un'altra stringa.
+
{{jsxref("String.prototype.indexOf()")}}
+
Restituisce l'indice all'interno dell'oggetto {{jsxref("String")}} chiamante della prima occorrenza del valore specificato o -1 se non trovato.
+
{{jsxref("String.prototype.lastIndexOf()")}}
+
Restituisce l'indice all'interno dell'oggetto {{jsxref("String")}} chiamante della prima occorrenza del valore specificato o -1 se non trovato.
+
{{jsxref("String.prototype.localeCompare()")}}
+
Restituisce un numero che indica se una stringa di riferimento viene prima o dopo o è uguale alla stringa specificata in ordine di ordinamento.
+
{{jsxref("String.prototype.match()")}}
+
Utilizzato per abbinare un'espressione regolare a una stringa.
+
{{jsxref("String.prototype.normalize()")}}
+
Restituisce il modulo di normalizzazione Unicode del valore della stringa chiamante.
+
{{jsxref("String.prototype.padEnd()")}}
+
Riempie la stringa corrente dalla fine con una determinata stringa per creare una nuova stringa di una determinata lunghezza.
+
{{jsxref("String.prototype.padStart()")}}
+
Riempie la stringa corrente dall'inizio con una determinata stringa per creare una nuova stringa da una determinata lunghezza.
+
{{jsxref("String.prototype.quote()")}} {{obsolete_inline}}
+
Avvolge la stringa tra virgolette (""").
+
{{jsxref("String.prototype.repeat()")}}
+
Restituisce una stringa composta da elementi dell'oggetto ripetuti i tempi indicati.
+
{{jsxref("String.prototype.replace()")}}
+
Utilizzato per trovare una corrispondenza tra un'espressione regolare e una stringa e per sostituire la sottostringa con corrispondenza con una nuova sottostringa.
+
{{jsxref("String.prototype.search()")}}
+
Esegue la ricerca di una corrispondenza tra un'espressione regolare e una stringa specificata.
+
{{jsxref("String.prototype.slice()")}}
+
Estrae una sezione di una stringa e restituisce una nuova stringa.
+
{{jsxref("String.prototype.split()")}}
+
Divide un oggetto  {{jsxref("Global_Objects/String", "String")}} in una matrice di stringhe separando la stringa in sottostringhe.
+
{{jsxref("String.prototype.startsWith()")}}
+
Determina se una stringa inizia con i caratteri di un'altra stringa.
+
{{jsxref("String.prototype.substr()")}} {{deprecated_inline}}
+
Restituisce i caratteri in una stringa che inizia nella posizione specificata attraverso il numero specificato di caratteri.
+
{{jsxref("String.prototype.substring()")}}
+
Restituisce i caratteri in una stringa tra due indici nella stringa.
+
{{jsxref("String.prototype.toLocaleLowerCase()")}}
+
I caratteri all'interno di una stringa vengono convertiti in minuscolo rispettando le impostazioni locali correnti. Per la maggior parte delle lingue, questo restituirà lo stesso di {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}.
+
{{jsxref("String.prototype.toLocaleUpperCase()")}}
+
I caratteri all'interno di una stringa vengono convertiti in maiuscolo rispettando le impostazioni locali correnti. Per la maggior parte delle lingue, ciò restituirà lo stesso di {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}}.
+
{{jsxref("String.prototype.toLowerCase()")}}
+
Restituisce il valore della stringa chiamante convertito in minuscolo.
+
{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}}
+
Restituisce un oggetto letterale che rappresenta l'oggetto specificato; puoi usare questo valore per creare un nuovo oggetto. Sostituisce il metodo {{jsxref("Object.prototype.toSource()")}} method.
+
{{jsxref("String.prototype.toString()")}}
+
Restituisce una stringa che rappresenta l'oggetto specificato. Sostituisce il metodo {{jsxref("Object.prototype.toString()")}} .
+
{{jsxref("String.prototype.toUpperCase()")}}
+
Restituisce il valore della stringa chiamante convertito in maiuscolo.
+
{{jsxref("String.prototype.trim()")}}
+
Taglia gli spazi bianchi all'inizio e alla fine della stringa. Parte dello standard ECMAScript 5.
+
{{jsxref("String.prototype.trimStart()")}}
+ {{jsxref("String.prototype.trimLeft()")}}
+
Taglia gli spazi bianchi dall'inizio della stringa.
+
{{jsxref("String.prototype.trimEnd()")}}
+ {{jsxref("String.prototype.trimRight()")}}
+
Taglia gli spazi bianchi dalla fine della stringa.
+
{{jsxref("String.prototype.valueOf()")}}
+
Restituisce il valore primitivo dell'oggetto specificato. Sostituisce il metodo {{jsxref("Object.prototype.valueOf()")}}.
+
{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}}
+
Restituisce un nuovo oggetto Iterator che itera sopra i punti di codice di un valore String, restituendo ogni punto di codice come valore String.
+
+ +

HTML metodi wrapper (involucro)

+ +

Questi metodi sono di uso limitato, in quanto forniscono solo un sottoinsieme dei tag e degli attributi HTML disponibili.

+ +
+
{{jsxref("String.prototype.anchor()")}} {{deprecated_inline}}
+
{{htmlattrxref("name", "a", "<a name=\"name\">")}} (hypertext target)
+
{{jsxref("String.prototype.big()")}} {{deprecated_inline}}
+
{{HTMLElement("big")}}
+
{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}
+
{{HTMLElement("blink")}}
+
{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}
+
{{HTMLElement("b")}}
+
{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}
+
{{HTMLElement("tt")}}
+
{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}
+
{{htmlattrxref("color", "font", "<font color=\"color\">")}}
+
{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}
+
{{htmlattrxref("size", "font", "<font size=\"size\">")}}
+
{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}
+
{{HTMLElement("i")}}
+
{{jsxref("String.prototype.link()")}} {{deprecated_inline}}
+
{{htmlattrxref("href", "a", "<a href=\"url\">")}} (link to URL)
+
{{jsxref("String.prototype.small()")}} {{deprecated_inline}}
+
{{HTMLElement("small")}}
+
{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}
+
{{HTMLElement("strike")}}
+
{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}
+
{{HTMLElement("sub")}}
+
{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}
+
{{HTMLElement("sup")}}
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioniStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale.
{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con il browser

+ + + +

{{Compat("javascript.builtins.String.prototype")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/string/raw/index.html b/files/it/web/javascript/reference/global_objects/string/raw/index.html new file mode 100644 index 0000000000..2d070b15cb --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/string/raw/index.html @@ -0,0 +1,108 @@ +--- +title: String.raw() +slug: Web/JavaScript/Reference/Global_Objects/String/raw +translation_of: Web/JavaScript/Reference/Global_Objects/String/raw +--- +
{{JSRef}}
+ +

Il metodo statico String.raw() è una funzione di tag del modello template string, simile al prefisso r in Python o al prefisso @ in C# per i valori letterali stringa (tuttavia c'è una differenza: vedere le spiegazioni in questo numero ). È usato per ottenere la stringa di stringhe di template non formattata, cioè le sostituzioni (ad esempio ${foo}) vengono elaborate, ma gli escape (ad esempio \n ) non lo sono.

+ +

Sintassi

+ +
String.raw(callSite, ...substitutions)
+String.raw`templateString`
+
+ +

Parametri

+ +
+
callSite
+
Oggetto del sito di chiamata template ben formato, come { raw: ['foo', 'bar', 'baz'] }.
+
...substitutions
+
Contiene valori di sostituzione.
+
templateString
+
A template string, puoi sostituirlo opzionalmente (${...}).
+
+ +

Valore resituto

+ +

Restituisce una stringa non elaborata di un determinato Template String.

+ +

Eccezioni

+ +
+
{{jsxref("TypeError")}}
+
Un oggetto {{jsxref("TypeError")}} viene generato se il primo argomento non è un oggetto formato.
+
+ +

Descrizione

+ +

Nella maggior parte dei casi, String.raw() viene utilizzato con template strings. La prima sintassi menzionata sopra è usata solo di rado, perché il motore JavaScript la chiamerà con argomenti appropriati, proprio come con altre funzioni tag .

+ +

String.raw() è l'unica funzione di built-in tag incorporata nei template strings; funziona proprio come la funzione predefinita del modello ed esegue la concatenazione. Puoi anche ri-implementarlo con il normale codice JavaScript.

+ +

Esempi

+ +

Utilizzo di String.raw()

+ +
String.raw`Ciao\n${2+3}!`;
+// 'Ciao\n5!', Il carattere dopo 'Ciao' non è un carattere di nuova riga,
+// '\' e 'n' sono due caratteri.
+
+String.raw`Hi\u000A!`;
+// 'Ciao\u000A!', Lo stesso qui, questa volta avremo il
+// \, u, 0, 0, 0, A, 6 caratteri.
+// Tutti i tipi di caratteri di escape saranno inefficaci
+// e backslash saranno presenti nella stringa di output
+// Puoi confermare questo controllando la proprietà .length
+// della stringa.
+
+let name = 'Bob';
+String.raw`Ciao\n${name}!`;
+// 'Ciao\nBob!', le sostituzioni vengono elaborate.
+
+// Normalmente non si chiama String.raw() come una funzione,
+// ma la si chiama per simulare `t${0}e${1}s${2}t` puoi fare:
+String.raw({ raw: 'test' }, 0, 1, 2); // 't0e1s2t'
+// Nota che la stringa 'test', è un oggetto simile ad un array
+// Il seguente è equivalente a
+// `foo${2 + 3}bar${'Java' + 'Script'}baz`
+String.raw({
+  raw: ['foo', 'bar', 'baz']
+}, 2 + 3, 'Java' + 'Script'); // 'foo5barJavaScriptbaz'
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + +
SpecificazioniStatoCommento
{{SpecName('ES2015', '#sec-string.raw', 'String.raw')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-string.raw', 'String.raw')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con il browser

+ + + +

{{Compat("javascript.builtins.String.raw")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/symbol/index.html b/files/it/web/javascript/reference/global_objects/symbol/index.html new file mode 100644 index 0000000000..5445a96009 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/symbol/index.html @@ -0,0 +1,230 @@ +--- +title: Symbol +slug: Web/JavaScript/Reference/Global_Objects/Symbol +tags: + - ECMAScript 2015 + - ECMAScript6 + - JavaScript + - Symbol +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol +--- +
{{JSRef}}
+ +

La funzione Symbol() restituisce un valore di tipo symbol, dispone di proprietà statiche che espongono diversi membri di oggetti built-in, ha metodi statici che espongono il registro globale dei symbol, ed assomiglia all'oggetto built-in class, ma non dispone di un costruttore e non supporta la sintassi "new Symbol()".  

+ +

Ogni valore symbol restituito da Symbol() è unico.  Un valore symbol può essere utilizzato come identificatore per proprietà di un oggetto; questo è lo scopo di tale tipo di dati.  Ulteriori spiegazioni circa il loro scopo ed uso può essere trovato nella pagina: glossary entry for Symbol.

+ +

Il tipo di dati symbol è un {{Glossary("Primitive", "primitive data type")}}.

+ +

Syntax

+ +
Symbol([description])
+ +

Parametri

+ +
+
description {{optional_inline}}
+
Opzionale, string. Una descrizione del symbol che può essere usata per il debug ma non per accedere al symbol stesso.
+
+ +

Descrizione

+ +

Per creare un nuovo primitive symbol, scrivereSymbol() con una stringa opzionale di descrizione:

+ +
var sym1 = Symbol();
+var sym2 = Symbol('foo');
+var sym3 = Symbol('foo');
+
+ +

Il codice sopra crea tre nuovi symbol. Notare che Symbol("foo") non costringe la stringa "foo" in un symbol. Esso crea un nuovo symbol ogni volta:

+ +
Symbol('foo') === Symbol('foo'); // false
+ +

La sintassi seguente con l'operatore {{jsxref("Operators/new", "new")}} genererà un {{jsxref("TypeError")}}:

+ +
var sym = new Symbol(); // TypeError
+ +

Questo previene gli autori dal creare un esplicito oggetto wrapper Symbol invece di un nuovo valore symbol e la cosa può sorprendere in quanto creare un oggetto wrapper esplicito attorno ad un tipo di dati primitivo è generalmente possibile (ad esempio, new Boolean, new String e new Number).

+ +

Se veramente si vuole creare un oggetto wrapper Symbol si può usare la funzione Object():

+ +
var sym = Symbol('foo');
+typeof sym;     // "symbol"
+var symObj = Object(sym);
+typeof symObj;  // "object"
+
+ +

Symbols condivisi nel registro globale dei symbol

+ +

La sintassi vista sopra che utilizza la funzione Symbol() non crea un symbol globale che sarà disponibile nell'intero codebase. Per creare dei symbol disponibili attraverso diversi files ed anche attraverso diversi realms (ognuno dei quali ha il proprio global scope), usare i metodi {{jsxref("Symbol.for()")}} e {{jsxref("Symbol.keyFor()")}} per impostare e leggere i symbol dal registro globale.

+ +

Cercare le proprietà symbol negli oggetti

+ +

Il metodo {{jsxref("Object.getOwnPropertySymbols()")}} restituisce un array di symbol e permette di trovare le proprietà symbol di un oggetto. Notare che ogni oggetto è inizializzato senza alcuna proprietà symbol, per cui l'array restituito sarà vuoto a meno che una proprietà symbol non sia stata creata sull'oggetto.

+ +

Proprietà

+ +
+
Symbol.length
+
Proprietà "lunghezza", il cui valore è 0.
+
{{jsxref("Symbol.prototype")}}
+
Rappresenta il prototype del costruttore Symbol.
+
+ +

Symbols ben noti

+ +

In aggiunta ai symbol definiti da voi, JavaScript dispone di alcuni symbol built-in che rappresentano alcuni comportamenti interni del linguaggio che non sono esposti agli sviluppatori in ECMAScript5 e precedenti. A tali symbol si può accedere tramite le seguenti proprietà:

+ +

Symbols di iterazione

+ +
+
{{jsxref("Symbol.iterator")}}
+
Un metodo che restituisce l'iteratore di default per un oggetto. Usato da for...of.
+
{{jsxref("Symbol.asyncIterator")}} {{experimental_inline}}
+
Un metodo che restituisce l'iteratore asincrono di default per un oggetto. Usato da for await of.
+
+ +

Symbols per le espressioni regolari

+ +
+
{{jsxref("Symbol.match")}}
+
Un metodo che effettua la corrispondenza su una stringa, usato anche per determinare se un oggetto può essere utilizzato come espressione regolare. Usato da {{jsxref("String.prototype.match()")}}.
+
{{jsxref("Symbol.replace")}}
+
Un metodo che sostituisce le sottostringhe di una stringa corrispondenti. Usato da {{jsxref("String.prototype.replace()")}}.
+
{{jsxref("Symbol.search")}}
+
Un metodo che restituisce l'indice all'interno di una stringa che corrisponde all'espressione regolare. Usato da {{jsxref("String.prototype.search()")}}.
+
{{jsxref("Symbol.split")}}
+
Un metodo che divide una stringa all'indice corrispondente ad una espressione regolare. Usato da {{jsxref("String.prototype.split()")}}.
+
+ +

Altri symbols

+ +
+
{{jsxref("Symbol.hasInstance")}}
+
Un metodo che determina se un oggetto costruttore riconosce un oggetto come propria istanza. Usato da {{jsxref("Operators/instanceof", "instanceof")}}.
+
{{jsxref("Symbol.isConcatSpreadable")}}
+
Un valore booleano indicante se un oggetto deve essere appiattito ai soui elementi array. Usato da {{jsxref("Array.prototype.concat()")}}.
+
{{jsxref("Symbol.unscopables")}}
+
An object value of whose own and inherited property names are excluded from the with environment bindings of the associated object.
+
{{jsxref("Symbol.species")}}
+
Una funzione costruttore utilizzata per creare oggetti derivati.
+
{{jsxref("Symbol.toPrimitive")}}
+
Un metodo che converte un oggetto in un valore primitivo.
+
{{jsxref("Symbol.toStringTag")}}
+
Una stringa usata per la descizione di default di un oggetto. Usato da {{jsxref("Object.prototype.toString()")}}.
+
+ +

Metodi

+ +
+
{{jsxref("Symbol.for()", "Symbol.for(key)")}}
+
Cerca la "key" fornita tra i symbol esistenti e la restituisce nel caso in cui venga trovata. In caso contrario un nuovo symbol viene creato nel registro globale dei symbol con la "key" indicata.
+
{{jsxref("Symbol.keyFor", "Symbol.keyFor(sym)")}}
+
Trova una chiave symbol condivisa dal registro globale dei symbol per il symbol fornito.
+
+ +

Symbol prototype

+ +

Tutti i simboli ereditano da {{jsxref("Symbol.prototype")}}.

+ +

Proprietà

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Properties')}}

+ +

Metodi

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Methods')}}

+ +

Esempi

+ +

Using the typeof operator with symbols

+ +

L'operatore {{jsxref("Operators/typeof", "typeof")}} può aiutare ad identificare i symbol.

+ +
typeof Symbol() === 'symbol'
+typeof Symbol('foo') === 'symbol'
+typeof Symbol.iterator === 'symbol'
+
+ +

Conversioni di tipo dei symbol

+ +

Alcune cose da notare quando si lavora con le conversioni di tipo dei symbol.

+ + + +

Symbols ed iterazione for...in

+ +

I symbol non sono enumerabili in un'iterazione for...in. In aggiunta, {{jsxref("Object.getOwnPropertyNames()")}} non restituirà le proprietà symbol dell'oggetto, tuttavia, si puù usare {{jsxref("Object.getOwnPropertySymbols()")}} per ottenerle.

+ +
var obj = {};
+
+obj[Symbol('a')] = 'a';
+obj[Symbol.for('b')] = 'b';
+obj['c'] = 'c';
+obj.d = 'd';
+
+for (var i in obj) {
+   console.log(i); // logs "c" and "d"
+}
+ +

Symbols e JSON.stringify()

+ +

Le proprietà le cui chiavi sono symbol vengono completamente ignorate da JSON.stringify():

+ +
JSON.stringify({[Symbol('foo')]: 'foo'});
+// '{}'
+ +

Per ulteriori dettagli, vedere {{jsxref("JSON.stringify()")}}.

+ +

Symbol wrapper objects come chiavi per le proprietà

+ +

Quando un oggetto wrapper symbol viene usato come chiave di una proprietà, tale oggetto verrà costretto al suo wrapped symbol:

+ +
var sym = Symbol('foo');
+var obj = {[sym]: 1};
+obj[sym];            // 1
+obj[Object(sym)];    // still 1
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + +
SpecificazioneStatoCommento
{{SpecName('ES2015', '#sec-symbol-objects', 'Symbol')}}{{Spec2('ES2015')}}Initial definition
{{SpecName('ESDraft', '#sec-symbol-objects', 'Symbol')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Symbol")}}

+ +

Vedere anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/undefined/index.html b/files/it/web/javascript/reference/global_objects/undefined/index.html new file mode 100644 index 0000000000..d16ca712cf --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/undefined/index.html @@ -0,0 +1,173 @@ +--- +title: undefined +slug: Web/JavaScript/Reference/Global_Objects/undefined +translation_of: Web/JavaScript/Reference/Global_Objects/undefined +--- +
+
+
{{jsSidebar("Objects")}}
+
+
+ +

Sommario

+ +

La variabile globale undefined rappresenta il valore primitivo {{Glossary("Undefined", "undefined")}}. È uno dei {{Glossary("Primitive", "valori primitivi")}} di JavaScript.

+ +

{{js_property_attributes(0,0,0)}}

+ +

Sintassi

+ +
undefined
+ +

Descrizione

+ +

undefined è una proprietà dell'oggetto globale, ossia una variablie nel contesto globale. Il valore iniziale di undefined è il valore primitivo {{Glossary("Undefined", "undefined")}}.

+ +

Secondo la specifica ECMAScript5, undefined è accessibile in sola lettura (implementato in JavaScript 1.8.5 / Firefox 4).

+ +

Una variabile alla quale non è ancora stato assegnato un valore è di tipo undefined. Un metodo o una dichiarazione restituisce undefined se la variabile che viene valutata non ha un valore assegnato. Una funzione restituisce undefined se non viene restituito un altro valore.

+ +

Siccome undefined non è una {{jsxref("Reserved_Words", "parola riservata")}}, può essere usato come nome di una variabile in qualsiasi contesto, eccetto quello globale.

+ +
// logs "foo string"
+(function(){ var undefined = 'foo'; console.log(undefined, typeof undefined); })();
+
+// logs "foo string"
+(function(undefined){ console.log(undefined, typeof undefined); })('foo');
+
+ +

Esempi

+ +

undefined e l'uguaglianza ristretta

+ +

Puoi usare undefined e gli operatori "strettamente uguale" e "strettamente diverso" per determinare se ad una variabile è stato assegnato un valore. In questo codice, la variabile x non è definita, qundi l'istruzione if viene valutata vera.

+ +
var x;
+
+x === undefined; // true
+
+ +
Nota: Qui devono essere utilizzati gli operatori di uguaglianza stretta, perché x == undefined è vero anche se x è null, mentre confrontandoli con l'ugualianza stretta no. null e undefined non sono equivalenti. Vedi gli {{jsxref("Operators/Comparsion_Operators", "operatori di comparazione")}} per altri dettagli.
+ +

undefined e l'operatore typeof

+ +

In alternativa può anche essere usato l'operatore {{jsxref("Operators/typeof", "typeof")}}:

+ +
var x;
+
+typeof x === 'undefined'; // true
+
+ +

Un motivo per cui usare l'operatore {{jsxref("Operators/typeof", "typeof")}} è che se la variabile non  stata dichiarata non viene generato un errore.

+ +
// x non è ancora stata dichiarata
+
+typeof x === "undefined"; // viene valutata come vera, senza generare erroi
+
+x === undefined;          // genera un ReferenceError
+
+ +

Comunque questa tecnica dovrebbe essere evitata. JavaScript è un linguaggio staticamente contestualizzato, quindi si può sapere se una variabile è stata dichiarata in un contesto guardando in quelli che lo contengono. L'unica eccezione è il contesto globale, che è rappresentato dall'oggetto globale: quindi per sapere se esiste una variabile basta controllare se esiste una proprietà nell'oggetto globale (per esempio usando l'operatore {{jsxref("Operators/in", "in")}} o il metodo {{jsxref("Global_Objects/Object/hasOwnProperty", "hasOwnProperty")}})

+ +
// x non è ancora stata dichiarata
+
+"x" in window;              // false
+window.hasOwnProperty("x"); // false
+
+var x = 3;
+
+"x" in window;              // true
+window.hasOwnProperty("y"); // true
+
+ +

undefined e l'operatore void

+ +

Una terza alternativa è l'operatore {{jsxref("Operators/void", "void")}}.

+ +
var x;
+x === void 0; // true
+
+// y non è ancora stata dichiarata
+y === void 0; // genera un ReferenceError (a differenza di `typeof`)
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardDefinizione iniziale. Implementato in JavaScript 1.3
{{SpecName('ES5.1', '#sec-15.1.1.3', 'undefined')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-undefined', 'undefined')}}{{Spec2('ES6')}} 
+ +

Compatibilità con i browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

diff --git a/files/it/web/javascript/reference/global_objects/unescape/index.html b/files/it/web/javascript/reference/global_objects/unescape/index.html new file mode 100644 index 0000000000..d3c31d5f96 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/unescape/index.html @@ -0,0 +1,124 @@ +--- +title: unescape() +slug: Web/JavaScript/Reference/Global_Objects/unescape +translation_of: Web/JavaScript/Reference/Global_Objects/unescape +--- +
+
+
{{jsSidebar("Objects")}} {{deprecated_header()}}
+
+
+ +

Sommario

+ +

La funzione unescape(), deprecata, crea una nuova stringa nella quale le sequenze di escape esadecimali vengono sostituite con il loro carattere corrispondente. Le sequenze di escape potrebbero essere state generate da funzioni simili a {{jsxref("Global_Objects/escape", "escape()")}}. Essendo unescape() deprecata, è preferibile utilizzare le funzioni {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} o {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}.

+ +
Nota: Non usare la funzione unescape() per decodificare degli {{Glossary("URI")}}, usa {{jsxref("Global_Objects/decodeURI", "decodeURI()")}}.
+ +

Sintassi

+ +
unescape(string)
+ +

Parametri

+ +
+
string
+
La stringa da decodificare.
+
+ +

Descrizione

+ +

La funzione unescape() è una proprietà dell'oggetto globale.

+ +

Esempi

+ +
unescape("abc123");     // "abc123"
+unescape("%E4%F6%FC");  // "äöü"
+unescape("%u0107");     // "ć"
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
ECMAScript 1st Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-B.2.2', 'unescape')}}{{Spec2('ES5.1')}}Definita nell'appendice B, "Compatibility"
{{SpecName('ES6', '#sec-unescape-string', 'unescape')}}{{Spec2('ES6')}}Definita nell'appendice B, "Additional ECMAScript Features for Web Browsers"
+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/global_objects/uneval/index.html b/files/it/web/javascript/reference/global_objects/uneval/index.html new file mode 100644 index 0000000000..965dc014b4 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/uneval/index.html @@ -0,0 +1,112 @@ +--- +title: uneval() +slug: Web/JavaScript/Reference/Global_Objects/uneval +translation_of: Web/JavaScript/Reference/Global_Objects/uneval +--- +
+
+
{{jsSidebar("Objects")}}{{Non-standard_header}}
+
+
+ +

Sommario

+ +

La funzione uneval() crea una stringa rappresentante il codice sorcente di un oggetto.

+ +

Sintassi

+ +
uneval(object)
+ +

Parametri

+ +
+
object
+
Una qualsiasi espressione o dichiarazione JavaScript
+
+ +
Nota: Questa funzione non restituisce una rappresentazione JSON valida. Usare il metodo {{jsxref("JSON.stringify()")}}
+ +

Descrizione

+ +

uneval() è una funzione globale e non è associata a nessun oggetto.

+ +

Esempi

+ +
var a = 1;
+uneval(a); // restituisce la stringa "1"
+
+var b = "1";
+uneval(b) // restituisce la stringa '"1"'
+
+uneval(function foo(){}); // restituisce "(function foo(){})"
+
+
+var a = uneval(function foo(){return "ciao"});
+var foo = eval(a);
+foo(); // restituisce "ciao"
+
+ +

Specifiche

+ +

Non fa parte di nessuna specifica.

+ +

Compatibilità con i browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FunzionalitàChromeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto di base{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FunzionalitàAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto di base{{ CompatNo() }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/index.html b/files/it/web/javascript/reference/index.html new file mode 100644 index 0000000000..47b1cdf0fd --- /dev/null +++ b/files/it/web/javascript/reference/index.html @@ -0,0 +1,49 @@ +--- +title: Riferimento JavaScript +slug: Web/JavaScript/Reference +tags: + - JavaScript + - TopicStub +translation_of: Web/JavaScript/Reference +--- +

{{JsSidebar}}

+ +

Questa sezione riguardante JavaScript contiene informazioni riguardo a tale linguaggio. Leggi altre informazioni {{jsxref("About", "riguardo a questa documentazione", "", 1)}}.

+ +

Oggetti globali

+ +

Questo capitolo documenta tutti gli {{jsxref("Global_Objects", "oggetti standard predefiniti", "", 1)}} di JavaScript, con i loro metodi e le loro proprietà.

+ +
{{page('/it/docs/Web/JavaScript/Reference/Global_Objects', 'Oggetti_standard_(per_categoria)')}}
+ +

Statements

+ +

Questo capitolo documenta tutti gli {{jsxref("Statements", "statements e le dichiarazioni", "", 1)}} JavaScript.

+ +
{{page('/it/docs/Web/JavaScript/Reference/Statements', "Statements_and_declarations_by_category")}}
+ +

Espressioni e operatori

+ +

Questo capitolo documenta {{jsxref("Operators", "espresisioni e operatori", "", 1)}} di JavaScript.

+ +
{{page('/it/docs/Web/JavaScript/Reference/Operators', "Expressions_and_operators_by_category", "", 1)}}
+ +

Funzioni

+ +

Questo capitolo documenta come usare le {{jsxref("Functions", "funzioni", "", 1)}} in JavaScript.

+ + + +

Altre pagine utili

+ + diff --git a/files/it/web/javascript/reference/operators/destructuring_assignment/index.html b/files/it/web/javascript/reference/operators/destructuring_assignment/index.html new file mode 100644 index 0000000000..12a790e45c --- /dev/null +++ b/files/it/web/javascript/reference/operators/destructuring_assignment/index.html @@ -0,0 +1,451 @@ +--- +title: Assegnamento di destrutturazione +slug: Web/JavaScript/Reference/Operators/Destructuring_assignment +translation_of: Web/JavaScript/Reference/Operators/Destructuring_assignment +--- +
{{jsSidebar("Operators")}}
+ +

La sintassi di assegnamento di destrutturazione è un'espressione JavaScript che rende possibile estrarre informazioni da array o oggetti in variabili distinte.

+ +

Sintassi

+ +
var a, b, rest;
+[a, b] = [1, 2];
+console.log(a); // 1
+console.log(b); // 2
+
+[a, b, ...rest] = [1, 2, 3, 4, 5];
+console.log(a); // 1
+console.log(b); // 2
+console.log(rest); // [3, 4, 5]
+
+({a, b} = {a:1, b:2});
+console.log(a); // 1
+console.log(b); // 2
+
+// ES2016 - non implementato in Firefox 47a01
+({a, b, ...rest} = {a:1, b:2, c:3, d:4});
+
+ +

Descrizione

+ +

Le espressioni lettali degli oggetti e degli array forniscono un modo facile per creare ad hoc pacchetti di data.

+ +
var x = [1, 2, 3, 4, 5];
+ +

L'assegnamento di destrutturazione utilizza una sintassi simile, ma a sinistra dell'assegnamento sono definiti quali elementi estrarre dalla variabile sorgente (array o oggetti).

+ +
var x = [1, 2, 3, 4, 5];
+var [y, z] = x;
+console.log(y); // 1
+console.log(z); // 2
+
+ +

Questa capacità è simile alle caratteristiche presenti in linguaggi come Perl e Python.

+ +

Destrutturazione di array

+ +

Assegnamento semplice di variabile

+ +
var foo = ["one", "two", "three"];
+
+var [one, two, three] = foo;
+console.log(one); // "one"
+console.log(two); // "two"
+console.log(three); // "three"
+
+ +

Assegnamento separato dalla dichiarazione

+ +

Il valore di una variabile può essere assegnato (sempre con la destrutturazione) in modo separato dalla dichiarazione della variabile stessa.

+ +
var a, b;
+
+[a, b] = [1, 2];
+console.log(a); // 1
+console.log(b); // 2
+
+ +

Valori default

+ +

Ad una variabile può essere assegnato un valore default nel caso in cui il valore estratto dall'array sia undefined.

+ +
var a, b;
+
+[a=5, b=7] = [1];
+console.log(a); // 1
+console.log(b); // 7
+
+ +

Scambio di variabili

+ +

Due valori di variabili possono essere scambiati in un assegnamento di destrutturazione.

+ +

Senza l'assegnamento di destrutturazione, scambiare due valori richiede una variabile momentanea (o, in alcuni linguaggi low-level, il XOR-swap trick).

+ +
var a = 1;
+var b = 3;
+
+[a, b] = [b, a];
+console.log(a); // 3
+console.log(b); // 1
+
+ +

Fare il parsing di un array ritornato da una funzione

+ +

È sempre stato possibile ritornare un array da una funzione. La destrutturazione può rendere più conciso lavorare con il valore di ritorno di un array

+ +

In questo esempio, f() ritorna i valori [1, 2] come output, e questi possono essere analizzati in una singola linea con la destrutturazione.

+ +
function f() {
+  return [1, 2];
+}
+
+var a, b;
+// puoi fare questo grazie alla destrutturazione
+[a, b] = f();
+
+// invece di questo
+a = f()[0];
+b = f()[1];
+
+// è la stessa identica cosa, però c'è un enorme differenza in termini
+//di leggibilità e concisione
+
+console.log(a); // 1
+console.log(b); // 2
+
+ +

Ignorare alcuni valori ritornati

+ +

Puoi ignorare i valori ritornati nei quali non sei interessato:

+ +
function f() {
+  return [1, 2, 3];
+}
+
+var [a, , b] = f();
+console.log(a); // 1
+console.log(b); // 3
+
+ +

Puoi anche ignorare tutti i valori ritornati:

+ +
[,,] = f();
+
+ +

Assegnare il resto di un array ad una variabile

+ +

Quando si destruttura un array, puoi assegnare la sua parte rimanente ad una variabile usando l'operatore rest (i 3 puntini):

+ +
var [a, ...b] = [1, 2, 3];
+console.log(a); // 1
+console.log(b); // [2, 3]
+ +

Estrarre valori da un match con un'espressione regolare

+ +

Quando il metodo exec() trova un match, ritorna un array contenente come 1° elemento l'intera porzione della stringa e poi le porzioni della stringa che hanno fatto match con ognuno dei gruppi in parentesi dell'espressione regolare. L'assegnamento di destrutturazione ti permetti di estrarre le parti di questo array facilmente, ignorando l'intero match se non ne hai bisogno.

+ +
var url = "https://developer.mozilla.org/en-US/Web/JavaScript";
+
+var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
+console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"]
+
+var [, protocol, fullhost, fullpath] = parsedURL;
+
+console.log(protocol); // "https"
+
+ +

Destrutturazione degli oggetti

+ +

Assegnamento base

+ +
var o = {p: 42, q: true};
+var {p, q} = o;
+
+console.log(p); // 42
+console.log(q); // true
+
+ +

Assegnamento senza dichiarazione

+ +

Il valore di una variabile può essere assegnato senza destrutturazione separatamente dalla sua dichiarazione.

+ +
var a, b;
+
+({a, b} = {a:1, b:2});
+ +
+

Le ( ) attorno l'assegnamento di destrutturazione sono obbligatorie quando si usa la destrutturazione degli oggetti letterali senza una dichiarazione.

+ +

{a, b} = {a:1, b:2} non è sintassi valida, dato che {a, b} sulla sinistra è considerato un blocco e non un oggetto letterale.

+ +

Tuttavia, ({a, b} = {a:1, b:2}) è valida, dato che var {a, b} = {a:1, b:2}

+
+ +

Assegnamento a nuovi nomi di variabili 

+ +

Una variabile può essere estratta da un oggetto e assegnata ad una variabile con un nome diverso da quello della proprietà dell'oggetto.

+ +
var o = {p: 42, q: true};
+var {p: foo, q: bar} = o;
+
+console.log(foo); // 42
+console.log(bar); // true  
+ +

Valori default

+ +

Ad una variabile può essere assegnato un valore default nel caso in cui il valore estratto dall'oggetto sia undefined.

+ +
var {a=10, b=5} = {a: 3};
+
+console.log(a); // 3
+console.log(b); // 5
+ +

Impostare i valore default dei parametri di una funzione

+ +

Versione ES5

+ +
function drawES5Chart(options) {
+  options = options === undefined ? {} : options;
+  var size = options.size === undefined ? 'big' : options.size;
+  var cords = options.cords === undefined ? { x: 0, y: 0 } : options.cords;
+  var radius = options.radius === undefined ? 25 : options.radius;
+  console.log(size, cords, radius);
+  // now finally do some chart drawing
+}
+
+drawES5Chart({
+  cords: { x: 18, y: 30 },
+  radius: 30
+});
+ +

Versione ES2015

+ +
function drawES2015Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
+  console.log(size, cords, radius);
+  // do some chart drawing
+}
+
+drawES2015Chart({
+  cords: { x: 18, y: 30 },
+  radius: 30
+});
+ +

Oggetti annidati e destrutturazione array

+ +
var metadata = {
+    title: "Scratchpad",
+    translations: [
+       {
+        locale: "de",
+        localization_tags: [ ],
+        last_edit: "2014-04-14T08:43:37",
+        url: "/de/docs/Tools/Scratchpad",
+        title: "JavaScript-Umgebung"
+       }
+    ],
+    url: "/en-US/docs/Tools/Scratchpad"
+};
+
+var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
+
+console.log(englishTitle); // "Scratchpad"
+console.log(localeTitle);  // "JavaScript-Umgebung"
+ +

Iterazione con for...of e destrutturazione

+ +
var people = [
+  {
+    name: "Mike Smith",
+    family: {
+      mother: "Jane Smith",
+      father: "Harry Smith",
+      sister: "Samantha Smith"
+    },
+    age: 35
+  },
+  {
+    name: "Tom Jones",
+    family: {
+      mother: "Norah Jones",
+      father: "Richard Jones",
+      brother: "Howard Jones"
+    },
+    age: 25
+  }
+];
+
+for (var {name: n, family: { father: f } } of people) {
+  console.log("Name: " + n + ", Father: " + f);
+}
+
+// "Name: Mike Smith, Father: Harry Smith"
+// "Name: Tom Jones, Father: Richard Jones"
+ +

Estrarre campi dagli oggetti passati come parametri delle funzioni

+ +
function userId({id}) {
+  return id;
+}
+
+function whois({displayName: displayName, fullName: {firstName: name}}){
+  console.log(displayName + " is " + name);
+}
+
+var user = {
+  id: 42,
+  displayName: "jdoe",
+  fullName: {
+      firstName: "John",
+      lastName: "Doe"
+  }
+};
+
+console.log("userId: " + userId(user)); // "userId: 42"
+whois(user); // "jdoe is John"
+ +

Questo estrae  id, displayNamefirstName da l'oggetto user e li stampa.

+ +

Proprietà calcolate degli oggetti e destrutturazione

+ +

I nomi delle proprietà calcolate degli oggetti, come sugli object literals, possono anche essere usate con la destrutturazione.

+ +
let key = "z";
+let { [key]: foo } = { z: "bar" };
+
+console.log(foo); // "bar"
+
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaratteristicaChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Supporto base{{CompatChrome(49.0)}}{{ CompatGeckoDesktop("1.8.1") }}14{{CompatNo}}{{CompatNo}}7.1
Nomi delle proprietà calcolate{{CompatChrome(49.0)}}{{ CompatGeckoDesktop("34") }}14{{CompatNo}}{{CompatNo}}{{CompatNo}}
Operatore spread{{CompatChrome(49.0)}}{{ CompatGeckoDesktop("34") }}12[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaratteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Supporto base{{CompatNo}}{{CompatChrome(49.0)}}{{ CompatGeckoMobile("1.0") }}{{CompatNo}}{{CompatNo}}8{{CompatChrome(49.0)}}
Nomi delle proprietà calcolate{{CompatNo}}{{CompatChrome(49.0)}}{{ CompatGeckoMobile("34") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(49.0)}}
Operatore spread{{CompatNo}}{{CompatChrome(49.0)}}{{ CompatGeckoMobile("34") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
+ +

[1] Richiede "Attiva le caratteristiche sperimentali di JavaScript" per essere abilitato sotto `about:flags`

+ +

Note specifiche a Firefox

+ + + +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/operators/in/index.html b/files/it/web/javascript/reference/operators/in/index.html new file mode 100644 index 0000000000..d6dcb196de --- /dev/null +++ b/files/it/web/javascript/reference/operators/in/index.html @@ -0,0 +1,198 @@ +--- +title: operatore in +slug: Web/JavaScript/Reference/Operators/in +tags: + - JavaScript + - Operatori + - Operatori Relazionali +translation_of: Web/JavaScript/Reference/Operators/in +--- +
{{jsSidebar("Operators")}}
+ +

L' operatore in dà come ritorno true se la proprietà specificata si trova nell'oggetto preso in considerazione.

+ +

Restituisce false se la proprietà è stata eliminata tramite delete ma non nel caso in cui sia stata inizializzata undefined dal programmatore.

+ +

Sintassi

+ +
prop in nomeOggetto
+ +

Parametri

+ +
+
prop
+
Una stringa o simbolo che rappresenta il nome di una proprietà o indice di un array (i non-simboli verranno automaticamente convertiti in stringhe).
+
+ +
+
nomeOggetto
+
Nome di un oggetto.
+
+ +

Descrizione

+ +

I seguenti esempi mostrano alcuni usi dell'operatore in.

+ +
// Array
+var alberi = ["sequoia", "lauro", "cedro", "quercia", "acero"];
+0 in alberi        // ritorna true
+3 in alberi        // ritorna true
+6 in alberi        // ritorna false, non ci sono proprietà in quell'indice su alberi
+"bay" in alberi    // ritorna false (devi specificare il
+                  // numero dell'indice, non il valore corrispondente a quell'indice)
+"length" in alberi // ritorna true (length è una proprietà degli array)
+Symbol.iterator in alberi // ritorna true (gli array sono iterabili, funziona solo in ES6+)
+
+// Oggetti predefiniti
+"PI" in Math          // ritorna true, "PI" è il nome di una proprietà dell'oggetto Math
+
+// Oggetti personalizzati
+var miaAuto = {marca: "Honda", modello: "Accord", anno: 1998};
+"marca" in miaAuto  // ritorna true
+"modello" in miaAuto // ritorna true
+
+ +

Devi specificare un oggetto sul lato destro dell'operatore in. Per esempio, puoi specificare una stringa creata con il costruttore String, ma non puoi specificare una stringa literal.

+ +
var colore1 = new String("verde");
+"length" in colore1 // ritorna true
+
+var color2 = "coral";
+// genera un errore (colore2 non è un oggetto String)
+"length" in colore2
+
+ +

Usare l'operatore in con le proprietà deleted o undefined

+ +

Se elimini una proprietà con l'operatore delete, l'operatore in ritorna false per quella proprietà.

+ +
var miaAuto = {marca: "Honda", modello: "Accord", anno: 1998};
+delete miaAuto.marca;
+"marca" in miaAuto;  // ritorna false
+
+var alberi = new Array("sequoia", "lauro", "cedro", "quercia", "acero");
+delete alberi[3];
+3 in alberti; // ritorna false
+
+ +

Se setti una proprietà ad {{jsxref("Global_Objects/undefined", "undefined")}} ma non la cancelli, l'operatore in darà come ritorno true per quella proprietà.

+ +
var miaAuto = {marca: "Honda", modello: "Accord", anno: 1998};
+miaAuto.marca = undefined;  //inizializzo manualmente la proprietà 'marca' undefined
+"marca" in miaAuto;  // ritorna true, non è stato usato usato delete sulla proprietà
+delete miaAuto.marca;
+"marca" in miaAuto // return false, è stata eliminata la proprietà
+ +

 

+ +

 

+ +

 

+ +
var alberi = new Array("sequoia", "lauro", "cedro", "quercia", "acero");
+alberi[3] = undefined;
+3 in alberi; // ritorna true
+
+ +

Proprietà ereditate

+ +

L'operatore in ritorna true per proprietà ereditate tramite prototipi.

+ +
"toString" in {}; // returns true
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.7', 'The in Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.7', 'The in Operator')}}{{Spec2('ES3')}}Definizione iniziale. Implementato in JavaScript 1.4.
+ +

Compatibilità con i browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/operators/index.html b/files/it/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..9e257e3038 --- /dev/null +++ b/files/it/web/javascript/reference/operators/index.html @@ -0,0 +1,282 @@ +--- +title: Expressions and operators +slug: Web/JavaScript/Reference/Operators +tags: + - JavaScript + - NeedsTranslation + - Operators + - TopicStub +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

Questo capitolo documenta tutti gli operatori, espressioni e parole chiave del linguaggio JavaScript.

+ +

Espressioni e operatori per categoria

+ +

Per la lista alfabetica consultare la sidebar di sinistra

+ +

Espressioni Primarie

+ +

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.
+
{{experimental_inline}} {{jsxref("Operators/class", "class")}}
+
The class keyword defines a class expression.
+
{{experimental_inline}} {{jsxref("Operators/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{experimental_inline}} {{jsxref("Operators/yield", "yield")}}
+
Pause and resume a generator function
+
{{experimental_inline}} {{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.
+
{{experimental_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
+
Array comprehensions.
+
{{experimental_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator comprehensions.
+
{{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.
+
{{experimental_inline}} {{jsxref("Operators/super", "super")}}
+
The super keyword calls the parent constructor.
+
{{experimental_inline}} {{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.
+
+ +

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.
+
+ +

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.
+
{{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{experimental_inline}} {{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.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial 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, Array comprehensions, Generator comprehensions
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/operators/new/index.html b/files/it/web/javascript/reference/operators/new/index.html new file mode 100644 index 0000000000..291917479e --- /dev/null +++ b/files/it/web/javascript/reference/operators/new/index.html @@ -0,0 +1,186 @@ +--- +title: operatore new +slug: Web/JavaScript/Reference/Operators/new +tags: + - Espressioni di sinistra + - JavaScript + - Operatore +translation_of: Web/JavaScript/Reference/Operators/new +--- +
{{jsSidebar("Operators")}}
+ +

L'operatore new crea un'istanza di un tipo di oggetto definito dall'utente o di uno dei tipi di oggetto nativi che ha una funzione costruttore.

+ +

Sintassi

+ +
new constructor[([arguments])]
+ +

Parametri

+ +
+
constructor
+
Una funzione che specifica il tipo dell'oggetto istanziato.
+
+ +
+
arguments
+
Una lista di valori con i quali constructor sarà chiamato.
+
+ +

Descrizione

+ +

Creare un oggetto definito dall'utente richiede due step:

+ +
    +
  1. Definire il tipo di oggetto scrivendo una funzione.
  2. +
  3. Creare un'istanza dell'oggetto con new.
  4. +
+ +

Per definire un tipo di oggetto, crea una funzione per il tipo di oggetto che specifichi il suo nome e le sue proprietà. Un oggetto può avere una proprietà che è se stessa un oggetto. Vedi l'esempio sotto.

+ +

Quando il codice new Foo(...) viene eseguito, ecco cosa accade:

+ +
    +
  1. Un nuovo oggetto viene creato ed eredita da Foo.prototype.
  2. +
  3. La funzione costruttore Foo viene chiamata con gli argomenti specificati e con this legato all'oggetto appena creato. new Foo è identica a new Foo(), ovvero se nessun argomento è specificato, Foo viene chiamato senza argumenti.
  4. +
  5. L'oggetto ritornato dalla funzione costruttore diventa il risultato dell'intera espressione new. Se la funzione costruttore non ritorna esplicitamente un oggetto, viene invece usato l'oggetto creato nello step 1. (Normalmente i costruttori non ritornano un valore, ma possono scegliere di farlo se vogliono sovrascrivere il processo di creazione di un normale oggetto).
  6. +
+ +

Puoi sempre aggiungere una proprietà all'oggetto che hai creato precedentemente. Per esempio, la dichiarazione car1.color = "black" aggiunge una proprietà  color a car1, e gli assegna il valore di "black". Tuttavia, questo non influenza nessun altro oggetto. Per aggiungere una nuova proprietà a tutti gli oggetti dello stesso tipo, devi aggiungere la proprietà alla definizione del tipo di oggetto, in questo caso Car.

+ +

Puoi aggiungere una proprietà condivisa ad un tipo di oggetto che hai definito prima usando la proprietà Function.prototype.

+ +

Questo definisce una proprietà che è condivisa da tutti gli oggetti creati con quella funzione, piuttosto che solo da un'istanza di quel tipo di oggetto. Il seguente codice aggiunge una proprietà con il valore null a tutti gli oggetti di tipo car, e poi sovrascrive quel valore con la stringa "black" solo nell'oggetto istanza car1. Per altre informazioni, vedi prototype.

+ +

 

+ +
function Car() {}
+car1 = new Car();
+car2 = new Car();
+
+console.log(car1.color);    // undefined
+
+Car.prototype.color = "original color";
+console.log(car1.color);    // original color
+
+car1.color = 'black';
+console.log(car1.color);   // black
+
+console.log(car1.__proto__.color) //original color
+console.log(car2.__proto__.color) //original color
+console.log(car1.color)  // black
+console.log(car2.color) // original color
+
+ +

Se non hai usato l'operatore newla funzione constructor verrà invocata come una qualunque altra funzionesenza creare un nuovo Object. in questo caaso, anche il valore di this è diverso.

+ +

Esempi

+ +

Tipo di oggetto e oggetto istanza

+ +

Metti caso di volere creare un tipo di oggetto per le macchine. Vuoi che questo tipo di oggetto si chiami car, e vuoi che abbia queste proprietà: make (brand, marca), model (modello) e year (anno). Per fare questo, potresti scrivere la seguente funzione:

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+
+ +

Adesso puoi creare un oggetto chiamato myCar in questo modo:

+ +
var mycar = new Car("Eagle", "Talon TSi", 1993);
+
+ +

Questa dichiarazione crea myCar e gli assegna i valori specificati per le sue proprietà. Poi il valore di mycar.make è "Eagle", mycar.year è il numero intero 1993, e così via.

+ +

Puoi creare quanti oggetti Car vuoi utilizzando new. Per esempio:

+ +
var kenscar = new Car("Nissan", "300ZX", 1992);
+
+ +

Proprietà dell'oggetto che è se stesso un oggetto

+ +

Supponi di definire un oggetto person in questo modo:

+ +
function Person(name, age, sex) {
+  this.name = name;
+  this.age = age;
+  this.sex = sex;
+}
+
+ +

E poi istanzi due nuove oggetti Person in questo modo:

+ +
var rand = new Person("Rand McNally", 33, "M");
+var ken = new Person("Ken Jones", 39, "M");
+
+ +

Poi puoi riscrivere la definizione di Car per includere una proprietà owner (proprietario) che accetta un oggetto persona, ecco come:

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+}
+
+ +

Per istanziare i nuovi oggetti, poi fai così:

+ +
var car1 = new Car("Eagle", "Talon TSi", 1993, rand);
+var car2 = new Car("Nissan", "300ZX", 1992, ken);
+
+ +

Invece di passare una stringa letterale o un valore intero quando crei i nuovi oggetti, le dichiarazioni sopra passano gli oggetti rand e ken come parametri per i proprietari. Per cercare il nome del proprietario (owner) in car2, puoi accedere alla seguente proprietà:

+ +
car2.owner.name
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificheStatusCommento
{{SpecName('ESDraft', '#sec-new-operator', 'The new Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-new-operator', 'The new Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

Compatibilità browser

+ +

{{Compat("javascript.operators.new")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/operators/operator_condizionale/index.html b/files/it/web/javascript/reference/operators/operator_condizionale/index.html new file mode 100644 index 0000000000..1ade61b085 --- /dev/null +++ b/files/it/web/javascript/reference/operators/operator_condizionale/index.html @@ -0,0 +1,171 @@ +--- +title: Operatore condizionale (ternary) +slug: Web/JavaScript/Reference/Operators/Operator_Condizionale +tags: + - JavaScript Operatore operatore +translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator +--- +

L'operatore condizionale (ternary) è  l'unico operatore JavaScript che necessità di tre operandi. Questo operatore è frequentemente usato al posto del comando if per la sua sintassi concisa e perché fornisce direttamente un espressione valutabile.

+ +

Sintassi

+ +
condizione ? espressione1 : espressione2 
+ +

Parametri

+ +
+
condizione
+
Un espressione booleana (che viene valutata in vero o falso).
+
+ +
+
espressione1, espressione2
+
Espressione di qualunque tipo (vedi avanti nella pagina).
+
+ +

Descrizione

+ +

Se la condizione è vera, l'operatore ritorna il valore di espressione1; altrimenti, ritorna il valore di espressione2.  Per esempio, puoi usare questa espressione per mostrare un messaggio che cambia in base al valore della variabile isMember:

+ +
"The fee is " + (isMember ? "$2.00" : "$10.00")
+
+ +

Puoi anche assegnare variabili dipendenti dal risultato di un operatore ternario:

+ +
var elvisLives = Math.PI > 4 ? "Yep" : "Nope";
+ +

Sono anche possibili espressioni con operatori ternari multipli (nota: l'operatore condizionale è associativo a destra):

+ +
var firstCheck = false,
+    secondCheck = false,
+    access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted";
+
+console.log( access ); // logs "Access granted"
+ +

Puoi anche usare l'operatore ternario direttamente senza assegnamenti e senza combinazioni con altre espressioni, con lo scopo di valutare operazioni alternative:

+ +
var stop = false, age = 16;
+
+age > 18 ? location.assign("continue.html") : stop = true;
+
+ +

Puoi anche valutare operazioni multiple separandole con delle virgole:

+ +
var stop = false, age = 23;
+
+age > 18 ? (
+    alert("OK, you can go."),
+    location.assign("continue.html")
+) : (
+    stop = true,
+    alert("Sorry, you are much too young!")
+);
+
+ +

Puoi anche valutare più operazioni durante l'assegnamento di una variabile. In questo caso, l'ultimo valore separato da una virgola nelle parentesi sarà il valore assegnato.

+ +
var age = 16;
+
+var url = age > 18 ? (
+    alert("OK, you can go."),
+    // alert returns "undefined", but it will be ignored because
+    // isn't the last comma-separated value of the parenthesis
+    "continue.html" // the value to be assigned if age > 18
+) : (
+    alert("You are much too young!"),
+    alert("Sorry :-("),
+    // etc. etc.
+    "stop.html" // the value to be assigned if !(age > 18)
+);
+
+location.assign(url); // "stop.html"
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

Compatibilità con Browser

+ +

{{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}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/operators/operatore_virgola/index.html b/files/it/web/javascript/reference/operators/operatore_virgola/index.html new file mode 100644 index 0000000000..e4027930a1 --- /dev/null +++ b/files/it/web/javascript/reference/operators/operatore_virgola/index.html @@ -0,0 +1,105 @@ +--- +title: Operatore virgola +slug: Web/JavaScript/Reference/Operators/Operatore_virgola +translation_of: Web/JavaScript/Reference/Operators/Comma_Operator +--- +
{{jsSidebar("Operators")}}
+ +

L'operatore virgola valuta ciascuno dei suoi operandi, da sinistra a destra, e restituisce il valore dell'ultimo operando.

+ +
{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}
+ + + +

Sintassi

+ +
expr1, expr2, expr3...
+ +

Parametri

+ +
+
expr1, expr2, expr3...
+
Qualsiasi espressione.
+
+ +

Descrizione

+ +

Puoi utilizzare l'operatore virgola quando vuoi includere più espressioni in una posizione che richiede una singola espressione. L'uso più comune di questo operatore è di fornire più parametri in un ciclo for.

+ +

L'operatore virgola è completamente differente dalla virgola utilizzata negli array, negli oggetti, e negli argomenti e parametri di funzione.

+ +

Esempi

+ +

Considerando a un array di 2 dimensioni contenente 10 elementi per ciascun lato, il seguente codice utilizza l'operatore virgola per incrementare i e decrementare j contemporaneamente.

+ +

Il seguente codice stampa i valori degli elementi in posizione diagonale dell'array:

+ +
for (var i = 0, j = 9; i <= 9; i++, j--)
+  console.log('a[' + i + '][' + j + '] = ' + a[i][j]);
+ +

Si noti che gli operatori virgola nelle assegnazioni potrebbero non avere l'effetto normale degli operatori virgola perché non esistono all'interno di un'espressione. Nel seguente esempio, a é impostato al valore di b = 3 (che é 3), ma l'espressione c = 4 continua a essere valutata e il suo valore viene restituito alla console (cioé 4). Questo é dovuto alla precedenza e all'associtività dell'operatore.

+ +
var a, b, c;
+
+a = b = 3, c = 4; // restituisce 4 nella console
+console.log(a); // 3 (più a sinistra)
+
+var x, y, z;
+
+x = (y = 5, z = 6); // restituisce 6 nella console
+console.log(x); // 6 (più a destra)
+
+ +

Elaborazione e restituzione

+ +

Un altro esempio che si potrebbe fare con l'operatore virgola è quello di eleborare prima di restituire. Come detto, solo l'ultimo elemento viene restituito ma anche tutti gli altri vengono valutati. Quindi, si potrebbe fare:

+ +
function myFunc() {
+  var x = 0;
+
+  return (x += 1, x); // stesso comportamento di ++x;
+}
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-comma-operator', 'Comma operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.14', 'Comma operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES1', '#sec-11.14', 'Comma operator')}}{{Spec2('ES1')}}Initial definition
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.operators.comma")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/operators/operatori_aritmetici/index.html b/files/it/web/javascript/reference/operators/operatori_aritmetici/index.html new file mode 100644 index 0000000000..991456bf93 --- /dev/null +++ b/files/it/web/javascript/reference/operators/operatori_aritmetici/index.html @@ -0,0 +1,291 @@ +--- +title: Operatori Aritmetici +slug: Web/JavaScript/Reference/Operators/Operatori_Aritmetici +tags: + - JavaScript + - Operatori + - Operatori Aritmetici +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +
Gli operatori aritmetici lavorano su operandi numerici (sia letterali che variabili) e ritornano un singolo valore numerico. Gli operatori aritmetici standard sono l'addizione (+), la sottrazione (-), la moltiplicazione (*) e la divisione (/).
+ +

Addizione (+)

+ +

L'operazione di addizione produce la somma di operandi numerici o la concatenzione di stringhe.

+ +

Sintassi

+ +
Operatore: x + y
+
+ +

Esempi

+ +
// Numero + Numero -> addizione
+1 + 2 // 3
+
+// Booleano + Numero -> addizione
+true + 1 // 2
+
+// Booleano + Booleano -> additione
+false + false // 0
+
+// Numero + Stringa -> concatenazione
+5 + "foo" // "5foo"
+
+// Stringa + Booleano -> concatenazione
+"foo" + false // "foofalse"
+
+// Stringa + Stringa -> concatenazione
+"foo" + "bar" // "foobar"
+
+ +

Sottrazione (-)

+ +

L'operatore di sottrazione fa la sottrazione dei due operandi e produce la loro differenza.

+ +

Sintassi

+ +
Operatore: x - y
+
+ +

Esempi

+ +
5 - 3 // 2
+3 - 5 // -2
+"foo" - 3 // NaN
+ +

Divisione (/)

+ +

L'operatore di divisione produce il quoziente dei suoi operandi dove l'operando di sinistra è il dividendo e l'operando di destra è il divisore.

+ +

Sintassi

+ +
Operatore: x / y
+
+ +

Esempi

+ +
1 / 2      // restituisce 0.5 in JavaScript
+1 / 2      // restituisce 0 in Java
+// (nessuno degli operandi è un numero in virgola mobile esplicito)
+
+1.0 / 2.0  // restituisce 0.5 in both JavaScript and Java
+
+2.0 / 0    // restituisce Infinity in JavaScript
+2.0 / 0.0  // restituisce Infinity too
+2.0 / -0.0 // restituisce -Infinity in JavaScript
+ +

Moltiplicazione (*)

+ +

The multiplication operator produces the product of the operands.

+ +

Sintassi

+ +
Operatore: x * y
+
+ +

Esempi

+ +
2 * 2 // 4
+-2 * 2 // -4
+Infinity * 0 // NaN
+Infinity * Infinity // Infinity
+"foo" * 2 // NaN
+
+ +

Resto (%)

+ +

L'operatore Resto o Modulo restituisce il “resto“ rimasto quando un operando viene diviso per un secondo operando. Calcola il resto della divisione fra il primo e il secondo operando. Porta sempre il segno del dividendo.

+ +

Sintassi

+ +
Operatore: var1 % var2
+
+ +

Esempi

+ +
12 % 5 // 2
+-1 % 2 // -1
+NaN % 2 // NaN
+1 % 2 // 1
+2 % 3 // 2
+-4 % 2 // -0
+
+ +

Esponente (**)

+ +

L'operatore Esponente o esponenziale in JavaScript. Una delle funzionalità di questa versione è l'operatore di esponenziazione. Esponente restituisce il risultato dell'elevamento a potenza dal primo operando al secondo. Cioè var1 var2 , var2. var1var2 sono variabili. L'operatore Esponente ha ragione associativa. a ** b ** c equivale a a ** (b ** c).

+ +

Sintassi

+ +
Operatore: var1 ** var2
+
+ +

Note

+ +

Nella maggior parte dei linguaggi come PHP e Python e altri che usano l'operatore Esponente (**), ha precedenza rispetto agli altri operatori unari come + e -, salvo in alcune eccezioni. Ad esempio, in Bash l'operatore ** ha una minor importanza rispetto agli operatori unari. In JavaScript, è impossibile scrivere un'espressione Esponente ambigua, ovvero non è possibile inserire un operatore unario ( +/-/~/!/delete/void/typeof ) immediatamente prima del numero di base. Il calcolo della potenza può essere espresso più sinteticamente usando la notazione infissa. Simile ad altri linguaggi come Python o F#, ** è usato per indicare l'operatore. 

+ +
-2 ** 2 // equals 4 in ES2016 or in Bash, equals -4 in other languages.
+ +

Accetta base sul lato sinistro ed esponente sul lato destro, rispettivamente.

+ +
let value = 5; value **= 2; // value: 25
+
+ +

Esempi

+ +
2 ** 3 // 8
+3 ** 2 // 9
+3 ** 2.5 // 15.588457268119896
+10 ** -1 // 0.1
+NaN ** 2 // NaN
+
+2 ** 3 ** 2 // 512
+2 ** (3 ** 2) // 512
+(2 ** 3) ** 2 // 64
+
+var a = 3;
+var b = a ** 3;
+alert("3x3x3 is = " + b); // 27
+
+ +

Per invertire il segno del risultato di un'espressione di Esponente:

+ +
-(2 ** 2) // -4
+
+ +

Per forzare la base di un'espressione di Esponente ad essere un numero negativo:

+ +
(-2) ** 2 // 4 
+ +

Incremento (++)

+ +

L'operatore di incremento incrementa (aggiunge uno a) il suo operando e restituisce un valore.

+ + + +

Sintassi

+ +
Operatore: x++ or ++x
+
+ +

Esempi

+ +
// Postfix // post posizione
+var x = 3;
+y = x++; // y = 3, x = 4
+
+// Prefix // Prefisso
+var a = 2;
+b = ++a; // a = 3, b = 3
+
+ +

Decremento (--)

+ +

L'operatore decrementa decrementa (sottrae uno da) il suo operando e restituisce un valore.

+ + + +

Sintassi

+ +
Operatore: x-- or --x
+
+ +

Esempi

+ +
// Postfix // post posizione
+var x = 3;
+y = x--; // y = 3, x = 2
+
+// Prefix // Prefisso
+var a = 2;
+b = --a; // a = 1, b = 1
+
+ +

Negazione unaria (-)

+ +

L'operatore di negazione unario precede il suo operando e lo nega.

+ +

Sintassi

+ +
Operatore: -x
+
+ +

Esempi

+ +
var x = 3;
+y = -x; // y = -3, x = 3
+
+//L'operatore di negazione unario può convertire numeri diversi in un numero
+var x = "4";
+y = -x; // y = -4
+ +

Unario più (+)

+ +

L'operatore unario più precede il suo operando e valuta il suo operando, ma tenta di convertirlo in un numero, se non lo è già. Anche se la negazione unaria (-) può anche convertire non numeri, unario è il modo più veloce e preferito per convertire qualcosa in un numero, perché non esegue altre operazioni sul numero. È in grado di convertire rappresentazioni di stringa di numeri interi e float, oltre ai valori non stringa true , false e null . Sono supportati i numeri interi decimali ed esadecimali ("0x" -prefixed). I numeri negativi sono supportati (sebbene non per hex). Se non può analizzare un valore particolare, valuterà in NaN.

+ +

Sintassi

+ +
Operatore: +x
+
+ +

Esempi

+ +
+3     // 3
++'3'   // 3
++true  // 1
++false // 0
++null  // 0
++function(val){  return val } // NaN
+ +

Specificazioni

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificazioniStatoCommento
ECMAScript 1st Edition.StandardDefinizione iniziale.
{{SpecName('ES5.1', '#sec-11.3')}}{{Spec2('ES5.1')}}Definito in diverse sezioni della specifica: Additive operators, Multiplicative operators, Postfix expressions, Unary operators.
{{SpecName('ES2015', '#sec-postfix-expressions')}}{{Spec2('ES2015')}}Definito in diverse sezioni della specifica: Additive operators, Multiplicative operators, Postfix expressions, Unary operators.
{{SpecName('ES2016', '#sec-postfix-expressions')}}{{Spec2('ES2016')}}Aggiunto Exponentiation operator.
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.operators.arithmetic")}}

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/operators/spread_syntax/index.html b/files/it/web/javascript/reference/operators/spread_syntax/index.html new file mode 100644 index 0000000000..9c300f9257 --- /dev/null +++ b/files/it/web/javascript/reference/operators/spread_syntax/index.html @@ -0,0 +1,257 @@ +--- +title: Spread syntax +slug: Web/JavaScript/Reference/Operators/Spread_syntax +tags: + - ECMAScript 2015 + - Iterator + - JavaScript + - Referenza +translation_of: Web/JavaScript/Reference/Operators/Spread_syntax +--- +
{{jsSidebar("Operators")}}
+ +

La Spread syntax consente un iterabile come un'espressione di un array o una stringa da espandere in punti in cui sono previsti zero o più argomenti (per chiamate di funzione) o elementi (per letterali di array) o un'espressione di oggetto da espandere in posizioni dove zero o più sono previste coppie di valori (per valori letterali oggetto)..

+ +
{{EmbedInteractiveExample("pages/js/expressions-spreadsyntax.html")}}
+ + + +

Sintassi

+ +

Per chiamate di funzione:

+ +
myFunction(...iterableObj);
+
+ +

Per letterali di un array o stringhe:

+ +
[...iterableObj, '4', 'five', 6];
+ +

Per gli oggetti letterali (novità in ECMAScript 2018):

+ +
let objClone = { ...obj };
+ +

Esempi

+ +

Spread nelle chiamate delle funzioni

+ +

Sostituire apply()

+ +

È comune utilizzare {{jsxref("Function.prototype.apply()")}} nei casi in cui vuoi utilizzare gli elementi di un array come argomenti di una funzione.

+ +
function myFunction(x, y, z) { }
+var args = [0, 1, 2];
+myFunction.apply(null, args);
+ +

Con la spread syntax può essere scritto come:

+ +
function myFunction(x, y, z) { }
+var args = [0, 1, 2];
+myFunction(...args);
+ +

Qualsiasi argomento nell'elenco di argomenti può utilizzare la spread syntax e può essere utilizzato più volte.

+ +
function myFunction(v, w, x, y, z) { }
+var args = [0, 1];
+myFunction(-1, ...args, 2, ...[3]);
+ +

Apply for new

+ +

When calling a constructor with {{jsxref("Operators/new", "new")}} it's not possible to directly use an array and apply (apply does a [[Call]] and not a [[Construct]]). However, an array can be easily used with new thanks to spread syntax:

+ +
var dateFields = [1970, 0, 1];  // 1 Jan 1970
+var d = new Date(...dateFields);
+
+ +

To use new with an array of parameters without spread syntax, you would have to do it indirectly through partial application:

+ +
function applyAndNew(constructor, args) {
+   function partial () {
+      return constructor.apply(this, args);
+   };
+   if (typeof constructor.prototype === "object") {
+      partial.prototype = Object.create(constructor.prototype);
+   }
+   return partial;
+}
+
+
+function myConstructor () {
+   console.log("arguments.length: " + arguments.length);
+   console.log(arguments);
+   this.prop1="val1";
+   this.prop2="val2";
+};
+
+var myArguments = ["hi", "how", "are", "you", "mr", null];
+var myConstructorWithArguments = applyAndNew(myConstructor, myArguments);
+
+console.log(new myConstructorWithArguments);
+// (internal log of myConstructor):           arguments.length: 6
+// (internal log of myConstructor):           ["hi", "how", "are", "you", "mr", null]
+// (log of "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}
+ +

Spread in array literals

+ +

A more powerful array literal

+ +

Without spread syntax, to create a new array using an existing array as one part of it, the array literal syntax is no longer sufficient and imperative code must be used instead using a combination of {{jsxref("Array.prototype.push", "push()")}}, {{jsxref("Array.prototype.splice", "splice()")}}, {{jsxref("Array.prototype.concat", "concat()")}}, etc. With spread syntax this becomes much more succinct:

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

Just like spread for argument lists, ... can be used anywhere in the array literal and it can be used multiple times.

+ +

Copiare un array

+ +
var arr = [1, 2, 3];
+var arr2 = [...arr]; // like arr.slice()
+arr2.push(4);
+
+// arr2 becomes [1, 2, 3, 4]
+// arr remains unaffected
+
+ +
+

Note: La spread syntax diventa effettivamente un livello profondo durante la copia di un array. Pertanto, potrebbe non essere adatto per copiare arrau multidimensionali come mostra il seguente esempio (è lo stesso con {{jsxref("Object.assign()")}} e spread syntax).

+
+ +
var a = [[1], [2], [3]];
+var b = [...a];
+b.shift().shift(); // 1
+// Adesso anche l'array a è influenzato: [[], [2], [3]]
+
+ +

Un modo migliore per concatenare gli array

+ +

{{jsxref("Array.prototype.concat()")}} è spesso usato per concatenare un array alla fine di un array esistente. Senza la spread syntax questo è fatto così:

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+// Append all items from arr2 onto arr1
+arr1 = arr1.concat(arr2);
+ +

Con la spread syntax questo diventa:

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+arr1 = [...arr1, ...arr2]; // arr1 is now [0, 1, 2, 3, 4, 5]
+
+ +

{{jsxref("Array.prototype.unshift()")}} è spesso usato per inserire un array di valori all'inizio di un array esistente. Senza la spread syntax questo è fatto così:

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+// Spostare all'inizio tutti gli elementi da arr2 a arr1
+Array.prototype.unshift.apply(arr1, arr2) // arr1 ora è [3, 4, 5, 0, 1, 2]
+ + + +

Con la spread syntax questo diventa:

+ + + +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+arr1 = [...arr2, ...arr1]; // arr1 is now [3, 4, 5, 0, 1, 2]
+
+ +
+

Note: A differenza di unshift(), questo crea un nuovo arr1, e non modifica l'array originale arr1.

+
+ +

Spread in object literals

+ +

The Rest/Spread Properties for ECMAScript proposal (stage 4) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object.

+ +

Lo Shallow-cloning (escluso il prototipo) o fusione di oggetti è ora possibile usando una sintassi più breve di {{jsxref("Object.assign()")}}.

+ +
var obj1 = { foo: 'bar', x: 42 };
+var obj2 = { foo: 'baz', y: 13 };
+
+var clonedObj = { ...obj1 };
+// Object { foo: "bar", x: 42 }
+
+var mergedObj = { ...obj1, ...obj2 };
+// Object { foo: "baz", x: 42, y: 13 }
+ +

Nota che {{jsxref("Object.assign()")}} attiva i setters mentre la spread syntax non lo fa.

+ +

Nota che non è possibile sostituire o imitare la funzione {{jsxref("Object.assign()")}}:

+ +
var obj1 = { foo: 'bar', x: 42 };
+var obj2 = { foo: 'baz', y: 13 };
+const merge = ( ...objects ) => ( { ...objects } );
+
+var mergedObj = merge ( obj1, obj2);
+// Object { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }
+
+var mergedObj = merge ( {}, obj1, obj2);
+// Object { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }
+ +

Nell'esempio precedente, la spread syntax non funziona come previsto: estende una serie di argomenti nel letterale dell'oggetto, a causa del parametro rest.

+ +

Solo per iterabili

+ +

La spread syntax (diversa dal caso delle spread properties) può essere applicata solo agli oggetti iterabili:

+ +
var obj = {'key1': 'value1'};
+var array = [...obj]; // TypeError: obj non è iterabile
+
+ +

Diffusione con molti valori

+ +

Quando si utilizza la sintassi di diffusione per le chiamate di funzione, tenere presente la possibilità di superare il limite di lunghezza dell'argomento del motore JavaScript. Vedi {{jsxref("Function.prototype.apply", "apply()")}} per maggiori dettagli.

+ +

Rest syntax (parametri)

+ +

La Rest syntax sembra esattamente come la spread syntax, ma è usata per destrutturare array e oggetti. In un certo senso, la Rest syntax è l'opposto della spread syntax: spread 'espande' un array nei suoi elementi, mentre la rest syntax raccoglie più elementi e li 'condensa' in un singolo elemento. Vedi rest parameters.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array-initializer')}}{{Spec2('ES2015')}}Definito in diverse sezioni della specifica: Array Initializer, Argument Lists
{{SpecName('ES2018', '#sec-object-initializer')}}{{Spec2('ES2018')}}Definito in Object Initializer
{{SpecName('ESDraft', '#sec-array-initializer')}}{{Spec2('ESDraft')}}Nessun cambiamento.
{{SpecName('ESDraft', '#sec-object-initializer')}}{{Spec2('ESDraft')}}Nessun cambiamento.
+ +

Compatibilità con i browser

+ + + +

{{Compat("javascript.operators.spread")}}

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/operators/super/index.html b/files/it/web/javascript/reference/operators/super/index.html new file mode 100644 index 0000000000..aee5f694b1 --- /dev/null +++ b/files/it/web/javascript/reference/operators/super/index.html @@ -0,0 +1,181 @@ +--- +title: super +slug: Web/JavaScript/Reference/Operators/super +translation_of: Web/JavaScript/Reference/Operators/super +--- +
{{jsSidebar("Operators")}}
+ +

La parola chiave super viene usata per chiamare le funzioni dell'oggetto padre.

+ +

Il super.prop ed espressioni con super[expr] sono valide in ogni  definizione di metodo sia nelle classi e oggetti literals.

+ +

Sintassi

+ +
super([arguments]); // chiama il costruttore padre.
+super.functionOnParent([arguments]);
+
+ +

Descrizione

+ +

Quando viene usata in un costruttore, la parola chiave super deve essere usata prima della parola chiave this. La parola chiave super può essere usata anche per chiamare funzioni dell'oggetto padre.

+ +

Esempio

+ +

Usare super nelle classi

+ +

Questo pezzo di codice è preso da classes sample (live demo). super è chiamato per evitare la duplicazione del codice comune ad entrambi i costruttori Rectangle e 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 deve essere chiamato per primo!
+
+    // Chiama il costruttore della classe padre
+    super(length, length);
+
+    // Nota: Nelle classi derivate super() deve essere chiamato prima
+    // dell'uso di 'this'.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.area = value;
+  }
+}
+ +

Usare super con metodi statici

+ +

Puoi usare super anche chiamare metodi statici.

+ +
class Rectangle {
+  constructor() {}
+  static logNbSides() {
+    return 'I have 4 sides';
+  }
+}
+
+class Square extends Rectangle {
+  constructor() {}
+  static logDescription() {
+    return super.logNbSides() + ' which are all equal';
+  }
+}
+Square.logDescription(); // 'I have 4 sides which are all equal'
+ +

Cancellare una proprietà del super causa eccezione

+ +

Non puoi cancellare una proprietà della classe padre usando l' operatore delete e super.propsuper[esperssione], questo causerà un {{jsxref("ReferenceError")}}.

+ +
class Base {
+  constructor() {}
+  foo() {}
+}
+class Derived extends Base {
+  constructor() {}
+  delete() {
+    delete super.foo;
+  }
+}
+
+new Derived().delete(); // ReferenceError: uso della delete con 'super'. 
+ +

Super.prop non può sovrascrivere proprietà non scrivibili

+ +

Quando si definisce una proprietà non riscrivibile con ad esempio {{jsxref("Object.defineProperty")}}, super non può modificarne il valore.

+ +
class X {
+  constructor() {
+    Object.defineProperty(this, 'prop', {
+      configurable: true,
+      writable: false,
+      value: 1
+    });
+  }
+}
+
+class Y extends X {
+  constructor() {
+    super();
+  }
+  foo() {
+    super.prop = 2;   // Non posso sovrascrivere il valore.
+  }
+}
+
+var y = new Y();
+y.foo(); // TypeError: "prop" is read-only
+console.log(y.prop); // 1
+ +

Uso di super.prop in oggetti literals

+ +

Super può essere utilizzato anche nella initializzazione di oggetti con notazione letterale. In questo esempio, due oggetti definiscono un metodo. Nel secondo oggetto, super chiama il metodo del primo oggetto. Questo funziona grazie all'aiuto di {{jsxref("Object.setPrototypeOf()")}} con cui siamo in grado di impostare il prototipo di obj2 con l'oggetto obj1, in modo che super sia in grado di trovare method1 in obj1.

+ +
var obj1 = {
+  method1() {
+    console.log("method 1");
+  }
+}
+
+var obj2 = {
+  method2() {
+   super.method1();
+  }
+}
+
+Object.setPrototypeOf(obj2, obj1);
+obj2.method2(); // logs "method 1"
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-super-keyword', 'super')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}{{Spec2('ESDraft')}}
+ +

Browser compatibili

+ +

{{Compat("javascript.operators.super")}}

+ +
+ +

Gecko specific notes

+ + + +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/operators/this/index.html b/files/it/web/javascript/reference/operators/this/index.html new file mode 100644 index 0000000000..cd324d2bcf --- /dev/null +++ b/files/it/web/javascript/reference/operators/this/index.html @@ -0,0 +1,410 @@ +--- +title: this +slug: Web/JavaScript/Reference/Operators/this +translation_of: Web/JavaScript/Reference/Operators/this +--- +
{{jsSidebar("Operators")}}
+ +

La keyword di funzione this si comporta in modo leggermente differente in JavaScript rispetto ad altri linguaggi. Esistono inoltre alcune differenze tra strict mode e non-strict mode.

+ +

Nella maggior parte dei casi, il valore di this è determinato da come la funzione viene invocata (chiamata). Il valore di this non può essere impostato per assegnamento durante l'esecuzione, e potrebbe essere differente ogni volta in cui la funzione viene chiamata. ES5 ha introdotto il metodo bind per impostare il valore di this indipendentemente da come la funzione è invocata. ECMAScript 2015 ha introdotto le funzione a freccia ( arrow function ), in cui la keyword this viene lessicalmente incorporata nello scope corrente ( lo scope del contesto di esecuzione relativo al blocco corrente ).

+ +

Sintassi

+ +
this
+ +

Contesto Globale

+ +

Nel contesto di esecuzione globale (fuori da qualsiasi funzione), this si riferisce all'oggetto globale, sia che ci si trovi in strict mode,  sia che ci si trovi in non-strict mode.

+ +
console.log(this.document === document); // true
+
+// In web browsers, the window object is also the global object:
+console.log(this === window); // true
+
+this.a = 37;
+console.log(window.a); // 37
+
+ +

Contesto di funzione

+ +

All'interno di una funzione, il valore di this dipende da come la funzione è invocata.

+ +

Chiamata semplice

+ +
function f1(){
+  return this;
+}
+
+f1() === window; // global object
+
+ +

In questo caso, il valore di this non viene impostato dalla chiamata. Visto che il codice non è in strict mode, il valore di this deve sempre essere un oggetto quindi viene impostato di default sull'oggetto globale.

+ +
function f2(){
+  "use strict"; // see strict mode
+  return this;
+}
+
+f2() === undefined;
+
+ +

In strict mode, il valore di this rimane impostato sul valore definito al momento dell'ingresso nel contesto di esecuzione. Se non è definito, resta undefined. Può anche essere impostato a qualsiasi valore, come null42"I am not this".

+ +
Nota: Nel secondo esempio, this dovrebbe essere undefined, perchè f2 viene invocata senza specificare alcuna base (per esempio, window.f2()). Alcuni browser non hanno implementato questo orientamento, quando hanno deciso di supportare lo strict mode. Come risultato, questi browser restituivano, in modo non corretto, l'oggetto window.
+ +

Funzioni Arrow

+ +

Nelle funzioni arrow, this è assegnato lessicalmente, assume cioè il valore del contesto di esecuzione che contiene this. In codice globale punta all'oggetto globale:

+ +
var globalObject = this;
+var foo = (() => this);
+console.log(foo() === globalObject); // true
+ +

Non importa come foo sia invocato, this punterà all'oggetto globale. Questo è ancora valido se è chiamato come metodo di un oggetto (che solitamente punterebbe il valore di this sullo stesso) tramite chiamate dei metodi call o apply o bind

+ +
// Call as a method of an object
+var obj = {foo: foo};
+console.log(obj.foo() === 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
+ +

in ogni caso il valore di this all'interno di foo è impostato al valore di quando è stato creato (nell'esempio di sopra, l'oggetto globale). Lo stesso si applica per funzioni arrow create all'interno di altre funzioni: il loro valore di this è impostato a quello del contesto di esecuzione esterno.

+ +
// Create obj with a method bar that returns a function that
+// returns its this. The returned function is created as 
+// an arrow function, so its this is permanently bound to the
+// this of its enclosing function. The value of bar can be set
+// in the call, which in turn sets the value of the 
+// returned function.
+var obj = { bar : function() {
+                    var x = (() => this);
+                    return x;
+                  }
+          };
+
+// Call bar as a method of obj, setting its this to obj
+// Assign a reference to the returned function to fn
+var fn = obj.bar();
+
+// Call fn without setting this, would normally default
+// to the global object or undefined in strict mode
+console.log(fn() === obj); // true
+ +

Nel codice sopra, la funzione (chiamiamola funzione anonima A) assegnata a obj.bar restituisce un altra funzione (chiamiamola funzione anonima B) che viene creata come funzione arrow. Il risultato, è che this della funzione B è impostata permanentemente al valore di this di obj.bar (funzione A) quando viene chiamata. quando la funzione restituita (B) viene chiamata, il relativo this sarà sempre impostato al valore di partenza. Nel codice di esempio  il this della funzione B è impostato al valore this della funzione A che è obj, pertanto resta impostato ad obj anche quando viene chiamato in un modo che imposterebbe this come undefined od oggetto globale (o qualunque altro metodo, come nel precedente esempio, nel contesto di esecuzione globale).

+ +

In the above, the function(call it anonymous function A) assigned to obj.bar returns another function(call it anonymous function B) that is created as an arrow function. As a result, function B's  this is permanently set to the this of obj.bar (function A)when called. When the returned function(function B) is called, its this will always be what it was set to initially. In the above code example, function B's this is set to function A's this which is obj, so it remains set to obj even when called in a manner that would normally set its this to undefined or the global object (or any other method as in the previous example in the global execution context).

+ +

Come metodo di un oggetto

+ +

Quando una funzione viene invocata come metodo di un oggetto, il this, all'interno della funzione, viene impostato sull'oggetto di cui la funzione è metodo.

+ +

Nell'esempio seguente, quando o.f() viene invocata, all'interno della funzione this è associato all'oggetto o.

+ +
var o = {
+  prop: 37,
+  f: function() {
+    return this.prop;
+  }
+};
+
+console.log(o.f()); // logs 37
+
+ +

Da notare che questo comportamento non è per nulla influenzato dal come e dal dove la funzione sia stata definita. Nell'esempio precedente, abbiamo definito la funzione inline, come membro f, nel corso della definizione di o. Tuttavia, avremmo potuto facilmente definire la funzione prima, per poi associarla a o.f. Il risultato sarebbe stato lo stesso:

+ +
var o = {prop: 37};
+
+function independent() {
+  return this.prop;
+}
+
+o.f = independent;
+
+console.log(o.f()); // logs 37
+
+ +

Questo dimostra che la cosa più importante è che la funzione venga invocata dal membro f di o.

+ +

In modo analogo, l'associazione di this è influenzata solo dal membro più vicino. Nell'esempio seguente, quando invochiamo la funzione, la invochiamo come metodo g dell'oggetto o.b. Questa volta, durante l'esecuzione, this, all'interno della funzione, sarà associata ad o.b. Il fatto che l'oggetto sia, esso stesso, un membro di o non ha alcuna conseguenza; la sola cosa che conti è il riferimento più immediato.

+ +
o.b = {g: independent, prop: 42};
+console.log(o.b.g()); // logs 42
+
+ +

this nella prototype chain dell'oggetto

+ +

La stessa notazione è valida per i metodi definiti altrove nella prototype chain dell'oggetto. Se il metodo è sulla prototype chain di un oggetto, this si riferisce all'oggetto su cui il metodo è stato chiamato, come se il metodo appartenesse all'oggetto.

+ +
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 questo esempio, l'oggetto assegnato alla variabile p non ha definita una proprietà f, la eredita dal suo prototipo. Non ha importanza che il controllo per f trovi eventualmente un membro con quel nome in o; il controllo è cominciato con un riferimento a p.f, quindi this all'interno della funzione assume il valore dell'oggetto a cui p si riferisce. Cioè, dal momento che f è chiamata come metodo di p, la parola chiave this al suo interno si riferisce a p. Questa è una interessante caratteristica dell'ereditarietà dei prototipi di javascript.

+ +

this all'interno di metodi getter o setter

+ +

Ancora, la stessa notazione è valida quando una funzione è invocata all'interno di metodi get o set. In una funzione usata come getter o setter this viene collegata all'oggetto dal quale la proprietà è settata o ricavata.

+ +
function modulus(){
+  return Math.sqrt(this.re * this.re + this.im * this.im);
+}
+
+var o = {
+  re: 1,
+  im: -1,
+  get phase(){
+    return Math.atan2(this.im, this.re);
+  }
+};
+
+Object.defineProperty(o, 'modulus', {
+    get: modulus, enumerable:true, configurable:true});
+
+console.log(o.phase, o.modulus); // logs -0.78 1.4142
+
+ +

Come costruttore

+ +

Quando una funzione è usata come un costruttore (tramite la parola chiave new), this è collegata al nuovo oggetto che viene costruito.

+ +

Nota: mentre di default un costruttore restituisce l'oggetto riferenziato da this, può invece restituire qualche altro oggetto (se il valore di ritorno non è un oggetto, allora viene restituito l'oggetto this).

+ +
/*
+ * 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); // logs 37
+
+
+function C2(){
+  this.a = 37;
+  return {a:38};
+}
+
+o = new C2();
+console.log(o.a); // logs 38
+
+ +

Nell'ultimo esempio (C2), dal momento che è stato restituito un oggetto durante la costruzione, il nuovo oggetto a cui this era collegato viene semplicemente scartato. (Questo rende essenzialmente l'assegnazione "this.a = 37;" codice inutile. Non lo è in senso stretto, in quanto viene eseguito, ma può essere eliminato senza conseguenze).

+ +

I metodi call e apply

+ +

Dove una funzione usa la parola chiave this, il suo valore può essere collegato ad un qualsivoglia oggetto nella chiamata usando i metodi call o apply che tutte le funzioni ereditano da Function.prototype. 

+ +
function add(c, d){
+  return this.a + this.b + c + d;
+}
+
+var o = {a:1, b:3};
+
+// The first parameter is the object to use as
+// 'this', subsequent parameters are passed as
+// arguments in the function call
+add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
+
+// The first parameter is the object to use as
+// 'this', the second is an array whose
+// members are used as the arguments in the function call
+add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
+
+ +

Notare che con call e apply, se il valore passato tramite this non è un oggetto, viene eseguito un tentativo di convertire tale valore in oggetto usando l'operazione interna ToObject. pertanto, se il valore passato è un primitivo come 7 o 'foo', questo verrà convertito ad Object usando il relativo costruttore, quindi il valore primitivo 7 viene convertito  come new Number(7) e la stringa 'foo' viene convertita come new String('foo'), per esempio:

+ +
function bar() {
+  console.log(Object.prototype.toString.call(this));
+}
+
+bar.call(7); // [object Number]
+
+ +

Il metodo bind

+ +

ECMAScript 5 ha introdotto Function.prototype.bind. Chiamare f.bind(someObject) crea una nuova funzione con lo stesso corpo e visibità di f, ma nella funzione originale si trova la parola chiave this, nella nuova funzione viene permanentemente collegato al primo argomento passato alla chiamata del metodo bind, ignorando come la funzione stessa venga usata. 

+ +
function f(){
+  return this.a;
+}
+
+var g = f.bind({a:"azerty"});
+console.log(g()); // azerty
+
+var o = {a:37, f:f, g:g};
+console.log(o.f(), o.g()); // 37, azerty
+
+ +

Come handler degli eventi del DOM

+ +

Quando una funzione viene usata come handler di eventi, i suoi riferimenti this sono puntati all'elemento che ha originato l'evento (alcuni Browser non seguono queste convenzioni per i listeners agguinti dinamicamente tramite metodi diversi da 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 un handler di eventi "in-line"

+ +

quando il codice è chiamato da un handler in-line, this punta all'elemento DOM sul quale il listener è posizionato:

+ +

When code is called from an in–line handler, its this is set to the DOM element on which the listener is placed:

+ +
<button onclick="alert(this.tagName.toLowerCase());">
+  Show this
+</button>
+
+ +

Sopra, alert mostra 'button'. Notare comunque che this assume tale valore solo al di fuori di una funzione:

+ +

 

+ +
<button onclick="alert((function(){return this}()));">
+  Show inner this
+</button>
+
+ +

 

+ +

in questo caso, nella funzione interna, this non punta all'elemento DOM quindi restituisce l'oggetto globale/window (cioè l'oggetto di default in modalità non-strict, in cui this non viene impostato dalla chiamata)

+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

 

+ +

Compatibilità dei browser

+ +

{{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}}
+
+ +

 

+ +

Vedere Anche

+ + diff --git a/files/it/web/javascript/reference/operators/yield/index.html b/files/it/web/javascript/reference/operators/yield/index.html new file mode 100644 index 0000000000..cd7fe6adfa --- /dev/null +++ b/files/it/web/javascript/reference/operators/yield/index.html @@ -0,0 +1,163 @@ +--- +title: yield +slug: Web/JavaScript/Reference/Operators/yield +translation_of: Web/JavaScript/Reference/Operators/yield +--- +
{{jsSidebar("Operators")}}
+ +

La parola chiave yield è usata per mettere in pausa e far ripartire un generatore di funzione ({{jsxref("Statements/function*", "function*")}} or legacy generator function).

+ +

Sintassi

+ +
[rv] = yield [expression];
+ +
+
espressione
+
Definisce il valore da ritornare dalla funzione generatore attraverso the iterator protocol. Se omesso, undefined viene restituito.
+
rv
+
Permette che il generatore catturi il valore dell'espressione per usarlo al prossimo avvio dell'esecuzione.
+
+ +

Descrizione

+ +

The yield keyword causes generator function execution to pause and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword.

+ +

The yield keyword actually returns an IteratorResult object with two properties, value and done. The value property is the result of evaluating the yield expression, and done is a Boolean indicating whether or not the generator function has fully completed.

+ +

Once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called. Each time the generator's next() method is called, the generator resumes execution and runs until it reaches one of the following:

+ + + +

If an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's next yield operation.

+ +

Between the generator's code path, its yield operators, and the ability to specify a new starting value by passing it to {{jsxref("Generator.prototype.next()")}}, generators offer enormous power and control.

+ +

Examples

+ +

The following code is the declaration of an example generator function, along with a helper function.

+ +
function* foo(){
+  var index = 0;
+  while (index <= 2) // when index reaches 3,
+                     // yield's done will be true
+                     // and its value will be undefined;
+    yield index++;
+}
+ +

Once a generator function is defined, it can be used by constructing an iterator as shown.

+ +
var iterator = foo();
+console.log(iterator.next()); // { value: 0, done: false }
+console.log(iterator.next()); // { value: 1, done: false }
+console.log(iterator.next()); // { value: 2, done: false }
+console.log(iterator.next()); // { value: undefined, done: true }
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#', 'Yield')}}{{Spec2('ES2015')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
IteratorResult object instead of throwing{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}{{ CompatUnknown}}{{CompatUnknown}}
IteratorResult object instead of throwing{{CompatUnknown}}{{CompatGeckoMobile("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Firefox-specific notes

+ + + +

See also

+ + diff --git a/files/it/web/javascript/reference/statements/break/index.html b/files/it/web/javascript/reference/statements/break/index.html new file mode 100644 index 0000000000..8799911ff9 --- /dev/null +++ b/files/it/web/javascript/reference/statements/break/index.html @@ -0,0 +1,130 @@ +--- +title: break +slug: Web/JavaScript/Reference/Statements/break +translation_of: Web/JavaScript/Reference/Statements/break +--- +
{{jsSidebar("Statements")}}
+ +

Lo statement break interrompe il loop corrente, termina uno statement {{jsxref("Statements/switch", "switch")}}, o trasferisce l'esecuzione verso un {{jsxref("Statements/label", "label")}} .

+ +
{{EmbedInteractiveExample("pages/js/statement-break.html")}}
+ + + +

Sinstassi

+ +
break [label];
+ +
+
label {{optional_inline}}
+
Identificatore che può essere anche associato ad una {{jsxref("Statements/label", "label")}}. Se lo statement non è un loop o uno {{jsxref("Statements/switch", "switch")}}, il label è necessario.
+
+ +

Descrizione

+ +

Lo statement break può contenere un parametro opzionale ({{jsxref("Statements/label", "label")}}) che impone al programma di interrompere l'esecuzione e saltare ad un determinato punto nel programma, indicato dalla label stessa. La label può anche essere uno degli statement jsxref("Statements/block", "block")}}; e non dovrà essere preceduto da uno statement loop.
+ Uno statement break, con o senza label opzionale, non può essere usato nel corpo di una funzione innestata in un loop o uno switch, poichè quando verrà eseguito break il programma verrà terminato insieme al loop o allo switch.

+ +

Esempi

+ +

break in un while loop

+ +

La seguente funzione contiene uno statement  break che interromperà il {{jsxref("Statements/while", "while")}} loop quando la variabile i avrà valore 3, quindi restituirà il valore di 3 * x.

+ +
function testBreak(x) {
+  var i = 0;
+
+  while (i < 6) {
+    if (i == 3) {
+      break;
+    }
+    i += 1;
+  }
+
+  return i * x;
+}
+ +

break in labeled blocks

+ +

Il seguente codice usa lo statement break con un blocco definito da una {{jsxref("Statements/label", "label")}}. Lo stetement break deve essere innestato all'interno di qualsiasi label a cui fa riferimento. Nota che inner_block è innestato dentro outer_block.

+ +
outer_block: {
+  inner_block: {
+    console.log('1');
+    break outer_block; // esce sia da inner_block che da outer_block
+    console.log(':-('); // non viene eseguito
+  }
+  console.log('2'); // non viene eseguito
+}
+
+ +

break in labeled blocks che genera un errore

+ +

Il codice seguente usa lo statement break nei labeled block, ma genera un SyntaxError poichè il break è all'interno del block_1 ma fa riferimento a block_2. Uno statement break deve sempre essere innestato all'interno dei blocchi a cui si riferiscono i {{jsxref("Statements/label", "label")}}.

+ +
block_1: {
+  console.log('1');
+  break block_2; // SyntaxError: label not found
+}
+
+block_2: {
+  console.log('2');
+}
+
+ +

break all'interno di funzioni

+ +

Verranno generati SyntaxError anche nei seguenti esempi di codice dove viene usato lo stetement break all'interno di funzioni che sono innestate nei cicli loop, oppure all'interno di funzioni innestate in labeled block, per cui lo stetemen break si intende come stop all'esecuzione e uscita.

+ +
function testBreak(x) {
+  var i = 0;
+
+  while (i < 6) {
+    if (i == 3) {
+      (function() {
+        break;
+      })();
+    }
+    i += 1;
+  }
+
+return i * x;
+}
+
+testBreak(1); // SyntaxError: Illegal break statement
+
+ +
block_1: {
+  console.log('1');
+  ( function() {
+    break block_1; // SyntaxError: Undefined label 'block_1'
+  })();
+}
+
+ +

Specifiche

+ + + + + + + + + + +
Specifiche
{{SpecName('ESDraft', '#sec-break-statement', 'Break statement')}}
+ +

Compatibilità dei Browser

+ + + +

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

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/statements/empty/index.html b/files/it/web/javascript/reference/statements/empty/index.html new file mode 100644 index 0000000000..bb10fd7165 --- /dev/null +++ b/files/it/web/javascript/reference/statements/empty/index.html @@ -0,0 +1,102 @@ +--- +title: empty +slug: Web/JavaScript/Reference/Statements/Empty +translation_of: Web/JavaScript/Reference/Statements/Empty +--- +
{{jsSidebar("Statements")}}
+ +

Un empty statement (istruzione vuota) è utilizzato per evitare di inserire uno statement nel caso in cui la sintassi JavaScript ne richieda uno.

+ +
{{EmbedInteractiveExample("pages/js/statement-empty.html")}}
+ + + +

Sintassi

+ +
;
+
+ +

Descrizione

+ +

L'empty statement è un punto e virgola (;) che indica che nessuno statement sarà eseguito, nonostante la sintassi JavaScript ne richieda uno. Il comportamento opposto, quando vuoi eseguire più statement ma JavaScript ne consente uno solo, è reso possibile dall'utilizzo di un block statement; esso ne combina diversi in un singolo statement .

+ +

Esempi

+ +

L'empty statement è utilizzato talvolta con i loop statements. Guarda l'esempio seguente con un copro del loop vuoto:

+ +
var arr = [1, 2, 3];
+
+// Assegna il valore 0 a tutti gli elementi dell'array
+for (i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ;
+
+console.log(arr)
+// [0, 0, 0]
+
+ +

Nota: E' una buona pratica commentare l'utilizzo intenzionale di empty statement, poichè non è immediatamente ovvia la differenza con un normale punto e virgola. Nell'esempio seguente l'uso è probabilmente non intenzionale:

+ +
if (condition);       // Attenzione, questo "if" non produce nessun effetto!
+   killTheUniverse()  // E quindi questo sarà eseguito sempre!!!
+
+ +

Un altro Esempio: Un if...else statement senza parentesi graffe ({}). Se three è true, non accadrà nulla, four non viene valutato, e neanche la funzione launchRocket()nel ramo else sarà eseguita.

+ +
if (one)
+  doOne();
+else if (two)
+  doTwo();
+else if (three)
+  ; // nothing here
+else if (four)
+  doFour();
+else
+  launchRocket();
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-12.3', 'Empty statement')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES1')}}Initial definition.
+ +

Compatibilità con i Browser

+ + + +

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

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/statements/export/index.html b/files/it/web/javascript/reference/statements/export/index.html new file mode 100644 index 0000000000..47d67a6eb2 --- /dev/null +++ b/files/it/web/javascript/reference/statements/export/index.html @@ -0,0 +1,259 @@ +--- +title: export +slug: Web/JavaScript/Reference/Statements/export +tags: + - ECMAScript 2015 + - JavaScript + - Moduli + - export +translation_of: Web/JavaScript/Reference/Statements/export +--- +
{{jsSidebar("Statements")}}
+ +
Il comando export è utilizzato per esportare funzioni, oggetti o tipi primitivi da un dato file (o modulo) in modo tale da poter essere riutilizzati in altri file con il comando {{jsxref("Statements/import", "import")}}
+ +
+ +
I moduli sono esportati sempre in {{jsxref("Strict_mode","strict mode", "", 1)}}  nonostante non sia dichiarato. Il comando export non può essere usato in embedded scripts.
+ +

Sintassi

+ +

Ci sono due tipi di exports:

+ +
    +
  1. Named exports (uno o più exports per modulo)
  2. +
  3. Default exports (uno per modulo)
  4. +
+ +
// Export di variabili, funzioni e oggetti singolarmente
+export let name1, name2, …, nameN; // also var, const
+export let name1 = …, name2 = …, …, nameN; // also var, const
+export function functionName(){...}
+export class ClassName {...}
+
+// Export di una lista
+export { name1, name2, …, nameN };
+
+// Rinominare gli exports
+export { variable1 as name1, variable2 as name2, …, nameN };
+
+// Exporting destructured assignments with renaming
+// Export di assegnazioni destrutturate rinominando l'export
+export const { name1, name2: bar } = o;
+
+// DEfault export
+export default expression;
+export default function (…) { … } // also class, function*
+export default function name1(…) { … } // also class, function*
+export { name1 as default, … };
+
+// Aggregazione di moduli
+export * from …; // does not set the default export
+export * as name1 from …; // Draft ECMAScript® 2O21
+export { name1, name2, …, nameN } from …;
+export { import1 as name1, import2 as name2, …, nameN } from …;
+export { default } from …;
+ +
+
nameN
+
Nome che deve essere esportato (così da poter essere importato via import in un altro script).
+
+ +

Descrizione

+ +

Ci sono due tipi diversi di export, named and default. Puoi avere più named exports per modulo ma solamente un default export.

+ +

Named exports:

+ +
// Export di variabili, funzioni, oggetti dichiarati precedentemente
+export { myFunction, myVariable };
+
+// export individual features (can export var, let,
+// const, function, class)
+export let myVariable = Math.sqrt(2);
+export function myFunction() { ... };
+ +

Default exports:

+ +
// Export di funzioni dichiarati precedentemente come default
+export { myFunction as default };
+
+// Export di singole funzioni, oggetti come default
+export default function () { ... }
+export default class { .. }
+
+// ogni export sovrascrive il precedente
+ +

I named exports sono utili per esportare più valori. Durante l'import, è obbligatorio usare lo stesso nome dell'oggetto corrispondente.

+ +

I defalt export invece possono essere importati con qualsiasi nome. Ad esempio:

+ +
// file test.js
+let k; export default k = 12;
+
+ +
// some other file
+import m from './test'; //notare che abbiamo la libertà di importare m invece di importate k, perché  k era il default export
+console.log(m);        // stamperà 12
+
+ +

Puoi anche rinominare i named exports per evitare conflitti:

+ +
export { myFunction as function1,
+         myVariable as variable };
+ +

Ri-esportare / Aggregare

+ +

È anche possibile importare ed esportare da più moduli nel modulo padre in modo tale da rendere rendere disponibili gli import da quel modulo. In altre parole è possibile creare un modulo che aggreghi i vari export da vari moduli.

+ +

È possibile farlo con la sintassi "export from":

+ +
export { default as function1,
+         function2 } from 'bar.js';
+
+ +

che è paragonabile ad una combinazione di import e export:

+ +
import { default as function1,
+         function2 } from 'bar.js';
+export { function1, function2 };
+ +

dove function1 e function2 non sono disponibili nel modulo corrente.

+ +
+

Note: I seguenti esempi sono sintatticamente invalidi nonostante siano equivalenti dal punto divista del comando import

+
+ +
import DefaultExport from 'bar.js'; // Valid
+ +
export DefaultExport from 'bar.js'; // Invalid
+ +

Il modo corretto di farlo è di rinominare gli export:

+ +
export { default as DefaultExport } from 'bar.js';
+ +

Esempi

+ +

Usare gli export espliciti

+ +

In un modulo my-module.js, potremmo includere il seguente codice:

+ +
// modulo "my-module.js"
+function cube(x) {
+  return x * x * x;
+}
+
+const foo = Math.PI + Math.SQRT2;
+
+var graph = {
+  options: {
+      color:'white',
+      thickness:'2px'
+  },
+  draw: function() {
+      console.log('From graph draw function');
+  }
+}
+
+export { cube, foo, graph };
+ +

E nel modulo principale incluso nella pagina HTML potremmo avere

+ +
import { cube, foo, graph } from './my-module.js';
+
+graph.options = {
+    color:'blue',
+    thickness:'3px'
+};
+
+graph.draw();
+console.log(cube(3)); // 27
+console.log(foo);    // 4.555806215962888
+ +

Notare che:

+ + + +

Usare i default export

+ +

Se vogliamo esportare un singolo valore o avere un valore di default per il tuo modulo, allora possiamo usare il default export:

+ +
// modulo "my-module.js"
+export default function cube(x) {
+  return x * x * x;
+}
+
+ +

Quindi, in un altro script, puoi importare il modulo direttamente:

+ +
import cube from 'my-module';
+console.log(cube(3)); // 27
+
+ +

Usare export from

+ +

Facciamo l'esempio dove abbiamo i seguenti moduli:

+ + + +

Questo è come sarebbe con il codice:

+ +
// Nel modulo childModule1.js
+let myFunction = ...; // assegna una funzione myFunction
+let myVariable = ...; // assegna un valore alla variabile myVariable
+export {myFunction, myVariable};
+
+ +
// Nel modulo childModule2.js
+let myClass = ...; // assegna qualcosa di utile a myClass
+export myClass;
+
+ +
// Nel modulo parentModule.js
+// Aggreghiamo solamente gli export dai moduli childModule1 e childModule2
+// per poi riesportarli
+export { myFunction, myVariable } from 'childModule1.js';
+export { myClass } from 'childModule2.js';
+
+ +
// Nel modulo principale
+// Possiamo usare gli export importandoli da un singolo modulo
+// che li colleziona/include in un singolo modulo
+import { myFunction, myVariable, myClass } from 'parentModule.js'
+ +

Specifiche

+ + + + + + + + + + + + +
Specifiche
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}
+ +

Compatibilità Browser

+ +

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

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/statements/for...of/index.html b/files/it/web/javascript/reference/statements/for...of/index.html new file mode 100644 index 0000000000..ffc6f472c0 --- /dev/null +++ b/files/it/web/javascript/reference/statements/for...of/index.html @@ -0,0 +1,264 @@ +--- +title: for...of +slug: Web/JavaScript/Reference/Statements/for...of +translation_of: Web/JavaScript/Reference/Statements/for...of +--- +

{{jsSidebar("Statements")}}

+ +

Il costrutto for...of crea un ciclo con gli oggetti iterabili (inclusi {{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("String")}}, {{jsxref("TypedArray")}}, argomenti di oggetti e così via), iterando le istruzioni per ogni valore di ogni proprietà.

+ +

Sintassi

+ +
for (variabile of oggettoIterabile) {
+  istruzioni
+}
+
+ +
+
variabile
+

+ Questa variabile assume il valore di una proprietà in ogni ciclo.
+
oggettoIterabile
+
Oggetto le cui proprietà sono iterate.
+
+ +

Esempi

+ +

Iterare un {{jsxref("Array")}}:

+ +
let array = [10, 20, 30];
+
+for (let valore of array) {
+  console.log(valore);
+}
+// Output:
+// 10
+// 20
+// 30
+
+ +

Si può utilizzare const anzichè let se 'value' non cambia valore durante il ciclo.

+ +
let iterable = [10, 20, 30];
+
+for (const value of iterable) {
+  console.log(value); // il valore di value di questo ciclo rimarrà costante
+  value++; // operazione non consentita.
+}
+// 10
+// 20
+// 30
+
+ +

Iterare un oggetto {{jsxref("String")}}:

+ +
let iterable = "boo";
+
+for (let value of iterable) {
+  console.log(value);
+}
+// output:
+// "b"
+// "o"
+// "o"
+
+ +

Iterare un oggetto {{jsxref("TypedArray")}}:

+ +
let iterable = new Uint8Array([0x00, 0xff]);
+
+for (let value of iterable) {
+  console.log(value);
+}
+// 0
+// 255
+
+ +

Iterare un oggetto {{jsxref("Map")}}:

+ +
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
+
+for (let entry of iterable) {
+  console.log(entry);
+}
+// [a, 1]
+// [b, 2]
+// [c, 3]
+
+for (let [key, value] of iterable) {
+  console.log(value);
+}
+// 1
+// 2
+// 3
+
+ +

Iterare un oggetto {{jsxref("Set")}}:

+ +
let iterable = new Set([1, 1, 2, 2, 3, 3]);
+
+for (let value of iterable) {
+  console.log(value);
+}
+// 1
+// 2
+// 3
+
+ +

Iterare un DOM collection

+ +
+

Iterare un DOM collection come {{domxref("NodeList")}}: il seguente esempio aggiunge una classe 'read' ai paragrafi che sono discendenti diretti di un elemento article:

+
+ +
+

Nota: Questo costrutto funziona soltanto con le piattaforme che implementano NodeList.prototype[Symbol.iterator]

+
+ +
+
let articleParagraphs = document.querySelectorAll("article > p");
+
+for (let paragraph of articleParagraphs) {
+  paragraph.classList.add("read");
+}
+
+
+ +

Iterare generatori

+ +

Si possono iterare i generatori:

+ +
function* fibonacci() { // generatore di funzione
+  let [prev, curr] = [0, 1];
+  while (true) {
+    [prev, curr] = [curr, prev + curr];
+    yield curr;
+  }
+}
+
+for (let n of fibonacci()) {
+  console.log(n);
+  // tronca la sequenza a 1000
+  if (n >= 1000) {
+    break;
+  }
+}
+
+ +

Differerenze tra for...of e for...in

+ +

Il for...in itera tutte le proprietà enumerabili di un oggetto.

+ +

Il for...of è specifico per le collezioni, piuttosto che tutti gli oggetti. Itera tutti gli oggetti di qualsiasi collection che abbia la proprietà [Symbol.iterator].

+ +

Il seguente esempio mostra le differenze tra for...of e for...in.

+ +
Object.prototype.objCustom = function () {};
+Array.prototype.arrCustom = function () {};
+
+let iterable = [3, 5, 7];
+iterable.foo = "hello";
+
+for (let i in iterable) {
+  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
+}
+
+for (let i of iterable) {
+  console.log(i); // logs 3, 5, 7
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ES6')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità con i browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeOperaSafari
Basic support{{CompatChrome(38)}} [1]
+ {{CompatChrome(51)}} [3]
{{CompatGeckoDesktop("13")}} [2]12257.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatChrome(38)}} [1]{{CompatGeckoMobile("13")}} [2]{{CompatUnknown}}{{CompatUnknown}}8
+
+ +

[1] Da Chrome 29 a Chrome 37 questa caratteristica era disponibile nel menu preferenze. In chrome://flags/#enable-javascript-harmony, bisognava attivare “Enable Experimental JavaScript”.

+ +

[2] Da Gecko 17 (Firefox 17 / Thunderbird 17 / SeaMonkey 2.14) a Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2) la proprietà iterator era usata (bug 907077), e da Gecko 27 a Gecko 35 era utilizzato "@@iterator" placeholder. In Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33), il simbolo symbolo @@iterator fu implementato (bug 918828).

+ +

[3] Il supporto dell'iteration of objects è stato aggiunto in Chrome 51.

+ +

Note

+ +

Se alcuni collegamenti su questa pagina fossero segnati in rosso e si volesse visualizzarli, essi sono dispoiìnibili solo in lingua inglese. In tal caso basta cambiare la lingua di questo stesso articolo.

+ +

See also

+ + + +

 

diff --git a/files/it/web/javascript/reference/statements/function_star_/index.html b/files/it/web/javascript/reference/statements/function_star_/index.html new file mode 100644 index 0000000000..a71ccfc55e --- /dev/null +++ b/files/it/web/javascript/reference/statements/function_star_/index.html @@ -0,0 +1,280 @@ +--- +title: function* +slug: Web/JavaScript/Reference/Statements/function* +translation_of: Web/JavaScript/Reference/Statements/function* +--- +
{{jsSidebar("Statements")}}
+ +

La dichiarazione function* (la parola chiave function seguita da un asterisco) definisce una funzione generatrice, la quale restituisce un oggetto di tipo {{jsxref("Global_Objects/Generator","Generator")}}.

+ +

{{EmbedInteractiveExample("pages/js/statement-functionasterisk.html")}}

+ +
+

È anche possibile definire una funzione generatrice usando il costrutto {{jsxref("GeneratorFunction")}} e una {{jsxref("Operators/function*", "espressione function*")}}.

+
+ +

Sintassi

+ +
function* nome([param[, param[, ... param]]]) {
+   istruzioni
+}
+
+ +
+
nome
+
Il nome della funzione.
+
+ +
+
param
+
Gli argomenti passati alla funzione. Una funzione può avere fino a 255 argomenti.
+
+ +
+
istruzioni
+
Le istruzioni che compongono il corpo della funzione.
+
+ +

Descrizione

+ +

I generatori sono funzioni  dalle quali è possibile uscire e poi rientrarvi in un secondo momento. Il loro contesto (binding delle variabili) verrà salvato all'uscita per quando vi entrerà successivamente.

+ +

La chiamata ad un generatore non viene eseguita immediatamente; la funzione ritornerà invece un oggetto iterator. Quando il metodo next() dell'iteratore viene chiamato, il corpo del generatore viene eseguito fino alla prima espressione {{jsxref("Operators/yield", "yield")}}, la quale specifica quale espressione ritornare dall'iteratore oppure, con l'espressione {{jsxref("Operators/yield*", "yield*")}}, delegare questo valore ad un'altra funzione generatrice. Il metodo next() restituisce un oggetto con proprietà value contenente il valore da restituito all'iteratore ed una proprietà done che contiene un valore di tipo boolean per indicare se il generatore ha restituito l'ultimo valore. Chiamando il metodo next() con un argomento farà riprendere l'esecuzione della funzione generatrice, sostituendo l'istruzione yield in cui l'esecuzione era stata fermata con l'argomento della funzione next()

+ +

Esempi

+ +

Esempio semplice

+ +
function* idMaker(){
+  var index = 0;
+  while(index < 3)
+    yield index++;
+}
+
+var gen = idMaker();
+
+console.log(gen.next().value); // 0
+console.log(gen.next().value); // 1
+console.log(gen.next().value); // 2
+console.log(gen.next().value); // undefined
+// ...
+ +

Esempio con 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
+
+ +

Passare argomenti ai Generatori

+ +
function* logGenerator() {
+  console.log(yield);
+  console.log(yield);
+  console.log(yield);
+}
+
+var gen = logGenerator();
+
+// the first call of next executes from the start of the function
+// until the first yield statement
+gen.next();
+gen.next('pretzel'); // pretzel
+gen.next('california'); // california
+gen.next('mayonnaise'); // mayonnaise
+
+ +

I generatori non sono costruttori

+ +
function* f() {}
+var obj = new f; // solleva "TypeError: f is not a constructor"
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommenti
{{SpecName('ES6', '#', 'function*')}}{{Spec2('ES6')}}Definizione iniziale
{{SpecName('ES7', '#', 'function*')}}{{Spec2('ES7')}}I generatori non devono avere essere usati come costruttori e deveo lanciare un eccezione quando vengono usati con la parola chiave new.
{{SpecName('ESDraft', '#', 'function*')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità per i browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet Explorer EdgeOperaSafari (WebKit)
Supporto base{{CompatChrome(39.0)}}{{CompatGeckoDesktop("26.0")}}{{CompatNo}}1326{{CompatNo}}
yield*{{CompatVersionUnknown}}{{CompatGeckoDesktop("27.0")}}{{CompatNo}}1326{{CompatNo}}
IteratorResult invece delle eccezioni{{CompatVersionUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatNo}}13{{CompatVersionUnknown}}{{CompatNo}}
Non istanziabile con new {ES2016){{CompatVersionUnknown}}{{CompatGeckoDesktop("43.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Supporto base{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("26.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(39.0)}}
yield*{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("27.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
IteratorResult invece delle eccezioni{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("29.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
Non istanziabile con new (ES2016){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("43.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Note specifiche per Firefox

+ +

Generatori e iteratori in Firefox nelle versioni precedenti alla 26

+ +

Versioni di FIrefox precedenti implementano una versione più vecchia della proposta di standard per i generatori. Tra le varie differenze, in queste versioni i generatori erano definiti usando la parola chiave function (senza asterisco) per le funzioni semplici. Per maggiori informazioni fare riferimento a {{jsxref("Statements/Legacy_generator_function", "funzioni generatrici (legacy)")}}.

+ +

IteratorResult al posto delle eccezioni

+ +

A partire da Gecko 29 {{geckoRelease(29)}}, la funzione generatrice completata non solleva più eccezioni {{jsxref("TypeError")}} "generator has already finished". Restituisce invece oggetti di tipo IteratorResult come il seguente { value: undefined, done: true } ({{bug(958951)}}).

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/statements/import/index.html b/files/it/web/javascript/reference/statements/import/index.html new file mode 100644 index 0000000000..9a6ac79920 --- /dev/null +++ b/files/it/web/javascript/reference/statements/import/index.html @@ -0,0 +1,167 @@ +--- +title: import +slug: Web/JavaScript/Reference/Statements/import +translation_of: Web/JavaScript/Reference/Statements/import +--- +
{{jsSidebar("Statements")}}
+ +

Il comando import si usa per importare bindings esportati da un altro modulo. I moduli importati sono in {{jsxref("Strict_mode","strict mode")}} indipendentemente dal fatto che venga dichiarato in modo esplicito. Il comando import non puo' essere usato negli script embedded.

+ +

Sintassi

+ +
import defaultExport from "module-name";
+import * as name from "module-name";
+import { export } from "module-name";
+import { export as alias } from "module-name";
+import { export1 , export2 } from "module-name";
+import { export1 , export2 as alias2 , [...] } from "module-name";
+import defaultExport, { export [ , [...] ] } from "module-name";
+import defaultExport, * as name from "module-name";
+import "module-name";
+ +
+
defaultExport
+
Nome riferito all'export di default nel modulo.
+
module-name
+
Il modulo da cui importare. E' spesso il path relativo o assoluto del file .js che contiene il modulo. Alcuni bundlers possono permettere o imporre l'uso dell'estensione; verifica nel tuo environment. Sono ammesse solo stringhe a singole o doppie virgolette.
+
name
+
Nome dell' oggetto-modulo che verra' usato come namespace quando si fa riferimento nelle importazioni.
+
export, exportN
+
Nome degli export da importare.
+
alias, aliasN
+
Nomi fittizi (alias) riferiti ai nomi importati.
+
+ +

Descrizione

+ +

Il parametro name e' il nome dell' "oggetto-modulo" che verra' usato come namespace per riferirsi agli export al suo interno. I parametri export indicano i nomi dei singoli export, mentre import * li importa tutti insieme. Seguiranno degli esempi per chiarire questa sintassi.

+ +

Importare l'intero contenuto di un modulo

+ +

L'esempio inserisce myModule nello scope corrente, che conterra' tutti gli export del modulo, il cui file si trova in /modules/my-module.js.

+ +
import * as myModule from '/modules/my-module.js';
+
+ +

Qui invece, si accede agli export usando il nome del modulo ("myModule" in this case) come namespace. Per esempio, se il modulo importato contiene l'export doAllTheAmazingThings(), lo indicherai in questo modo:

+ +
myModule.doAllTheAmazingThings();
+ +

Importare un singolo export da un modulo

+ +

Dato un oggetto o valore di nome myExport che sia esportato dal modulo my-module, sia implicitamente (perche' viene esportato l'intero modulo) che esplicitamente (usando il comando {{jsxref("Statements/export", "export")}}), l'esempio che segue inserira' myExport nello scope corrente.

+ +
import {myExport} from '/modules/my-module.js';
+ +

Importare export multipli da un modulo

+ +

In questo esempio, sia foo che bar verranno inseriti nello scope corrente.

+ +
import {foo, bar} from '/modules/my-module.js';
+ +

Importare un export usando un alias

+ +

E' possibile rinominare un export in fase di importazione, ad esempio, shortName verra' inserito in questo modo nello scope corrente:

+ +
import {reallyReallyLongModuleExportName as shortName}
+  from '/modules/my-module.js';
+ +

Rinominare export multipli in un importazione

+ +

Importazione multipla di export da un modulo, usando per comodita' degli alias:

+ +
import {
+  reallyReallyLongModuleExportName as shortName,
+  anotherLongModuleName as short
+} from '/modules/my-module.js';
+ +

Importare solo gli 'effetti collaterali' di un modulo

+ +

Importazione dei soli 'effetti collaterali' di un modulo, senza importare tutto il resto. Cio' che segue eseguira' soltanto il codice nello scope globale ma senza importare alcun valore.

+ +
import '/modules/my-module.js';
+
+ +

Importare defaults

+ +

E' possibile che in un modulo ci sia un esportazione di default {{jsxref("Statements/export", "export")}} (che sia un oggetto, una funzione, una classe, ecc...) e il comando import potra' servire per importarlo.

+ +

La versione piu' semplice che importa direttamente il default e' questa:

+ +
import myDefault from '/modules/my-module.js';
+ +

E' possibile usare questa sintassi all'interno delle altre che abbiamo gia' visto (importazioni con namespace o nomi specifici) ma, in questo caso, l'importazione di default dovra' essere indicata per prima:

+ +
import myDefault, * as myModule from '/modules/my-module.js';
+// myModule used as a namespace
+ +

oppure

+ +
import myDefault, {foo, bar} from '/modules/my-module.js';
+// specific, named imports
+
+ +

Esempi

+ +

Importazione di una funzione helper da un modulo secondario che processa una richiesta AJAX JSON.

+ +

Modulo: file.js

+ +
function getJSON(url, callback) {
+  let xhr = new XMLHttpRequest();
+  xhr.onload = function () {
+    callback(this.responseText)
+  };
+  xhr.open('GET', url, true);
+  xhr.send();
+}
+
+export function getUsefulContents(url, callback) {
+  getJSON(url, data => callback(JSON.parse(data)));
+}
+ +

Main program: main.js

+ +
import { getUsefulContents } from '/modules/file.js';
+
+getUsefulContents('http://www.example.com',
+    data => { doSomethingUseful(data); });
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificaStatusCommento
{{SpecName('ES2015', '#sec-imports', 'Imports')}}{{Spec2('ES2015')}}Definizione iniziale.
{{SpecName('ESDraft', '#sec-imports', 'Imports')}}{{Spec2('ESDraft')}} 
+ +

Compatibilitá

+ + + +

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

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/statements/index.html b/files/it/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..e997b9799f --- /dev/null +++ b/files/it/web/javascript/reference/statements/index.html @@ -0,0 +1,131 @@ +--- +title: Statements +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.
+
{{experimental_inline}} {{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{experimental_inline}} {{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Functions and classes

+ +
+
{{jsxref("Statements/function", "function")}}
+
Declares a function with the specified parameters.
+
{{experimental_inline}} {{jsxref("Statements/function*", "function*")}}
+
Generators functions enable writing iterators more easily.
+
{{jsxref("Statements/return", "return")}}
+
Specifies the value to be returned by a function.
+
{{experimental_inline}} {{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.
+
{{experimental_inline}} {{jsxref("Statements/for...of", "for...of")}}
+
Iterates over iterable objects (including arrays, 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.
+
{{experimental_inline}} {{jsxref("Statements/export", "export")}}
+
Used to export functions to make them available for imports in external modules, another scripts.
+
{{experimental_inline}} {{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
ECMAScript 1st Edition.StandardInitial definition.
{{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
+ +

See also

+ + diff --git a/files/it/web/javascript/reference/statements/let/index.html b/files/it/web/javascript/reference/statements/let/index.html new file mode 100644 index 0000000000..7900b7673a --- /dev/null +++ b/files/it/web/javascript/reference/statements/let/index.html @@ -0,0 +1,208 @@ +--- +title: let +slug: Web/JavaScript/Reference/Statements/let +translation_of: Web/JavaScript/Reference/Statements/let +--- +
{{jsSidebar("Statements")}}
+ +

L'istruzione let dichiara una variabile locale nel blocco di codice e, facoltativamente, la inizializza ad un valore.

+ +
{{EmbedInteractiveExample("pages/js/statement-let.html")}}
+ + + +

Sintassi

+ +
let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];
+
+ +

Parametri

+ +
+
var1, var2, …, varN
+
Il nome della variabile o delle variabili da dichiarare. Devono essere identificatori JavaScript validi.
+
value1, value2, …, valueN {{optional_inline}}
+
Per ogni variabile definita, è possibile specificare il valore iniziale usando qualunque espressione JavaScript valida.
+
+ +

Descrizione

+ +

let permette di dichiarare variabili limitandone la visibilità ad un {{jsxref("statements/block", "blocco di codice", "", 1)}}, o ad un'espressione in cui è usata, contrariamente alla parola chiave var, che invece definisce una variabile globalmente in uno script o localmente in una funzione a prescindere dal blocco di codice. L'altra differenza tra {{jsxref("statements/var", "var")}} e let è che la seconda è inizializzata ad un valore solo quando un parser la evaluta (vedi sotto).

+ +

Esempi

+ +

Regole di visibilità

+ +

Le variabili inizializzate da let sono legate al blocco dell'espressione in cui sono dichiarate. Il suo funzionamento è del tutto simile a quello di var, ma le variabili definite da quest'ultima istruzione sono sempre variabili globali a livello di programma o di funzione, hanno quindi una visibilità più ampia.

+ +
function varTest() {
+  var x = 1;
+  {
+    var x = 2;  // same variable!
+    console.log(x);  // 2
+  }
+  console.log(x);  // 2
+}
+
+function letTest() {
+  let x = 1;
+  {
+    let x = 2;  // different variable
+    console.log(x);  // 2
+  }
+  console.log(x);  // 1
+}
+ +

Dichiarare nuovamente la stessa variabile con let restituisce l'errore TypeError.

+ +

+if (x) {
+  let foo;
+  let foo; // lancia un errore TypeError.
+}
+ +

Se usata al livello più alto di programma, let, a differenza di var, non crea una proprietà seuul'oggetto globale. Per esempio:

+ +
var x = 'global';
+let y = 'global';
+console.log(this.x); // "global"
+console.log(this.y); // undefined
+ +

Potresti imbatterti in errori in un blocco switch perché i casi non vengono separati ma fanno parte tutti dello stesso blocco.

+ +

+switch (x) {
+  case 0:
+    let foo;
+    break;
+
+  case 1:
+    let foo; // TypeError for redeclaration.
+    break;
+}
+ +

Esempi

+ +

Una let expression può essere usata per limitare la visibilità della variabile dichiarata alla sola espressione chiamata.

+ +

+var a = 5;
+let(a = 6) alert(a); // 6
+alert(a); // 5
+ +

Usando let in un blocco di codice ne limitiamo la visibilità al solo blocco racchiuso. Nel codice di esempio nota come le due assegnazioni nel blocco if diano due risultati diversi.

+ +

+var a = 5;
+var b = 10;
+
+if (a === 5) {
+  let a = 4; // La visibilità è dentro il blocco if
+  var b = 1; // La visibilità è dentro la funzione
+
+  console.log(a);  // 4
+  console.log(b);  // 1
+}
+
+console.log(a); // 5
+console.log(b); // 1
+ +

Puoi usare let come iteratore in un ciclo for invece di usare una nuova variabile globale.

+ +

+for (let i = 0; i<10; i++) {
+  alert(i); // 1, 2, 3, 4 ... 9
+}
+
+alert(i); // i non è definita
+ +

Quando lavori con i costruttori puoi usare let per creare in'interfaccia privata senza chiusure.

+ +

+/*\
+|*|
+|*|  :: Una API pubblica e riutilizzabile per i costruttori ... ::
+|*|
+\*/
+
+let (
+  switchScope = function (oOwner, fConstructor) {
+    return oOwner && oOwner.constructor === fConstructor ? oOwner : this;
+  }
+) {
+  function buildIndoors (fConstructor) {
+    const oPrivate = new fConstructor(this);
+    this.getScope = oPrivate.getScope = switchScope.bind(this, oPrivate);
+    return oPrivate;
+  }
+}
+
+/*\
+|*|
+|*|  :: Use of the *let* statement in order to create a private interface without closures... ::
+|*|
+\*/
+
+let (
+
+  /* "Secrets" is the constructor of the private interface */
+
+  Secrets = function Secrets (oPublic /* (the public interface) */) {
+    /* setting a private property... */
+    this.password = Math.floor(Math.random() * 1e16).toString(36);
+    /* you can also store the public interface into a private property... */
+    /* this.publicInterface = oPublic; */
+    alert("I\'m getting a public property from a private constructor...: somePublicProperty: " + oPublic.somePublicProperty);
+  }
+
+) {
+
+  /* "User" is the constructor of the public interface */
+
+  function User (sNick) {
+    /* setting a public property... */
+    this.somePublicProperty = "Hello World!";
+    const oPrivate = this.createScope(Secrets); /* (the private interface) */
+    /* setting a public property... */
+    this.user = sNick;
+    alert("I\'m getting a private property from a public constructor...: password: " + oPrivate.password);
+  }
+
+  User.prototype.somePublicMethod = function () {
+    const oPrivate = this.getScope(Secrets); /* (the private interface) */
+    alert("I\'m getting a public property from a public method...: user: " + this.user);
+    alert("I\'m getting a private property from a public method...: password: " + oPrivate.password);
+    oPrivate.somePrivateMethod();
+  };
+
+  Secrets.prototype.somePrivateMethod = function () {
+    const oPublic = this.getScope(); /* (the public interface) */
+    alert("I\'m getting a public property from a private method...: user: " + oPublic.user);
+    alert("I\'m getting a private property from a private method...: password: " + this.password);
+  };
+
+  /* ...creating a mutual access... */
+
+  User.prototype.createScope = buildIndoors;
+}
+
+/* out of the *let* statement you have not access to the private interface! */
+
+const johnSmith = new User("John Smith");
+johnSmith.somePublicMethod();
+ +

Browser compatibility

+ + + +

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

+ +

+ +

See also

+ + diff --git a/files/it/web/javascript/reference/statements/switch/index.html b/files/it/web/javascript/reference/statements/switch/index.html new file mode 100644 index 0000000000..aef4d668ce --- /dev/null +++ b/files/it/web/javascript/reference/statements/switch/index.html @@ -0,0 +1,320 @@ +--- +title: switch +slug: Web/JavaScript/Reference/Statements/switch +tags: + - JavaScript + - Reference + - Statement + - Web +translation_of: Web/JavaScript/Reference/Statements/switch +--- +
{{jsSidebar("Statements")}}
+ +

Il comandoswitch valuta un espressione, confronta il valore dell'espressione con ciascuna delle clausole case ed esegue i comandi (statements) associati alla clausola (case) che verifica il confronto.

+ +

Sintassi

+ +
switch (espressione) {
+  case valore1:
+    //Comandi eseguiti quando il valore dell'espressione coincide con valore1
+    [break;]
+  case valore2:
+    //Comandi eseguiti quando il valore dell'espressione coincide con valore2
+    [break;]
+  ...
+  case valoreN:
+    //Comandi eseguiti quando il valore dell'espressione coincide con valoreN
+    [break;]
+  default:
+    //Comandi eseguiti quando nessuno dei valori coincide col valore dell'epressione
+    [break;]
+}
+ +
+
espressione
+
Un'espressione il cui risultato è confrontato con ogni clausola case.
+
case valoreN
+
Clausola case usata nel confronto con l' espressione.
+
default
+
Una clausola default è facoltativa e, se specificata, la clausola viene eseguita se il valore dell'espressione non corrisponde a nessuna clausola case.
+
+ +

Descrizione

+ +

Un comando switch per prima cosa valuta espressione; poi cerca la prima clausola case la cui essa ha lo stesso valore del risultato dell'espressione di switch (utilizzando la strict comparison, ===); quindi il comando switch trasferisce il controllo alla clausola case, eseguendone i comandi. Se più clausole case sono verificate dal confronto con l'espressione di switch,  viene scelta la prima che verifica il confronto, anche se le clausole non sono uguali. Se nessuna clausola case risulta verificata dal confronto, il programma cerca la clausola facoltativa default, e se la trova, trasferisce il controllo a questa, eseguendone i comandi. Se non viene trovata alcuna clausola default, il programma continua eseguendo il comando successivo alla fine del comando switch. Convenzionalmente, ma non necessariamente, la clausola default è l'ultima clausola.

+ +

Il comando facoltativo break associato a ciascuna etichetta case assicura che, una volta eseguiti i comandi della clausola che verifica l'espressione di switch, il programma interrompa il comando switch e che continui eseguendo il comando successivo. Se il comando break viene omesso, il programma continua l'esecuzione dal comando successivo all'interno del comando di switch, quindi dal primo della successiva clausola case.

+ +

Esempi

+ +

Utilizzo di switch

+ +

Nell'esempio seguente, se expr vale "Banane", il programma confronta il valore con la clausola "Banane" ed esegue i comandi associati. Quando incontra break, il programma interrompe il comando switch ed esegue il comando successivo a switch. Se break fosse omesso, sarebbero eseguiti anche i comandi della clausola "Ciliegie".

+ +
switch (expr) {
+  case "Arance":
+    console.log("Le arance costano €1,0 al chilo.");
+    break;
+  case "Mele":
+    console.log("Le mele costano €0.64 al chilo.");
+    break;
+  case "Banane":
+    console.log("Le banane costano €0.92 al chilo.");
+    break;
+  case "Ciliege":
+    console.log("Le ciliegie costano €2.59 al chilo.");
+    break;
+  case "Manghi":
+  case "Papaye":
+    console.log("I manghi e le papaye costano €1.79 al chilo.");
+    break;
+  default:
+    console.log("Spiacenti, non abbiamo " + expr + ".");
+}
+
+console.log("Desidera qualcos'altro ?");
+
+ +

Cosa accade se dimentico un break?

+ +

Se vi dimenticate un break, lo script partirà dalla clausola il cui criterio è verificato, e proseguirà con la clausola successiva anche se il criterio non era verifcato. Ecco alcuni esempi:

+ +
var foo = 0;
+switch (foo) {
+  case -1:
+    console.log('1 negativo');
+    break;
+  case 0: // foo è 0 quindi il criterio è verificato; questo blocco verrà eseguito
+    console.log(0);
+    // NOTA: il break dimenticato sarebbe dovuto essere qui
+  case 1: // manca il comando break in 'case 0:' quindi anche questo blocco sarà eseguito
+    console.log(1);
+    break; // incontra questo break così con proseguirà in 'case 2:'
+  case 2:
+    console.log(2);
+    break;
+  default:
+    console.log('default');
+}
+ +

Posso mettere un default in mezzo?

+ +

Certo che puoi! JavaScript passerà al default se non troverà nessun criterio corrispondente:

+ +
var foo = 5;
+switch (foo) {
+  case 2:
+    console.log(2);
+    break; // incontra un break, quindi non procederà automaticamente su "default:"
+  default:
+    console.log('default')
+    // non c'è un break, quindi verrà eseguito anche il contenuto di "case 1:"!
+  case 1:
+    console.log('1');
+}
+ +

Funziona anche se metti default prima di ogni altra clausola.

+ +

Riscrivere molteplici istruzioni If con Switch

+ +

Di seguito viene fornito un esempio:

+ +
var a = 100;
+var b = NaN;
+switch (true) {
+  case isNaN(a) || isNaN(b):
+    console.log('NaNNaN');
+    break;
+  case a === b:
+    console.log(0);
+    break;
+  case a < b:
+    console.log(-1);
+    break;
+  default:
+    console.log(1);
+}
+ + + +

Metodi per i case con più criteri

+ +

I sorgenti per questa tecnica possono essere scaricati qui:

+ +

Switch statement multiple cases in JavaScript (Stack Overflow)

+ +

Multi-case - operazione singola

+ +

Questo metodo si avvale del fatto che se non c'è un break break prima di un comando di case continuerà eseguento il successivo comando di case ingnorando se verifica il criterio di esecuzione. Vedi la sezione  "Cosa accade se dimentico un break?"

+ +

Questo è un esempio di un comando di switch a singola operazione sequenziale, dove quattro valori diversi realizzano la stessa cosa.

+ +
var Animale = 'Giraffa';
+switch (Animale) {
+  case 'Mucca':
+  case 'Giraffa':
+  case 'Cane':
+  case 'Maiale':
+    console.log('Queso animale anndrà sull'Arca di Noè.');
+    break;
+  case 'Dinosauro':
+  default:
+    console.log('Questo animale non andrà.');
+}
+ +

Multi-case - operazioni concatenate

+ +

Questo è un esempio di un comando di switch ad operazione multipla sequenziale, dove, a seconda del numero intero fornito, si ricevono diversi output. Mostra come sia possibile sfruttare l'ordine in cui sono scritte le clausole, e come non debbano essere numericamente in sequenza. In JavaScript, si possono anche inserire definizioni di stringhe nei comandi case.

+ +
var foo = 1;
+var output = 'Output: ';
+switch (foo) {
+  case 10:
+    output += 'quindi ';
+  case 1:
+    output += 'quale ';
+    output += 'è ';
+  case 2:
+    output += ' il tuo ';
+  case 3:
+    output += 'nome';
+  case 4:
+    output += '?';
+    console.log(output);
+    break;
+  case 5:
+    output += '!';
+    console.log(output);
+    break;
+  default:
+    console.log('Per favore prendere un numero da 1 a 5 o 10!');
+}
+ +

Output per questo esempio:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValoreTesto di log
foo è diverso da 1, 2, 3, 4, 5 or 10Per favore prendere un numero da 1 a 5 o 10!
10Output: quindi quale è il tuo nome?
1Output: quale è il tuo nome?
2Output: il tuo nome?
3Output: nome?
4Output: ?
5Output: !
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificheStatusCommento
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale. Relaizzata in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.11', 'switch statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-switch-statement', 'switch statement')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-switch-statement', 'switch statement')}}{{Spec2('ESDraft')}}
+ +

Compatibilità dei browser

+ +

{{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}}
+
+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/statements/throw/index.html b/files/it/web/javascript/reference/statements/throw/index.html new file mode 100644 index 0000000000..1aecd9ca9a --- /dev/null +++ b/files/it/web/javascript/reference/statements/throw/index.html @@ -0,0 +1,195 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Statements/throw +tags: + - JavaScript + - Statement +translation_of: Web/JavaScript/Reference/Statements/throw +--- +
{{jsSidebar("Statements")}}
+ +

L'istruzione throw chiama un'eccezione definita dall'utente. L'esecuzione della funzione corrente si interrompe (ovvero i comandi successivi a throw non verranno eseguiti), e il controllo verrà passato al primo blocco catch nella pila delle chiamate. Se non è previsto nessun blocco catch esiste nella funzione chiamante, il programma verrà terminato.

+ +
{{EmbedInteractiveExample("pages/js/statement-throw.html")}}
+ + + +

Sintassi

+ +
throw espressione; 
+ +
+
espressione
+
L'espressione da chiamare.
+
+ +

Descrizione

+ +

Usa l'istruzione throw per chiamare un'eccezione. Quando chiami un'eccezione, l'espressione specifica il valore dell'eccezione. Ognuna delle seguenti righe chiama un'eccezione.

+ +
throw 'Error2'; // genera un'eccezione con una stringa con valore Error2
+throw 42;       // genera un'eccezione con valore 42
+throw true;     // genera un'eccezione con valore true
+ +

Nota bene che l'istruzione throw viene gestita dall'automatic semicolon insertion (ASI) e quindi non puoi andare a capo fra throw e l'espressione.

+ +

Esempi

+ +

Chiama un oggetto

+ +

Puoi specificare un oggetto quando chiami un eccezione. In seguito puoi riportare le proprietà dell'oggetto nel blocco catch. L'esempio seguente crea un oggetto di tipo UserException e poi lo usa nell'istruzione throw.

+ +
function UserException(message) {
+   this.message = message;
+   this.name = 'UserException';
+}
+function getMonthName(mo) {
+   mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
+   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
+      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+   if (months[mo] !== undefined) {
+      return months[mo];
+   } else {
+      throw new UserException('InvalidMonthNo');
+   }
+}
+
+try {
+   // statements to try
+   var myMonth = 15; // 15 is out of bound to raise the exception
+   var monthName = getMonthName(myMonth);
+} catch (e) {
+   monthName = 'unknown';
+   console.log(e.message, e.name); // pass exception object to err handler
+}
+
+ +

Un altro esempio di chiamata ad un oggetto

+ +

L'esempio seguente testa una stringa in input per un codice postale di avviamento postale (CAP) americano. Se il CAP fornito è in un formato non valido, l'istruzione throw chiama un'eccezione creando un oggetto di tipo ZipCodeFormatException.

+ +
/*
+ * Creates a ZipCode object.
+ *
+ * Accepted formats for a zip code are:
+ *    12345
+ *    12345-6789
+ *    123456789
+ *    12345 6789
+ *
+ * If the argument passed to the ZipCode constructor does not
+ * conform to one of these patterns, an exception is thrown.
+ */
+
+function ZipCode(zip) {
+   zip = new String(zip);
+   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
+   if (pattern.test(zip)) {
+      // zip code value will be the first match in the string
+      this.value = zip.match(pattern)[0];
+      this.valueOf = function() {
+         return this.value
+      };
+      this.toString = function() {
+         return String(this.value)
+      };
+   } else {
+      throw new ZipCodeFormatException(zip);
+   }
+}
+
+function ZipCodeFormatException(value) {
+   this.value = value;
+   this.message = 'does not conform to the expected format for a zip code';
+   this.toString = function() {
+      return this.value + this.message;
+   };
+}
+
+/*
+ * This could be in a script that validates address data
+ * for US addresses.
+ */
+
+const ZIPCODE_INVALID = -1;
+const ZIPCODE_UNKNOWN_ERROR = -2;
+
+function verifyZipCode(z) {
+   try {
+      z = new ZipCode(z);
+   } catch (e) {
+      if (e instanceof ZipCodeFormatException) {
+         return ZIPCODE_INVALID;
+      } else {
+         return ZIPCODE_UNKNOWN_ERROR;
+      }
+   }
+   return z;
+}
+
+a = verifyZipCode(95060);         // returns 95060
+b = verifyZipCode(9560);          // returns -1
+c = verifyZipCode('a');           // returns -1
+d = verifyZipCode('95060');       // returns 95060
+e = verifyZipCode('95060 1234');  // returns 95060 1234
+
+ +

Richiamare un'eccezione

+ +

Puoi usare throw per richiamare un'eccezione dopo averla già gestita. L'esempio seguente gestisce un'eccezione con un valore numerico e la richiama se tale valore supera 50. Un'eccezione richiamata si propaga fino alla funzione che la racchiude oppure fino al livello più alto in modo che l'utente la veda.

+ +
try {
+   throw n; // throws an exception with a numeric value
+} catch (e) {
+   if (e <= 50) {
+      // statements to handle exceptions 1-50
+   } else {
+      // cannot handle this exception, so rethrow
+      throw e;
+   }
+}
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Definizione iniziale. Implementata in JavaScript 1.4
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità dei browser

+ + + +

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

+ +

Vedi anche

+ + diff --git a/files/it/web/javascript/reference/statements/var/index.html b/files/it/web/javascript/reference/statements/var/index.html new file mode 100644 index 0000000000..41ee508d3c --- /dev/null +++ b/files/it/web/javascript/reference/statements/var/index.html @@ -0,0 +1,221 @@ +--- +title: var +slug: Web/JavaScript/Reference/Statements/var +tags: + - Dichiarazioni + - Globali + - JavaScript + - Locali + - Valore + - Variabili + - funzione +translation_of: Web/JavaScript/Reference/Statements/var +--- +
{{jsSidebar("Statements")}}
+ +

La dichiarazione variabile  dichiara una variabile, opzionalmente inizializzabile ad un valore.

+ +
{{EmbedInteractiveExample("pages/js/statement-var.html")}}
+ + + +

Sintassi

+ +
var nomevariabile1 [= valore1] [, nomevariabile2 [= valore2] ... [, nomevariabileN [= valoreN]]];
+ +
+
nomevariabileN
+
Il nome della variabile. Può essere qualunque identificatore legale.
+
+ +
+
valoreN
+
Valore iniziale della variabile. Può essere qualunque espressione legale. Il valore di default è undefined (non definito).
+
+ +

 Descrizione

+ +

Le dichiarazioni di variabile, ovunque appaiano, sono processate prima dell'esecuzione di qualsiasi codice. L'ambiente di una variabile dichiarata con var è il suo attuale contesto di esecuzione, che è la funzione di chiusura o, per le variabili dichiarate al di fuori di qualsiasi funzione, globale. Se si dichiara nuovamente una variabile JavaScript, il suo valore non sarà perso.

+ +

Assegnando un valore a una variabile non dichirata la rende implicitamente globale (diventa una proprietà dell'oggetto) quando viene eseguita. Le differenze fra variabili dichiarate e non dichiarate sono:

+ +

1. Le variabili dichiarate sono legate al contesto in cui sono dichiarate. Quelle non dichiarate sono sempre globali.

+ +
function x() {
+  y = 1;   // Genera un ReferenceError in strict mode
+  var z = 2;
+}
+
+x();
+
+console.log(y); // scrive "1" in console
+console.log(z); // Genera un ReferenceError: z non è definita fuori dalla funzione x
+
+ +

2. Variabili dichiarate sono create prima dell'esecuzione del codice. Variabili non dichiarate non esistono finchè il codice assegnato loro non viene eseguito.

+ +
console.log(a);                // Genera un ReferenceError.
+console.log('still going...'); // Non verrà eseguito.
+ +
var a;
+console.log(a);                // scrive in console "undefined" o "" a seconda del browser usato.
+console.log('still going...'); // scrive in console "still going...".
+ +

3. Variabili dichiarate diventano una proprietà non configurabile del loro contesto di esecuzione (funzione o globale). Quelle non dichiarate sono configurabili (per esempio, possono essere cancellate).

+ +
var a = 1;
+b = 2;
+
+delete this.a; // Genera un TypeError in strict mode. Altrimenti fallisce senza generare messaggi.
+delete this.b;
+
+console.log(a, b); // Genera un ReferenceError.
+// La proprietà 'b' è stata cancellata e non esiste più.
+ +

A causa di queste tre differenze, il fallimento della dichiarazione di variabile porta molto probabilmente a risultati inaspettati. Pertanto è raccomandato di dichiarare sempre le variabili, indipendentemente dal loro contesto di appartenenza (funzione o globale). In ECMAScript 5 strict mode, assegnare una variabile non dichiarata genera un errore.

+ +

Hoisting di var

+ +

Poichè le dichiarazioni di variabile (come le dichiarazioni in generale) sono processate prima dell'esecuzione del codice, dichiararne una in qualsiasi punto del codice è equivalente al dichiararle in cima. Questo significa anche che quella variabile può essere usata prima della dichiarazione. Questo comportamento è chiamato "hoisting" (sollevamento, innalzamento), poichè sembra che la dichiarazione di variabile sia portata in cima alla funzione o al codice globale.

+ +
bla = 2;
+var bla;
+// ...
+
+// è implicitamente interpretato come:
+
+var bla;
+bla = 2;
+
+ +

Per questa ragione, è consigliato sempre dichiarare le variabili in cima al loro ambiente (in cima al codice globale o della funzione in cui appaiono) al fine di rendere chiaro quali variabili appartengono alle funzioni (locali) e quali no.

+ +

È importante precisare che l'hoisting è applicato alla dichiarazione della variabile, ma non all'inizializzazione del suo valore. Il valore verrà infatti assegnato al raggiungimento della dichiarazione :

+ +
function fai_qualcosa() {
+  console.log(bar); // non definito
+  var bar = 111;
+  console.log(bar); // 111
+}
+
+// è implicitamente interpretato come:
+function fai_qualcosa() {
+  var bar;
+  console.log(bar); // non definito
+  bar = 111;
+  console.log(bar); // 111
+}
+
+ +

 

+ +

Esempi

+ +

Dichiarare e inizializzare due variabili

+ +
var a = 0, b = 0;
+
+ +

Assegnare un singolo valore stinga a due variabili

+ +
var a = 'A';
+var b = a;
+
+// è come dire:
+
+var a, b = a = 'A';
+
+ +

Prestare attenzione all'ordine:

+ +
var x = y, y = 'A';
+console.log(x + y); // non definito
+
+ +

Qui, x e y sono dichiarate prima dell'esecuzione del codice, gli assegnamenti verranno eseguiti in seguito. Nel momento in cui "x = y" viene valutato, y esiste quindi nessun ReferenceError viene generato e il suo valore risulta essere 'undefined' (non definit). Quindi, x è assegnata ad un valore non definito. Ora, ad y è assegnato il valore 'A'. Di conseguenza, dopo la prima riga, x === undefined && y === 'A'. Da qui il risultato.

+ +

Inizializzazione di più variabili

+ +
var x = 0;
+
+function f() {
+  var x = y = 1; // x è dichiarata localmente. y invece no!
+}
+f();
+
+console.log(x, y); // Genera un ReferenceError in strict mode (y non è definita). 0, 1 altrimenti.
+// In modalità non-strict mode:
+// x è la globale come si ci aspettava
+// però, y è uscita fuori dalla funzione!
+ +

Globali implicite e ambienti esterni alle funzioni

+ +

Le variabili che sembrano essere globali implicite possono essere riferimenti a variabili nell'ambito di una funzione esterna:

+ +
var x = 0;  // x è dichiarata dentro l'ambiente file, poi le è assegnato valore 0
+
+console.log(typeof z); // undefined, poichè z ancora non esiste
+
+function a() { // quando a è chiamata,
+  var y = 2;   // y è dichiarata dentro l'ambiente della funzione a, e le è assegnato valore 2
+
+  console.log(x, y);   // 0 2
+
+  function b() {       // quando b è chiamata
+    x = 3;  // assegna 3 all'esistente ambiente x, non crea una nuova variabile globale
+    y = 4;  // assegna 4 all'esistente esterna y, non crea una nuova variabile globale
+    z = 5;  // crea una nuova variabile globale z e le assegna valore 5.
+  }         // (Throws a ReferenceError in strict mode.)
+
+  b();     // chiamare b crea z come variabile globale
+  console.log(x, y, z);  // 3 4 5
+}
+
+a();                   // chiamando a si richiama b
+console.log(x, z);     // 3 5
+console.log(typeof y); // non definito, perchè y è locale alla funzione a
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaStatoCommento
{{SpecName('ES1')}}{{Spec2('ES1')}}Definizione iniziale, implementata in JavaScript 1.0
{{SpecName('ES5.1', '#sec-12.2', 'var statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-variable-statement', 'variable statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-variable-statement', 'variable statement')}}{{Spec2('ESDraft')}} 
+ +

Compatibilità Browser

+ + + +

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

+ +

Guarda anche

+ + diff --git a/files/it/web/javascript/reference/template_strings/index.html b/files/it/web/javascript/reference/template_strings/index.html new file mode 100644 index 0000000000..5bb4890ad8 --- /dev/null +++ b/files/it/web/javascript/reference/template_strings/index.html @@ -0,0 +1,210 @@ +--- +title: Stringhe template +slug: Web/JavaScript/Reference/template_strings +translation_of: Web/JavaScript/Reference/Template_literals +--- +
{{JsSidebar("More")}}
+ +

Le stringhe template sono stringhe letterali che consentono espressioni incorporate. Puoi usare stringhe multi-linea e caratteristiche di interpolazione stringa con esse.

+ +

Sintassi

+ +
`stringa testo`
+
+`stringa testo linea 1
+ stringa testo linea 2`
+
+`stringa testo ${espressione} stringa testo`
+
+tag `stringa testo ${espressione} stringa testo`
+
+ +

Descrizione

+ +

Le stringhe template sono racchiuse dal carattere backtick (` `) (accento grave) invece delle singole o doppie virgolette. Le stringhe template possono contenere segnaposti. Questi sono indicati dal segno del Dollaro e parentesi graffe (${espressione}). Le espressioni nei segnaposti e nel testo compreso vengono passati ad una funzione. La funzione predefinita semplicemente concatena le parti in una stringa. Se c'è un'espressione che precede (tag qui), la stringa template è chiamata "stringa template taggata". In questo caso, l'espressione tag (di solito una funzione) viene chiamata con la stringa template processata, con cui puoi in seguito manipolare prima dell'output.

+ +

Stringhe multilinea

+ +

Ogni carattere di nuova linea inseriti nel sorgente sono parte della stringa template. Usando stringhe normali, potresti usare la seguente sintassi per ottenere stringhe multilinea:

+ +
console.log("stringa testo linea 1\n"+
+"stringa testo linea 2");
+// "stringa testo linea 1
+// stringa testo linea 2"
+ +

Per avere lo stesso effetto con le stringhe multilinea, puoi adesso scrivere:

+ +
console.log(`stringa testo linea 1
+stringa testo linea 2`);
+// "stringa testo linea 1
+// stringa testo linea 2"
+ +

Interpolazione di espressioni

+ +

Per incorporare espressioni dentro normale stringhe, potresti fare uso della seguente sintassi:

+ +
var a = 5;
+var b = 10;
+console.log("Quindici è " + (a + b) + " e\nnon " + (2 * a + b) + ".");
+// "Quindici è 15 e
+// non 20."
+ +

Adesso, con le stringhe template, puoi fare uso della sintassi ridotta facendo sostituzioni come questa più leggibile:

+ +
var a = 5;
+var b = 10;
+console.log(`Quindici è ${a + b} e\nnon ${2 * a + b}.`);
+// "Quindici è 15 e
+// non 20."
+ +

Stringhe template taggate

+ +

Una forma più avanzata di stringhe template sono le stringhe template taggate. Con esse puoi modificare l'output delle stringhe template usando una funzione. Il primo argomento contiene un array di stringhe letterali ("Ciao" e " mondo" in questo esempio). Il secondo, ed ogni argomento dopo il primo, sono i valori delle espressioni di sostituzione ("15" e "50" qui) processate (o a volte detto lavorate). Alla fine, la tua funzione ritorna la stringa manipolata. Non c'è nulla di speciale sul nome tag nel seguente esempio. Il nome della funzione può essere qualsiasi cosa tu voglia.

+ +
var a = 5;
+var b = 10;
+
+function tag(strings, ...values) {
+  console.log(strings[0]); // "Ciao "
+  console.log(strings[1]); // " mondo "
+  console.log(values[0]);  // 15
+  console.log(values[1]);  // 50
+
+  return "Bazinga!";
+}
+
+tag`Ciao ${ a + b } mondo ${ a * b }`;
+// "Bazinga!"
+
+ +

Le funzioni Tag non devono per forza ritornare una stringa, come mostrato nel seguente esempio.

+ +
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('');
+  });
+}
+
+template`${0}${1}${0}!`('Y', 'A');  // "YAY!"
+template`${0} ${'foo'}!`('Ciao', {foo: 'Mondo'});  // "Ciao Mondo!"
+
+ +

Stringhe grezze

+ +

La proprietà speciale raw, disponibile sull'argomento della prima funzione delle stringhe template taggate, ti consente di accedere alle stringhe grezze per come sono state inserite.

+ +
function tag(strings, ...values) {
+  console.log(strings.raw[0]);
+  // "stringa testo linea 1 \\n stringa testo linea 2"
+}
+
+tag`stringa testo linea 1 \n stringa testo linea 2`;
+
+ +

In aggiunta, il metodo {{jsxref("String.raw()")}} esiste per creare stringhe grezze proprio come la funzione template predefinita e contatenazione di stringhe potrebbero creare.

+ +
String.raw`Salve\n${2+3}!`;
+// "Salve\n5!"
+ +

Sicurezza

+ +

Le stringhe template NON DEVONO essere costruite da utenti non fidati, poichè hanno accesso a variabili e funzioni.

+ +
`${console.warn("this is",this)}`; // "this is" Window
+
+let a = 10;
+console.warn(`${a+=20}`); // "30"
+console.warn(a); // 30
+
+ +

Specifiche

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-template-literals', 'Template Literals')}}{{Spec2('ES6')}}Definizione iniziale. Definita in molte sezioni della specifica: Template Literals, Tagged Templates
{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}{{Spec2('ESDraft')}}Definita in molte sezioni della specifica: Template Literals, Tagged Templates
+ +

Compatibilità browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaratteristicaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Supporto base{{CompatChrome(41)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("34")}}{{CompatNo}}{{CompatOpera(28)}}{{CompatSafari(9)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaratteristicaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supporto base{{CompatNo}}{{CompatChrome(41)}}{{CompatGeckoMobile("34")}}{{CompatNo}}{{CompatOpera(28)}}{{CompatSafari(9)}}
+
+ +

Vedi anche

+ + -- cgit v1.2.3-54-g00ecf