2017-12-03 144 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);