如何将此JavaScript字符串变为“myArray [0] .myPrice”在参考myPrice? [英] How to turn this JavaScript string "myArray[0].myPrice" in to a reference to myPrice?

查看:63
本文介绍了如何将此JavaScript字符串变为“myArray [0] .myPrice”在参考myPrice?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个myArray [0] .myPrice字符串,我如何将其转换为对 myPrice的引用

If I have a string of "myArray[0].myPrice", how do I turn this in to a reference to myPrice?

这是代码上下文:

binding.value = convert(binding.data[binding.field], 
                        binding.converter, binding.data, elem); 

binding.field 包含myArray [0] .myPrice。

binding.field is what contains "myArray[0].myPrice".

binding.data 引用了具有Array属性的分层对象of myArray,第一个元素是一个属性为myPrice的对象。

binding.data has a reference to the hierarchical object which has an Array property of myArray, and the first element is an object with a property of myPrice.

编辑:根据答案,这个工作:

based on the answers, this worked:

binding.value = convert(eval('(binding.data.' + binding.field + ')'), 
              binding.converter, binding.data, elem);

这样使用eval好吗?我认为eval会在较新的JavaScript中消失?

Is it good to use eval like this? I thought eval was going away in newer JavaScript?

推荐答案

你可以使用 eval ,但这是一个更好的解决方案:

You can use eval, but here is a better solution:

// The following code results in the same as that scary eval(...)

var data = binding.data,
    chain = binding.field.split(/[\.\[\]]+/);

for (var i = 0; data[chain[i]]; i++) {
    data = data[chain[i]];      
}

// Embrace JavaScript Awesomeness!

我在这里做的细分:

在JS中,任何属性都可以被称为 object [propertyName]

In JS any property can be called as object[propertyName].

包括数组,即 a [3] a ['3'] 相同。

因此,我们使用以下字符之一拆分字符串: [ + 是有的,因为没有它,如果你有 a [3] .b [3] ]。会给你一个空的
字符串。

Therefore, we split the string using one of the characters: ., [, ]. The + is there because without it if you have a[3].b[3] the ]. will give you an empty string.

我们最后可能得到一个空字符串,但那不是一个问题,因为与JS中的 false 类似。

We might get an empty string in the end, but that's not a problem since "" is like false in JS.

你可以更进一步,过滤掉所有无效的变量名,这些名称在javascript中的名称不符合 [a-zA-Z _ $] [0-9a-zA-Z_ $] * 。但我不确定为什么会这样做......

You could go further and filter out all the invalid variable names, which in javascript is a name that does not conform to [a-zA-Z_$][0-9a-zA-Z_$]*. But I am not quite sure as to why one would do that...

这篇关于如何将此JavaScript字符串变为“myArray [0] .myPrice”在参考myPrice?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆