Variable name as a string in Javascript

前端 未结 17 1528
难免孤独
难免孤独 2020-11-22 06:20

Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)

I would like to do like this:

var myFirstName =         


        
17条回答
  •  既然无缘
    2020-11-22 06:44

    Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.

    Here is an example:

    // Get John’s properties (firstName, lastName)
    var john = {firstName: 'John', lastName: 'Doe'};
    var properties = Object.keys(john);
    
    // Show John’s properties
    var message = 'John’s properties are: ' + properties.join(', ');
    document.write(message);

提交回复
热议问题