【问题标题】:Iterating and enumerating an array, not getting same results迭代和枚举数组,没有得到相同的结果
【发布时间】:2018-08-29 20:29:08
【问题描述】:

我必须通过这行代码的测试,并且在阅读了有关确保我正在迭代数组而不是枚举的各种帖子后,我必须尝试避免原型链接等可能出现的并发症(老实说,我没有了解一切,但我正在到达那里)。

我有两段代码似乎在做同样的事情,只有一段在枚举,一段在迭代。但是,让我大吃一惊的部分是,如果我枚举然后我通过了所有测试,但如果我迭代然后我没有,我失败了“应该将属性从源复制到目标”的部分

这里是迭代:

function copy(destination, source){
var index;
for (index = 0; index <= source.length; index++) {
  if (source.propertyIsEnumerable(index) && destination[index] === undefined) {
    destination[index] = source[index];
  }
}
return destination;

我正在将名为“source”的函数中的第二个参数传递给名为“destination”的第一个函数。

现在,当我将枚举代码放入时,我通过了所有测试:

function copy(destination, source){
var index;
for (var index in source) {
  if (source.propertyIsEnumerable(index) && destination[index] === undefined)
    destination[index] = source[index];
}
return destination;
};

现在我相信他们正在做同样的事情,但看起来他们不是?

【问题讨论】:

  • 测试是什么样的?对于两个 sn-ps,destination 是什么样的?
  • 请同时添加变量的内容。
  • 您遗漏了最重要的问题:您正在迭代的实际对象。向我们展示它是如何定义的,并展示在这两种情况下使用迭代的结果。现在我想目的地是一个数组,在这种情况下你不应该首先使用 for in ,因为它枚举了可枚举的属性。如果destination是一个对象,那么你应该使用Object.keys,而不是for in。
  • 迭代版本忽略数组的命名属性,它只复制索引元素。

标签: javascript iteration enumeration


【解决方案1】:

迭代版本在这样的示例中失败。两个版本都复制索引元素,但只有枚举版本复制数组对象的命名属性。

var oldArray = [1, 2, , 4];
oldArray.someProp = "foo";

var newArray1 = copyArrayIter(oldArray);
console.log(newArray1);
console.log(newArray1.someProp);

var newArray2 = copyArrayEnum(oldArray);
console.log(newArray2);
console.log(newArray2.someProp);

function copyArrayIter(source) {
  var index;
  var destination = [];
  for (index = 0; index <= source.length; index++) {
    if (source.propertyIsEnumerable(index) && destination[index] === undefined) {
      destination[index] = source[index];
    }
  }
  return destination;
}

function copyArrayEnum(source) {
  var index;
  var destination = [];
  for (var index in source) {
    if (source.propertyIsEnumerable(index) && destination[index] === undefined)
      destination[index] = source[index];
  }
  return destination;
};

它将复制索引0、1 和3 处的元素,但不会复制someProp 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多