javascript - 如何从变量参数值中找到对象的数组位置?
问题描述
我试图创建一个类,其中从给定数组访问的值是类参数的依赖项。
我有一个看起来像这样的数组:
const wstv = [{
"shortName": "DMW",
"toExport": false,
"longName": "Dennis Manuel Walhter",
"date": "15.06.1978",
"value": 3
}, {
"shortName": "RTW",
"toExport": true,
"longName": "Ronald T. Wellov",
"date": "02.11.1966",
"value": 1,
}];
我想创建一个类来查找数组对象的索引,然后将信息输出到文档。
const Bund = class Bund {
//expected input: (arrayName, valueOfArray[index].shortname to display
constructor(vrbnd, krzl) {
this.vrbnd = vrbnd;
this.krzl = krzl;
}
getElement(vrbnd, krzl){
const index = vrbnd.krzl.findIndex(shortName => shortName === this.krzl);
return index
}
//expected output: position of the given value of shortName in the given arrayName i.e. 0
draw() {
return this.toDraw();
}
toDraw() {
return function(){
document.write(vrbnd[getElement].longName + " " + vrbnd[getElement].date)
}
}
//ecpected output: given arrayName[index].longName i.e. "Dennis Manuel Walhter"
}
然后我想创建一个类对象var dmw = new Bund(wstv, dmw);
然后调用dmw.draw();
. 这样做的全部目的是在 div 中显示信息。由于最终数据集由大约 15 个数组组成,总共大约有 250 个对象,我需要能够将这些参数传递给类对象。
理想情况下,我之后能够写出类似的东西:
for(let i = 0; i < givenArray.length; i++){
const givenArray[i].shortname = new Bund(givenArray, givenArray[i].shortName);
givenArray[i].shortname.draw();
}
显示数组的所有元素。
是否可以将参数传递给类以在给定的数组中搜索给定的值?
另外,我很清楚 getElement()“搜索功能”不能像这样工作,但我似乎无法找到一种解决方案来搜索对象内部原型值数组中的对象位置。(我希望这句话有意义......)
编辑:这个问题似乎有些混乱,所以我会尽力澄清。
我有多个数组。我想创建一个可以将以下信息传递给的类: 我要从中访问数据的数组的名称;( [this.arrayName]
) 对象参数之一的值(来自我正在寻找的数组中的对象),以从该对象获取所需的其余信息;([this.valueOfObjectArgument]
这将是来自对象参数的字符串shortName
),
我的班级应该能够从每个班级对象中获取和使用所需的信息。类本身应该获取该信息( [this.arrayName]
& [this.valueOfObjectArgument]
),将其传递给函数(getElement()
),该函数为我提供[this.valueOfObjectArgument]
from的位置[this.arrayName]
(.shortName
因为我知道我在哪里寻找该值)并返回 in 中的位置[this.arrayName]
。然后第二个函数获取getElement()
(一个整数,我在数组中查找的对象的位置)的返回值,然后将该对象的所有信息显示到一个 html 元素。
我希望这有帮助。
解决方案
我认为你的问题是过度工程。使用 afor loop
可以帮助您轻松获取索引。然后你只需比较键/值并返回你需要的。告诉我这是否有帮助
function searchForShortInArray(shortName) {
for (let i = 0; i < wstv.length; i++) {
if (wstv[i].shortName == shortName) {
return {index: i, entry: wstv[i]}
}
}
}
console.log(searchForShortInArray("RTW"));
输出:
{ index: 1,
entry:
{ shortName: 'RTW',
toExport: true,
longName: 'Ronald T. Wellov',
date: '02.11.1966',
value: 1 } }
推荐阅读
- javascript - 显示结果 mongodb nodejs
- vue.js - Vuelidate 两个表单在一个组件中
- vue.js - 如何在 Vue-Application 中全局使用导入?
- android - 世博会:我的应用因位置政策而被 Google Play 拒绝
- android - 用于连续存储数据的 Android 共享首选项
- go - Cloud Firestore SDK(Golang)中的调试权限被拒绝
- sql - 显示最高价值的交易
- eclipse-hawkbit - 设置hawkbit更新服务器时出现很多问题
- javascript - 如何从php中的echo中获取responseText
- powerbi-custom-visuals - 用于比较功率 bi 中的最大值、最小值和平均值的可视化