search

Home  >  Q&A  >  body text

javascript - js square bracket problem

import {INCREMENT} from "./types"

const mutations = {
    [INCREMENT] (state) {
      state.count++;
    }
}

[INCREMENT] Can't INCREMENT be used directly as a variable? Why do we need to add a bracket?

高洛峰高洛峰2836 days ago681

reply all(2)I'll reply

  • 黄舟

    黄舟2017-05-16 13:44:12

    [INCREMENT]是计算INCREMENT这个变量的值作为函数名,不使用中括号是把INCREMENTThis string is used as the function name.

    const INCREMENT = 'myfunc';
    
    const mutations = {
        [INCREMENT] (state) {
          state.count++;
        }
    }
    

    Equivalent to the above code, the result is

    const mutations = {
        myfunc(state) {
          state.count++;
        }
    }

    And

    const INCREMENT = 'myfunc';
    const mutations = {
        INCREMENT (state) {
          state.count++;
        }
    }
    The result of

    is

    const mutations = {
        INCREMENT(state) {
          state.count++;
        }
    }

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-16 13:44:12

    These are computed property names

    https://developer.mozilla.org...

    reply
    0
  • Cancelreply