【问题标题】:not able to dynamically access an object property using a variable无法使用变量动态访问对象属性
【发布时间】:2018-11-15 14:58:09
【问题描述】:

我正在尝试使用变量添加查找对象的属性,但它不起作用。当我写变量的对象名称iso时,它正在工作,虽然变量和对象名称完全相同..

function calCulate(nrs){
const product = {DE2599:{name:"tet", bar:2.5, price: 3.5}};
var nr = document.getElementById(nrs).value;
var sku = ("prod" + nr);
var qty = ("qty" + nr);
var pric = ("price"+nr);
var pal = ("pallet"+nr);
var ctry = document.getElementById('country').value;
var x = document.getElementById(qty).value;
var test = document.getElementById(prod).value;
var tests = test.toString(); // way of getting the result
var testr = tests.indexOf(" "); // way of getting the result
var testt = tests.slice(0,testr); // way of getting the result
var uniqueID = ctry+testt; // this value returns DE2599
var mywindow = window.open('','PRINT','height=800,width=800');
var ter = product.uniqueID; // I use uniqueID because it can vary 
var tar = ter.price;
mywindow.document.write(tar); // this is not showing any result; but if I change the uniqueID with the actualy key, ie DE2599, it is working correctly

【问题讨论】:

    标签: javascript object variables key


    【解决方案1】:

    uniqueId 不是product 的属性,因此您的ter 将存储undefined(并且您应该收到tar 的错误)。

    当需要使用变量的值来访问对象的属性时,需要使用括号表示法。

    const product = {DE2599:{name:"tet", bar:2.5, price: 3.5}};
    let uniqueId = 'DE2599';
    
    console.log('with dot notation');
    console.log(product.uniqueId);
    console.log('with bracket notation');
    console.log(product[uniqueId]);

    【讨论】:

      猜你喜欢
      • 2021-10-25
      相关资源
      最近更新 更多