【问题标题】:eval() working and assigning differenceeval() 工作和分配差异
【发布时间】:2014-01-31 05:47:46
【问题描述】:

我有一个包装函数,我在其中使用变量 dataObject。我有一个动作可以触发包装函数中的一些外部函数。

function wrapper() {
    var dataObject;
    var jsonPath = "dataObject[0]['Set1'][0]['Attribute1']";
    eval('outsideFunction(dataObject, jsonPath)');
}


function outsideFunction(dataObject, jsonPath) {
    dataObject[0]['Set1'][0]['Attribute1'] = 'asde';  //This sets the value to dataObject in the wapper
    var attrVal = '123';
    eval("jsonPath = attrVal");  //This doesn't set value to dataObject in the wrapper but in the local dataObject
}

为什么直接赋值和使用eval赋值的动作有区别?

【问题讨论】:

  • eval(jsonPath + " = attrVal"); 怎么样?
  • ^^^^ 在您的代码中,您正在评估的是表达式"dataObject[0]['Set1'][0]['Attribute1']" = '123',即您正在将一个字符串值分配给另一个字符串值,这是不可能的。但是,如果将jsonPath 与另一个字符串连接,则结果将是表达式dataObject[0]['Set1'][0]['Attribute1'] = '123'。但是,请注意,这是非常糟糕的代码。看看这个问题吧:stackoverflow.com/q/13719593/218196

标签: javascript eval


【解决方案1】:

根据你data[0]['Set1'][0]['Attribute1']的结构,可以写成data[0].Set1[0].Attribute1,这里是代码,但是我想你不太明白你要多少套。

var wrapper, outsideFunction;

wrapper = function(){

  someOb = {};

  var data = [
    {
      Set1: [
        {
          Attribute1: null, // we will change null to 'asdf' below
        },
      ],
    },
  ];

  outsideFunction(data, someOb);

  console.log( someOb.newProp, someOb.dumb );
  // outputs 'hehehehe', undefined

};

outsideFunction = function(data, blah) {

  data[0].Set1[0].Attribute1 = 'asdf';

  //blah is a reference to someOb
  // we can change a part of blah and it will look at the reference and change someOb
  blah.newProp = 'hehehehe';

  // but if we do `blah =`, then we reference a new object
  // This won't affect  someOb, blah will just be a different object talking about something else
  blah = { dumb: false };

};

所以,就像我说的,您的数据对象是一个编号集(您有 [0]),然后是一个命名集(Set1),然后是一个编号集([0]),我没有认为你是想嵌套这么多。

numberedSet = [
  { 
    name: 'dan',
    likes: [
      'coding', 'girls', 'food',
    ],
  },
  { 
    name: 'Sreekesh',
  },
]

namedSet = {

  dan: {
    isPerson: true,
    likes: [
      'coding', 'girls', 'food',
    ],
  },

  Sreekesh: {
    isPerson: true,
    askedQuestion: function(){
      return true;
    },
  }

};

numberedSet[0].name == dan; // true
numberedSet[0].likes[1] == 'girls'; // true
namedSet.dan.isPerson == true; // true
namedSet.Sreekesh.askedQuestion(); // true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2018-06-17
    相关资源
    最近更新 更多