简体   繁体   中英

javascript evaluate the expression containing the array literal each time

If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal.

Source: MDN, "Values, variables, and literals"

I can't understand it well.
Someone can give me a example detailly.

Without knowing more context, it's hard to say what the author meant. (I checked, that text isn't from the spec.) Okay, now we know the source of the quote, I've checked, and the below applies.

Say you have this script:

var a = [1, 2, 3];

Every time that script is evaluated, that array initialiser ("literal") is evaluated. The array isn't created once and cached. In browser applications, it's rare to re-evaluate the top-level script without reloading the entire environment, but it's possible to do it, and if you do a new array is created each time.

I don't know why the quote would say "...in a top-level script..." as this is true anywhere. For instance:

function foo() {
    var a = [1, 2, 3];

    // ...
}

Every call to foo results in a new array. The expression, like all expressions, is evaluated every time it is encountered. (There was a bug in the ES3 spec in this regard around regular expression literals, but it was fixed in ES5.)

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