简体   繁体   中英

Why doesn't this cycling function in javaScript return 0 every time? How would I do something similar in python?

I'm new to programming and am learning a bit of javaScript after knowing a bit of Python. I'm using javaScript to control elements inside a mobile AR app and I created a very simple cycler function that works exactly as I want it to but honestly I'm trying to understand WHY it works! I wanted a function that would cycle 1,2,3 on each tap. First tap would return '1', second tap '2', third tap '3', then repeat this sequence on additional taps. Here is what I came up with after lots of trial, error and googling:

 const cycler = { current: -1, cycle: function() { if (cycler.current == 3) { cycler.current = 0; } else { cycler.current++; } console.log(cycler.current); } } cycler.cycle() cycler.cycle() cycler.cycle() cycler.cycle() cycler.cycle() 

On the tap event, I call cycler.cycle(); and it works...returning 1,2,3,1,2,3,etc. corresponding to my taps...but I don't understand why it doesn't just return 0 every time I tap. Why isn't 'current' being reset to '-1' every time I call this? How would I do something similar in python? How do I think about this? Thanks for any insight!

当在内存中创建对象时,它将初始当前值设置为-1,除非删除该对象并在内存中重新创建,否则该值将是您上一次将其设置为的值。

Your cycler is an object literal in javascript. It has a property, current , and a method, cycle . Calling the method does not re-create the object, it just runs the function.
As you know, the function simply increments the value of the current property (unless the current value is 3 , of course, in which case it resets the value to 0 .)

In python you might make a class that creates a counter object. Its constructor would contain code very similar to the object you created here.
If you keep making new instances from that class and call .cycle once on each instance, your log will contain a bunch of 0 s as you were expecting.
However, if you call .cycle on the same instance repeatedly, you'll get the behavior you found here.

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