如何通过在函数中传递部分变量名称来获取变量名称

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

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

回答:

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。

回答:

由于您未定义键:值对,因此目前您的新对象('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);

以上是 如何通过在函数中传递部分变量名称来获取变量名称 的全部内容, 来源链接: utcz.com/qa/259032.html

回到顶部