简体   繁体   English

JavaScript变量名称冲突

[英]Javascript variable name conflict

 var name = document.querySelectorAll('.info input[type=text]'); var name1 = document.querySelectorAll('.info input[type=text]'); console.log(name); console.log(name1); 
  <div class='info'> <div> <div><label id="dd">Name</label><input type='text'></div> <div><label>Father Name</label><input type='text'></div> </div> </div> 

javascript is producing different results for same code, only variable name is different. javascript对于相同的代码会产生不同的结果,只是变量名不同。 this is the output produced on my device 这是我的设备上产生的输出

There is a property called name on the window object that you are printing out: 您要打印的window对象上有一个名为name的属性:

 var name2 = document.querySelectorAll('.info input[type=text]'); var name1 = document.querySelectorAll('.info input[type=text]'); console.log(name === window.name); console.log(name2); console.log(name1); 
  <div class='info'> <div> <div><label id="dd">Name</label><input type='text'></div> <div><label>Father Name</label><input type='text'></div> </div> </div> 

The problem has to do with window.name : https://developer.mozilla.org/en-US/docs/Web/API/Window/name 该问题与window.name有关: https : //developer.mozilla.org/en-US/docs/Web/API/Window/name

As you're in the top scope, you are modifying window.name instead of creating a new var. 当您处于顶部范围时,您正在修改window.name而不是创建新的var。 window.name is being converted to a string, that's why it logs something different. window.name被转换为字符串,这就是为什么它记录了一些不同的原因。 You need to wrap that code in a function or use a different variable name. 您需要将该代码包装在函数中或使用其他变量名称。

let [ name1, name2 ] = document.querySelectorAll('.info input[type=text]');

<div class='info'>
   <div>
     <div><label id="dd">Name</label><input type='text'></div>
     <div><label>Father Name</label><input type='text'></div>       
   /div>
</div>

Try using a variable instead of name since that might conflict with window.name , this will only conflict if you are using this variable in your root scope. 尝试使用变量而不是name因为这可能与window.name冲突,这仅在您在根范围内使用此变量时才冲突。 Use a modular approach instead. 请改用模块化方法。 To avoid errors like these. 为了避免此类错误。

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

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