保持简单:根据输入的值从许多不确定变量中检测数组内的字符串/值



我有以下几行代码:
HTML:*

<ul>
<li id="ukVal"></li>
<li id="hrgVal"></li>
<li id="wrVal"></li>
</ul>
<input type='hidden' class='txtukuran' name='txtukuran' value='M/25'/>
<input type='hidden' class='txtwarna' name='txtwarna' value='Putih'/> 
<div class='hasil'></div>

Javascript,:

//array data
const m25kuning = { ukuran:"M/25", harga:"12000", warna:"Kuning" }; 
const m25putih  = { ukuran:"M/25", harga:"45000", warna:"Putih"  }; 
const m25hijau  = { ukuran:"M/25", harga:"30000", warna:"Hijau"  }; 
const m25biru   = { ukuran:"M/25", harga:"77000", warna:"Biru"   }; 
//get dan place data of m25kuning array into HTML above
document.getElementById("ukVal").innerHTML  = m25kuning.ukuran;
document.getElementById("hrgVal").innerHTML = m25kuning.harga;
document.getElementById("wrVal").innerHTML  = m25kuning.warna;
//I don't know how to continue the codes based on my question :)
//store innerHTML variable
var ukVal_set  = document.getElementById("ukVal").innerHTML;
var hrgVal_set = document.getElementById("hrgVal").innerHTML;
var wrVal_set  = document.getElementById("wrVal").innerHTML;
const varToString = varObj => Object.keys(varObj)[0];
const strNilai = varToString({m25kuning});
const strUpper = strNilai.toUpperCase();
var valPisahin = strUpper.substr(0,1) + "/" + strUpper.substr(1);
var ukValue    = valPisahin.substr(0,4);  // ukuran
var wrValue    = valPisahin.substr(4,10); // warna

if (ukValue=ukVal_set) {
if (wrValue=hrgVal_set) {
document.querySelector(".hasil").innerHTML = m25kuning.harga;
}
}

从上面的代码,我有m25kuning,m25putih等(实际上我有超过10行数组数据存储在变量中)。
之后,我将获得数组的每个成员并将其放置到HTML中的innerHTML中。上面的代码。

:
我如何检测变量的名称(如果是m25kuningm25putihm25hijaum25biru),其中包含值txtukurantxtwarna输入。

一个选择是将数据存储在单个对象中,而不是4个不同的变量中:

//array data
const data = {
"m25kuning": {ukuran:"M/25", harga:"12000", warna:"Kuning"},
"m25putih": {ukuran:"M/25", harga:"45000", warna:"Putih"},
"m25hijau": {ukuran:"M/25", harga:"30000", warna:"Hijau"},
"m25biru": {ukuran:"M/25", harga:"77000", warna:"Biru"},
};

您可以通过名称引用单个数据项:

const m25kuning = data["m25kuning"];
//get dan place data of m25kuning array into HTML above
document.getElementById("ukVal").innerHTML = m25kuning.ukuran;
document.getElementById("hrgVal").innerHTML = m25kuning.harga;
document.getElementById("wrVal").innerHTML = m25kuning.warna;

然后可以遍历"变量"。(数据对象中的属性)来搜索所需的内容。下面是一种方法:

const findData = (ukuran, warna) =>
Object.values(data).find(
value =>
value.ukuran === ukuran &&
value.warna === warna
);
findData("M/25", "Kuning"); // returns {ukuran:"M/25", harga:"12000", warna:"Kuning"}

所以,把它放在一起(尽我所能理解):

var ukVal_set  = document.getElementById("ukVal").innerHTML;
var hrgVal_set = document.getElementById("hrgVal").innerHTML;
var wrVal_set  = document.getElementById("wrVal").innerHTML;
const matchingData = findData(ukVal_set, wrVal_set);
document.querySelector(".hasil").innerHTML = matchingData.harga;

相关内容

  • 没有找到相关文章

最新更新