【问题标题】:For Each loop ---> For loopFor Each 循环 ---> For 循环
【发布时间】:2016-06-23 01:42:19
【问题描述】:

我遇到一个错误,指出 data.forEach 不是函数。代码是:

function getProperGeojsonFormat(data) {
    isoGeojson = {"type": "FeatureCollection", "features": []};

    console.log("After getProperGeojsonFormat function")
    console.log(data)
    console.log("")

    data.forEach(function(element, index) {
        isoGeojson.features[index] = {};
        isoGeojson.features[index].type = 'Feature';
        isoGeojson.features[index].properties = element.properties;
        isoGeojson.features[index].geometry = {};
        isoGeojson.features[index].geometry.coordinates = [];
        isoGeojson.features[index].geometry.type = 'MultiPolygon';

        element.geometry.geometries.forEach(function(el) {
            isoGeojson.features[index].geometry.coordinates.push(el.coordinates);
        });
    });
    $rootScope.$broadcast('isochrones', {isoGeom: isoGeojson});



}

我得到的错误是:

当我控制台日志数据时:

【问题讨论】:

  • 看data是不是数组
  • 他们已经帮你了
  • @SamuelToh 我的回复是 JSON
  • JS 中的 JSON 是一个字符串。 JS 中的字符串没有forEach 方法。

标签: javascript for-loop


【解决方案1】:

data 是一个对象。看起来您想在该对象内循环遍历 features 数组,所以这样做:

data.features.forEach(function(element, index) {
    isoGeojson.features[index] = {
        type: 'Feature',
        properties: element.properties,
        geometry: {
            type: 'MultiPolygon',
            coordinates: element.coordinates.slice()
        }            
    }
});

【讨论】:

  • 感谢您更改 data.features.forEach 的提示。现在我对下一个 forEach 有疑问
  • 道歉,但它在后面
  • 停止将答案放入问题中。我把原来的问题放回去了。
【解决方案2】:

forEach 适用于数组,而不适用于对象。这里似乎data 是一个对象。

改用这个。

Object.keys(data).forEach(function(index) {
    var element = data[index];
    isoGeojson.features[index] = {};
    isoGeojson.features[index].type = 'Feature';
    isoGeojson.features[index].properties = element.properties;
    isoGeojson.features[index].geometry = {};
    isoGeojson.features[index].geometry.coordinates = [];
    isoGeojson.features[index].geometry.type = 'MultiPolygon';

    element.geometry.geometries.forEach(function(el) {
        isoGeojson.features[index].geometry.coordinates.push(el.coordinates);
    });
});

Object.keys 从对象的键创建一个数组。然后,您可以遍历这些键并获取关联的值。 这种方法适用于任何对象。

【讨论】:

    猜你喜欢
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多