0

从函数返回对象时,我遇到了概念性的 Javascript 问题。有人可以指出我在这里做错了什么吗?

var productsPartsObj = {
  layers: ['toe', 'base', 'shaft'],
  layer: [
    {
      name: 'toe',
      height: 75,
      width: 78,
      coords: {
        x: 20,
        y: 120
      }
    }
  ]
}

var coords = {};
coords = (function() {
  productsPartsObj.layer.forEach(function(layerObj){
    if ( layerObj.name === "toe" ) {
      return layerObj.coords;
    }
  })
})()

console.log(coords); //logs undefined
4

2 回答 2

6

You are returning from the forEach callback, not from the immediately-executed function expression. You could do this instead (assuming you know there will only ever be one element of the layer array with a name matching the value in question:

var coords = (function() {
  return productsPartsObj.layer.filter(function(layerObj){
      return layerObj.name === "toe";
  })[0].coords;
})();

Notice that there are 2 return statements - the first one returns from the IIFE, and the second returns from the filter callback.

Also notice that I've moved the var keyword into this statement. There is no point assigning an empty object to coords and then simply overwriting it.

于 2013-04-17T06:46:14.440 回答
0

您的匿名函数没有返回任何值。

var productsPartsObj = {
    layers : ['toe', 'base', 'shaft'],
    layer : [{
                name : 'toe',
                height : 75,
                width : 78,
                coords : {
                    x : 20,
                    y : 120
                }
            }]
}

var coords = {};
coords = (function() {
    var x;
    productsPartsObj.layer.forEach(function(layerObj) {
                if (layerObj.name === "toe") {
                    x = layerObj.coords;
                }
            })
    return x;
})()

console.log(coords);

否则直接使用设置坐标值

var coords = {};
(function() {
    productsPartsObj.layer.forEach(function(layerObj) {
                if (layerObj.name === "toe") {
                    coords = layerObj.coords;
                }
            })
})()
于 2013-04-17T06:48:04.717 回答