[英]Using template literals for dynamic expression in Javascript
How can i using dynamic values for evaluating expressions? 如何使用动态值评估表达式? For instance, consider the below example,
例如,考虑以下示例,
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`);
What if a and b are dynamic names? 如果a和b是动态名称怎么办? means instead of a and b it can be anything like 'someValue' .
意思是代替a和b可以是'someValue'之类的东西。 how to do something like below?
怎么做下面这样的事情? (name can be dynamic)
(名称可以是动态的)
var 'someValue' = 1;
console.log(`*Fifteen is ${'someValue' + b}* and not ${2 * a + b}.`);
In a nutshell i want to evaluate an expression where the field names are dynamic. 简而言之,我想评估一个表达式,其中字段名称是动态的。 So i wont be able to define variables statically.
所以我将无法静态定义变量。 How do i overcome this?
我该如何克服呢?
You can use bracket
notation and this
keyword which is a reference to the window object. 您可以使用
bracket
符号和this
关键字,它是对window对象的引用。
window.name="Vicky"; window.test="test"; const message = (p0, p1) => `Hello, ${p0}. This is a ${p1}`; console.log(message(window['name'],window['test']));
You can use a temporary Object with variables as its attributes 您可以使用带有变量作为其属性的临时对象
let temp = Object.create(null);
temp["someVar"] =3;
temp["anotherVar"]=2;
console.log(temp["someVar"] + temp["anotherVar"]);
But you can also use the more elegant 但是你也可以用比较优雅
let temp = Object.create(null);
temp.someVar =3;
temp.anotherVar=2;
console.log(temp.someVar+ temp.anotherVar);
Do be careful about your "this" bindings 请注意您的“ this”绑定
If your field names are completely custom, you can get use of Object.keys(..)
. 如果您的字段名称是完全自定义的,则可以使用
Object.keys(..)
。 This method will let you loop through the properties in an object. 通过此方法,您可以循环访问对象中的属性。
The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
Object.keys()方法返回给定对象自己的可枚举属性的数组,其顺序与for ... in循环提供的顺序相同(不同之处在于for-in循环枚举原型链中的属性为:好)。
Example (Just to show usage) 示例 (仅显示用法)
const customObject = { name: 'Foo', age: 23, city: 'Bar City' }; const getFormatedObject = (fieldsObject) => { const fields = {}; Object.keys(fieldsObject).forEach((fieldName, index) => { fields[`f${index}`] = fieldsObject[fieldName]; }); return fields; } const formatedObject = getFormatedObject(customObject); for (let i = 0; i < Object.keys(formatedObject).length; i++) { console.log(formatedObject[`f${i}`]); }
If you know the number of fields on your object you can go with something like below. 如果您知道对象上的字段数,则可以进行如下操作。
const customObject = { name: 'Foo', age: 23, city: 'Bar City' }; const keys = Object.keys(customObject); console.log(`His ${keys[0]} is ${customObject[keys[0]]} and ${keys[1]} is ${customObject[keys[1]]} and ${keys[2]} is ${customObject[keys[2]]}`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.