IT

연관 배열 객체의 Javascript foreach 루프

lottoking 2020. 5. 31. 10:33
반응형

연관 배열 객체의 Javascript foreach 루프


for-each 루프가 JavaScript 연관 배열 객체를 반복하지 않는 이유는 무엇입니까?

// defining an array
var array = [];

// assigning values to corresponding keys
array["Main"] = "Main page";
array["Guide"] = "Guide page";
array["Articles"] = "Articles page";
array["Forum"] = "Forum board";

// expected: loop over every item,
// yet it logs only "last" assigned value - "Forum"
for (var i = 0; i < array.length; i++) {
    console.log(array[i]);
}

편집 : jQuery each()가 도움이 될 수 있습니다 : https://api.jquery.com/jQuery.each/


.length속성은 숫자 인덱스 (키)가 있는 속성 만 추적합니다. 키에 문자열을 사용하고 있습니다.

당신은 이것을 할 수 있습니다 :

var arr_jq_TabContents = {}; // no need for an array

arr_jq_TabContents["Main"] = jq_TabContents_Main;
arr_jq_TabContents["Guide"] = jq_TabContents_Guide;
arr_jq_TabContents["Articles"] = jq_TabContents_Articles;
arr_jq_TabContents["Forum"] = jq_TabContents_Forum;

for (var key in arr_jq_TabContents) {
    console.log(arr_jq_TabContents[key]);
}

안전을 위해 예기치 않은 상속 결과가없는 속성이 없는지 확인하는 것이 좋습니다.

for (var key in arr_jq_TabContents) {
  if (arr_jq_TabContents.hasOwnProperty(key))
    console.log(arr_jq_TabContents[key]);
}

편집 - Object.keys()현대 브라우저와 노드 등에서이 기능을 사용할 수 있습니다.이 기능은 객체의 "자체"키를 배열로 반환합니다.

Object.keys(arr_jq_TabContents).forEach(function(key, index) {
  console.log(this[key]);
}, arr_jq_TabContents);

에 전달 된 콜백 함수는에서 .forEach()반환 된 배열의 각 키와 키 색인으로 호출됩니다 Object.keys(). 또한 함수가 반복되는 배열을 전달했지만 해당 배열은 실제로 우리에게 유용하지 않습니다. 우리는 원래 객체 가 필요 합니다 . 이름으로 직접 액세스 할 수는 있지만 명시 적으로 전달하는 것이 조금 더 좋습니다. 두 번째 인수 ( .forEach()원래 객체)를 this콜백 내부에 바인딩 하여 전달합니다 . (이것이 아래 주석에서 언급 된 것을 보았습니다.)


이것은 매우 간단한 접근법입니다. 장점은 키도 얻을 수 있다는 것입니다.

for (var key in array) {
    var value = array[key];
    console.log(key, value);
}

ES6의 경우 :

array.forEach(value => {
  console.log(value)
})  

ES6의 경우 : (값, 색인 및 배열 자체를 원하는 경우)

array.forEach((value, index, self) => {
  console.log(value, index, self)
})  

arr_jq_TabContents[key] 배열을 0 인덱스 형식으로 본다.


There are some straightforward examples already, but I notice from how you've worded your question that you probably come from a PHP background, and you're expecting JavaScript to work the same way -- it does not. A PHP array is very different from a JavaScript Array.

In PHP, an associative array can do most of what a numerically-indexed array can (the array_* functions work, you can count() it, etc.) You simply create an array and start assigning to string-indexes instead of numeric.

In JavaScript, everything is an object (except for primitives: string, numeric, boolean), and arrays are a certain implementation that lets you have numeric indexes. Anything pushed to an array will effect its length, and can be iterated over using Array methods (map, forEach, reduce, filter, find, etc.) However, because everything is an object, you're always free to simply assign properties, because that's something you do to any object. Square-bracket notation is simply another way to access a property, so in your case:

array['Main'] = 'Main Page';

is actually equivalent to:

array.Main = 'Main Page';

From your description, my guess is that you want an 'associative array', but for JavaScript, this is a simple case of using an object as a hashmap. Also, I know it's an example, but avoid non-meaningful names that only describe the variable type (e.g. array), and name based on what it should contain (e.g. pages). Simple objects don't have many good direct ways to iterate, so often we'll turn then into arrays first using Object methods (Object.keys in this case -- there's also entries and values being added to some browsers right now) which we can loop.

// assigning values to corresponding keys
const pages = {
  Main: 'Main page',
  Guide: 'Guide page',
  Articles: 'Articles page',
  Forum: 'Forum board',
};

Object.keys(pages).forEach((page) => console.log(page));

Here is a simple way to use an associative array as a generic Object type:

Object.prototype.forEach = function(cb){
   if(this instanceof Array) return this.forEach(cb);
   let self = this;
   Object.getOwnPropertyNames(this).forEach(
      (k)=>{ cb.call(self, self[k], k); }
   );
};

Object({a:1,b:2,c:3}).forEach((value, key)=>{ 
    console.log(`key/value pair: ${key}/${value}`);
});


If the node.js or browser supported Object.entries(), it can be used as an alternative to using Object.keys() (https://stackoverflow.com/a/18804596/225291).

const h = {
  a: 1,
  b: 2
};

Object.entries(h).forEach(([key, value]) => console.log(value));
// logs 1, 2

in this example, forEach uses Destructuring assignment of an array.


var obj = {
  no: ["no", 32],
  nt: ["no", 32],
  nf: ["no", 32, 90]
};

count = -1; // which must be static value
for (i in obj) {
  count++;
  if (obj.hasOwnProperty(i)) {
    console.log(obj[i][count])
  };
};

in this code i used brackets method for call values in array because it contained array , however briefly the idea which a variable i has a key of property and with a loop called both values of associate array

perfect Method , if you interested, press like


This is (essentially) incorrect in most cases:

var array = [];
array["Main"] = "Main page";

That creates a non-element property on the array with the name Main. Although arrays are objects, normally you don't want to create non-element properties on them.

If you want to index into array by those names, typically you'd use a Map or a plain object, not an array.

With a Map (ES2015+), which I'll call map because I'm creative:

let map = new Map();
map.set("Main", "Main page");

you then iterate it using the iterators from its values, keys, or entries methods, for instance:

for (const value of map.values()) {
    // Here, `value` will be `"Main page"`, etc.
}

Using a plain object, which I'll creatively call obj:

let obj = Object.create(null); // Creates an object with no prototype
obj.Main = "Main page"; // Or: `obj["Main"] = "Main page";`

you'd then iterate its contents using Object.keys, Object.values, or Object.entries, for instance:

for (const value of Object.values(proches_X)) {
    // Here, `value` will be `"Main page"`, etc.
}

Use numeric keys. length on an Array only tracks numeric keys. Use Objects or Maps for key-value pairs.

var array = [];

// assigning values to corresponding keys
array[0] = "Main page";
array[1] = "Guide page";
array[2] = "Articles page";
array[3] = "Forum board";

for (var i = 0; i < array.length; i++) {
    console.log(i); //0 1 2 3
    //OR:
    console.log(array[i]);
}

참고URL : https://stackoverflow.com/questions/18804592/javascript-foreach-loop-on-associative-array-object

반응형