2017-12-03 143 views
0

我试图创建一个函数,我将重复使用该函数以通过名称获取对象,将部分对象名称传入函数。如何通过在函数中传递部分变量名称来获取变量名称

我尝试过使用下面的代码片段,它正在输出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>

+0

@fubar感谢,但我会如何使用动态名称指的是变量在其当前的范围,因为我想干什么? –

+1

通过拼接名称部分来使用变量访问的一般想法很糟糕。想象一下,你将使用代码缩小,你所有的var变量将改变名称,逻辑将变得不正确。我会建议使用名称作为某些对象的键。 –

+0

@SerejaNagin好的,我怎样才能通过传递它的全名而不是连接它来引用变量?或者你能否举一个你建议用名称作为对象键的例子?我认为我的问题可能与查找变量的父项有关。 –

回答

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。

0

由于您未定义键:值对,因此目前您的新对象('image','kepler')将很难访问。您可以尝试使用下面的代码,将对象文字分配给对象中的某个方向,以使事情更简单。

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);