search

Home  >  Q&A  >  body text

javascript - What kind of data is the variable tag in js loop

As shown below, in a loop, after the loop variable is deleted, the loop can still proceed. Is it because this variable is specially defined as non-editable, or because the compiler creates an internal variable with the same name in the context for the loop? use?

for (var j = 0; j < 10; j++) {
  delete j;
  console.log(j); // 正常输出 0 1 2 3 ...
}
漂亮男人漂亮男人2790 days ago498

reply all(1)I'll reply

  • 为情所困

    为情所困2017-05-19 10:43:43

    Because delete can only affect instance attributes and cannot directly delete variables or functions.
    If you execute the following command, the return value will be false, indicating that the deletion is invalid.

    // 删除变量的场景
    var j = 1;  
    delete j;  // 返回false
    console.log(j);  // 依然是1
    
    // 删除函数的场景
    function x() {    
      console.log('hello'); 
    }
    delete x;     // 返回false
    x();          // 输出'hello', 函数依然有效
    
    // 删除对象属性的场景
    var a = {prop: 1};  
    delete a.prop;   // 返回true,表示删除成功
    console.log(a.prop);   // undefined

    Attachment: delete operator syntax, from MDN documentation

    delete expression 

    The expression is a reference to an object property

    delete object.property
    delete object['property']

    reply
    0
  • Cancelreply