How well is the `for of` JavaScript statement supported? [closed]

霸气de小男生 提交于 2019-11-27 17:33:13

问题


var nameArray = [

{ name: 'john', surname: 'smith'  },
{ name: 'paul', surname: 'jones' },
{ name: 'timi', surname: 'abel' },

];  

for (str of nameArray) {    
   console.log( str.name );

}

I want to know, how supported is for( item of array ) in terms of browser support, mobile JavaScript support - I realize you cannot do greater than > and this is pure iteration?

I have just discovered this, is this as good as I hope it is?


回答1:


The classic way of doing this is as follows:

  for(var i = 0; i < nameArray.length; i++){
    var str = nameArray[i];
  }

This will give you the exact functionality of a "foreach" loop, which I suspect is what you're really after here. This also gives you the added benefit of working in Internet Explorer.

There is also extensive knowledge of the exact loop described in the MDN. At this time Android web and it seems not everything supports your method so check the compatibility list on that page; seems to be a future release of the new JavaScript that will probably have OOP inside it.




回答2:


MDN:

While for...in iterates over property names, for...of iterates over property values.

The above is what for...of loop does. The below is its current status.

This is an experimental technology, part of the Harmony (ECMAScript 6) proposal. Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.




回答3:


This is the ES6 for..of loop. According to the MDN article i just linked, it's supported by several browsers (see there for exact versions), but not IE. Currently, several mobile browsers also support it.




回答4:


In the meantime, you could use something like this:

for(element_idx in elements) {
    element = elements[element_idx];
    ...
}

for...in has been standard since ECMAScript 1st Edition.




回答5:


It's not.

Even if it were, it would be inappropriate to use it on an array.

For arrays, you should always use a traditional for loop.

You can, however, spice it up a bit:

for( var i=0, l=nameArray.length, str=nameArray[0];
     i<l;
     i++,str=nameArray[i]) {
  console.log(str.name);
}


来源:https://stackoverflow.com/questions/27384494/how-well-is-the-for-of-javascript-statement-supported

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!