for acquiring key (key) and the value (value) json circulating in the

.For in a cycle

1. Obtain the json key (key) and the value (value):

var Data = {name: 'John Doe', age: '20 years', sex: 'M' }; 
for ( var A in Data) { the console.log (A); / * attribute names * / the console.log ( Data [A]); / * attribute value * / };

 

2. Obtain values ​​in the array

var A = [ 'Apple', 'Banana', 'PEAR' ]; 
for ( var I in A) { the console.log (I); / * position in the array * / the console.log (A [I]) ; / * value * /
}

Use for in the array can be traversed, but there will be the following questions:

1.index string index numbers, geometric operations can not be directly

2. traversal order may not be the actual array according to an internal sequence

3. Use for in will traverse an array of all enumerable properties, including prototypes.

So more suitable for in traversing the object, do not use for in traversing the array.

In addition to using a for loop, how much simpler right through the array up to our expectations of it, ES6 in the for of be a little better.

 

Two, for of methods (for ES6)

var newArray=[1,2,4,5,6,7];
for (var value of newArray) {
  console.log(value);

Note that, for in the index array is traversed (i.e., key name key), it is traversed for of the array element value (i.e., value).

In summary, it is recommended for in cyclic object, for of loop array

Guess you like

Origin www.cnblogs.com/SallyShan/p/11530727.html