JavaScript的 - 从.split产生的谷歌浏览器塞满阵列() [英] javascript - Google Chrome cluttering Array generated from .split()

查看:101
本文介绍了JavaScript的 - 从.split产生的谷歌浏览器塞满阵列()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下字符串:

var str = "one,two,three";

如果我分裂的逗号字符串,我通常会得到一个数组,符合市场预期:

If I split the string on the commas, I normally get an array, as expected:

var arr = str.split(/\s*,\s*/);

麻烦的是,谷歌浏览器(适用于Mac),追加额外的属性到数组中。

Trouble is that in Google Chrome (for Mac), it appends extra properties to the array.

从Chrome的调试器输出:

Output from Chrome's debugger:

arr: Array
    0: one
    1: two
    2: three
    constructor: function Array()
    index: undefined
    input: undefined
    length: 3

所以,如果我重复了的/在循环阵列上,它遍历新的属性。特别是输入首页属性。使用的hasOwnProperty 似乎并没有帮助。

So if I iterate over the array with a for/in loop, it iterates over the new properties. Specifically the input and index properties. Using hasOwnProperty doesn't seem to help.

一个解决将是做基于数组的长度循环。不过我想知道如果任何人有了解为什么Chrome的行为这种方式。 Firefox和Safari浏览器没有这个问题。

A fix would be to do a for loop based on the length of the Array. Still I'm wondering if anyone has insight into why Chrome behaves this way. Firefox and Safari don't have this issue.

推荐答案

使用不遍历数组为中... 循环!这是使用Javascript的许多缺陷之一(<一个href=\"http://stackoverflow.com/questions/2749952/what-are-the-top-javascript-pitfalls/2901139#2901139\">plug) - 为中... 循环是循环遍历对象的属性只

Don't iterate over arrays using for...in loops!! This is one of the many pitfalls of Javascript (plug) - for...in loops are for iterating over object properties only.

使用正常的循环吧。

for (var i=0, max = arr.length; i < max; i++) { ... } 



Firefox和Safari浏览器的的ECMAScript / JavaScript引擎让这些特殊属性不可枚举( {DontEnum特性} 属性),所以他们不会在进行迭代的...在循环。尽管如此,为中... 循环并非要遍历数组索引。


Firefox and Safari's ECMAScript/Javascript engines make those particular properties non-enumerable ({DontEnum} attribute), so they would not be iterated over in a for...in loop. Still, for...in loops were not intended to iterate over array indexes.

这篇关于JavaScript的 - 从.split产生的谷歌浏览器塞满阵列()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆