简体   繁体   English

为什么JavaScript会更改Array.push上的数据类型?

[英]Why does javascript change the data type on Array.push?

I was working on a small javascript coding challenge that was simple enough, but ran into a odd bit of strange behavior that I couldn't find documented anywhere. 我当时正在研究一个小型的javascript编码挑战,这个挑战很简单,但是遇到了奇怪的行为,我在任何地方都找不到它。 Maybe someone could point me to where it states that this is expected behavior? 也许有人可以指出我的预期行为?

myIntegerArray = [1,2,3,4];
b = new Array();

for(var v in a)
{
    b.push(v);
}
console.log(b); // returns ["1","2","3","4"]. Note String result

If I were to use the forEach() however I get an array of Numbers back: 如果我使用forEach()但是我会得到一个Numbers数组:

a.forEach(function(element,index,ay)
    {
        b.push(element)
    });
//a console.log(b) will return [1,2,3,4]

You're pushing the key name, not the value. 您要推送键名,而不是值。 You need to to do this: 您需要这样做:

b.push(a[v]);

This might help you understand: 这可以帮助您了解:

for (var key in obj) {
  var value = obj[key];
  arr.push(value);
}
for(var v in a)

In JavaScript, Arrays are just like Objects. 在JavaScript中,数组就像对象。 for..in loop will get the keys of the Array objects, which are the actual array indices. for..in循环将获取Array对象的键,它们是实际的数组索引。 As we know that, JavaScript Object keys can only be Strings. 众所周知,JavaScript对象键只能是字符串。 So, what you are actually getting is, the Array indices in String format. 因此,您实际上得到的是String格式的Array索引。

And another reason why for..in should not be used, is in MDN docs. MDN文档是不应该使用for..in另一个原因。 Quoting from for..in 引用自..in

for..in should not be used to iterate over an Array where index order is important. for..in不应用于遍历索引顺序很重要的Array。 Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. 数组索引只是具有整数名称的可枚举属性,其他方面与常规Object属性相同。 There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited. 无法保证for ... in将以任何特定顺序返回索引,并且将返回所有可枚举的属性,包括具有非整数名称的属性和被继承的属性。

Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. 因为迭代的顺序取决于实现,所以在数组上进行迭代可能不会以一致的顺序访问元素。 Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop) when iterating over arrays where the order of access is important. 因此,在访问顺序很重要的数组上进行迭代时,最好使用带有数字索引的for循环(或Array.forEach或非标准的for ... of循环)。

So, you either use 因此,您要么使用

for(var index = 0; index < array.length; index += 1) {
    array[index];
}

Or the forEach which you have shown in the question itself. 或者您在问题本身中显示的forEach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM