简体   繁体   English

如何在Javascript中通过点运算符访问对象的属性

[英]How to access properties of object by dot operator in Javascript

var changeJsonKeyName, newObj, obj;
changeJsonKeyName = function(json, oldName, newName) {
  json[newName] = json[oldName];
  delete json[oldName];
//    json.newName = json.oldName;
//    delete json.oldName;
    // if i use point in this ,i  can not get my result that i want   


  return json;
};
obj = {
  'aaa': '1111',
  'bb': {
    'cc': 333
  }
};
newObj = {};
newObj = changeJsonKeyName(obj, 'aaa', 'nnn');
console.log(newObj);

If I use point here ,I can not get my result that's what I want ,what is the wrong,please help me,thank you very much. 如果我在这里使用point,我无法得到我想要的结果,出了什么问题,请帮助我,非常感谢。

I'm not sure if I understood you correctly, but : 我不确定我是否正确理解您,但是:

json[newName]

access property named with the value of newName variable 以newName变量的值命名的访问属性

json.newName

access a property named 'newName', which does not exist 访问名为“ newName”的属性,该属性不存在

First, as a comment points out, this is a Javascript question, not a JSON question. 首先,正如评论所指出的,这是一个Javascript问题,而不是JSON问题。

But you seem to be asking why this works: 但是您似乎在问为什么这样做:

 json[newName] = json[oldName];
 delete json[oldName];

but this doesn't: 但这不是:

 json.newName. = json.oldName.;
 delete json.oldName;

does not. 才不是。

And the answer is the second form is actually equivalent to 答案是第二种形式实际上等效于

 json["newName"] = json["oldName"];
 delete json["oldName"];

In other words, you are dealing with attributes whose names are the constants "oldName" and "newName" rather than attributes whose names are passed as parameters to that method. 换句话说,您要处理的名称是常量“ oldName”和“ newName”的属性,而不是将名称作为参数传递给该方法的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM