program story

객체 인 것처럼 명명 된 속성을 배열에 추가 할 수있는 이유는 무엇입니까?

inputbox 2020. 8. 15. 09:10
반응형

객체 인 것처럼 명명 된 속성을 배열에 추가 할 수있는 이유는 무엇입니까?


다음 두 가지 코드 스 니펫은 나에게 동일하게 보입니다.

var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";

var myObject = {'A': 'Athens', 'B':'Berlin'};

둘 다 동일하게 행동하기 때문에 typeof(myArray) == typeof(myObjects)(둘 다 '객체'를 산출합니다).

이 변종들간에 차이점이 있습니까?


자바 스크립트의 거의 모든 것이 객체이므로 임의의 속성을 설정 하여 Array 객체를 "남용"할 수 있습니다 . 그러나 이것은 해로운 것으로 간주되어야합니다 . 배열은 숫자 인덱스 데이터 용입니다. 숫자가 아닌 키의 경우 Object를 사용합니다.

다음은 숫자가 아닌 키가 배열에 맞지 않는보다 구체적인 예입니다.

var myArray = Array();
myArray['A'] = "Athens";
myArray['B'] = "Berlin";

alert(myArray.length);

이것은 '2'를 표시하지 않지만 '0'을 표시합니다. 사실상 배열에 요소가 추가되지 않고 배열 객체에 몇 가지 새로운 속성이 추가됩니다.


JS 배열에서 객체는 약간 수정 된 것입니다 (몇 가지 추가 기능 포함).

다음과 같은 기능 :

concat
every   
filer
forEach
join
indexOf
lastIndexOf
map
pop
push
reverse
shift
slice
some
sort
splice
toSource
toString
unshift
valueOf 

나는 이전 답변에 대해 너무 은유적이고 비밀 스럽습니다. 설명은 다음과 같습니다.

Array, Boolean, Date, Function, Number, RegExp, String의 인스턴스는 Object이지만 각 유형에 특정한 메서드와 속성으로 향상되었습니다. 예를 들어, 배열에는 미리 정의 된 length속성이 있지만 일반 객체에는 없습니다.

javascript:alert([].length+'\n'+{}.length)

디스플레이

0
찾으시는 주소가 없습니다

본질적으로 FF Gecko 인터프리터는 언어 구성을 평가하는 뚜렷한 차이점을 가지고 배열과 일반 객체를 구별합니다.

javascript:
  ra=[  "one",   "two",   "three"]; ra.a=4;
  ob={0:"one", 1:"two", 2:"three"}; ob.a=4;
  alert(
    ra            +"\n\n"+
    ob            +"\n\n"+
    ra.toSource() +"\n\n"+
    ra.a          +"\t .toSource() forgot me! \n\n"+
    ra.length     +"\t and my length! \n\n"+
    ob.toSource());
  ps=""; for(i in ra)ps+=i+" "; alert(ps);  /* NB .length is missing! */
  ps=""; for(i in ob)ps+=i+" "; alert(ps);

표시

하나 둘 셋

[객체 객체]

["하나 둘 셋"]

4 .toSource ()가 나를 잊었습니다! 

3 그리고 내 길이! 

({0 : "one", 1 : "two", 2 : "three", a : 4})

0 1 2 a0 1 2 a.

Regarding the statement that all objects are functions:

It is neither syntactically nor semantically correct to use an arbitrary object instance as a function like 123() or "abc"() or []() or {}() or obj() where obj is any type other than Function, so an arbitrary object INSTANCE is not a Function. However, given an object obj and it's type as Array, Boolean, Date, ..., how did obj come to be as an Array, Boolean, Date, ...? What is an Array, Boolean, Date, ...?

javascript:
    alert([Array, Boolean, Date, Function, 
              Number, Object, RegExp, String] . join('\n\n') );

displays

function Array() {
    [native code]
}

function Boolean() {
    [native code]
}

function Date() {
    [native code]
}

function Function() {
    [native code]
}

function Number() {
    [native code]
}

function Object() {
    [native code]
}

function RegExp() {
    [native code]
}

function String() {
    [native code]
}

In every case, without equivocation, the object type manifests as a function definition, hence the statement that all objects are functions! (The tongue-in-cheek is that I intentionally obscured and blurred the distinction of an object instance with that of it's type! Still, this shows "you can't have one without the other", Object and Function! Capitalization emphasizes type as opposed to instance.)

Both a functional and object paradigm seem to be fundamental to the programming and implementing of the JS interpreter low level built-in primitives, such as Math and JSON and true.

 javascript:alert([Math, JSON, true.toSource()].join("\n\n"));

displays

[object Math]

[object JSON]

(new Boolean(true))

At the time of the development of Javascript, an object-centric programming style (OOP's - Object Oriented Programming style - the "'s" is my own pun!) was in vogue and the interpreter was similarly christened with Java to give it greater credibility. Functional programming techniques were relegated to more abstract and esoteric examinations studying the theories of Automata, Recursive Functions, Formal Languages, etc. and as such not as palatable. However, the strengths of these formal considerations are clearly manifest in Javascript particularly as implemented in FF's Gecko engine (ie. .toSource()).


The Object definition for Function is particularly satisfying for it is defined as a recurrence relation! defined using it's own definition!

function Function() { [native code] }
and since a function is an Object the same sentiment holds for
function Object() { [native code] }.

Most of the other definitions quiesce to a static terminal value. However, eval() is a particularly powerful primitive and so a String can also embed arbitrary functionality.

Note again, the vernacular used above obscures object type and instance distinction.


Everything in JavaScript is an object besides primitive types.

The code

var myArray = Array();

creates an instance of the Array object while

var myObject = {'A': 'Athens', 'B':'Berlin'};

creates an instance of Object object.

Try the following code

alert(myArray.constructor)
alert(myObject.constructor)

So you will see the difference is in the type of object constructor.

The instance of the Array object will contain all the properties and methods of the Array prototype.


One practical difference is when using JSON.stringify on an array all non-numeric indexes are ignored:

var arr = [];
var obj = {};

arr['name'] = 'John';
obj['name'] = 'John';

console.log(arr);    // will output [name: "John"]
console.log(obj);    // will output {name: "John"}

JSON.stringify(arr); // will return []
JSON.stringify(obj); // will return {"name":"John"}

The difference between the arrays and the other objects in JavaScript. While arrays have a magically updating length property, for objects other than the arrays there is no way to implement such a property.

var arrName = [];
arrName[5] = "test";
arrName.length; // <- 6

Array are used to store things with an ordinal index - use it like a traditional array, stack, or queue. An object is a hash - use it for data that has a distinct key.


The {}-notation is just syntactical sugar to make the code nicer ;-)

JavaScript has many similar constructs like the construction of functions, where function() is just a synonym for

var Func = new Function("<params>", "<code>");

참고URL : https://stackoverflow.com/questions/874205/why-can-i-add-named-properties-to-an-array-as-if-it-were-an-object

반응형