如何通过在函数

时间:2017-12-03 00:45:56

标签: javascript jquery string

我正在尝试创建一个函数,我将重复使用它来按名称获取对象,将部分对象名称传递给函数。

我使用以下代码段尝试了此操作,并输出undefined

如何通过将部分名称传递给函数来获取实际变量?

function writeObject(name){
   console.log(placeObjects[name+'Item']);
}

function placeObjects(){
  var availableObjects = new Array();

  availableObjects.push(new Object('image','kepler'));
  availableObjects.push(new Object('image','lightning'));
  availableObjects.push(new Object('image','tomato'));
  availableObjects.push(new Object('image','us'));
  
    var topItem = availableObjects[0];
    var leftItem = availableObjects[1];
    var bottomItem = availableObjects[2];
    var rightItem = availableObjects[3];

    writeObject('top');
    writeObject('left');
}

placeObjects();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

2 个答案:

答案 0 :(得分:2)

var placeObject={};
function writeObject(name){
   console.log(placeObject[name+'Item']);
}

function placeObjects(){
  var availableObjects = new Array();

  availableObjects.push(new Object('image','kepler'));
  availableObjects.push(new Object('image','lightning'));
  availableObjects.push(new Object('image','tomato'));
  availableObjects.push(new Object('image','us'));
  placeObject={topItem:availableObjects[0],leftItem:availableObjects[1],bottomItem:availableObjects[2],rightItem:availableObjects[3]};
   // var topItem = availableObjects[0];
   // var leftItem = availableObjects[1];
   // var bottomItem = availableObjects[2];
   // var rightItem = availableObjects[3];

writeObject('top');
writeObject('left');
}

placeObjects();

这会奏效。请记住,我已经更改了顶部的变量名称。这将在writeObject调用时返回所需的abject。

答案 1 :(得分:0)

目前您的新对象(&#39;图像&#39; kepler&#39;)将难以访问,因为您没有定义键:值对。您可以尝试使用下面的代码,将对象文字分配给对象中的某个方向,以使事情更简单

&#13;
&#13;
function PageObject(top, left, bottom, right) {
    this.top = top;
    this.left = left;
    this.bottom = bottom;
    this.right = right;
    this.writeObject = function(direction) {
      return this[direction];
    };
}

var pageObject = new PageObject({'image':'kepler'}, {'image':'lightning'}, {'image':'tomato'}, {'image':'tomato'});
console.log(pageObject.top);
&#13;
&#13;
&#13;