JavaScript 배열을 선언 할 때“Array ()”와“[]”의 차이점은 무엇입니까?
다음과 같은 배열 선언의 실제 차이점은 무엇입니까?
var myArray = new Array();
과
var myArray = [];
차이가 있지만 그 예에는 차이가 없습니다.
보다 자세한 방법을 사용하면 new Array()매개 변수에 추가 옵션이 하나 있습니다. 생성자에 숫자를 전달하면 해당 길이의 배열을 얻게됩니다.
x = new Array(5);
alert(x.length); // 5
배열을 만드는 다양한 방법을 설명하려면 :
var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings
// these are different:
e = [3] // e.length == 1, e[0] == 3
f = new Array(3), // f.length == 3, f[0] == undefined
;
또 다른 차이점은 사용할 때 new Array()스택 크기에 영향을 미치는 배열의 크기를 설정할 수 있다는 것입니다. 이는 스택 오버플로 ( Array.push 대 Array.unshift의 성능) 가 발생하는 경우 유용 할 수 있습니다. 이는 어레이의 크기가 스택의 크기를 초과 할 때 발생하며 다시 만들어야합니다. 따라서 실제로 사용 사례에 따라 new Array()오버플로 발생을 방지 할 수 있으므로 사용시 성능이 향상 될 수 있습니다.
에서 지적 이 답변 , new Array(5)실제로 다섯 개 추가하지 않습니다 undefined배열에 항목을. 단순히 5 개의 항목을위한 공간을 추가합니다. Array이 방법 을 사용 하면 array.length계산 에 의존하기가 어렵습니다 .
암시 적 배열을 사용하여 배열을 만드는 것과 배열 생성자의 차이는 미묘하지만 중요합니다.
다음을 사용하여 배열을 만들 때
var a = [];
인터프리터에게 새 런타임 배열을 만들도록 지시하고 있습니다. 추가 처리가 전혀 필요하지 않습니다. 끝난.
사용하는 경우 :
var a = new Array();
여러분은 인터프리터에게 " Array" 생성자를 호출하고 객체를 생성하고 싶습니다 . 그런 다음 실행 컨텍스트를 조회하여 호출 할 생성자를 찾고 호출하여 배열을 만듭니다.
"글쎄, 이건 전혀 중요하지 않아. 그들은 똑같아!"라고 생각할 수도 있습니다. 불행히도 당신은 그것을 보장 할 수 없습니다.
다음 예를 살펴보십시오.
function Array() {
this.is = 'SPARTA';
}
var a = new Array();
var b = [];
alert(a.is); // => 'SPARTA'
alert(b.is); // => undefined
a.push('Woa'); // => TypeError: a.push is not a function
b.push('Woa'); // => 1 (OK)
위의 예에서 첫 번째 호출은 예상대로 'SPARTA'를 경고합니다. 두 번째는 그렇지 않습니다. 정의되지 않은 것을 보게 될 것입니다. 또한 b에는와 같은 기본 Array 객체 함수가 모두 포함되어 push있지만 다른 함수에는 포함 되지 않습니다.
이 일 것으로 예상 할 수 있지만, 그것은 단지 사실 설명 []과 동일하지입니다 new Array().
[]배열을 원하는 경우 에만 사용 하는 것이 가장 좋습니다 . 나는 또한 돌아 다니며 배열을 재정의하는 것을 제안하지 않습니다.
아무도 언급하지 않은 큰 차이가 있습니다.
이전 new Array(2)과 동일 하다고 생각할 수 있습니다.[undefined, undefined]
new Array(2).length // 2
new Array(2)[0] === undefined // true
new Array(2)[1] === undefined // true
하지만 그렇지 않습니다!
시도 해보자 map():
[undefined, undefined].map(e => 1) // [1, 1]
new Array(2).map(e => 1) // "(2) [undefined × 2]" in Chrome
보다? 그것은 다르다! 하지만 그 이유는 무엇입니까?
ES6 Spec 22.1.1.2에 따르면로 설정된 Array(len)새 어레이 만 생성합니다 . 따라서 새 배열 내부에는 실제 요소가 없습니다.lengthlen
function map(), spec 22.1.3.15에 따르면 먼저 HasProperty콜백을 확인한 다음 호출하지만 다음과 같이 밝혀졌습니다.
new Array(2).hasOwnProperty(0) // false
[undefined, undefined].hasOwnProperty(0) // true
그렇기 때문에 반복 함수가 .NET에서 생성 된 배열에 평소와 같이 작동 할 것으로 기대할 수 없습니다new Array(len) .
BTW, Safari 및 Firefox는 이에 대해 훨씬 더 나은 표현을 제공합니다.
// Safari
new Array(2) // [](2)
new Array(2).map(e => 1) // [](2)
[undefined, undefined] // [undefined, undefined] (2)
// Firefox
new Array(2) // Array [ <2 empty slots> ]
new Array(2).map(e => 1) // Array [ <2 empty slots> ]
[undefined, undefined] // Array [ undefined, undefined ]
이 혼란스러운 로그를 수정하도록 Chrome에 이미 문제를 제출했습니다. https://bugs.chromium.org/p/chromium/issues/detail?id=732021
업데이트 : 이미 수정되었습니다. 이제 Chrome에서 다음으로 로그인
new Array(2) // (2) [empty × 2]
이상하게도 Chrome new Array(size)보다 거의 2 배 빠르며 []FF와 IE에서 거의 동일합니다 (배열을 만들고 채우는 것으로 측정 됨). 배열의 대략적인 크기를 알고있는 경우에만 중요합니다. 지정한 길이보다 더 많은 항목을 추가하면 성능 향상이 손실됩니다.
보다 정확하게 : Array(메모리를 할당하지 않는 빠른 상수 시간 작업이고, []유형과 값을 설정하는 선형 시간 작업입니다.
자세한 내용 은 다음 페이지 에서 사용할 필요가없는 이유를 설명합니다.new Array()
You never need to use
new Object()in JavaScript. Use the object literal{}instead. Similarly, don’t usenew Array(), use the array literal[]instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.Do not use
new Number,new String, ornew Boolean. These forms produce unnecessary object wrappers. Just use simple literals instead.
Also check out the comments - the new Array(length) form does not serve any useful purpose (at least in today's implementations of JavaScript).
In order to better understand [] and new Array():
> []
[]
> new Array()
[]
> [] == []
false
> [] === []
false
> new Array() == new Array()
false
> new Array() === new Array()
false
> typeof ([])
"object"
> typeof (new Array())
"object"
> [] === new Array()
false
> [] == new Array()
false
The above result is from Google Chrome console on Windows 7.
The first one is the default object constructor call. You can use it's parameters if you want.
var array = new Array(5); //initialize with default length 5
The second one gives you the ability to create not empty array:
var array = [1, 2, 3]; // this array will contain numbers 1, 2, 3.
I can explain in a more specific way starting with this example that's based on Fredrik's good one.
var test1 = [];
test1.push("value");
test1.push("value2");
var test2 = new Array();
test2.push("value");
test2.push("value2");
alert(test1);
alert(test2);
alert(test1 == test2);
alert(test1.value == test2.value);
I just added another value to the arrays, and made four alerts: The first and second are to give us the value stored in each array, to be sure about the values. They will return the same! Now try the third one, it returns false, that's because
JS treats test1 as a VARIABLE with a data type of array, and it treats test2 as an OBJECT with the functionality of an array, and there are few slight differences here.
The first difference is when we call test1 it calls a variable without thinking, it just returns the values that are stored in this variable disregarding its data type! But, when we call test2 it calls the Array() function and then it stores our "Pushed" values in its "Value" property, and the same happens when we alert test2, it returns the "Value" property of the array object.
So when we check if test1 equals test2 of course they will never return true, one is a function and the other is a variable (with a type of array), even if they have the same value!
To be sure about that, try the 4th alert, with the .value added to it; it will return true. In this case we tell JS "Disregarding the type of the container, whether was it function or variable, please compare the values that are stored in each container and tell us what you've seen!" that's exactly what happens.
I hope I said the idea behind that clearly, and sorry for my bad English.
There is no difference when you initialise array without any length. So var a = [] & var b = new Array() is same.
But if you initialise array with length like var b = new Array(1);, it will set array object's length to 1. So its equivalent to var b = []; b.length=1;.
This will be problematic whenever you do array_object.push, it add item after last element & increase length.
var b = new Array(1);
b.push("hello world");
console.log(b.length); // print 2
vs
var v = [];
a.push("hello world");
console.log(b.length); // print 1
The first one is the default object constructor call.mostly used for dynamic values.
var array = new Array(length); //initialize with default length
the second array is used when creating static values
var array = [red, green, blue, yellow, white]; // this array will contain values.
There is no big difference, they basically do the same thing but doing them in different ways, but read on, look at this statement at W3C:
var cars = ["Saab", "Volvo","BMW"];
and
var cars = new Array("Saab", "Volvo", "BMW");
The two examples above do exactly the same. There is no need to use new Array().
For simplicity, readability and execution speed, use the first one (the array literal method).
But at the same time, creating new array using new Array syntax considered as a bad practice:
Avoid new Array()
There is no need to use the JavaScript's built-in array constructor new Array().
Use [] instead.
These two different statements both create a new empty array named points:
var points = new Array(); // Bad
var points = []; // Good
These two different statements both create a new array containing 6 numbers:
var points = new Array(40, 100, 1, 5, 25, 10); // Bad
var points = [40, 100, 1, 5, 25, 10]; // Good
The new keyword only complicates the code. It can also produce some unexpected results:
var points = new Array(40, 100); // Creates an array with two elements (40 and 100)
What if I remove one of the elements?
var points = new Array(40); // Creates an array with 40 undefined elements !!!!!
So basically not considered as the best practice, also there is one minor difference there, you can pass length to new Array(length) like this, which also not a recommended way.
The difference of using
var arr = new Array(size);
Or
arr = [];
arr.length = size;
As been discussed enough in this question.
I would like to add the speed issue - the current fastest way, on google chrome is the second one.
But pay attention, these things tend to change a lot with updates. Also the run time will differ between different browsers.
For example - the 2nd option that i mentioned, runs at 2 million [ops/second] on chrome, but if you'd try it on mozilla dev. you'd get a surprisingly higher rate of 23 million.
Anyway, I'd suggest you check it out, every once in a while, on different browsers (and machines), using site as such
As I know the diference u can find the slice(or the other funcitons of Array) like code1.and code2 show u Array and his instances:
code1:
[].slice; // find slice here
var arr = new Array();
arr.slice // find slice here
Array.prototype.slice // find slice here
code2:
[].__proto__ == Array.prototype; // true
var arr = new Array();
arr.__proto__ == Array.prototype; // true
conclusion:
as u can see [] and new Array() create a new instance of Array.And they all get the prototype functions from Array.prototype
They are just different instance of Array.so this explain why [] != []
:)
I've incurred in a weird behaviour using [].
We have Model "classes" with fields initialised to some value. E.g.:
require([
"dojo/_base/declare",
"dijit/_WidgetBase",
], function(declare, parser, ready, _WidgetBase){
declare("MyWidget", [_WidgetBase], {
field1: [],
field2: "",
function1: function(),
function2: function()
});
});
I found that when the fields are initialised with [] then it would be shared by all Model objects. Making changes to one affects all others.
This doesn't happen initialising them with new Array(). Same for the initialisation of Objects ({} vs new Object())
TBH I am not sure if its a problem with the framework we were using (Dojo)
I've found one difference between the two constructions that bit me pretty hard.
Let's say I have:
function MyClass(){
this.property1=[];
this.property2=new Array();
};
var MyObject1=new MyClass();
var MyObject2=new MyClass();
In real life, if I do this:
MyObject1.property1.push('a');
MyObject1.property2.push('b');
MyObject2.property1.push('c');
MyObject2.property2.push('d');
What I end up with is this:
MyObject1.property1=['a','c']
MyObject1.property2=['b']
MyObject2.property1=['a','c']
MyObject2.property2=['d']
I don't know what the language specification says is supposed to happen, but if I want my two objects to have unique property arrays in my objects, I have to use new Array().
Using the Array constructor makes a new array of the desired length and populates each of the indices with undefined, the assigned an array to a variable one creates the indices that you give it info for.
'Programing' 카테고리의 다른 글
| 파이썬에서 do-while 루프를 에뮬레이트합니까? (0) | 2020.09.30 |
|---|---|
| Git에서 유효하지 않은 원격 분기 참조를 어떻게 제거합니까? (0) | 2020.09.30 |
| 하나의 클라이언트에서 여러 SSH 개인 키를 사용하는 가장 좋은 방법 (0) | 2020.09.29 |
| Java에서 InputStream을 바이트 배열로 변환 (0) | 2020.09.29 |
| substr과 substring의 차이점은 무엇입니까? (0) | 2020.09.29 |