简体   繁体   中英

Why can't I assign new value to variable inside a block?

Below I have two examples of code. They are the same except I change the value of w at the beginning. In either example, m has a value. All I'm trying to do is set x = m . Why can I do this in the first but not the second? I'm testing this in the console in Chrome (68.0.3440.84)

This works (m = 100| x = 100)

  var c = [], w="word", x = 0; for (l=0; l<w.length; l++){ c.push(w.charCodeAt(l)); } for (i in c) { if (c.length > 0) { var m = c[1]; if (m > Math.min(m, c[i])) { m = Math.min(m, c[i]); x = m; console.log(x); } } } 

This does not work (m = 97| x = 0):

  var c = [], w="cancel", x = 0; for (l=0; l<w.length; l++){ c.push(w.charCodeAt(l)); } for (i in c) { if (c.length > 0) { var m = c[1]; if (m > Math.min(m, c[i])) { m = Math.min(m, c[i]); x = m; //why cant I set this? console.log(x); } } } 

There is more I want to do but in my process of figuring out this learning problem I have I have been unable to set this variable x reliably and I'm trying to figure out why.

It is because if (m > Math.min(m, c[i])) condition is never met. In your example both m and Math.min(m, c[i]) have the same value. Replacing > with >= seems to be fixing your issue. Or moving console.log outside if statement - depending on what you're actually trying to achieve.

 var c = [], w = "cancel", x = 0; for (l = 0; l < w.length; l++) { c.push(w.charCodeAt(l)); } for (i in c) { if (c.length > 0) { var m = c[1]; if (m >= Math.min(m, c[i])) { // because m > Math.min(m, c[i]) would return false m = Math.min(m, c[i]); x = m console.log(x); } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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