简体   繁体   中英

If statement fails to define variable unless shorthand is used (javascript)

I am attempting to define a variable x which will serve to check the location along the x-axis of a moving dot in a circular display, and replot it if it is outside of an allowed radius. It worked when only specified to one direction using just the line:

let x = ((this.state.centerx[point] + frame * this.props.jump) < (0.5 * this.props.width - 0.15 * this.props.width)) ?
(this.state.centerx[point] + frame * this.props.jump) + (0.3 * this.props.width) : this.state.centerx[point] + frame * this.props.jump

however when I attempted to add another check in the form of an if statement I would receive error:

63:20  error    'x' is not defined

Here is the entire code that I am attempting to use:

for(var frame = 0; frame < this.props.numframes; frame++) {
    var startpoint = (frame % 2 === 0) ? 0 : this.props.numpoints
    for(var point = startpoint; point < startpoint + this.props.numpoints; point++) {
        if(this.state.direction > 0) {
            let x = ((this.state.centerx[point] + frame * this.props.jump) < (0.5 * this.props.width - 0.15 * this.props.width)) ? (this.state.centerx[point] + frame * this.props.jump) + (0.3 * this.props.width) : (this.state.centerx[point] + frame * this.props.jump)
        } else {
            let x = ((this.state.centerx[point] + frame * this.props.jump) > (0.5 * this.props.width + 0.15 * this.props.width)) ? (this.state.centerx[point] + frame * this.props.jump) - (0.3 * this.props.width) : (this.state.centerx[point] + frame * this.props.jump)
    }

Thank you for any insight you may be able to provide.

The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.

Also, variables declared with let are not accessible before they are declared in their enclosing block. As seen in the demo, this will throw a ReferenceError exception

Try change variable defining method

let x

to

const 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