简体   繁体   中英

Get Name of Object in Array in Javascript

var MD5 = require("crypto-js/md5");
var hash = [MD5, SHA1, SHA256, SHA224, SHA512, SHA384, SHA3, RIPEMD160];

console.log(JSON.stringify(hash[1]));

outputs undefined. I want it to output MD5 how can I do this?

console.log(hash[1].constructor.name);

outputs "Function"

You shouldn't have to find the name property under the constructor. Try doing:

console.log(hash[0].name);

and it should print out MD5 if the code you are requiring under require("crypto-js/md5"); is a function.

Also note the edit to change hash[1] to hash[0] . JS arrays start at index 0.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

If it outputs function, that means it's an anonymous function.

For instance, both func0 and func1 are functions.

var func0 = function (){}
var func1 = function func(){}

console.log(func0.name); // nothing...
console.log(func1.name); // func

When you try this, you should see empty for name.

var MD5 = require("crypto-js/md5");
console.log('MD5.name:' ,MD5.name); // 'MD5.name'

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