Node.js 在我的节点应用程序中,为什么相同的东西会给出不同的输出?
Node.js 在我的节点应用程序中,为什么相同的东西会给出不同的输出?,node.js,ejs,Node.js,Ejs,var b=“pp.specifications.完整规范。”; var c=arr[i] 这里,arr[i]的值是内存 var a=b+c; 控制台日志(a) 它在控制台上打印pp.specification.full_specs.Memory 但是当我使用 console.log(pp.specifications.full_specs.Memory) 然后将json对象打印为: {系列:“Inspiron”, 型号:“A562103SIN9”, 实用工具:“日常使用”, 操作系统:“Win
var b=“pp.specifications.完整规范。”;
var c=arr[i]代码>
这里,arr[i]的值是内存
var a=b+c;
控制台日志(a)代码>
它在控制台上打印pp.specification.full_specs.Memory
但是当我使用
console.log(pp.specifications.full_specs.Memory)代码>
然后将json对象打印为:
{系列:“Inspiron”,
型号:“A562103SIN9”,
实用工具:“日常使用”,
操作系统:“Windows 10 Home(64位)”,
尺寸:“274.73 x 384.9 x 25.44 mm”,
重量:“2.62公斤”,
保修:“1年现场保修”}
每当a的值包含pp.specifications.full_specs.Memory时
那么,获得不同输出的原因是什么呢?两者之间有一个基本的区别
console.log(pp.specifications.full_specs.Memory)代码>
及
console.log(“pp.specifications.full_specs.Memory”)代码>
注意引用
所以表达式:console.log(pp.specifications.full_specs.Memory)代码>可以从左到右读取:
打印到pp.specifications.full_specs.Memory的输出值
,这是pp
对象在获取其属性specifications
后的值,然后是其属性full_specs
等
而“pp.specifications.full_specs.Memory”
仅表示一段文本
代码中发生的事情现在应该更清楚了:
// B is piece of text
var b = "pp.specifications.full_specs.";
// C is some other value - let's say also textual one
var c = arr[i]
// So b+c will mean add text to some other text
// It's expected that the result of such operations is concatenated text
// So then console.log(b+c) will mean
// Print the concatenated text from b and c
// And it's just plain text
console.log(b+c);
//It's the same as:
console.log("pp.specifications.full_specs.Memory");
// And this one means print some specific object attributes
// which is different operation!
console.log(pp.specifications.full_specs.Memory);
如果要通过文本访问对象,可以执行以下操作:
var d = eval(b+c);
这是相当危险的,评估应该避免,但我只是想展示一下基本的想法。Eval执行字符串,就像它们是代码一样。
所以字符串“pp.specifications.full_specs.Memory”
将作为实际对象的值进行计算(是的!)
由于eval可以执行任何操作,因此应该始终避免它,而且它是超流的
相反,如果您想在某些文本输入上访问pp
basic的某些属性,您可以执行以下操作:
pp['specifications']['full_specs']['Memory']
因为pp.x
符号等同于表达式:pp['x']
我希望我的回答能帮助您更好地理解Javascript机制:)谢谢您,先生,这真的很有帮助。