JavaScript 객체의 속성은 어떻게 계산합니까? [복제]
이 질문에는 이미 답변이 있습니다.
JavaScript에 다음과 같은 객체가 있다고 가정합니다.
var object = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
};
객체에 몇 개의 값이 있는지 어떻게 알 수 있습니까?
Object
JavaScript의 모든 객체에서 파생되는 모든 속성에는 자동으로 많은 속성이 포함되며 정확한 속성 세트는 특정 인터프리터 및 코드가 실행되기 전에 실행 한 코드에 따라 달라 지기 때문에 쉬운 대답은 없습니다 . 그래서, 당신은 어떻게 든 당신이 정의한 것을 "무료로"얻은 것과 분리해야합니다.
한 가지 방법이 있습니다.
var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
Object.prototype.foobie = 'bletch'; // add property to foo that won't be counted
var count = 0;
for (var k in foo) {
if (foo.hasOwnProperty(k)) {
++count;
}
}
alert("Found " + count + " properties specific to foo");
두 번째 줄은 다른 코드가 모든 Object
파생물 에 속성을 추가하는 방법을 보여줍니다 . hasOwnProperty()
루프 내 에서 검사 를 제거하면 속성 수가 4 이상으로 증가합니다.이 코드 이외의 다른 JavaScript가있는 페이지에서 다른 코드도 Object
프로토 타입을 수정하면 4보다 클 수 있습니다 .
이 간단한 코드를 사용하여이를 수행 할 수 있습니다.
Object.keys(myObject).length
밑줄 라이브러리를 사용 하면 매우 유용합니다 _.keys(obj).length
..
객체를 반복하여 키 또는 값을 얻을 수 있습니다.
function numKeys(obj)
{
var count = 0;
for(var prop in obj)
{
count++;
}
return count;
}
"맞춤법 오류"처럼 보이지만 예제가 유효하지 않은 구문임을 지적하려고합니다.
var object = {"key1":"value1","key2":"value2","key3":"value3"};
var miobj = [
{"padreid":"0", "sw":"0", "dtip":"UNO", "datos":[]},
{"padreid":"1", "sw":"0", "dtip":"DOS", "datos":[]}
];
alert(miobj.length) //=== 2
그러나
alert(miobj[0].length) //=== undefined
이 기능은 매우 좋습니다
Object.prototype.count = function () {
var count = 0;
for(var prop in this) {
if(this.hasOwnProperty(prop))
count = count + 1;
}
return count;
}
alert(miobj.count()) // === 2
alert(miobj[0].count()) // === 4
이 기능은 __count__
모든 속성을 반복하는 것보다 빠른 속도로 사용 가능한 경우 Mozilla 속성 을 사용 합니다.
function countProperties(obj) {
var count = "__count__",
hasOwnProp = Object.prototype.hasOwnProperty;
if (typeof obj[count] === "number" && !hasOwnProp.call(obj, count)) {
return obj[count];
}
count = 0;
for (var prop in obj) {
if (hasOwnProp.call(obj, prop)) {
count++;
}
}
return count;
};
countProperties({
"1": 2,
"3": 4,
"5": 6
}) === 3;
EDIT: this will case errors with jquery to happen, plus some other inconveniences. YOU SHOULD NOT USE IT: (perhaps if one could add a privaate method instead of a public property function, this would be OK, but don't have the time now). Community wikied
do not use:
Even though javascript's object by default doesn't have the count function, classes are easily extendable, and one can add it oneself:
Object.prototype.count = function () {
var count = 0;
for(var prop in this) {
if(this.hasOwnProperty(prop))
count = count + 1;
}
return count;
}
So that after that one can execute
var object = {'key1': 'val1', 'key2':'val2', 'key3':'val3'};
console.log(object.count()); // 3
As a conclusion, if you want count functionality in objects, you need to copy the code from code block 1, and paste it early in execution time ( before you call the count ).
Let me know if that works for you!
Regards, Pedro
For those which will read this question/answers, here is a JavaScript implementation of Dictionary collection very similar as functionality as .NET one: JavaScript Dictionary
Although it wouldn't be a "true object", you could always do something like this:
var foo = [
{Key1: "key1"},
{Key2: "key2"},
{Key3: "key3"}
];
alert(foo.length); // === 3
참고URL : https://stackoverflow.com/questions/1345939/how-do-i-count-a-javascript-objects-attributes
'Programming' 카테고리의 다른 글
MySQL에서 날짜 시간이 오늘보다 크거나 같음 (0) | 2020.06.04 |
---|---|
데이터베이스의 기본 데이터 정렬을 변경하는 방법은 무엇입니까? (0) | 2020.06.04 |
UITableViewStylePlain을 사용하여 UITableView에서 부동 헤더를 비활성화 할 수 있습니까? (0) | 2020.06.03 |
목록을 변환하는 방법 (0) | 2020.06.03 |
Gradle에서 transitive = true는 정확히 무엇입니까 (wrt crashlytics)? (0) | 2020.06.03 |